text:
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web;
using Bender.Common;
using Bender.Configuration;
using Newtonsoft.Json.Linq;

namespace Bender.Module
{
    [Export(typeof(IModule))]
    public class GirlUp : IModule
    {
        private static Regex regex = new Regex(@"girl\s+up\s+the\s+chat", RegexOptions.IgnoreCase | RegexOptions.Singleline);

        private Random random = new Random();

        private IConfiguration config;
        private IBackend backend;

        public void OnStart(IConfiguration config, IBackend backend)
        {
            this.config = config;
            this.backend = backend;
        }

        public async void OnMessage(IMessage message)
        {
            try
            {
                if (!message.IsFromMyself && !message.IsHistorical)
                {
                    var match = regex.Match(message.FullBody);

                    if (match.Success)
                    {
                        await backend.SendMessageAsync(message.ReplyTo, await GetRandomProgrammerGoslingUrlAsync() + " " + new String('~', 3 + random.Next(11)));
                    }
                }
            }
            catch(Exception e)
            {
                Console.Error.WriteLine(e); // TODO: Handle better
            }
        }

        private async Task<string> GetRandomProgrammerGoslingUrlAsync()
        {
            var apiKey = this.config[Constants.ConfigKey.TumblrApiKey];

            var infoUrl = "http://api.tumblr.com/v2/blog/programmerryangosling.tumblr.com/info?api_key=" + HttpUtility.UrlEncode(apiKey);

            var infoResponse = await new HttpClient().GetAsync(infoUrl);
            infoResponse.EnsureSuccessStatusCode();

            int posts = (JObject.Parse(await infoResponse.Content.ReadAsStringAsync()) as dynamic).response.blog.posts;

            var imageUrl = "http://api.tumblr.com/v2/blog/programmerryangosling.tumblr.com/posts?limit=1&api_key=" + HttpUtility.UrlEncode(apiKey) + "&offset=" + random.Next(posts);
            var imageResponse = await new HttpClient().GetAsync(imageUrl);
            imageResponse.EnsureSuccessStatusCode();

            var image = (JObject.Parse(await imageResponse.Content.ReadAsStringAsync()) as dynamic);

            return image.response.posts[0].photos[0].original_size.url;
        }
    }
}


text:
layout: default
---

Calendar

redpajama_set_name: RedPajamaGithub


text:
<?php

declare(strict_types=1);

namespace Codeception;

use ArrayAccess;
use Codeception\Exception\ModuleConfigException;
use Codeception\Exception\ModuleException;
use Codeception\Lib\Interfaces\RequiresPackage;
use Codeception\Lib\ModuleContainer;
use Codeception\Util\Shared\Asserts;
use Exception;

/**
 * Basic class for Modules and Helpers.
 * You must extend from it while implementing own helpers.
 *
 * Public methods of this class start with `_` prefix in order to ignore them in actor classes.
 * Module contains **HOOKS** which allow to handle test execution routine.
 *
 */
abstract class Module
{
    use Asserts;

    /**
     * By setting it to false module wan't inherit methods of parent class.
     */
    public static bool $includeInheritedActions = true;

    /**
     * Allows to explicitly set what methods have this class.
     */
    public static array $onlyActions = [];

    /**
     * Allows to explicitly exclude actions from module.
     */
    public static array $excludeActions = [];

    /**
     * Allows to rename actions
     */
    public static array $aliases = [];

    protected array $storage = [];

    protected array $config = [];

    protected array $backupConfig = [];

    protected array $requiredFields = [];

    /**
     * Module constructor.
     *
     * Requires module container (to provide access between modules of suite) and config.
     */
    public function __construct(protected ModuleContainer $moduleContainer, ?array $config = null)
    {
        $this->backupConfig = $this->config;
        if (is_array($config)) {
            $this->_setConfig($config);
        }
    }

    /**
     * Allows to define initial module config.
     * Can be used in `_beforeSuite` hook of Helpers or Extensions
     *
     * ```php
     * <?php
     * public function _beforeSuite($settings = []) {
     *     $this->getModule('otherModule')->_setConfig($this->myOtherConfig);
     * }
     * ```
     *
     * @throws ModuleConfigException|ModuleException
     */
    public function _setConfig(array $config): void
    {
        $this->config = array_merge($this->config, $config);
        $this->backupConfig = $this->config;
        $this->validateConfig();
    }

    /**
     * Allows to redefine config for a specific test.
     * Config is restored at the end of a test.
     *
     * ```php
     * <?php
     * // cleanup DB only for specific group of tests
     * public function _before(Test $test) {
     *     if (in_array('cleanup', $test->getMetadata()->getGroups()) {
     *         $this->getModule('Db')->_reconfigure(['cleanup' => true]);
     *     }
     * }
     * ```
     *
     * @throws ModuleConfigException|ModuleException
     */
    public function _reconfigure(array $config): void
    {
        $this->config = array_merge($this->backupConfig, $config);
        $this->onReconfigure();
        $this->validateConfig();
    }

    /**
     * HOOK to be executed when config changes with `_reconfigure`.
     */
    protected function onReconfigure()
    {
        // update client on reconfigurations
    }

    /**
     * Reverts config changed by `_reconfigure`
     */
    public function _resetConfig(): void
    {
        $this->config = $this->backupConfig;
    }

    /**
     * Validates current config for required fields and required packages.
     *
     * @throws ModuleConfigException|ModuleException
     */
    protected function validateConfig(): void
    {
        $fields = array_keys($this->config);
        if (array_intersect($this->requiredFields, $fields) !== $this->requiredFields) {
            throw new ModuleConfigException(
                $this::class,
                "\nOptions: " . implode(', ', $this->requiredFields) . " are required\n" .
                "Please, update the configuration and set all the required fields\n\n"
            );
        }
        if ($this instanceof RequiresPackage) {
            $errorMessage = '';
            foreach ($this->_requires() as $className => $package) {
                if (class_exists($className)) {
                    continue;
                }
                $errorMessage .= "Class {$className} can't be loaded, please add {$package} to composer.json\n";
            }
            if ($errorMessage !== '') {
                throw new ModuleException($this, $errorMessage);
            }
        }
    }

    /**
     * Returns a module name for a Module, a class name for Helper
     */
    public function _getName(): string
    {
        $moduleName = '\\' . $this::class;

        if (str_starts_with($moduleName, ModuleContainer::MODULE_NAMESPACE)) {
            return substr($moduleName, strlen(ModuleContainer::MODULE_NAMESPACE));
        }

        return $moduleName;
    }

    /**
     * Checks if a module has required fields
     */
    public function _hasRequiredFields(): bool
    {
        return !empty($this->requiredFields);
    }

    /**
     * **HOOK** triggered after module is created and configuration is loaded
     */
    public function _initialize()
    {
    }

    /**
     * **HOOK** executed before suite
     */
    public function _beforeSuite(array $settings = [])
    {
    }

    /**
     * **HOOK** executed after suite
     */
    public function _afterSuite()
    {
    }

    /**
     * **HOOK** executed before step
     */
    public function _beforeStep(Step $step)
    {
    }

    /**
     * **HOOK** executed after step
     */
    public function _afterStep(Step $step)
    {
    }

    /**
     * **HOOK** executed before test
     */
    public function _before(TestInterface $test)
    {
    }

    /**
     * **HOOK** executed after test
     */
    public function _after(TestInterface $test)
    {
    }

    /**
     * **HOOK** executed when test fails but before `_after`
     */
    public function _failed(TestInterface $test, Exception $fail)
    {
    }

    /**
     * Print debug message to the screen.
     */
    protected function debug(mixed $message): void
    {
        codecept_debug($message);
    }

    /**
     * Print debug message with a title
     */
    protected function debugSection(string $title, mixed $message): void
    {
        if (is_array($message) || is_object($message)) {
            $message = stripslashes(json_encode($message, JSON_THROW_ON_ERROR | JSON_INVALID_UTF8_SUBSTITUTE));
        }
        $this->debug("[{$title}] {$message}");
    }

    /**
     * Short text message to an amount of chars
     */
    protected function shortenMessage(string $message, int $chars = 150): string
    {
        return mb_substr($message, 0, $chars, 'utf-8');
    }

    /**
     * Checks that module is enabled.
     */
    protected function hasModule(string $name): bool
    {
        return $this->moduleContainer->hasModule($name);
    }

    /**
     * Get all enabled modules
     */
    protected function getModules(): array
    {
        return $this->moduleContainer->all();
    }

    /**
     * Get another module by its name:
     *
     * ```php
     * <?php
     * $this->getModule('WebDriver')->_findElements('.items');
     * ```
     *
     * @throws ModuleException
     */
    protected function getModule(string $name): Module
    {
        if (!$this->hasModule($name)) {
            $this->moduleContainer->throwMissingModuleExceptionWithSuggestion(__CLASS__, $name);
        }
        return $this->moduleContainer->getModule($name);
    }

    /**
     * Get config values or specific config item.
     *
     * @param string|null $key
     * @return mixed the config item's value or null if it doesn't exist
     */
    public function _getConfig(string $key = null): mixed
    {
        if (!$key) {
            return $this->config;
        }
        if (isset($this->config[$key])) {
            return $this->config[$key];
        }
        return null;
    }

    protected function scalarizeArray(array $array): array
    {
        foreach ($array as $k => $v) {
            if (!is_null($v) && !is_scalar($v)) {
                $array[$k] = (is_array($v) || $v instanceof ArrayAccess)
                    ? $this->scalarizeArray($v)
                    : (string)$v;
            }
        }

        return $array;
    }
}


text:
using System;
using System.Text.Json;
using System.Threading.Tasks;
using Amazon;
using Amazon.Runtime;
using FluentAssertions;
using Paramore.Brighter.AWSSQS.Tests.TestDoubles;
using Paramore.Brighter.MessagingGateway.AWSSQS;
using Xunit;

namespace Paramore.Brighter.AWSSQS.Tests.MessagingGateway
{
    [Trait("Category", "AWS")]
    [Trait("Fragile", "CI")]
    public class SqsMessageConsumerRequeueTests : IDisposable
    {
        private readonly Message _message;
        private readonly IAmAChannel _channel;
        private readonly SqsMessageProducer _messageProducer;
        private readonly ChannelFactory _channelFactory;
        private readonly MyCommand _myCommand;

        public SqsMessageConsumerRequeueTests()
        {
            _myCommand = new MyCommand{Value = "Test"};
            Guid correlationId = Guid.NewGuid();
            string replyTo = "http:\\queueUrl";
            string contentType = "text\\plain";
            var channelName = $"Consumer-Requeue-Tests-{Guid.NewGuid().ToString()}".Truncate(45);
            string topicName = $"Consumer-Requeue-Tests-{Guid.NewGuid().ToString()}".Truncate(45);
            var routingKey = new RoutingKey(topicName);

            SqsSubscription<MyCommand> subscription = new(
                name: new SubscriptionName(channelName),
                channelName: new ChannelName(channelName),
                routingKey: routingKey
            );

            _message = new Message(
                new MessageHeader(_myCommand.Id, topicName, MessageType.MT_COMMAND, correlationId, replyTo, contentType),
                new MessageBody(JsonSerializer.Serialize((object) _myCommand, JsonSerialisationOptions.Options))
            );

            //Must have credentials stored in the SDK Credentials store or shared credentials file
            (AWSCredentials credentials, RegionEndpoint region) = CredentialsChain.GetAwsCredentials();
            var awsConnection = new AWSMessagingGatewayConnection(credentials, region);

            //We need to do this manually in a test - will create the channel from subscriber parameters
            _channelFactory = new ChannelFactory(awsConnection);
            _channel = _channelFactory.CreateChannel(subscription);

            _messageProducer = new SqsMessageProducer(awsConnection, new SnsPublication{MakeChannels = OnMissingChannel.Create});
        }

        [Fact]
        public void When_rejecting_a_message_through_gateway_with_requeue()
        {
            _messageProducer.Send(_message);

            var message = _channel.Receive(5000);

            _channel.Reject(message);

            //Let the timeout change
            Task.Delay(TimeSpan.FromMilliseconds(3000));

            //should requeue_the_message
            message = _channel.Receive(5000);

            //clear the queue
            _channel.Acknowledge(message);

            message.Id.Should().Be(_myCommand.Id);
        }

        public void Dispose()
        {
            //Clean up resources that we have created
            _channelFactory.DeleteTopic();
            _channelFactory.DeleteQueue();
        }
    }
}


text:
source /var/cpm/bin/setenv.sh

# when the container starts, see if there is a pg instance we can start up
if [ -f /pgdata/postgresql.conf ]; then
	rm /pgdata/postmaster.pid
	su - postgres -c 'source /var/cpm/bin/setenv.sh && pg_ctl -D /pgdata start'
fi

# if the syslog config file is found, assume the user wants to start the syslog daemon
if [ -f /syslogconfig/rsyslog.conf ]; then
	cp /syslogconfig/listen.conf /etc/rsyslog.d/
	rsyslogd -f /syslogconfig/rsyslog.conf
fi

cpmcontainerserver

#dummyserver


text:
package org.jetbrains.plugins.groovy.griffon;

import com.intellij.lang.annotation.AnnotationHolder;
import com.intellij.psi.PsiAnnotationOwner;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiElement;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.plugins.groovy.annotator.CustomAnnotationChecker;
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.annotation.GrAnnotation;
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.annotation.GrAnnotationMemberValue;
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.annotation.GrAnnotationNameValuePair;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrField;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition;

/**
 * @author Max Medvedev
 */
public class GriffonPropertyListenerAnnotationChecker extends CustomAnnotationChecker {
  @Override
  public boolean checkArgumentList(@NotNull AnnotationHolder holder, @NotNull GrAnnotation annotation) {
    if (!"griffon.transform.PropertyListener".equals(annotation.getQualifiedName())) return false;

    final GrAnnotationNameValuePair[] attributes = annotation.getParameterList().getAttributes();
    if (attributes.length != 1) return false;

    final GrAnnotationNameValuePair attribute = attributes[0];
    final GrAnnotationMemberValue value = attribute.getValue();

    final PsiAnnotationOwner owner = annotation.getOwner();
    if (owner instanceof GrField) {
      if (value instanceof GrClosableBlock) {
        return true;
      }
    }
    else if (owner instanceof GrTypeDefinition) {
      if (value instanceof GrReferenceExpression) {
        final PsiElement resolved = ((GrReferenceExpression)value).resolve();
        if (resolved instanceof GrField) {
          final PsiClass containingClass = ((GrField)resolved).getContainingClass();
          if (annotation.getManager().areElementsEquivalent((PsiElement)owner, containingClass)) {
            return true;
          }
        }
      }
    }

    return false;
  }
}


text:
'use strict';
/**
 * Created by nprikazchikov on 3/2/15.
 */

var reportApp = angular.module('reportApp',
    [
        'ngRoute',
        'ngResource',
        'reportControllers',
        'reportServices']
);

reportApp.config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) {

    $locationProvider.html5Mode(true);
    $routeProvider
        .when('/', {
            templateUrl: '/partials/testcases.html',
            controller: 'TestCasesController'
        })

        .when('/testcases', {
            templateUrl: '/partials/testcases.html',
            controller: 'TestCasesController'
        })

        .when('/testcases/:id', {
            templateUrl: '/partials/testcase.html',
            controller: 'TestCaseController'
        })

        .when('/report', {
            redirectTo: 'report/summary'
        })

        .when('/report/summary', {
            templateUrl: '/partials/report_summary.html',
            controller: 'SummaryReportController'
        });
}]);


text:
require 'helper'

class TestHipsterIpsum < Test::Unit::TestCase
  def test_paragraph
    assert_match /1\+|[ a-z]+/i, Faker::HipsterIpsum.paragraph
  end

  def test_sentence
    assert_match /1\+|[ a-z]+/i, Faker::HipsterIpsum.sentence
  end

  def test_paragraphs
    assert_match /1\+|[ a-z]+/i, Faker::HipsterIpsum.paragraphs.join(" ")
  end

  def test_sentences
    assert_match /1\+|[ a-z]+/i, Faker::HipsterIpsum.sentences.join(" ")
  end

  def test_words
    assert_match /1\+|[ a-z]+/i, Faker::HipsterIpsum.words.join(" ")
  end

  def test_word
    assert_match /1\+|[a-z]+/i, Faker::HipsterIpsum.word
  end
end


text:
@implementation TableViewDemoCell{

    __weak IBOutlet UIButton *_button;
    __weak IBOutlet UILabel *_textLable;
}

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
}

- (void)setDataInfo:(User *)dataInfo {
    _textLable.text = dataInfo.name;
    [_button setTitle:dataInfo.sex forState:UIControlStateNormal];

    int i = arc4random()*100;
    if(i % 2 == 0){
        _textLable.backgroundColor = [UIColor orangeColor];
    }else{
        _textLable.backgroundColor = [UIColor grayColor];
    }
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

@end


text:
while read dir; do
    chmod a+x $dir
done <SCGB.directories.txt

source_folder='/bio/lillyl1/ATACseq/processed_data/A4_ED_Rep2'
partialpathtofile=`head -n $SGE_TASK_ID SCGB.files.txt | tail -n 1`
dest_folder='/pub/public-www/lillyl1'

chmod a+r $source_folder/$partialpathtofile
mkdir -p $dest_folder/$(dirname $partialpathtofile)
ln -s $source_folder/$partialpathtofile $dest_folder/$partialpathtofile


text:
(function () {
    'use strict'
    angular.module('events', ['ui.router', 'mwl.calendar'])
        .config(function ($stateProvider, $urlRouterProvider) {
            $stateProvider
                /*=events*/
                .state("app.manager.create-event", {
                    url: "/create-event",
                    controller: "CreateSvetEventCtrl as createSvetEvent",
                    templateUrl: "scripts/events/views/create-svet-eventCtrl.html"
                })
                .state("app.events", {
                    url: "/events",
                    abstract: true,
                    controller: "EventsCtrl as events",
                    templateUrl: "scripts/events/views/eventsCtrl.html"
                })
                .state("app.events.calendar", {
                    url: "/event-calendar",
                    controller: "EventCalendarCtrl as eventCalendar",
                    templateUrl: "scripts/events/views/event-calendarCtrl.html"
                })
                .state("app.events.field", {
                    url: "/events/field-event/:year",
                    controller: "FieldEventCtrl as fieldEvent",
                    templateUrl: "scripts/events/views/field-eventCtrl.html"
                })
                .state("app.events.ravinia", {
                    url: "/ravinia-event",
                    controller: "RaviniaEventCtrl as raviniaEvent",
                    templateUrl: "scripts/events/views/ravinia-eventCtrl.html"
                })
                .state("app.events.kohl2015", {
                    url: "/kohl2015",
                    controller: "Kohl2015Ctrl",
                    templateUrl: "scripts/events/views/kohl2015Ctrl.html"
                })
                .state("app.events.one-event", {
                    url: "/one-event/:eid",
                    controller: "OneEventCtrl",
                    templateUrl: "scripts/events/views/one-eventCtrl.html"
                })
                .state("app.events.event-article", {
                    url: "/event-article",
                    controller: "Event-articleCtrl",
                    templateUrl: "scripts/events/views/event-articleCtrl.html"
                })

                .state("app.events.one-event-gallery", {
                    url: "/one-event-gallery",
                    controller: "One-event-galleryCtrl",
                    templateUrl: "scripts/events/views/one-event-galleryCtrl.html"
                })
//#state'
        });
})();


text:
<!DOCTYPE html>
<html>
  <head>
    <title>Listing 14.8</title>
    <meta charset="utf-8">
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
    <script type="text/javascript" src="../scripts/assert.js"></script>
    <link href="../styles/assert.css" rel="stylesheet" type="text/css">
  </head>
  <body>
    <script type="text/javascript">

      var div = document.createElement("div");

      if (div.attachEvent && div.fireEvent) {
        div.attachEvent("onclick", function () {
          // cloning a node shouldn't copy over any
          // bound event handlers (ie does this)
          jquery.support.noCloneEvent = false;
          div.detachEvent("onclick", arguments.callee);
        });
        div.cloneNode(true).fireEvent("onclick");
      }

    </script>
  </body>
</html>


text:
package org.gradle.tooling.internal.adapter;

import java.util.List;
import java.util.Map;
import java.util.Set;

public class TypeInspectorTestHelper {
    interface Item1 {
    }

    interface Item2 {
    }

    interface Item3 {
    }

    interface Item4 {
    }

    interface Item5 {
    }

    interface SuperThing {
        Runnable method1();

        List<Item1> method2();

        Map<Set<Item2>, String> method3();
    }

    interface GenericThing {
        Item3[] method1(String p);
        List<Item5>[] method2(String p);
    }

    interface Thing extends SuperThing, GenericThing {
        <T extends Item4> List<T> get();
    }

    interface Parent {
        Child getFirstChild();
    }

    interface Child {
        Parent getParent();
        Child getNextSibling();
    }

    interface GenericItem1<T> {
    }

    interface GenericItem2<T> {
    }

    interface  GenericChild<T extends GenericItem1<? extends T>> extends GenericItem1<T> {
        <U extends GenericItem2<? super U>> void method(GenericItem2<U> p);
    }
}


text:
{% extends base_template %}

{#################################################################################################################}

{% block title %}
 homepage{% endblock title %}

{#################################################################################################################}

{% block content %}

What would you like to do?

View

All patients

Add

New patient

Search

By text

By ID

Administer

Your account

{% if user.is_selected_dom_admin %}

This domain

{% endif %}

New domain

{% endblock content %}

{#################################################################################################################}


text:
**Namespace:** [OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201512](OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201512.md)
**Assembly:** OfficeDevPnP.Core.dll
## Inheritance Hierarchy
System.Object
## Syntax
```C#
public class ComposedLook
```
## Constructors
|**Name**|**Description**|
|:-----|:-----|
| [ComposedLook()](OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201512.ComposedLook.ctor1.md) |
## Properties
|**Name**|**Description**|
|:-----|:-----|
| [BackgroundFile](OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201512.ComposedLook.BackgroundFile.md) |
| [ColorFile](OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201512.ComposedLook.ColorFile.md) |
| [FontFile](OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201512.ComposedLook.FontFile.md) |
| [Name](OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201512.ComposedLook.Name.md) |
| [Version](OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201512.ComposedLook.Version.md) |
| [VersionSpecified](OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201512.ComposedLook.VersionSpecified.md) |
## See also
- [OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201512](OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201512.md)


text:
/**
 * @fileoverview Disallow sparse arrays
 * @author Nicholas C. Zakas
 */
"use strict";

//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------

module.exports = function(context) {

    //--------------------------------------------------------------------------
    // Public
    //--------------------------------------------------------------------------

    return {

        "ArrayExpression": function(node) {

            var emptySpot = node.elements.indexOf(null) > -1;

            if (emptySpot) {
                context.report(node, "Unexpected comma in middle of array.");
            }
        }

    };

};

module.exports.schema = [];


text:
package com.github.aureliano.achmed.client.types;

import static com.github.aureliano.achmed.client.types.OperatingSystemFamily.*;
import static org.junit.Assert.assertEquals;

import org.junit.Test;

import com.github.aureliano.achmed.client.types.OS;

public class OperatingSystemFamilyTest {

	@Test
	public void testGetOperatingSystem() {
		assertEquals(OS.LINUX, DEBIAN.getOperatingSystem());
		assertEquals(OS.LINUX, RED_HAT.getOperatingSystem());
		assertEquals(null, APP.getOperatingSystem());
		assertEquals(OS.LINUX, UBUNTU.getOperatingSystem());
	}

	@Test
	public void testGetAncestor() {
		assertEquals(null, DEBIAN.getAncestor());
		assertEquals(null, RED_HAT.getAncestor());
		assertEquals(null, APP.getAncestor());
		assertEquals(DEBIAN, UBUNTU.getAncestor());
	}
}


text:
/* This file was generated by upbc (the upb compiler) from the input
 * file:
 *
 *     envoy/type/tracing/v3/custom_tag.proto
 *
 * Do not edit -- your changes will be discarded when the file is
 * regenerated. */

#include <stddef.h>
#include "upb/msg_internal.h"
#include "envoy/type/tracing/v3/custom_tag.upb.h"
#include "envoy/type/metadata/v3/metadata.upb.h"
#include "udpa/annotations/status.upb.h"
#include "udpa/annotations/versioning.upb.h"
#include "validate/validate.upb.h"

#include "upb/port_def.inc"

static const upb_MiniTable_Sub envoy_type_tracing_v3_CustomTag_submsgs[4] = {
  {.submsg = &envoy_type_tracing_v3_CustomTag_Literal_msginit},
  {.submsg = &envoy_type_tracing_v3_CustomTag_Environment_msginit},
  {.submsg = &envoy_type_tracing_v3_CustomTag_Header_msginit},
  {.submsg = &envoy_type_tracing_v3_CustomTag_Metadata_msginit},
};

static const upb_MiniTable_Field envoy_type_tracing_v3_CustomTag__fields[5] = {
  {1, UPB_SIZE(4, 8), UPB_SIZE(0, 0), kUpb_NoSub, 9, kUpb_FieldMode_Scalar | (kUpb_FieldRep_StringView << kUpb_FieldRep_Shift)},
  {2, UPB_SIZE(12, 24), UPB_SIZE(-1, -1), 0, 11, kUpb_FieldMode_Scalar | (kUpb_FieldRep_Pointer << kUpb_FieldRep_Shift)},
  {3, UPB_SIZE(12, 24), UPB_SIZE(-1, -1), 1, 11, kUpb_FieldMode_Scalar | (kUpb_FieldRep_Pointer << kUpb_FieldRep_Shift)},
  {4, UPB_SIZE(12, 24), UPB_SIZE(-1, -1), 2, 11, kUpb_FieldMode_Scalar | (kUpb_FieldRep_Pointer << kUpb_FieldRep_Shift)},
  {5, UPB_SIZE(12, 24), UPB_SIZE(-1, -1), 3, 11, kUpb_FieldMode_Scalar | (kUpb_FieldRep_Pointer << kUpb_FieldRep_Shift)},
};

const upb_MiniTable envoy_type_tracing_v3_CustomTag_msginit = {
  &envoy_type_tracing_v3_CustomTag_submsgs[0],
  &envoy_type_tracing_v3_CustomTag__fields[0],
  UPB_SIZE(16, 40), 5, kUpb_ExtMode_NonExtendable, 5, 255, 0,
};

static const upb_MiniTable_Field envoy_type_tracing_v3_CustomTag_Literal__fields[1] = {
  {1, UPB_SIZE(0, 0), UPB_SIZE(0, 0), kUpb_NoSub, 9, kUpb_FieldMode_Scalar | (kUpb_FieldRep_StringView << kUpb_FieldRep_Shift)},
};

const upb_MiniTable envoy_type_tracing_v3_CustomTag_Literal_msginit = {
  NULL,
  &envoy_type_tracing_v3_CustomTag_Literal__fields[0],
  UPB_SIZE(8, 24), 1, kUpb_ExtMode_NonExtendable, 1, 255, 0,
};

static const upb_MiniTable_Field envoy_type_tracing_v3_CustomTag_Environment__fields[2] = {
  {1, UPB_SIZE(0, 0), UPB_SIZE(0, 0), kUpb_NoSub, 9, kUpb_FieldMode_Scalar | (kUpb_FieldRep_StringView << kUpb_FieldRep_Shift)},
  {2, UPB_SIZE(8, 16), UPB_SIZE(0, 0), kUpb_NoSub, 9, kUpb_FieldMode_Scalar | (kUpb_FieldRep_StringView << kUpb_FieldRep_Shift)},
};

const upb_MiniTable envoy_type_tracing_v3_CustomTag_Environment_msginit = {
  NULL,
  &envoy_type_tracing_v3_CustomTag_Environment__fields[0],
  UPB_SIZE(16, 40), 2, kUpb_ExtMode_NonExtendable, 2, 255, 0,
};

static const upb_MiniTable_Field envoy_type_tracing_v3_CustomTag_Header__fields[2] = {
  {1, UPB_SIZE(0, 0), UPB_SIZE(0, 0), kUpb_NoSub, 9, kUpb_FieldMode_Scalar | (kUpb_FieldRep_StringView << kUpb_FieldRep_Shift)},
  {2, UPB_SIZE(8, 16), UPB_SIZE(0, 0), kUpb_NoSub, 9, kUpb_FieldMode_Scalar | (kUpb_FieldRep_StringView << kUpb_FieldRep_Shift)},
};

const upb_MiniTable envoy_type_tracing_v3_CustomTag_Header_msginit = {
  NULL,
  &envoy_type_tracing_v3_CustomTag_Header__fields[0],
  UPB_SIZE(16, 40), 2, kUpb_ExtMode_NonExtendable, 2, 255, 0,
};

static const upb_MiniTable_Sub envoy_type_tracing_v3_CustomTag_Metadata_submsgs[2] = {
  {.submsg = &envoy_type_metadata_v3_MetadataKind_msginit},
  {.submsg = &envoy_type_metadata_v3_MetadataKey_msginit},
};

static const upb_MiniTable_Field envoy_type_tracing_v3_CustomTag_Metadata__fields[3] = {
  {1, UPB_SIZE(4, 8), UPB_SIZE(1, 1), 0, 11, kUpb_FieldMode_Scalar | (kUpb_FieldRep_Pointer << kUpb_FieldRep_Shift)},
  {2, UPB_SIZE(8, 16), UPB_SIZE(2, 2), 1, 11, kUpb_FieldMode_Scalar | (kUpb_FieldRep_Pointer << kUpb_FieldRep_Shift)},
  {3, UPB_SIZE(12, 24), UPB_SIZE(0, 0), kUpb_NoSub, 9, kUpb_FieldMode_Scalar | (kUpb_FieldRep_StringView << kUpb_FieldRep_Shift)},
};

const upb_MiniTable envoy_type_tracing_v3_CustomTag_Metadata_msginit = {
  &envoy_type_tracing_v3_CustomTag_Metadata_submsgs[0],
  &envoy_type_tracing_v3_CustomTag_Metadata__fields[0],
  UPB_SIZE(20, 40), 3, kUpb_ExtMode_NonExtendable, 3, 255, 0,
};

static const upb_MiniTable *messages_layout[5] = {
  &envoy_type_tracing_v3_CustomTag_msginit,
  &envoy_type_tracing_v3_CustomTag_Literal_msginit,
  &envoy_type_tracing_v3_CustomTag_Environment_msginit,
  &envoy_type_tracing_v3_CustomTag_Header_msginit,
  &envoy_type_tracing_v3_CustomTag_Metadata_msginit,
};

const upb_MiniTable_File envoy_type_tracing_v3_custom_tag_proto_upb_file_layout = {
  messages_layout,
  NULL,
  NULL,
  5,
  0,
  0,
};

#include "upb/port_undef.inc"


text:
/*	$NetBSD: lstRemove.c,v 1.14 2008/12/13 15:19:29 dsl Exp $	*/

/*
 * Copyright (c) 1988, 1989, 1990, 1993
 *	The Regents of the University of California.  All rights reserved.
 *
 * This code is derived from software contributed to Berkeley by
 * Adam de Boor.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

#ifndef MAKE_NATIVE
static char rcsid[] = "$NetBSD: lstRemove.c,v 1.14 2008/12/13 15:19:29 dsl Exp $";
#else
#include <sys/cdefs.h>
#ifndef lint
#if 0
static char sccsid[] = "@(#)lstRemove.c	8.1 (Berkeley) 6/6/93";
#else
__RCSID("$NetBSD: lstRemove.c,v 1.14 2008/12/13 15:19:29 dsl Exp $");
#endif
#endif /* not lint */
#endif

/*-
 * LstRemove.c --
 *	Remove an element from a list
 */

#include	"lstInt.h"

/*-
 *-----------------------------------------------------------------------
 * Lst_Remove --
 *	Remove the given node from the given list.
 *
 * Results:
 *	SUCCESS or FAILURE.
 *
 * Side Effects:
 *	The list's firstPtr will be set to NULL if ln is the last
 *	node on the list. firsPtr and lastPtr will be altered if ln is
 *	either the first or last node, respectively, on the list.
 *
 *-----------------------------------------------------------------------
 */
ReturnStatus
Lst_Remove(Lst l, LstNode ln)
{
    List 	list = l;
    ListNode	lNode = ln;

    if (!LstValid (l) ||
	!LstNodeValid (ln, l)) {
	    return (FAILURE);
    }

    /*
     * unlink it from the list
     */
    if (lNode->nextPtr != NULL) {
	lNode->nextPtr->prevPtr = lNode->prevPtr;
    }
    if (lNode->prevPtr != NULL) {
	lNode->prevPtr->nextPtr = lNode->nextPtr;
    }

    /*
     * if either the firstPtr or lastPtr of the list point to this node,
     * adjust them accordingly
     */
    if (list->firstPtr == lNode) {
	list->firstPtr = lNode->nextPtr;
    }
    if (list->lastPtr == lNode) {
	list->lastPtr = lNode->prevPtr;
    }

    /*
     * Sequential access stuff. If the node we're removing is the current
     * node in the list, reset the current node to the previous one. If the
     * previous one was non-existent (prevPtr == NULL), we set the
     * end to be Unknown, since it is.
     */
    if (list->isOpen && (list->curPtr == lNode)) {
	list->curPtr = list->prevPtr;
	if (list->curPtr == NULL) {
	    list->atEnd = Unknown;
	}
    }

    /*
     * the only way firstPtr can still point to ln is if ln is the last
     * node on the list (the list is circular, so lNode->nextptr == lNode in
     * this case). The list is, therefore, empty and is marked as such
     */
    if (list->firstPtr == lNode) {
	list->firstPtr = NULL;
    }

    /*
     * note that the datum is unmolested. The caller must free it as
     * necessary and as expected.
     */
    if (lNode->useCount == 0) {
	free(ln);
    } else {
	lNode->flags |= LN_DELETED;
    }

    return (SUCCESS);
}


text:
#include <stdio.h>
#include <stdbool.h>
#include "Queue.h"
#include "GraphTraversal.h"

void searchInit(Graph *G, enum State *vstate, int *parent) {
  int i;
  for (i = 0; i <= G->nvertices; i++) {
    vstate[i] = UNDISCOVERED;
    parent[i] = -1;
  }
}

/**
 * G: The graph
 * startV: start vertex
 * state: vertex state (undiscovered, discovered, processed)
 * parent: the array to store parent-child relations, the tree
 *  edges, in escense.
 */
void BFS(Graph *G, int startV, enum State *vstate, int *parent, GraphOps *ops) {
  Queue *q;

  /* Initialization */
  q = createQueue();

  vstate[startV] = DISCOVERED;
  enqueue(q, (void *)&startV);

  while (!isQueueEmpty(q)) {
    int v = *(int *)dequeue(q);

    /* Set vertex state to DISCOVERED */
    vstate[v] = DISCOVERED;
    if (ops)
      ops->processVertexEarly(v);

    /* Visit all adjacent vertices of v */
    Edge *list = G->edges[v];
    while (list) {
        G->degree[v] += 1;
        int *y = &list->y;

        /* Found undiscovered vertex */
        if (vstate[*y] == UNDISCOVERED) {
          vstate[*y] = DISCOVERED;
          enqueue(q, (void *)y);
          parent[*y] = v;

        /**
         * Note: if the Graph is directed, that's the only time we
         * will have the chance to process this edge, since it will
         * not appear in the adjacency list of y.
         *
         * If the Graph is undirected and we want to process each
         * edge only once, we can process it EITHER when y is
         * unprocessed OR when y is processed.
         *
         * If we do not include such a conditional checking then
         * each edge will be processed twice.
         *
         */
        }

        if (G->directed || vstate[*y] != PROCESSED) {
            if (ops)
              ops->processEdge(v, *y);
        }

        list = list->next;
    }

    /* Set vertex state to PROCESSED */
    vstate[v] = PROCESSED;
    if (ops)
      ops->processVertexLate(v);
  }
}

void DFS(Graph *G, int startV, enum State *vstate, int *parent, GraphOps *ops) {
  /* Set vertex state to DISCOVERED */
  vstate[startV] = DISCOVERED;
  if (ops)
    ops->processVertexLate(startV);

  Edge *list = G->edges[startV];
  while (list) {
    int *y = &list->y;

    /**
     * If y is undiscovered, then we know this is the first time
     * we see this edge..
     */
    if (vstate[*y] == UNDISCOVERED) {
      parent[*y] = startV;
      if (ops)
        ops->processEdge(startV, *y);

      DFS(G, *y, vstate, parent, ops);
      /*
       * We don't want an if here. Assume we had a simple if (not else if )
       * and consider graph 1 -> 2. Edge 1-2 will be processed once when 2 is
       * undiscovered and the algorithm will recurse into 2. Then 2 is marked
       * as processed. When the algorithm backtracks the second if condition
       * will hold true (vstate[*y] == PROCESSED and the edge will be processed
       * twice. Therefore we want an 'else if' to avoid double edge processing
       * when the algorithm backtracks.
       */
    } else if (G->directed || vstate[*y] == PROCESSED) {
        if (ops)
          ops->processEdge(startV, *y);
    }

    list = list->next;
  }

  /* Set vertex state to PROCESSED */
  vstate[startV] = PROCESSED;
  if (ops)
    ops->processVertexLate(startV);
}


text:
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=windows-1252">
<META NAME="Generator" CONTENT="Microsoft Word 97">
<TITLE>#echo</TITLE>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"><OBJECT TYPE="application/x-oleobject" CLASSID="clsid:1e2a7bd0-dab9-11d0-b93a-00c04fc99f9e"><PARAM NAME="Keyword" VALUE="#echo"></OBJECT>

#echo

Syntax: #echo [on/off]

This command toggles echoing of action commands. While echo mode is ON, all triggered action will be displayed on your screen. If echo mode is OFF, then the commands will be "silently" sent to the mud without showing it on screen.

Second parametr of this command is not necessary. Valid values is "ON" or "OFF". If you don't use it JMC will change current echo state to the inverted state.

Example:

#echo

Turns echo on/off.


text:
var fs = require('fs');
var os = require('os');
var util = require('util');
var events = require('events');
var spawn = require('child_process').spawn;
var async = require('async');

var numCpus = os.cpus().length;

var reProcVmSize = /.*VmSize:\s+([0-9]+)\s/;
var reProcVmRSS = /.*VmRSS:\s+([0-9]+)\s/;
var rePname = /.*\((.*)\).*/;

var logColumns = "Time,PID,ProcessName,CPU,AvgCPU,UserCPU,SysCPU,VmRSS,VmSize,rcharPerSecond,wcharPerSecond,syscrPerSecond,syscwPerSecond\n";

function getPidOf(pname, cb) {
  var pidof = spawn('pidof', [pname]);
  var buf = '';
  pidof.stdout.on('data', function (d) {
    buf += d;
  });
  pidof.on('close', function (code) {
    if (code !== 0) return cb({code: code});
    cb(null, buf.trim().split(' ').map(parseInt));
  });
}

function parseTotalTime(str) {
  return str.toString().split('\n')[0].split('cpu')[1].trim().split(' ').reduce(function (p, t) {
    return p + parseInt(t, 10);
  }, 0);
}

function parseProcStat(str, dst) {
  var parts = str.toString().split(')')[1].trim().split(' ');
  dst.utime = parseInt(parts[11], 10);
  dst.stime = parseInt(parts[12], 10);
  dst.num_threads = parseInt(parts[17], 10);
}

function parseProcStatus(str, dst) {
  str = str.toString();
  dst.VmSize = parseInt(reProcVmSize.exec(str)[1], 10);
  dst.VmRSS = parseInt(reProcVmRSS.exec(str)[1], 10);
}

function parseIoInfo(str, dst) {
  var parts;
  str.toString().split('\n').forEach(function (l) {
    parts = l.split(': ');
    dst[parts[0]] = parseInt(parts[1], 10);
  });
}

function PUsage (opts) {
  events.EventEmitter.call(this);
  var self = this;

  // Some settings:
  self.interval = opts.interval || 500;
  self.logStream = opts.logStream || null;
  self.logFile = opts.logFile || null;

  // State that is not configurable:
  self.running = false;
  self.startTime = 0;

  self.statFd = null;
  self.statBuff = new Buffer(1024);

  self.pids = [];
  self.names = [];
  self.processes = {};

  if (opts && typeof opts !== 'object')
    throw new TypeError('PUsage(): invalid arguments: expected an options hash (object)');
  opts = opts || {};

  if (self.logFile && typeof self.logFile !== 'string')
    throw new TypeError('PUsage(): invalid option: logFile must be a string');
  if (self.logStream && (typeof self.logStream !== 'object' || !self.logStream.write))
    throw new TypeError('PUsage(): invalid option: logStream must be a writable stream');

  if (self.logFile)
    self.logStream = fs.createWriteStream(self.logFile);
}
util.inherits(PUsage, events.EventEmitter);

function getState(self, callback) {
    var toRead = [function (cb) {
      fs.read(self.statFd, self.statBuff, 0, 1024, 0, cb);
    }];
    self.forEachProc(function (p) {
      if (!p.watch) return;
      toRead.push(function (cb) {
        fs.read(p.statFd, p.statBuff, 0, 1024, 0, function (err, num, buff) {
          cb(err, 'stat', p.name, num, buff);
        });
      });
      toRead.push(function (cb) {
        fs.read(p.ioFd, p.ioBuff, 0, 1024, 0, function (err, num, buff) {
          cb(err, 'io', p.name, num, buff);
        });
      });
      toRead.push(function (cb) {
        fs.read(p.statusFd, p.statusBuff, 0, 1024, 0, function (err, num, buff) {
          cb(err, 'status', p.name, num, buff);
        });
      });
    });
    async.parallel(toRead, function (error, results) {
      if (error) throw new Error('PUsage: could not read a /proc/ file: a process probably stopped running');
      var state = {
        total: parseTotalTime(results.shift()[1]),
        processes: {}
      };
      results.forEach(function (args) {
        if (!state.processes[args[1]]) state.processes[args[1]] = {};
        if (args[0] === 'stat')
          parseProcStat(args[3], state.processes[args[1]]);
        if (args[0] === 'status')
          parseProcStatus(args[3], state.processes[args[1]]);
        else if (args[0] === 'io')
          parseIoInfo(args[3], state.processes[args[1]]);
      });

      callback(error, state);
    });
}

function calcAvgUtil(current, log) {
  var some = log.slice(-10);
  return some.reduce(function (sum, e) {
    return sum + e.cpu;
  }, current) / (some.length + 1);
}

function stopLoop(self) {
  fs.close(self.statFd);
  if (self.logFile) self.logStream.end();
  self.forEachProc(function (p) {
    fs.close(p.statFd);
    fs.close(p.statusFd);
    fs.close(p.ioFd);
    if (p.logfile) p.logStream.end();
  });
}

function serializeLogEntry(p, e) {
  return [
    e.time,             // 1
    p.pid,              // 2
    p.name,             // 3
    e.cpu,              // 4
    e.avg_cpu,          // 5
    e.user_cpu,         // 6
    e.sys_cpu,          // 7
    e.VmRSS,            // 8
    e.VmSize,           // 9
    e.rcharPerSecond,   // 10
    e.wcharPerSecond,   // 11
    e.syscrPerSecond,   // 12
    e.syscwPerSecond    // 13
  ].map(function (e) { return e.toString(); }).join(',') + '\n';
}

function loop(self, state_before) {
    if (!self.running) return stopLoop(self);
    getState(self, function (error, state_after) {
      state_after.time = os.uptime() - self.startTime;
      if (error) throw error;
      if (state_before !== null) {
        var elapsed = state_after.time - state_before.time;
        var total_time = state_after.total - state_before.total;
        var utime, stime, user_util, sys_util, tot_util;
        var logLine, manyLogLines = '';
        self.forEachProc(function (p) {
          if (!p.watch) return;
          if (!state_before.processes[p.name]) return;
          utime = state_after.processes[p.name].utime - state_before.processes[p.name].utime;
          stime = state_after.processes[p.name].stime - state_before.processes[p.name].stime;
          user_util = numCpus * 100 * utime / total_time;
          sys_util = numCpus * 100 * stime / total_time;
          tot_util = user_util + sys_util;

          var e = {
            pid: p.pid,
            name: p.name,
            time: state_after.time,
            cpu: tot_util,
            avg_cpu: calcAvgUtil(tot_util, p.log),
            user_cpu: user_util,
            sys_cpu: sys_util,
            utime: utime,
            stime: stime,
            VmRSS: state_after.processes[p.name].VmRSS,
            VmSize: state_after.processes[p.name].VmSize,
            syscr: state_after.processes[p.name].syscr,
            syscw: state_after.processes[p.name].syscw,
            syscrPerSecond: (state_after.processes[p.name].syscr - state_before.processes[p.name].syscr) / elapsed,
            syscwPerSecond: (state_after.processes[p.name].syscw - state_before.processes[p.name].syscw) / elapsed,
            rchar: state_after.processes[p.name].rchar,
            wchar: state_after.processes[p.name].wchar,
            rcharPerSecond: (state_after.processes[p.name].rchar - state_before.processes[p.name].rchar) / elapsed,
            wcharPerSecond: (state_after.processes[p.name].wchar - state_before.processes[p.name].wchar) / elapsed
          };
          p.log.push(e);
          logLine = serializeLogEntry(p, e);
          if (p.logStream) p.logStream.write(logLine);
          manyLogLines += logLine;
          self.emit('log', e, logLine);
        });
        if (self.logStream && manyLogLines.length > 0)
            self.logStream.write(manyLogLines);
      }

      setTimeout(function () {
        loop(self, state_after);
      }, self.interval);
    });
}

PUsage.prototype.forEachProc = function (callback) {
  var self = this;
  self.names.forEach(function (n) {
    callback(self.processes[n]);
  });
};

PUsage.prototype.start = function () {
  var self = this;
  if (self.running) throw new Error('PUsage.start(): already running');
  self.running = true;

  fs.open('/proc/stat', 'r', function (error, fd) {
    if (error) throw error;
    self.statFd = fd;
    self.startTime = os.uptime();
    if (self.logStream)
      self.logStream.write(logColumns);
    loop(self, null);
  });
};

PUsage.prototype.stop = function () {
  var self = this;
  self.running = false;
};

function getProccess(self, pidOrName) {
  var p, name;
  for (name in self.processes) {
    if (!self.processes.hasOwnProperty(name)) continue;
    p = self.processes[name];
    if (p.name === pidOrName || p.pid === pidOrName)
      return p;
  }
  return null;
}

PUsage.prototype.unwatch = function (pidOrName) {
  var self = this;
  var p = getProccess(self, pidOrName);
  if (!p) throw new Error("PUsage.unwatch(): could not find process: " + pidOrName);
  p.watch = false;
};

PUsage.prototype.watch = function () {
  var self = this;
  var pid = arguments[0];
  if (pid === parseInt(pid, 10)) { // is interger, i.e. PID
    var statBuff = new Buffer(1024);
    var statusBuff = new Buffer(1024);
    var ioBuff = new Buffer(1024);
    var logFile = null, logStream = null;
    if (arguments.length > 1) {
      if (typeof arguments[1] === 'string')
        logFile = arguments[1];
      else if (typeof arguments[1] === 'object' && arguments[1].write) // is writeStream
        logStream = arguments[1];
      else
        throw new TypeError("PUsage.watch(): invalid argument #2: expected filename or writeStream.");
    }
    fs.open('/proc/' + pid.toString() + '/stat', 'r', function (error, statFd) {
      if (error) throw error;
      fs.read(statFd, statBuff, 0, 1024, 0, function (error, num, buff) {
        if (error) throw error;
        if (logFile) logStream = fs.createWriteStream(logFile);
        if (logStream) logStream.write(logColumns);
        var proc = {
          name: rePname.exec(buff.toString())[1],
          watch: true,
          pid: pid,
          statFd: statFd,
          statusFd: fs.openSync('/proc/' + pid.toString() + '/status', 'r'),
          ioFd: fs.openSync('/proc/' + pid.toString() + '/io', 'r'),
          statBuff: statBuff,
          statusBuff: statusBuff,
          ioBuff: ioBuff,
          logStream: logStream,
          log: []
        };
        self.processes[proc.name] = proc;
        self.pids.push(pid);
        self.names.push(proc.name);
        if (!self.running)
          self.start();
      });
    });
  }
  else if (typeof arguments[0] === 'string'){ // it should be a process name
    var pname = arguments[0];
    var args = Array.prototype.slice.call(arguments); // copy args
    getPidOf(pname, function (error, pids) {
      if (error) throw new Error("PUsage.watch(): process '" + pname + "' not running: `pidof` returned code " + error.code.toString());
      args[0] = pids[pids.length - 1];
      console.log(args);
      self.watch.apply(self, args);
    });
  }
  else
    throw new TypeError("PUsage.watch(): invalid arguments: expects a PID or process name.");
};

module.exports = function (opts) {
  return new PUsage(opts);
};
module.exports.PUsage = PUsage;


text:
#include "CommandMode.h"
#include "PromptTextInput.h"
#include "Prompt.h"

#include "../autocomplete/AutoComplete.h"
#include "../handlers/GenericHandler.h"
#include "../commands/CommandExecutionEngine.h"
#include "../commands/CommandSuggestion.h"
#include "../commands/CommandResult.h"
#include "../vis/TextAndDescription.h"

#include "VisualizationBase/src/items/Static.h"

namespace Interaction {

const QString TYPE_HINT = "Type a command";

Visualization::Item* CommandMode::createInputItem(const QString& initialCommandText)
{
	auto commandText = initialCommandText;
	if (commandText.isNull()) commandText = TYPE_HINT;
	inputItem_ = new PromptTextInput{nullptr, commandText};
	return inputItem_;
}

Visualization::StaticStyle* CommandMode::modeIcon() const
{
	return Visualization::Static::itemStyles().get("command-prompt-command-mode");
}

void CommandMode::setSelection(InputSelection selection)
{
	inputItem_->setSelection(selection);
}

void CommandMode::onShellUpdate()
{
	updateSuggestions();
}

void CommandMode::updateSuggestions()
{
	removeSuggestions();
	QString text = inputItem_->text() == TYPE_HINT ? "" : inputItem_->text();
	addSuggestions( GenericHandler::executionEngine()->autoComplete(
							 Prompt::commandReceiver(), text, Prompt::commandReceiverCursor()));
}

void CommandMode::addSuggestions(QList<CommandSuggestion*> suggestions)
{
	for (auto s : suggestions)
		suggestions_.emplace_back(s);
	showAutocompleteBasedOnSuggestions();
}

void CommandMode::removeSuggestions()
{
	suggestions_.clear();
	AutoComplete::hide();
}

void CommandMode::showAutocompleteBasedOnSuggestions()
{
	auto executeFunction = [this](AutoCompleteEntry* e){
		if (Prompt::mode() == this)
		{
			takeSuggestion(static_cast<CommandSuggestion*>(e));
			onEnterKeyPress(Qt::NoModifier);
		}
	};

	QList<AutoCompleteEntry*> entries;
		for (auto& s : suggestions_) entries.append(new AutoCompleteEntry{s->text(), s->description(),
				s->visualization(), executeFunction});

	if (entries.isEmpty() || Prompt::mode() != this)
		AutoComplete::hide();
	else
		AutoComplete::show(entries, true);
}

void CommandMode::takeSuggestion(CommandSuggestion* suggestion)
{
	inputItem_->setText(suggestion->text());
	inputItem_->setSelection(PromptMode::AtEnd);
}

void CommandMode::onTabKeyPress(Qt::KeyboardModifiers)
{
	if (suggestions_.size() == 1) takeSuggestion(suggestions_[0].get());
}

void CommandMode::onEnterKeyPress(Qt::KeyboardModifiers)
{
	Prompt::commandReceiver()->execute( inputItem_->text(), Prompt::commandReceiverCursor());

	auto result = GenericHandler::executionEngine()->result();

	if ( result->code() == CommandResult::OK) Prompt::hide();
	else
	{
		QList<Visualization::Item*> errorItems;

		for (auto& error : result->errors() )
		{
			if (error->visualization() == nullptr)
			{
				auto vis = new TextAndDescription{nullptr, TextAndDescription::itemStyles().get("command-prompt-error")};
				vis->setContents(error->message(), error->resolutionTips().join(" OR "));
				errorItems.append(vis);
			}
			else
			{
				//Extract the visualization
				errorItems.append(error->visualization());
				error->setVisualization(nullptr);
			}
		}

		showErrors(errorItems);
	}
}

}


text:
import { Component } from '@angular/core';

 @Component({
       selector: 'body',
       templateUrl: './body.html',
       styleUrls: ['./body.css'],
   })

export class MainBodyModule{

}


text:
\section{/home/vernkin/projects/chinese-\/ma-\/chen/source/src/CMA\_\-ME\_\-Knowledge.cc File Reference}
\label{CMA__ME__Knowledge_8cc}\index{/home/vernkin/projects/chinese-\/ma-\/chen/source/src/CMA\_\-ME\_\-Knowledge.cc@{/home/vernkin/projects/chinese-\/ma-\/chen/source/src/CMA\_\-ME\_\-Knowledge.cc}}

The Knowledge class of the CMAC.
{\ttfamily \#include $<$string$>$}\par
{\ttfamily \#include \char`\"{}CMA\_\-ME\_\-Knowledge.h\char`\"{}}\par
{\ttfamily \#include \char`\"{}CMABasicTrainer.h\char`\"{}}\par
{\ttfamily \#include \char`\"{}strutil.h\char`\"{}}\par
{\ttfamily \#include $<$assert.h$>$}\par
\subsection*{Functions}
\begin{DoxyCompactItemize}
\item
bool {\bfseries cma::fileExists} (const char $\ast$path)\label{namespacecma_ab1851cbc3cd9a0183ff1d20a8732cf9a}

\end{DoxyCompactItemize}

\subsection{Detailed Description}
The Knowledge class of the CMAC. \begin{DoxyAuthor}{Author}
vernkin
\end{DoxyAuthor}
\begin{DoxyVersion}{Version}
0.1
\end{DoxyVersion}
\begin{DoxyDate}{Date}
Feb 17, 2009
\end{DoxyDate}


text:
package org.testcontainers.jdbc.mysql;

import org.junit.Test;
import org.testcontainers.jdbc.ContainerDatabaseDriver;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

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

public class MySQLDatabaseContainerDriverTest {

    @Test
    public void shouldRespectBothUrlPropertiesAndParameterProperties() throws SQLException {
        ContainerDatabaseDriver driver = new ContainerDatabaseDriver();
        String url = "jdbc:tc:mysql:5.7.22://hostname/databasename?padCharsWithSpace=true";
        Properties properties = new Properties();
        properties.setProperty("maxRows", "1");

        try (Connection connection = driver.connect(url, properties)) {
            try (Statement statement = connection.createStatement()) {
                statement.execute("CREATE TABLE arbitrary_table (length_5_string CHAR(5))");
                statement.execute("INSERT INTO arbitrary_table VALUES ('abc')");
                statement.execute("INSERT INTO arbitrary_table VALUES ('123')");

                // Check that maxRows is set
                try (ResultSet resultSet = statement.executeQuery("SELECT * FROM arbitrary_table")) {
                    resultSet.next();
                    assertThat(resultSet.isFirst()).isTrue();
                    assertThat(resultSet.isLast()).isTrue();
                }

                // Check that pad with chars is set
                try (ResultSet resultSet = statement.executeQuery("SELECT * FROM arbitrary_table")) {
                    assertThat(resultSet.next()).isTrue();
                    assertThat(resultSet.getString(1)).isEqualTo("abc  ");
                }
            }
        }
    }
}


text:
//////////////////////////////////////////////////////////////////////////////
//
// License Agreement:
//
// The following are Copyright � 2008, Daniel �nnerby
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//    * Redistributions of source code must retain the above copyright notice,
//      this list of conditions and the following disclaimer.
//
//    * Redistributions in binary form must reproduce the above copyright
//      notice, this list of conditions and the following disclaimer in the
//      documentation and/or other materials provided with the distribution.
//
//    * Neither the name of the author nor the names of other contributors may
//      be used to endorse or promote products derived from this software
//      without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////////

#include "pch.hpp"
#include <core/PluginFactory.h>
#include <core/config_filesystem.h>
#include <core/Common.h>

using namespace musik::core;

PluginFactory PluginFactory::sInstance;

PluginFactory::PluginFactory(void){
    this->LoadPlugins();
#ifdef _DEBUG
    std::cerr << "Loading DLLs" << std::endl;
#endif
}

PluginFactory::~PluginFactory(void){
    for (size_t i=0; i<this->loadedPlugins.size(); ++i)
    {
        this->loadedPlugins[i]->Destroy();
    }
    //this->loadedPlugins.clear();		//This causes a segmentation fault on linux due to loadedPlugins being already empty. Jooles
    //Also somewhere here is another seg fault that only seems to occur when the program is run from within its directory
    //eg. cd'ing to musikCube/bin and running square then quitting segfaults here. cd'ing to musikCube and running
    // bin/square then quitting works fine.. Any ideas anyone? Jooles
#ifdef _DEBUG
    std::cerr << "Unloading DLLs" << std::endl;
#endif
    // Unload dlls
    for(std::vector<void*>::iterator oDLL=this->loadedDLLs.begin();oDLL!=this->loadedDLLs.end();){
        #ifdef WIN32
//            FreeLibrary( (HMODULE)(*oDLL) );
	#else
	      dlclose(*oDLL);
        #endif
        oDLL    = this->loadedDLLs.erase(oDLL);
    }
}

void PluginFactory::LoadPlugins(){
    boost::mutex::scoped_lock lock(this->mutex);
    utfstring sPluginDir(GetPluginDirectory());

    // Open plugin directory
    boost::filesystem::utfpath oDir(sPluginDir);

    try{
        boost::filesystem::utfdirectory_iterator oEndFile;
        for(boost::filesystem::utfdirectory_iterator oFile(oDir);oFile!=oEndFile;++oFile){
            if(boost::filesystem::is_regular(oFile->status())){
                // This is a file
                utfstring sFile(oFile->path().string());

                #ifdef WIN32
                    if(sFile.substr(sFile.size()-4)==UTF(".dll")){    // And a DLL

                        HMODULE oDLL = LoadLibrary(sFile.c_str());
                        if(oDLL!=NULL){
                            CallGetPlugin getPluginCall = (CallGetPlugin)GetProcAddress(oDLL,"GetPlugin");
                            if(getPluginCall){
                                this->loadedPlugins.push_back(getPluginCall());
                                this->loadedDLLs.push_back(oDLL);
                            }else{
                                FreeLibrary( oDLL );
                            }
/*
                            // Check for tagreader
                            CallGetTagReader getTagReader = (CallGetTagReader)GetProcAddress(oDLL,"GetTagReader");
                            if(getTagReader){
                                this->aTagReaders.push_back(getTagReader());
                            }*/
                        }

                    }
		#else	//GNU or other
                    if(sFile.substr(sFile.size()-3)==UTF(".so")){    // And a shared lib
		        void* oDLL = dlopen(sFile.c_str(), RTLD_NOW);
			char* err;
			if ((err = dlerror()) != NULL) {
			    std::cerr << "Couldn't open shared library " << sFile << std::endl;
			    std::cerr << "Error: " << err << std::endl;
			}
			else	{
				IPlugin* getPluginCall = (IPlugin*)dlsym(oDLL,"GetPlugin");
                if(getPluginCall){
                	this->loadedPlugins.push_back(getPluginCall);
			        this->loadedDLLs.push_back(oDLL);
#ifdef _DEBUG
			        std::cout << "Shared library " << sFile.c_str() << " loaded and opened." << std::endl;
#endif
			    }
			    else	{
			        dlclose(oDLL);
			    }
			}
		    }
                #endif //WIN32
            }
        }
    }
    catch(...){
    }
}


text:
import puttext from 'puttext';
import en from './en.po.json';

const ru = {};
const messages = {en, ru};

let currentLang;

export function setLang(lang) {
  if (lang in messages) {
    currentLang = lang;
  } else {
    currentLang = 'ru';
  }
}
export function getLang() {
  return currentLang;
}

export default function() {
  return puttext(messages[currentLang]);
}


text:
export const SET_ITEM = 'SET_ITEM'
export const FETCHING = 'FETCHING'
export const FETCH_FAIL = 'FETCH_FAIL'

import CONSTANT from '../util/constant.js'

export function confirmAction(dispatch, id){
    return new Promise((done, notDone)=>{
        dispatch({
            type: FETCHING
        })
        fetch(CONSTANT.confirmCGI+'?itemId='+id,{
            credentials: 'include',
            headers: {
                'kookie': document.cookie
            }
        })
        .then(response=>response.json())
        .then(json=>{
          done({
            type: SET_ITEM,
            payload: json
          })
        })
        .catch(err=>{
            dispatch({
                type: FETCH_FAIL
            })
        })
    })
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Annls mycol. 4(6): 491 (1906)

#### Original name
Didymosphaeria perexigua Sacc.

### Remarks
null


text:
module MotionStylez
  VERSION = "0.1.2"
end


text:
<?php

namespace Base\Table;

use Zend\Db\TableGateway\TableGateway;

class OptionTable extends TableGateway
{

    const NAME = 'bs_options';

}


text:
package org.encog.ml.genetic.sort;

import junit.framework.Assert;

import org.encog.Encog;
import org.encog.ml.ea.genome.BasicGenome;
import org.encog.ml.ea.sort.MaximizeAdjustedScoreComp;
import org.encog.ml.genetic.genome.IntegerArrayGenome;
import org.junit.Test;

public class TestMaximizeAdjustedScoreComp {

    @Test
    public void testCompare() {

        BasicGenome genome1 = new IntegerArrayGenome(1);
        genome1.setAdjustedScore(10);
        genome1.setScore(4);

        BasicGenome genome2 = new IntegerArrayGenome(1);
        genome2.setAdjustedScore(4);
        genome2.setScore(10);

        MaximizeAdjustedScoreComp comp = new MaximizeAdjustedScoreComp();

        Assert.assertTrue(comp.compare(genome1, genome2) < 0);
    }

    @Test
    public void testIsBetterThan() {
        MaximizeAdjustedScoreComp comp = new MaximizeAdjustedScoreComp();
        Assert.assertFalse(comp.isBetterThan(10, 20));
    }

    @Test
    public void testShouldMinimize() {
        MaximizeAdjustedScoreComp comp = new MaximizeAdjustedScoreComp();
        Assert.assertFalse(comp.shouldMinimize());
    }

    @Test
    public void testApplyBonus() {
        MaximizeAdjustedScoreComp comp = new MaximizeAdjustedScoreComp();
        Assert.assertEquals(11, comp.applyBonus(10, 0.1),
                            Encog.DEFAULT_DOUBLE_EQUAL);
    }

    @Test
    public void testApplyPenalty() {
        MaximizeAdjustedScoreComp comp = new MaximizeAdjustedScoreComp();
        Assert.assertEquals(9, comp.applyPenalty(10, 0.1),
                            Encog.DEFAULT_DOUBLE_EQUAL);
    }
}


text:
var serverUrl = params.url.replace(/[\/]+$/, '') + '/';
var MD5_REGEX = /\b[a-fA-F\d]{32}\b/m;
var SHA256_REGEX = /\b[a-fA-F\d]{64}\b/m;

var getAccessToken = function(clientID, secret) {
    var res = http(serverUrl + 'atpapi/oauth2/tokens', {
        Method: 'POST',
        Headers: {
            Accept: ['application/json'],
            'Content-Type': ['application/x-www-form-urlencoded']
        },
        Username: clientID,
        Password: secret,
        Body: 'grant_type=client_credentials&scope=customer'
    }, params.insecure, params.proxy);
    if (res.StatusCode < 200 || res.StatusCode > 299) {
        throw 'Failed to retrieve access token. Request status code: ' + res.StatusCode + ', body: ' + res.Body + ' - ' + JSON.stringify(res);
    }
    try {
        var body = JSON.parse(res.Body);
        return body.access_token;
    } catch (ex) {
        throw 'Error parsing access token body - ' + res.Body + ' - ' + ex;
    }
};

var token = getAccessToken(params.client.identifier, params.client.password);

var doReq = function(method, path, parameters) {
    if (!parameters) {
        parameters = {};
    }
    var result = http(
        serverUrl + 'atpapi/v1/' + path + (method === 'GET' ? encodeToURLQuery(parameters) : ''),
        {
            Headers: {'Content-Type': ['application/json'], 'Accept': ['application/json'], 'Authorization': ['Bearer ' + token]},
            Method: method,
            Body: method == 'POST' ? JSON.stringify(parameters) : ''
        },
        params.insecure,
        params.proxy
    );

    if (result.StatusCode < 200 || result.StatusCode > 299) {
        throw 'Failed to perform request ' + path + ', request status code: ' + result.StatusCode + ', body: ' + result.Body;
    }
    if (result.Body === '') {
        throw 'No content received from path ' + path;
    }
    var obj;
    try {
        obj = JSON.parse(result.Body);
    } catch (ex) {
        throw 'Error parsing reply - ' + result.Body + ' - ' + ex;
    }
    return {body: result.Body, obj: obj, statusCode: result.StatusCode};
};

var getAppliances = function() {
    var res = doReq('GET', 'appliances');
    return {Type: entryTypes.note, Contents: res.body, ContentsFormat: formats.json,
        HumanReadable: tableToMarkdown('Symantec ATP Appliances', res.obj.appliance_list, ['appliance_id', 'appliance_name', 'software_version',
            'appliance_time', 'role']),
        EntryContext: {ATPAppliance: res.obj.appliance_list}
    };
};

var doCommand = function(action, targets) {
    if (action === 'delete_endpoint_file') {
        targets = targets.map(function(t) {
            if (typeof t === 'string') {
                var parts = t.split(':');
                if (parts.length !== 2) {
                    throw 'Targets format needs to be hash:endpoint_uid, hash:device_uid';
                }
                return {hash: parts[0].trim(), device_uid: parts[1].trim()};
            } else {
                return t;
            }
        });
    }
    var res = doReq('POST', 'commands', {action: action, targets: targets});
    return {Type: entryTypes.note, Contents: res.body, ContentsFormat: formats.json,
        HumanReadable: '## Symantec ATP Command\nID: ' + res.obj.command_id,
        EntryContext: {'ATPCommand(val.ID == obj.ID)': {ID: res.obj.command_id, Action: action}}
    };
};

var getCommandState = function(command) {
    var res = doReq('GET', 'commands/' + command);
    var md = '## Symantec ATP Command State\n';
    md += 'Command ID: ' + command + '\n';
    md += 'Action: ' + res.obj.action + '\n\n';
    md += tableToMarkdown('State for target', res.obj.status, ['target', 'state', 'error_code', 'message']);
    return {Type: entryTypes.note, Contents: res.body, ContentsFormat: formats.json, HumanReadable: md,
        EntryContext: {'ATPCommand(val.ID == obj.ID)': {ID: res.obj.command_id, Action: res.obj.action, Status: res.obj.status}}
    };
};

var doCommandCancel = function(command) {
    var res = doReq('PATCH', 'commands/' + command, [{op: 'replace', path: '/state', value: 3}]);
    return {Type: entryTypes.note, Contents: res.body, ContentsFormat: formats.json,
        HumanReadable: tableToMarkdown('Symantec ATP Command Cancel', res.obj),
        EntryContext: {'ATPCommand(val.ID == obj.ID)': {ID: res.obj.command_id, ErrorCode: res.obj.error_code, Message: res.obj.message}}
    };
};

var add = function(p, name, val) {
    if (val) {
        p[name] = val;
    }
};

var addTime = function(p, name, val) {
    if (val) {
        // This is string time
        if (val.indexOf('-') > 0) {
            p[name] = val;
        } else { // this is milliseonds
            p[name] = new Date(val).toISOString();
        }
    }
};

var getEvents = function(query, startTime, endTime, limit, next) {
    var p = {verb: 'query'};
    add(p, 'where', query);
    add(p, 'next', next);
    addTime(p, 'start_time', startTime);
    addTime(p, 'end_time', endTime);
    if (limit) {
        p.limit = parseInt(limit);
    }
    var res = doReq('POST', 'events', p);
    if (!res.obj.result || res.obj.result.length === 0) {
        return 'No events match your criteria';
    }
    return {Type: entryTypes.note, Contents: res.body, ContentsFormat: formats.json,
        HumanReadable: tableToMarkdown('Symantec ATP Events', res.obj.result) + '\nTotal: ' + res.obj.total + (res.obj.next ? '\nNext: ' + res.obj.next : ''),
        EntryContext: {'ATPEvents(true)': {Result: res.obj.result, Total: res.obj.total, Next: res.obj.next}}
    };
};

var getIncidentEvents = function(query, startTime, endTime, limit, next) {
    var p = {verb: 'query'};
    add(p, 'where', query);
    add(p, 'next', next);
    addTime(p, 'start_time', startTime);
    addTime(p, 'end_time', endTime);
    if (limit) {
        p.limit = parseInt(limit);
    }
    var res = doReq('POST', 'incidentevents', p);
    if (!res.obj.result || res.obj.result.length === 0) {
        return 'No events match your criteria';
    }
    return {Type: entryTypes.note, Contents: res.body, ContentsFormat: formats.json,
        HumanReadable: tableToMarkdown('Symantec ATP Incident Events', res.obj.result) + '\nTotal: ' + res.obj.total + (res.obj.next ? '\nNext: ' + res.obj.next : ''),
        EntryContext: {'ATPIncidentEvents(true)': {Result: res.obj.result, Total: res.obj.total, Next: res.obj.next}}
    };
};

var getIncidents = function(query, startTime, endTime, limit, next) {
    var p = {verb: 'query'};
    add(p, 'where', query);
    add(p, 'next', next);
    addTime(p, 'start_time', startTime);
    addTime(p, 'end_time', endTime);
    if (limit) {
        p.limit = parseInt(limit);
    }
    var res = doReq('POST', 'incidents', p);
    if (!res.obj.result || res.obj.result.length === 0) {
        return 'No events match your criteria';
    }
    return {Type: entryTypes.note, Contents: res.body, ContentsFormat: formats.json,
        HumanReadable: tableToMarkdown('Symantec ATP Incidents', res.obj.result) + '\nTotal: ' + res.obj.total + (res.obj.next ? '\nNext: ' + res.obj.next : ''),
        EntryContext: {'ATPIncidents(true)': {Result: res.obj.result, Total: res.obj.total, Next: res.obj.next}}
    };
};

var getFiles = function(hash) {

    if (!MD5_REGEX.test(hash) && !SHA256_REGEX.test(hash)){
        throw 'Invalid hash. Only SHA256 and MD5 are supported.';
    }

    var p = {};
    if (hash.length === 32) { // MD5 hash
        p.hash_type = 'md5';
    }
    var res = doReq('GET', 'files/' + hash, p);

    // If ATP has not seen the file hash before, then the API will return a blank response with HTTP 200 code.
    if(res.body === '{}'){
        return 'ATP has not seen the file ' + hash + ' before';

    }

    return {Type: entryTypes.note, Contents: res.body, ContentsFormat: formats.json,
        HumanReadable: tableToMarkdown('Symantec ATP Files', res.obj.file_list) + '\nTotal: ' + res.obj.total,
        EntryContext: {'File(val.MD5 == obj.MD5 || val.SHA256 == obj.SHA256)': res.obj.file_list.map(function(f) {
            var file = {MD5: f.md5, SHA256: f.sha2, Instances: f.file_instances, Type: f.mime_type, Size: f.size, SignatureCompany: f.signature_company_name,
                SignatureIssuer: f.signature_issuer, Age: f.file_age, Threat: f.threat_name, Cynic: f.cynic_verdict, TargetedAttack: f.targeted_attack,
                ReputationBand: f.reputation_band, PrevalenceBand: f.prevalence_band, Health: f.file_health};
            if (f.file_health === 3) {
                file.properties_to_append = ['Malicious'];
                file.Malicious = {Vendor: 'Symantec', Description: 'File health: ' + f.file_health};
            }
            return file;
        })}
    };

};

var parseOffsetDate = function(offset_str) {
    var range_split = offset_str.trim().split(' ');
    if (range_split.length != 2){
        throw 'date_range must be "number date_range_unit", examples: (2 hours, 4 minutes,6 months, 1 day, etc.)';
    }
    var number = parseInt(range_split[0]);
    var unit = range_split[1].toLowerCase();
    var d = new Date();
    if (unit.indexOf('minute') >= 0) {
        d.setTime(d.getTime() - (number * 60 * 1000));
    } else if (unit.indexOf('hour') >= 0) {
        d.setTime(d.getTime() - (number * 60 * 60 * 1000));
    } else if (unit.indexOf('day') >= 0) {
        d.setTime(d.getTime() - (number * 24 * 60 * 60 * 1000));
    } else if (unit.indexOf('month') >= 0) {
        d.setTime(d.getTime() - (number * 30 * 24 * 60 * 60 * 1000));
    } else if (unit.indexOf('year') >= 0) {
        d.setTime(d.getTime() - (number * 365 * 24 * 60 * 60 * 1000));
    } else {
        throw 'The unit of date_range is invalid. Must be minutes, hours, days, months or years.';
    }
    return d;
};

var getIncidentsFromIncidentsResult = function(res, lastRun) {
    var max_timestamp = lastRun;
    incidents = res.map(function(r){
        max_timestamp = Date.parse(r.time) > Date.parse(max_timestamp) ? r.time : max_timestamp;
        return {
            name: r.summary,
            occurred: r.time,
            rawJSON: JSON.stringify(r)
        };
    });
    // Adding a millisecond to the timestamp to avoid conflicts when fetching.
    max_timestamp = new Date(Date.parse(max_timestamp) + 1).toISOString()
    return [max_timestamp, incidents]
};

var getIncidentsFromEventsResult = function(res, lastRun) {
    var max_timestamp = lastRun;
    incidents = res.map(function(r){
        max_timestamp = Date.parse(r.device_time) > Date.parse(max_timestamp) ? r.device_time : max_timestamp;
        var name;
        if ('message' in r){
            name = r.message;
        } else if ('uuid' in r){
            name = r.uuid;
        } else {
            name = r.type_id;
        }
        return {
            name: name,
            occurred: r.device_time,
            rawJSON: JSON.stringify(r)
        };
    });
    // Adding a millisecond to the timestamp to avoid conflicts when fetching.
    max_timestamp = new Date(Date.parse(max_timestamp) + 1).toISOString()
    return [max_timestamp, incidents]

};

var fetchIncidents = function(type, query, limit, first_fetch_time) {

    if (type != 'incidents' && type != 'incidentevents' && type != 'events'){
        throw 'Unknown incident type.';
    }
    var DAY_IN_MILLIS = 24*60*60*1000;

    var lastRun = getLastRun();
    var now = new Date();
    var endTime = now.toISOString();
    var startTime, currentFetch;
    var next = null;

    if (lastRun && lastRun.time && lastRun.time !== '') {
        startTime = lastRun.time;
        if (lastRun.next && lastRun.next !== '') {
            next = lastRun.next;

            if (lastRun.end_time && lastRun.end_time !== '') {
                endTime = lastRun.end_time;
            }
        }
    } else if (first_fetch_time) {
        startTime = parseOffsetDate(first_fetch_time).toISOString();
    } else {
        var n = now;
        n.setTime(now.getTime() - 1 * DAY_IN_MILLIS);
        startTime = n.toISOString();
    }
    var p = {verb: 'query'};
    add(p, 'where', query);
    addTime(p, 'start_time', startTime);
    addTime(p, 'end_time', endTime);
    add(p, 'next', next);

    if (limit) {
        p.limit = parseInt(limit);
    }
    var incidents = [];
    var res = doReq('POST', type, p);
    if (res.obj.result && res.obj.result.length !== 0) {
        if (type == 'incidents') {
            var result = getIncidentsFromIncidentsResult(res.obj.result, startTime);
            currentFetch = result[0];
            incidents = incidents.concat(result[1]);
        } else {
            var result = getIncidentsFromEventsResult(res.obj.result, startTime);
            currentFetch = result[0];
            incidents = incidents.concat(result[1]);
        }
    }
    next = 'next' in res.obj ? res.obj.next : null;

    if (next) {
        setLastRun({ time: startTime, next: next, end_time: endTime });
    } else {
        setLastRun({ time: currentFetch ? currentFetch : startTime});
    }
    return JSON.stringify(incidents);
};

// The command input arg holds the command sent from the user.
switch (command) {
    // This is the call made when pressing the integration test button.
    case 'test-module':
        getAppliances();
        return 'ok';
    case 'fetch-incidents':
        return fetchIncidents(params.fetch_incidents_type, params.fetch_incidents_query, params.max_fetch, params.first_fetch);
    case 'satp-appliances':
        return getAppliances();
    case 'satp-command':
        return doCommand(args.action, argToList(args.targets));
    case 'satp-command-state':
        return getCommandState(args.command);
    case 'satp-command-cancel':
        return doCommandCancel(args.command);
    case 'satp-events':
        return getEvents(args.query, args.start_time, args.end_time, args.limit, args.next);
    case 'satp-files':
        return getFiles(args.hash);
    case 'satp-incident-events':
        return getIncidentEvents(args.query, args.start_time, args.end_time, args.limit, args.next);
    case 'satp-incidents':
        return getIncidents(args.query, args.start_time, args.end_time, args.limit, args.next);
    default:
        // Should never come here
        throw 'Unknown command: ' + command;
}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest
    package="com.ToxicBakery.app.tabsontallahassee"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:allowBackup="true"
        android:fullBackupContent="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        tools:ignore="GoogleAppIndexingWarning">

        <activity
            android:name=".ActivityMain"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar"/>

        <activity
            android:name=".ActivityPerson"
            android:theme="@style/AppTheme.NoActionBar.DefaultStatusBar"/>

        <activity
            android:name=".ActivityBill"
            android:theme="@style/AppTheme.NoActionBar.DefaultStatusBar"/>

        <activity-alias
            android:name=".LauncherMain"
            android:targetActivity=".ActivityMain">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>

                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity-alias>

    </application>

</manifest>


text:
made css3 transform super easy

## Home

[http://alloyteam.github.io/PhyTouch/transformjs/](http://alloyteam.github.io/PhyTouch/transformjs/)

## Install

You can install it via npm:

```html
npm install css3transform-react
```

## Demo

- [https://alloyteam.github.io/PhyTouch/transformjs/react/example/](https://alloyteam.github.io/PhyTouch/transformjs/react/example/)
- [http://alloyteam.github.io/PhyTouch/transformjs/example/stars.html](http://alloyteam.github.io/PhyTouch/transformjs/example/stars.html)

## Usage

```js
//set "translateX", "translateY", "translateZ", "scaleX", "scaleY", "scaleZ", "rotateX", "rotateY", "rotateZ", "skewX", "skewY", "originX", "originY", "originZ"
render() {
    return (
        <Transform
          translateX={100}
          scaleX={0.5}
          originX={0.5}>
          <div>sth</div>
        </Transform>
    );
}

// you can also use other porps, such as "className" or "style"
render() {
    return (
        <Transform
          translateX={100}
          className="ani"
          style={{width: '100px', background: 'red'}}
          <div>sth</div>
        </Transform>
    );
}
```

# License
This content is released under the [MIT](http://opensource.org/licenses/MIT) License.


text:
using System.Threading;
using MediatR;

namespace TestApp;

using System.IO;
using System.Threading.Tasks;

public class PingedHandler : INotificationHandler<Pinged>
{
    private readonly TextWriter _writer;

    public PingedHandler(TextWriter writer)
    {
        _writer = writer;
    }

    public Task Handle(Pinged notification, CancellationToken cancellationToken)
    {
        return _writer.WriteLineAsync("Got pinged async.");
    }
}

public class PongedHandler : INotificationHandler<Ponged>
{
    private readonly TextWriter _writer;

    public PongedHandler(TextWriter writer)
    {
        _writer = writer;
    }

    public Task Handle(Ponged notification, CancellationToken cancellationToken)
    {
        return _writer.WriteLineAsync("Got ponged async.");
    }
}

//public class ConstrainedPingedHandler<TNotification> : INotificationHandler<TNotification>
//    where TNotification : Pinged
//{
//    private readonly TextWriter _writer;

//    public ConstrainedPingedHandler(TextWriter writer)
//    {
//        _writer = writer;
//    }

//    public Task Handle(TNotification notification, CancellationToken cancellationToken)
//    {
//        return _writer.WriteLineAsync("Got pinged constrained async.");
//    }
//}

public class PingedAlsoHandler : INotificationHandler<Pinged>
{
    private readonly TextWriter _writer;

    public PingedAlsoHandler(TextWriter writer)
    {
        _writer = writer;
    }

    public Task Handle(Pinged notification, CancellationToken cancellationToken)
    {
        return _writer.WriteLineAsync("Got pinged also async.");
    }
}


text:
import json, itertools

from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect

from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required

from instaapp.forms import LoginForm, PhotoForm, MemberPhotoForm
from instaapp.models import Follow, Photo, Member, Comment, Like

from annoying.functions import get_object_or_None

# Create your views here.

def index(request):
    if request.user.is_authenticated():
        return HttpResponseRedirect('/insta/feed')
    return render(request, 'instaapp/index.html', {})

@login_required
def feed(request):
    """
    View that displays the uploaded photos of users that the
    `logged user` follows
    """
    user = request.user
    photos = []
    liked_photos = []
    user_following = Follow.objects.filter(follower__id=user.id)

    for user_object in user_following:
        following_photos = Photo.objects.filter(owner__id=user_object.following.id)

        if following_photos is not None:
            photos.append(following_photos)

    # flatten list of photos
    chain = itertools.chain(*photos)
    photos = list(chain)
    for photo in photos:
        photo_like = get_object_or_None(Like,
            owner=user.member,
            photo=photo
            )
        if photo_like:
            liked_photos.append(photo.pk)

    return render(request, 'instaapp/feed.html', {
        'photos': photos,
        'liked_photos': liked_photos
        })

def user_login(request):
    form = LoginForm()

    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(username=username, password=password)
        if user is not None:
            login(request, user)
            return HttpResponseRedirect('/insta')
        else:
            return HttpResponse('Invalid Login')
    else:
        form = LoginForm()

    return render(request, 'instaapp/login.html', {'form': form})

def user_logout(request):
    logout(request)
    return HttpResponseRedirect('/insta/login')

@login_required
def upload_photo(request):
    """
    Method that lets user upload an image
    """
    uploader = request.user
    form = PhotoForm()

    if request.method == 'POST':
        form = PhotoForm(request.POST, request.FILES)
        if form.is_valid():
            obj = form.save(commit=False)
            obj.owner = uploader
            obj.save()

            return HttpResponseRedirect('/insta/upload')
    else:
        form = PhotoForm()

    return render(request, 'instaapp/upload_photo.html', {'form': form})

@login_required
def user_profile(request, username=None):
    """
    View to display the `logged user's` profile and uploaded photos
    """

    upload_prof_pic_form = MemberPhotoForm()

    if username is None:
        user = request.user

    else:
        user = User.objects.get(username=username)

    dp_obj = get_object_or_None(Member, user__pk=user.id)
    if dp_obj is None:
        user_dp = False
    else:
        user_dp = dp_obj

    user_photos = Photo.objects.filter(owner__pk=user.id)
    photos_count = user_photos.count()
    return render(request, 'instaapp/profile.html', {
        'user': user,
        'user_dp': user_dp,
        'photos': user_photos,
        'count': photos_count,
        'dp_form': upload_prof_pic_form
        })

def users(request):
    """
    View to display a list of all users registered to the app
    """
    userlist = []
    users = User.objects.all()[:10]

    for user in users:
        queryset = Follow.objects.filter(
                            follower__pk=request.user.id,
                            following__pk=user.pk,
                            active=True
                            )
        follow_status = get_object_or_None(queryset)

        if follow_status is None:
            userlist.append(user)

    return render(request, 'instaapp/users.html', {'users': userlist})

@login_required
def user_following(request):
    """
    View to display a list of users that the `logged user` is following
    """
    user = request.user

    following = Follow.objects.filter(follower__pk=user.id, active=True)

    return render(request, 'instaapp/user_following.html', {
        'following': following
        })

@login_required
def user_followers(request):
    """
    View to display a list of users who follow the `logged user`
    """
    followers = Follow.objects.filter(following__pk=request.user.id)

    # Check if you follow the users who follow you
    for user in followers:
        queryset = Follow.objects.filter(
            follower__id=request.user.id,
            following__id=user.follower.id
            )
        user.is_followed = get_object_or_None(queryset)

    return render(request, 'instaapp/user_followers.html', {
        'followers': followers,
        })

def search(request):
    query = request.GET.get('q', '')

    followlist = []
    results = User.objects.filter(username__contains=query)

    # Check follow status on a result
    if request.user.is_authenticated():
        for user in results:
            queryset = Follow.objects.filter(
                                follower__pk=request.user.id,
                                following__pk=user.pk,
                                active=True
                                )
            follow_status = get_object_or_None(queryset)

            if follow_status is not None:
                followlist.append(user.id)

    return render(request, 'instaapp/search.html', {
        'results': results,
        'followlist': followlist
        })


text:
declare module 'react-dev-utils/InterpolateHtmlPlugin' {
  const InterpolateHtmlPlugin: any;
  export = InterpolateHtmlPlugin;
}

declare module 'react-dev-utils/WatchMissingNodeModulesPlugin' {
  const WatchMissingNodeModulesPlugin: any;
  export = WatchMissingNodeModulesPlugin;
}


text:
<?php

/**
 * BuddyPress - Members Directory
 *
 * @package BuddyPress
 * @subpackage bp-default
 */

?>

<?php get_header( 'buddypress' ); ?>

	<?php do_action( 'bp_before_directory_members_page' ); ?>

	<div id="content" class="content<?php echo get_option('fungames_sidebar_position'); ?>">

		<?php do_action( 'bp_before_directory_members' ); ?>
		<form action="" method="post" id="members-directory-form" class="dir-form">

<?php _e( 'Members Directory', 'buddypress' ); ?>

			<?php do_action( 'bp_before_directory_members_content' ); ?>

				<?php bp_directory_members_search_form(); ?>

<a href="<?php echo trailingslashit( bp_get_root_domain() . '/' . bp_get_members_root_slug() ); ?>"><?php printf( __( 'All Members %s', 'buddypress' ), bp_get_total_member_count() ); ?>

					<?php if ( is_user_logged_in() && bp_is_active( 'friends' ) && bp_get_total_friend_count( bp_loggedin_user_id() ) ) : ?>

<a href="<?php echo bp_loggedin_user_domain() . bp_get_friends_slug() . '/my-friends/' ?>"><?php printf( __( 'My Friends %s', 'buddypress' ), bp_get_total_friend_count( bp_loggedin_user_id() ) ); ?>

					<?php endif; ?>

					<?php do_action( 'bp_members_directory_member_types' ); ?>

					<?php do_action( 'bp_members_directory_member_sub_types' ); ?>

						<?php _e( 'Order By:', 'buddypress' ); ?>
						<select id="members-order-by">
							<option value="active"><?php _e( 'Last Active', 'buddypress' ); ?></option>
							<option value="newest"><?php _e( 'Newest Registered', 'buddypress' ); ?></option>

							<?php if ( bp_is_active( 'xprofile' ) ) : ?>

								<option value="alphabetical"><?php _e( 'Alphabetical', 'buddypress' ); ?></option>

							<?php endif; ?>

							<?php do_action( 'bp_members_directory_order_options' ); ?>

						</select>

				<?php locate_template( array( 'members/members-loop.php' ), true ); ?>

			<?php do_action( 'bp_directory_members_content' ); ?>

			<?php wp_nonce_field( 'directory_members', '_wpnonce-member-filter' ); ?>

			<?php do_action( 'bp_after_directory_members_content' ); ?>

		</form>

		<?php do_action( 'bp_after_directory_members' ); ?>

	<?php do_action( 'bp_after_directory_members_page' ); ?>

<?php get_sidebar( 'buddypress' ); ?>
<?php get_footer( 'buddypress' ); ?>


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:weightSum="1" >

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:paddingTop="10dp" >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:text="@string/para_about_us1"
            android:textSize="20sp" />
    </LinearLayout>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:text="@string/para_about_us2"
        android:textSize="15sp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:text="@string/para_about_us3"
        android:textSize="15sp" />

</LinearLayout>


text:
module PacketGen
  module Header
    class DHCPv6
      # Container class for DHCPv6 {Option options}.
      #
      # == Add DHCPv6 options to an +Options+ instance
      #   options = PacketGen::Header::DHCP::Options.new
      #   # Add an ElapsedTime option
      #   options << { type: 'ElapsedTime', value: 3600 }
      #   # Add a ClientID. Here, use integer type
      #   duid = PacketGen::Header::DHCPv6::DUID_LL.new(link_addr: '08:00:27:fe:8f:95')
      #   options << { type: 1, duid: duid }
      # @author Sylvain Daubert
      class Options < Types::Array
        set_of DHCPv6::Option

        # Separator used in {#to_human}.
        HUMAN_SEPARATOR = ';'

        private

        def real_type(opt)
          real_klass = Option.subclasses[opt.type]
          real_klass.nil? ? Option : real_klass
        end
      end
    end
  end
end


text:
package com.wonderpush.sdk.segmentation.parser;

import org.junit.Assert;
import org.junit.Test;

import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.MatcherAssert.assertThat;

public class GeohashTest {

    @Test
    public void testItShouldReject() {
        try {
            Geohash.parse("u09#");
            Assert.fail();
        } catch (BadInputError ex) {
            assertThat(ex, instanceOf(BadInputError.class));
        }
    }

}


text:
package com.github.robozonky.strategy.natural.conditions;

import java.util.Optional;

public final class SmpFeePresenceCondition extends AbstractBooleanCondition {

    public static final MarketplaceFilterCondition PRESENT = new SmpFeePresenceCondition();
    public static final MarketplaceFilterCondition NOT_PRESENT = PRESENT.negate();

    private SmpFeePresenceCondition() {
        super(w -> w.getSellFee()
            .map(fee -> fee.signum() > 0)
            .orElse(false), true, true);
    }

    @Override
    public Optional<String> getDescription() {
        return Optional.of("Sale fee present.");
    }
}


text:
import {JobController} from "./../controllers/JobController";

export class JobComponent {
    constructor() {
        this.template = require('./../views/job.html');
        this.controller = JobController;
    }
}