text:
' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.

Imports Microsoft.CodeAnalysis.LanguageServices

Namespace Microsoft.CodeAnalysis.VisualBasic.LanguageServices
    Friend Class VisualBasicSyntaxKinds
        Implements ISyntaxKinds

        Public Shared ReadOnly Instance As New VisualBasicSyntaxKinds()

        Protected Sub New()
        End Sub

        Public Function Convert(Of TSyntaxKind As Structure)(kind As Integer) As TSyntaxKind Implements ISyntaxKinds.Convert
            ' Boxing/Unboxing casts from Object to TSyntaxKind will be erased by jit.
            Return CType(CType(CType(kind, SyntaxKind), Object), TSyntaxKind)
        End Function

        Public ReadOnly Property ConflictMarkerTrivia As Integer = SyntaxKind.ConflictMarkerTrivia Implements ISyntaxKinds.ConflictMarkerTrivia
        Public ReadOnly Property DisabledTextTrivia As Integer = SyntaxKind.DisabledTextTrivia Implements ISyntaxKinds.DisabledTextTrivia
        Public ReadOnly Property EndOfLineTrivia As Integer = SyntaxKind.EndOfLineTrivia Implements ISyntaxKinds.EndOfLineTrivia
        Public ReadOnly Property SkippedTokensTrivia As Integer = SyntaxKind.SkippedTokensTrivia Implements ISyntaxKinds.SkippedTokensTrivia
        Public ReadOnly Property WhitespaceTrivia As Integer = SyntaxKind.WhitespaceTrivia Implements ISyntaxKinds.WhitespaceTrivia
        Public ReadOnly Property SingleLineCommentTrivia As Integer = SyntaxKind.CommentTrivia Implements ISyntaxKinds.SingleLineCommentTrivia
        Private ReadOnly Property MultiLineCommentTrivia As Integer? Implements ISyntaxKinds.MultiLineCommentTrivia

        Public ReadOnly Property CloseBraceToken As Integer = SyntaxKind.CloseBraceToken Implements ISyntaxKinds.CloseBraceToken
        Public ReadOnly Property ColonToken As Integer = SyntaxKind.ColonToken Implements ISyntaxKinds.ColonToken
        Public ReadOnly Property CharacterLiteralToken As Integer = SyntaxKind.CharacterLiteralToken Implements ISyntaxKinds.CharacterLiteralToken
        Public ReadOnly Property DotToken As Integer = SyntaxKind.DotToken Implements ISyntaxKinds.DotToken
        Public ReadOnly Property InterpolatedStringTextToken As Integer = SyntaxKind.InterpolatedStringTextToken Implements ISyntaxKinds.InterpolatedStringTextToken
        Public ReadOnly Property QuestionToken As Integer = SyntaxKind.QuestionToken Implements ISyntaxKinds.QuestionToken
        Public ReadOnly Property StringLiteralToken As Integer = SyntaxKind.StringLiteralToken Implements ISyntaxKinds.StringLiteralToken

        Public ReadOnly Property IfKeyword As Integer = SyntaxKind.IfKeyword Implements ISyntaxKinds.IfKeyword

        Public ReadOnly Property GenericName As Integer = SyntaxKind.GenericName Implements ISyntaxKinds.GenericName
        Public ReadOnly Property IdentifierName As Integer = SyntaxKind.IdentifierName Implements ISyntaxKinds.IdentifierName
        Public ReadOnly Property QualifiedName As Integer = SyntaxKind.QualifiedName Implements ISyntaxKinds.QualifiedName

        Public ReadOnly Property TupleType As Integer = SyntaxKind.TupleType Implements ISyntaxKinds.TupleType

        Public ReadOnly Property CharacterLiteralExpression As Integer = SyntaxKind.CharacterLiteralExpression Implements ISyntaxKinds.CharacterLiteralExpression
        Public ReadOnly Property DefaultLiteralExpression As Integer = SyntaxKind.NothingLiteralExpression Implements ISyntaxKinds.DefaultLiteralExpression
        Public ReadOnly Property FalseLiteralExpression As Integer = SyntaxKind.FalseLiteralExpression Implements ISyntaxKinds.FalseLiteralExpression
        Public ReadOnly Property NullLiteralExpression As Integer = SyntaxKind.NothingLiteralExpression Implements ISyntaxKinds.NullLiteralExpression
        Public ReadOnly Property StringLiteralExpression As Integer = SyntaxKind.StringLiteralExpression Implements ISyntaxKinds.StringLiteralExpression
        Public ReadOnly Property TrueLiteralExpression As Integer = SyntaxKind.TrueLiteralExpression Implements ISyntaxKinds.TrueLiteralExpression

        Public ReadOnly Property AnonymousObjectCreationExpression As Integer = SyntaxKind.AnonymousObjectCreationExpression Implements ISyntaxKinds.AnonymousObjectCreationExpression
        Public ReadOnly Property AwaitExpression As Integer = SyntaxKind.AwaitExpression Implements ISyntaxKinds.AwaitExpression
        Public ReadOnly Property BaseExpression As Integer = SyntaxKind.MyBaseExpression Implements ISyntaxKinds.BaseExpression
        Public ReadOnly Property ConditionalAccessExpression As Integer = SyntaxKind.ConditionalAccessExpression Implements ISyntaxKinds.ConditionalAccessExpression
        Public ReadOnly Property ConditionalExpression As Integer = SyntaxKind.TernaryConditionalExpression Implements ISyntaxKinds.ConditionalExpression
        Public ReadOnly Property InvocationExpression As Integer = SyntaxKind.InvocationExpression Implements ISyntaxKinds.InvocationExpression
        Public ReadOnly Property LogicalAndExpression As Integer = SyntaxKind.AndAlsoExpression Implements ISyntaxKinds.LogicalAndExpression
        Public ReadOnly Property LogicalOrExpression As Integer = SyntaxKind.OrElseExpression Implements ISyntaxKinds.LogicalOrExpression
        Public ReadOnly Property LogicalNotExpression As Integer = SyntaxKind.NotExpression Implements ISyntaxKinds.LogicalNotExpression
        Public ReadOnly Property ObjectCreationExpression As Integer = SyntaxKind.ObjectCreationExpression Implements ISyntaxKinds.ObjectCreationExpression
        Public ReadOnly Property ParenthesizedExpression As Integer = SyntaxKind.ParenthesizedExpression Implements ISyntaxKinds.ParenthesizedExpression
        Public ReadOnly Property QueryExpression As Integer = SyntaxKind.QueryExpression Implements ISyntaxKinds.QueryExpression
        Public ReadOnly Property ReferenceEqualsExpression As Integer = SyntaxKind.IsExpression Implements ISyntaxKinds.ReferenceEqualsExpression
        Public ReadOnly Property ReferenceNotEqualsExpression As Integer = SyntaxKind.IsNotExpression Implements ISyntaxKinds.ReferenceNotEqualsExpression
        Public ReadOnly Property SimpleMemberAccessExpression As Integer = SyntaxKind.SimpleMemberAccessExpression Implements ISyntaxKinds.SimpleMemberAccessExpression
        Public ReadOnly Property TernaryConditionalExpression As Integer = SyntaxKind.TernaryConditionalExpression Implements ISyntaxKinds.TernaryConditionalExpression
        Public ReadOnly Property ThisExpression As Integer = SyntaxKind.MeExpression Implements ISyntaxKinds.ThisExpression
        Public ReadOnly Property TupleExpression As Integer = SyntaxKind.TupleExpression Implements ISyntaxKinds.TupleExpression

        Public ReadOnly Property EndOfFileToken As Integer = SyntaxKind.EndOfFileToken Implements ISyntaxKinds.EndOfFileToken
        Public ReadOnly Property AwaitKeyword As Integer = SyntaxKind.AwaitKeyword Implements ISyntaxKinds.AwaitKeyword

        Public ReadOnly Property IdentifierToken As Integer = SyntaxKind.IdentifierToken Implements ISyntaxKinds.IdentifierToken
        Public ReadOnly Property GlobalKeyword As Integer = SyntaxKind.GlobalKeyword Implements ISyntaxKinds.GlobalKeyword
        Public ReadOnly Property IncompleteMember As Integer = SyntaxKind.IncompleteMember Implements ISyntaxKinds.IncompleteMember
        Public ReadOnly Property HashToken As Integer = SyntaxKind.HashToken Implements ISyntaxKinds.HashToken

        Public ReadOnly Property ExpressionStatement As Integer = SyntaxKind.ExpressionStatement Implements ISyntaxKinds.ExpressionStatement
        Public ReadOnly Property ForEachStatement As Integer = SyntaxKind.ForEachStatement Implements ISyntaxKinds.ForEachStatement
        Public ReadOnly Property LocalDeclarationStatement As Integer = SyntaxKind.LocalDeclarationStatement Implements ISyntaxKinds.LocalDeclarationStatement
        Public ReadOnly Property LockStatement As Integer = SyntaxKind.SyncLockStatement Implements ISyntaxKinds.LockStatement
        Public ReadOnly Property ReturnStatement As Integer = SyntaxKind.ReturnStatement Implements ISyntaxKinds.ReturnStatement
        Public ReadOnly Property UsingStatement As Integer = SyntaxKind.UsingStatement Implements ISyntaxKinds.UsingStatement

        Public ReadOnly Property Attribute As Integer = SyntaxKind.Attribute Implements ISyntaxKinds.Attribute
        Public ReadOnly Property Parameter As Integer = SyntaxKind.Parameter Implements ISyntaxKinds.Parameter
        Public ReadOnly Property TypeConstraint As Integer = SyntaxKind.TypeConstraint Implements ISyntaxKinds.TypeConstraint
        Public ReadOnly Property VariableDeclarator As Integer = SyntaxKind.VariableDeclarator Implements ISyntaxKinds.VariableDeclarator
        Public ReadOnly Property FieldDeclaration As Integer = SyntaxKind.FieldDeclaration Implements ISyntaxKinds.FieldDeclaration
        Public ReadOnly Property ParameterList As Integer = SyntaxKind.ParameterList Implements ISyntaxKinds.ParameterList
        Public ReadOnly Property TypeArgumentList As Integer = SyntaxKind.TypeArgumentList Implements ISyntaxKinds.TypeArgumentList
        Public ReadOnly Property GlobalStatement As Integer? Implements ISyntaxKinds.GlobalStatement

        Public ReadOnly Property EqualsValueClause As Integer = SyntaxKind.EqualsValue Implements ISyntaxKinds.EqualsValueClause

        Public ReadOnly Property Interpolation As Integer = SyntaxKind.Interpolation Implements ISyntaxKinds.Interpolation
        Public ReadOnly Property InterpolatedStringExpression As Integer = SyntaxKind.InterpolatedStringExpression Implements ISyntaxKinds.InterpolatedStringExpression
        Public ReadOnly Property InterpolatedStringText As Integer = SyntaxKind.InterpolatedStringText Implements ISyntaxKinds.InterpolatedStringText
    End Class
End Namespace


text:
404

Page not found

        Go Back to Home Page

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

    {% load staticfiles %}
    <meta charset="UTF-8">
    <title>Neighbors</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"
          crossorigin="anonymous">
    <link rel="stylesheet" type="text/css" href="{% static 'neighborhood/css/map_home.css' %}"/>
    <link rel="stylesheet" type="text/css" href="{% static 'budget/style.css' %}"/>

Neighbors

        map
        status

New Expense

        <form id="expense_form" action="{% url 'budget:new_expense' %}" method="post"
                enctype="multipart/form-data">
            {% csrf_token %}
            {{ expense_form.as_p }}
            <input class='btn btn-default' type="submit" name="submit" value="Create Expense"/>
        </form>
        Return


text:
package javax.jms;

import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

@Retention(RUNTIME)
@Target(TYPE)
public @interface JMSConnectionFactoryDefinition {
    String name();

    String className() default "";

    String resourceAdapter() default "";

    String user() default "";

    String password() default "";

    String clientId() default "";

    String[] properties() default {};

    boolean transactional() default true;

    int maxPoolSize() default -1;

    int minPoolSize() default -1;

    String description() default "";

    String interfaceName() default "";
}


text:
<html>
<head>
<title>Original Title</title>
<script>
function debugOutput(str) {
    text = document.createTextNode(str);
    console = document.getElementById('console');
    div = document.createElement('div');
    div.appendChild(text);
    console.appendChild(div);
}

function runTests() {
    if (window.testRunner) {
        testRunner.dumpAsText();
        testRunner.dumpTitleChanges();
    }

    titleElem = document.getElementsByTagName('title').item(0);
    debugOutput('Original title is: \'' + titleElem.text + '\'');

    newTitle = 'This is the new title';
    debugOutput('Setting new title to: \'' + newTitle + '\'');
    titleElem.text = newTitle;

    debugOutput('New title is: \'' + titleElem.text + '\'');
}

function test() {
    t = document.getElementsByTagName('title').item(0);
    alert(t.text);
    t.text = 'new title';
    alert(t.text);
}
</script>
</head>
<body onload='runTests();'>
<div id='console'>
</div>
</body>
</html>


text:
using Xunit;

namespace System.IO.Tests
{
    public class DirectoryInfo_Delete : Directory_Delete_str
    {
        protected override void Delete(string path)
        {
            new DirectoryInfo(path).Delete();
        }

        [Fact]
        public void ExistsDoesntRefreshOnDelete()
        {
            DirectoryInfo dir = Directory.CreateDirectory(Path.Combine(TestDirectory, Path.GetRandomFileName()));

            Assert.True(dir.Exists);

            dir.Delete();

            Assert.True(dir.Exists);
            dir.Refresh();
            Assert.False(dir.Exists);
        }
    }

    public class DirectoryInfo_Delete_bool : Directory_Delete_str_bool
    {
        protected override void Delete(string path)
        {
            new DirectoryInfo(path).Delete(false);
        }

        protected override void Delete(string path, bool recursive)
        {
            new DirectoryInfo(path).Delete(recursive);
        }
    }
}


text:
import * as React from 'react';
import { JsonFormFieldProps, JsonFormFieldState } from '@shared/components/json-form/react/json-form.models';
import FormControlLabel from '@material-ui/core/FormControlLabel';
import { FormLabel, Radio, RadioGroup } from '@material-ui/core';
import FormControl from '@material-ui/core/FormControl';
import ThingsboardBaseComponent from '@shared/components/json-form/react/json-form-base-component';

class ThingsboardRadios extends React.Component<JsonFormFieldProps, JsonFormFieldState> {
  render() {
    const items = this.props.form.titleMap.map((item, index) => {
      return (
          <FormControlLabel value={item.value} control={<Radio />} label={item.name} key={index} />
      );
    });

    let row = false;
    if (this.props.form.direction === 'row') {
      row = true;
    }

    return (
      <FormControl component='fieldset'
                   className={this.props.form.htmlClass}
                   disabled={this.props.form.readonly}>
        <FormLabel component='legend'>{this.props.form.title}</FormLabel>
        <RadioGroup row={row} name={this.props.form.title} value={this.props.value} onChange={(e) => {
          this.props.onChangeValidate(e);
        }}>
          {items}
        </RadioGroup>
      </FormControl>
    );
  }
}

export default ThingsboardBaseComponent(ThingsboardRadios);


text:
/**
 * \file
 * \brief Shell and console interface implementation.
 * \author Erich Styger
 *
 * This module implements the front to the console/shell functionality.
 */

#include "Shell.h"
#include "BLUETOOTH.h"
#include "Application.h"
#include "FRTOS1.h"
#include "BT1.h"
#include "PID.h"
#include "WatchDog.h"
#include "SurfaceScan.h"
#include "ColorSensor.h"
#include "ContainerRecognizer.h"
#include "Servos.h"

#include "MotionController.h"

#define PL_CONFIG_HAS_BLUETOOTH (1)

/* forward declaration */
static uint8_t SHELL_ParseCommand(const unsigned char *cmd, bool *handled, const BLUETOOTH_StdIOType *io);

static const BLUETOOTH_ParseCommandCallback CmdParserTable[] =
{
  BLUETOOTH_ParseCommand, /* Processor Expert Shell component, is first in list */
  SHELL_ParseCommand, /* our own module parser */
  MOT_ParseCommand,
  PID_ParseCommand,
  WDG_ParseCommand,
  SCN_ParseCommand,
  COL_ParseCommand,
  COR_ParseCommand,
  SRV_ParseCommand,
  NULL /* Sentinel */
};

static uint32_t SHELL_val; /* used as demo value for shell */

void SHELL_SendString(unsigned char *msg) {
#if PL_CONFIG_HAS_SHELL_QUEUE
  SQUEUE_SendString(msg);
#elif CLS1_DEFAULT_SERIAL
  CLS1_SendStr(msg, CLS1_GetStdio()->stdOut);
#else
#endif
}

/*!
 * \brief Prints the help text to the console
 * \param io StdIO handler
 * \return ERR_OK or failure code
 */
static uint8_t SHELL_PrintHelp(const BLUETOOTH_StdIOType *io) {
	BLUETOOTH_SendHelpStr("Shell", "Shell commands\r\n", io->stdOut);
	BLUETOOTH_SendHelpStr("  help|status", "Print help or status information\r\n", io->stdOut);
	BLUETOOTH_SendHelpStr("  val <num>", "Assign number value\r\n", io->stdOut);
	return ERR_OK;
}

/*!
 * \brief Prints the status text to the console
 * \param io StdIO handler
 * \return ERR_OK or failure code
 */
static uint8_t SHELL_PrintStatus(const BLUETOOTH_StdIOType *io) {
  uint8_t buf[16];

  BLUETOOTH_SendStatusStr("Shell", "\r\n", io->stdOut);
  UTIL1_Num32sToStr(buf, sizeof(buf), SHELL_val);
  UTIL1_strcat(buf, sizeof(buf), "\r\n");
  BLUETOOTH_SendStatusStr("  val", buf, io->stdOut);
  return ERR_OK;
}

static uint8_t SHELL_ParseCommand(const unsigned char *cmd, bool *handled, const BLUETOOTH_StdIOType *io) {
  uint32_t val;
  const unsigned char *p;

  if (UTIL1_strcmp((char*)cmd, BLUETOOTH_CMD_HELP)==0 || UTIL1_strcmp((char*)cmd, "Shell help")==0) {
    *handled = TRUE;
    return SHELL_PrintHelp(io);
  } else if (UTIL1_strcmp((char*)cmd, BLUETOOTH_CMD_STATUS)==0 || UTIL1_strcmp((char*)cmd, "Shell status")==0) {
    *handled = TRUE;
    return SHELL_PrintStatus(io);
  } else if (UTIL1_strncmp(cmd, "Shell val ", sizeof("Shell val ")-1)==0) {
    p = cmd+sizeof("Shell val ")-1;
    if (UTIL1_xatoi(&p, &val)==ERR_OK) {
      SHELL_val = val;
      *handled = TRUE;
    } else {
      return ERR_FAILED; /* wrong format of command? */
    }
  }
  return ERR_OK;
}

#if PL_CONFIG_HAS_BLUETOOTH
/* Bluetooth stdio */
static BLUETOOTH_ConstStdIOType BT_stdio = {
  (BLUETOOTH_StdIO_In_FctType)BT1_StdIOReadChar, /* stdin */
  (BLUETOOTH_StdIO_OutErr_FctType)BT1_StdIOSendChar, /* stdout */
  (BLUETOOTH_StdIO_OutErr_FctType)BT1_StdIOSendChar, /* stderr */
  BT1_StdIOKeyPressed /* if input is not empty */
};
#endif

#if PL_CONFIG_HAS_SEGGER_RTT
static CLS1_ConstStdIOType RTT_stdio = {
  (CLS1_StdIO_In_FctType)RTT1_StdIOReadChar, /* stdin */
  (CLS1_StdIO_OutErr_FctType)RTT1_StdIOSendChar, /* stdout */
  (CLS1_StdIO_OutErr_FctType)RTT1_StdIOSendChar, /* stderr */
  RTT1_StdIOKeyPressed /* if input is not empty */
};
#endif

#define SHELL_COMBINED_STDIO  0

#if SHELL_COMBINED_STDIO /* copy */
static void CombineStdOut(uint8_t ch) {
#if CLS1_DEFAULT_SERIAL
  CLS1_GetStdio()->stdOut(ch);
#endif
#if PL_CONFIG_HAS_SEGGER_RTT
  RTT_stdio.stdOut(ch);
#endif
#if PL_CONFIG_HAS_BLUETOOTH
  BT_stdio.stdOut(ch);
#endif
}

static void CombineStdErr(uint8_t ch) {
#if CLS1_DEFAULT_SERIAL
  CLS1_GetStdio()->stdErr(ch);
#endif
#if PL_CONFIG_HAS_SEGGER_RTT
  RTT_stdio.stdErr(ch);
#endif
#if PL_CONFIG_HAS_BLUETOOTH
  BT_stdio.stdErr(ch);
#endif
}

static void CombineStdIn(uint8_t *ch) {
#if CLS1_DEFAULT_SERIAL
  CLS1_GetStdio()->stdIn(ch);
  if (*ch!='\0') {
    return;
  }
#endif
#if PL_CONFIG_HAS_SEGGER_RTT
  RTT_stdio.stdIn(ch);
  if (*ch!='\0') {
    return;
  }
#endif
#if PL_CONFIG_HAS_BLUETOOTH
  BT_stdio.stdIn(ch);
  if (*ch!='\0') {
    return;
  }
#endif
  *ch = '\0'; /* nothing received */
}

static bool CombineKeyPressed(void) {
#if CLS1_DEFAULT_SERIAL
  if (CLS1_GetStdio()->keyPressed()) {
    return TRUE;
  }
#endif
#if PL_CONFIG_HAS_SEGGER_RTT
  if (RTT_stdio.keyPressed()) {
    return TRUE;
  }
#endif
#if PL_CONFIG_HAS_BLUETOOTH
  if (BT_stdio.keyPressed()) {
    return TRUE;
  }
#endif
  return FALSE;
}

static CLS1_ConstStdIOType CombineStdio = {
  (CLS1_StdIO_In_FctType)CombineStdIn, /* stdin */
  (CLS1_StdIO_OutErr_FctType)CombineStdOut, /* stdout */
  (CLS1_StdIO_OutErr_FctType)CombineStdErr, /* stderr */
  CombineKeyPressed /* if input is not empty */
};
#endif

void SHELL_ParseCmd(unsigned char *cmd) {
#if SHELL_COMBINED_STDIO
  (void)CLS1_ParseWithCommandTable(cmd, &CombineStdio, CmdParserTable);
#else
  #if CLS1_DEFAULT_SERIAL
    (void)CLS1_ParseWithCommandTable(cmd, CLS1_GetStdio(), CmdParserTable);
  #endif
  #if PL_CONFIG_HAS_BLUETOOTH
    (void)BLUETOOTH_ParseWithCommandTable(cmd, &BT_stdio, CmdParserTable);
  #endif
  #if PL_CONFIG_HAS_SEGGER_RTT
    (void)CLS1_ParseWithCommandTable(cmd, &RTT_stdio, CmdParserTable);
  #endif
#endif
}

static void ShellTask(void *pvParameters) {

#define DEFAULT_BUF_SIZE 48
#if BLUETOOTH_DEFAULT_SERIAL
  static unsigned char localConsole_buf[DEFAULT_BUF_SIZE];
#endif
#if PL_CONFIG_HAS_BLUETOOTH
  static unsigned char bluetooth_buf[DEFAULT_BUF_SIZE];
#endif
#if BLUETOOTH_DEFAULT_SERIAL
  BLUETOOTH_ConstStdIOTypePtr ioLocal = BLUETOOTH_GetStdio();
#endif

  (void)pvParameters; /* not used */

#if PL_CONFIG_HAS_BLUETOOTH
  bluetooth_buf[0] = '\0';
#endif
#if BLUETOOTH_DEFAULT_SERIAL
  localConsole_buf[0] = '\0';
#endif
#if BLUETOOTH_DEFAULT_SERIAL
  (void)BLUETOOTH_ParseWithCommandTable((unsigned char*)BLUETOOTH_CMD_HELP, ioLocal, CmdParserTable);
#endif
  for(;;) {
#if BLUETOOTH_DEFAULT_SERIAL
    (void)BLUETOOTH_ReadAndParseWithCommandTable(localConsole_buf, sizeof(localConsole_buf), ioLocal, CmdParserTable);
#endif
#if PL_CONFIG_HAS_BLUETOOTH
    (void)BLUETOOTH_ReadAndParseWithCommandTable(bluetooth_buf, sizeof(bluetooth_buf), &BT_stdio, CmdParserTable);
#endif

#if PL_CONFIG_HAS_SHELL_QUEUE
#if PL_CONFIG_SQUEUE_SINGLE_CHAR
    {
        /*! \todo Handle shell queue */
      unsigned char ch;

      while((ch=SQUEUE_ReceiveChar()) && ch!='\0') {
    #if CLS1_DEFAULT_SERIAL
       ioLocal->stdOut(ch);
    #endif
    #if PL_CONFIG_HAS_BLUETOOTH
        BT_stdio.stdOut(ch); /* copy on Bluetooth */
    #endif
    #if PL_CONFIG_HAS_SEGGER_RTT
        CDC_stdio.stdOut(ch); /* copy on USB CDC */
    #endif
      }
    }
#else /* PL_CONFIG_SQUEUE_SINGLE_CHAR */
    {
      const unsigned char *msg;

      msg = SQUEUE_ReceiveMessage();
      if (msg!=NULL) {
        CLS1_SendStr(msg, CLS1_GetStdio()->stdOut);
        FRTOS1_vPortFree((void*)msg);
      }
    }
#endif /* PL_CONFIG_SQUEUE_SINGLE_CHAR */
#endif /* PL_CONFIG_HAS_SHELL_QUEUE */
    FRTOS1_vTaskDelay(10/portTICK_PERIOD_MS);
  } /* for */
}

void SHELL_Init(void) {
  SHELL_val = 0;

  (void)BLUETOOTH_SetStdio(&BT_stdio); /* use the Bluetooth stdio as default */

  if (FRTOS1_xTaskCreate(ShellTask, "Shell", configMINIMAL_STACK_SIZE+100, NULL, tskIDLE_PRIORITY+1, NULL) != pdPASS) {
    for(;;){} /* error */
  }

}

void SHELL_Deinit(void) {
}


text:
from oauth2app.authenticate import JSONAuthenticator, AuthenticationException
from oauth2app.models import AccessRange
from oauth2app.models import Client, AccessToken, Code
import traceback

def date_joined(request):
    scope = AccessRange.objects.get(key="date_joined")
    authenticator = JSONAuthenticator(scope=scope)
    try:
        authenticator.validate(request)
    except AuthenticationException:
        return authenticator.error_response()

    response = authenticator.response({
            "date_joined":str(authenticator.user.date_joined)})
    print "response = ", response
    return response

def last_login(request):
    print "in last_login"
    scope = AccessRange.objects.get(key="last_login")
    authenticator = JSONAuthenticator(scope=scope)
    try:
        authenticator.validate(request)
    except AuthenticationException:
        return authenticator.error_response()
    response = authenticator.response({
            "last_login":str(authenticator.user.last_login)})
    print "returning ", response
    return response

def email(request):
    print "in email"
    authenticator = JSONAuthenticator()
    try:
        authenticator.validate(request)
    except AuthenticationException:
        return authenticator.error_response()
    response = authenticator.response({"email":authenticator.user.email})
    print "returning ", response
    return response


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace SimpleTcpServer.Server
{
    public class TcpServer : IDisposable
    {
        int _port;
        public int Port { get { return _port; } }

        bool _running = true;

        public bool Running
        {
            get { return _running; }
            set { _running = value; }
        }

        TcpListener _listener;
        Task _loopTask;

        public TcpServer(int port)
            : this(IPAddress.Any, port)
        {
        }
        public TcpServer(IPAddress listeningAddress, int port)
        {
            _port = port;

            _listener = new TcpListener(listeningAddress, Port);
            _listener.Start();

            _loopTask = Task.Factory.StartNew(ListenLoop);
        }

        private async void ListenLoop()
        {
            while (_running)
            {
                var socket = await _listener.AcceptSocketAsync();
                if (socket == null)
                    break;

                var client = new ClientHandler(this, socket);

                /// Never use this, but suppresses the warning.
                var clientTask = Task.Factory.StartNew(client.HandleRequest);
            }
        }

        public void Dispose()
        {
            if (_loopTask != null)
            {
                _listener.Stop();
                _loopTask.Wait(5000);
                _loopTask.Dispose();
            }
        }

        class ClientHandler
        {
            TcpServer _server;
            Socket _socket;

            public ClientHandler(TcpServer server, Socket socket)
            {
                _server = server;
                _socket = socket;
            }
            public async void HandleRequest()
            {
                while (true)
                {
                    using (var nws = new NetworkStream(_socket, true))
                    using (var sr = new StreamReader(nws))
                    {
                        var line = await sr.ReadLineAsync();
                        if (!_socket.Connected || line == null)
                            return;

                        var chs = line.ToCharArray();
                        Array.Reverse(chs);
                        var reverseLIne = new string(chs);

                        var responseBytes = System.Text.Encoding.ASCII.GetBytes(reverseLIne);
                        await nws.WriteAsync(responseBytes, 0, responseBytes.Length);
                        await nws.FlushAsync();
                    }
                    return;
                }
            }
        }
    }
}


text:
<?php

if (!interface_exists('Serializable')) {
    interface Serializable {
        public function serialize();

        public function unserialize($serialized);
    }
}


text:
package com.hotmail.hboutilier1996.MineSkills;

import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;

import org.bukkit.event.enchantment.EnchantItemEvent;
import org.bukkit.event.hanging.HangingBreakEvent;
import org.bukkit.event.hanging.HangingPlaceEvent;
import org.bukkit.event.weather.LightningStrikeEvent;

public class OtherListeners implements Listener{
    @EventHandler (priority  = EventPriority.MONITOR, ignoreCancelled = true)
    public void BlockBroken (BlockBreakEvent event){
        //BlockBreakCodeHere
    }
}


text:
using Steam.Models;
using Steam.Models.SteamCommunity;
using Steam.Models.SteamPlayer;
using SteamWebAPI2.Utilities;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace SteamWebAPI2.Interfaces
{
    public interface ISteamUserStats
    {
        Task<ISteamWebResponse<IReadOnlyCollection<GlobalAchievementPercentageModel>>> GetGlobalAchievementPercentagesForAppAsync(uint appId);

        Task<ISteamWebResponse<IReadOnlyCollection<GlobalStatModel>>> GetGlobalStatsForGameAsync(uint appId, IReadOnlyList<string> statNames, DateTime? startDate = null, DateTime? endDate = null);

        Task<ISteamWebResponse<uint>> GetNumberOfCurrentPlayersForGameAsync(uint appId);

        Task<ISteamWebResponse<PlayerAchievementResultModel>> GetPlayerAchievementsAsync(uint appId, ulong steamId, string language = "");

        Task<ISteamWebResponse<SchemaForGameResultModel>> GetSchemaForGameAsync(uint appId, string language = "");

        Task<ISteamWebResponse<UserStatsForGameResultModel>> GetUserStatsForGameAsync(ulong steamId, uint appId);
    }
}


text:
extern "C" uintptr_t get_cpu_esp();

constexpr auto STACK_SIZE = 0x20000;
static const double float1 = 0.987;
static const double float2 = 0.654;
static const double float3 = 0.321;

static double much_float(double d) {
  return sqrt(2) * d;
}

void Service::start(const std::string&)
{
  INFO("Context", "Testing stack switches");

  auto esp0 = get_cpu_esp();

  auto res1 = much_float(float1);
  auto res2 = much_float(float2);
  auto res3 = much_float(float3);

  Context::create(STACK_SIZE,
  [res1, res2] ()
  {
    const auto esp1 = get_cpu_esp();
    printf("Context 1, stack at %p\n", (void*) esp1);
    Expects(esp1 >= OS::heap_begin() and esp1 <= OS::heap_end());

    const volatile double my_float = much_float(float1);

    Context::create(STACK_SIZE,
    [esp1, res2] ()
    {
      const auto esp2 = get_cpu_esp();

      Expects(esp2 >= OS::heap_begin() and esp2 <= OS::heap_end());
      Expects(std::abs(long(esp2 - esp1)) >= STACK_SIZE);

      auto my_float = much_float(float2);
      Expects(my_float == res2);

      printf("Context 2, stack at %p\n", (void*) esp2);
    });

    Expects(my_float == res1);
  });

  // Stack should be back to where it was.
  auto esp3 = get_cpu_esp();
  Expects(esp0 == esp3);

  auto my_float = much_float(float3);
  Expects(my_float == res3);

  INFO("Context","SUCCESS");
}


text:
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using Contest.Core;
using Contest.Tests;

namespace Inception.Test.Runner {
	using static Console;
	using static ContestConstants;

    class Program {

        static void Main(string[] args) {

            try {
                Trace.Listeners.Add(new ConsoleTraceListener());

                if (!args.Any()) {
                    PrintHelp();
                    return;
                }

                if (args.Any(a => a == "-dbg")) {
                    WriteLine("Attach the debugger and press [Enter] to continue.");
                    ReadLine();
                }

				var printHeaders = !args.Any(a => a == "--no-head" || a == "-nh");

				//clean args list (no flags).
				args = (from a in args where !a.StartsWith("-") select a).ToArray();

                var cmd = args[0];
                switch (cmd) {
                    case "run":
                    case "r":
						if(args.Length <=1) {
							WriteLine("File name expected. (The name of the assembly that contains test cases)");
							return;
						}

						var root = Path.GetDirectoryName(args[1]);
						CopyToLocalTmp(root);
						AppDomain.CurrentDomain.AssemblyResolve += (s, e) => {
							try {
								var name = string.Format("{0}.dll", e.Name.Split(',')[0]);
								var localpath = Path.GetFullPath(Path.Combine(TMP, name));
								if (File.Exists(localpath)) {
									var assm = Assembly.LoadFile(localpath);
									Debug.Assert(assm != null);
									return assm;
								}
							}
							catch (Exception ex) {
								WriteLine(ex);
							}
							return null;
						};

						//args[0] == cmd
						var testAssm = args[1];
						var pattern  = args.Length >= 3 ? args[2] : null;

						RunTests(testAssm, pattern, printHeaders);

                        break;
                    default: {
						 PrintHelp();
						 break;
					}
                }
            }
            catch (Exception ex) {
                WriteLine(ex);
            }
        }

        static void CopyToLocalTmp(string root) {
			root = string.IsNullOrEmpty(root)?".":root;
#if DEBUG
			WriteLine("Copying to local tmp...");
			WriteLine("tmp:  '{0}'", TMP);
			WriteLine("root: '{0}'", root);
#endif
            if (!Directory.Exists(TMP)){
#if DEBUG
				WriteLine("Creating tmp dir '{0}'", TMP);
#endif
                Directory.CreateDirectory(TMP);
			}

            Directory.GetFiles(root, "*.dll").Each(
                f => {
				 var to = Path.Combine(TMP, Path.GetFileName(f) ?? "");
#if DEBUG
					WriteLine("copying '{0}' to {1}", f, to);
#endif
					File.Copy(
						f ?? throw new ArgumentNullException(nameof(f)),
						to, true);
				});
#if DEBUG
			WriteLine("Done!");
#endif
        }

        static void RunTests(string assmFileName, string cerryPicking=null, bool printHeaders=true) {
            WriteLine("\nConfiguring Assembies....");

            if (string.IsNullOrEmpty(assmFileName))
                throw new ArgumentException("Assembly name is required.");

            if (!assmFileName.EndsWith(".dll"))
                assmFileName = "{0}.dll".Interpol(assmFileName);

            var fullpath = Path.GetFullPath(assmFileName);

            if (!File.Exists(fullpath)) {
                var pwd = Directory.GetCurrentDirectory();
                    throw new IOException(
                        "Pwd: {0}\n".Interpol(pwd) +
                        "File not found. ('{0}')".Interpol(assmFileName));
            }

            var assm = Assembly.LoadFile(fullpath);
            if (assm == null)
                throw new Exception("Can't load assembly '{0}'.".Interpol(assmFileName));

			// IMPORTANT!
			// This is the _only_ difference with main program. should refator and
			// get just one program asap!
			Func<Type, bool> ifNonCoreTest = t => t != typeof(contest_core_tests);
			//
            var finder = new TestCaseFinder(getIgnoredFromFile: null, ignoreType: ifNonCoreTest);

            var suite = Contest.Core.Contest.GetCasesInAssm(finder, assm, null);
            var runner = new Contest.Core.Runner();
			SyntaxSugar.SetRunner(runner);//To enable syntax sugar.

			runner.Verbose = true;

            WriteLine("\nDone!\n");
            runner.Run(suite, cerryPicking, printHeaders );
        }

        static void PrintHelp() {
            Print("=================================================================================");
            Print("| Contest - Console Test Runner                                                 |");
            Print("=================================================================================");

            Print("=================================================================================");
            Print("| Commands                                                                      |");
            Print("=================================================================================");
            Print("| name  | args              | summary                                           |");
            Print("=================================================================================");
            Print("| help  |                   | Shows help.                                       |");
            Print("| run   | test.dll          | Runs all tests within the given file.             |");
            Print("| run   | test.dll wildcard | Runs all tests within the given file where the    |");
		    Print("|       |                   | test name matches the wildcard pattern.           |");
            Print("=================================================================================");
			Print("");
			Print("-- More --");
			ReadLine();

            Print("=================================================================================");
            Print("| Flags                                                                         |");
            Print("=================================================================================");
            Print("| name  | summary                                                               |");
            Print("=================================================================================");
            Print("| -nh   | Don't print fixture names.                                            |");
            Print("| -dbg  | Stop the runner until the user presses [Enter].                       |");
            Print("=================================================================================");
			Print("");
			Print("-- More --");
			ReadLine();

            Print("=================================================================================");
            Print("| Alias                                                                         |");
            Print("=================================================================================");
            Print("| name      | summary                                                           |");
            Print("=================================================================================");
            Print("| --no-head | -nh                                                               |");
            Print("| r         | run                                                               |");
            Print("=================================================================================");
			Print("");

            Print("\nMore about contest at:");
            Print("https://github.com/amiralles/contest\n");

        }

        static void Print(string msg, params object[] args) {
            WriteLine(msg, args);
        }
    }
}


text:
class CreateSpreeTaxonImages < ActiveRecord::Migration
  def change
    create_table :spree_taxon_images do |t|
      t.references :taxon
      t.text       :alt
      t.timestamps
    end
  end
end


text:
package br.unb.cic.iris.mail.secure.smime.internal;

import br.unb.cic.iris.mail.EmailProvider;
import br.unb.cic.iris.mail.secure.EmailSecurityManager;
import br.unb.cic.iris.mail.secure.internal.EmailReceiverSecure;

public class EmailReceiverSmime extends EmailReceiverSecure {

	public EmailReceiverSmime(EmailProvider provider, String encoding) {
		super(provider, encoding);
	}

	@Override
	protected EmailSecurityManager getEmailSecurityManager() {
		return EmailSecurityManagerSmime.instance();
	}

}


text:
This directory contains examples of packet processors written using Pax's API:
* [Hub](#hub)
* [Learning switch](#learningswitch)
* [Mirror](#mirror)
* [NAT](#nat)
* [Packet generator](#packetgenerator)
* [Ethernet Echo](#ethernetecho)

These examples are written in C#, but any [.NET language](https://en.wikipedia.org/wiki/List_of_CLI_languages) can be used.
For an example in F# see [Recap](https://github.com/niksu/recap).

# Examples

## Hub
The [Hub](Hub.cs) simply forwards all receives all traffic that's received on a
port to every other port, as illustrated below.

![Hub](../doc/hub.png)

## Learning Switch
The [Learning Switch](LearningSwitch.cs) forwards traffic between ports based on
a mapping that it "learned" by forwarding traffic(!) If its mapping doesn't
specify where to forward traffic, then the switch forwards it to all other
ports. In the example below, we receive a frame for destination Yellow, from
Pink. The switch learns that Pink can be reached through port 3. Not knowing how
to reach Yellow, it forwards the frame through all ports. When it later receives
a packet from Green to Pink, it only forwards the frame through port 3.

![LearningSwitch](../doc/learningswitch.png)

## Mirror
The [Mirror](Mirror.cs) duplicates a frame and sends it over an additional port.

![Mirror](../doc/mirror.png)

[Test](Test.cs) includes a variety of different packet processors (mostly
contrived), including nested and chained packet processors. This means that
packet processors can be combined with others to form a new kind of packet
processor. Our assembly can accommodate such packet processors, as illustrated
below. [Test](Test.cs) contains an example of a Mirror chained with a Switch.

![Chained](../doc/chained.png)

## Network Address Translation
[Network Address Translation](NAT.cs) is perhaps the most interesting example.
Our example works for TCP. You can find out more about NAT from article such as
[Wikipedia's](https://en.wikipedia.org/wiki/Network_Address_Translation).

### Configuration
The configuration needs to specify three parameters to the NAT's constructor:

* The IP address of the NAT. This will be used as the source address of packets crossing from the Inside to the Outside of the NAT.
* The starting TCP port to use on the NAT, to proxy TCP connections crossing from the Inside to the Outside of the NAT.
* The MAC address of the next hop to Outside; the address of the node which the Out port (port 0) of the NAT is connected to.

These parameters are provided as part of the `args` map, as shown in the example NAT configuration below.

```javascript
{
  "handlers": [
    {
      "class_name": "NAT",
      "args": {
        "my_address" : "10.0.0.3",
        "next_port" : "35000",
        "next_hop_mac" : "00:00:00:00:00:09"
      }
    }
  ],
  "interfaces": [
    {
      "interface_name" : "nat0-eth0",
      "lead_handler" : "NAT",
      "pcap_filter" : "tcp"
    },
    {
      "interface_name" : "nat0-eth1",
      "lead_handler" : "NAT",
      "pcap_filter" : "tcp"
    },
    {
      "interface_name" : "nat0-eth2",
      "lead_handler" : "NAT",
      "pcap_filter" : "tcp"
    }
  ]
}
```

### Testing
I set up tcpdump to monitor the different network ports between which the NAT
is mediating, and see if the NAT's behaviour matches my intended behaviour.  Of
course, you need to generate network traffic to observe how the NAT behaves.
One could simple use a TCP-based application (e.g., telnet or a web browser) for
this, but I use [Scapy](https://en.wikipedia.org/wiki/Scapy) to craft specific packets as follows.

I use the following code skeleton to generate TCP packets, sometimes setting
`tcp_flags="S"` to generate TCP packets with the SYN flag set.  (You must fill
in specific values for each `"..."` of course, depending on your network
setup.)

```python
destination_ip = "..."
source_ip = "..."
destination_tcp_port = ...
source_tcp_port = ...
tcp_flags = "..."
interface = "..."
send((IP(dst=destination_ip,src=source_ip)/TCP(dport=destination_tcp_port,sport=source_tcp_port,flags=tcp_flags)/"Pax"),iface=interface)
```

I use the following snippet to send a reply.

```python
# Reusing some values from above.
destination_ip = "..."
destination_tcp_port = ...

# Probably updating some fields from above.
interface = "..."
flags = "..."

# Additional values used for reply.
nat_ip = "..."
nat_assigned_tcp_port = ...
send((IP(dst=nat_ip,src=destination_ip)/TCP(dport=nat_assigned_tcp_port,sport=destination_tcp_port,flags=tcp_flags)/"Reply"),iface=interface)
```

**FIXME**: It might be worth wrapping this into a tiny library of Python functions, and to automate the testing.

# Port constraints
Note that the examples are not sensitive to a fixed number of ports.
The Hub, Switch and Mirror work with any number of ports -- though it would not be sensible to have fewer than two.
The NAT needs at least one port (for the Outside), but it would not be sensible to have fewer than two ports.
You need at least one port for the Inside.

# Test workflow
As described for the NAT example above,
I set up tcpdump to monitor an interface over which I expect to see data, and
use tools like ping or [Scapy](https://en.wikipedia.org/wiki/Scapy) to generate generic or customised traffic, and
send it to a specific port. I then observe how the packet processor behaves,
through diagnostic messages it emits to the console, and through the packets
sniffed up by tcpdump on recipient interfaces.
I use `sudo tcpdump -vvvnXX -i IF` to see a detailed description of each packet,
replacing `IF` with the interface you want to sniff on.

# Testing the NAT with Mininet
[Mininet](http://mininet.org/) is a tool for emulating networks on your local machine.
This is quite handy because we can run reproducible tests and experiment with
networks when we don't have the physical machines otherwise needed.

To test the NAT implementation:
- [Install](http://mininet.org/download/) Mininet - it doesn't matter which way. We used Mininet 2.2.1 on Ubuntu 14.04 LTS.
- cd into your cloned Pax directory and run `$ sudo ./examples/Nat/nat_topo.py test`
- You can also jump into the Mininet CLI by running `$ sudo ./examples/Nat/nat_topo.py`

You will find it very helpful to learn more about Mininet if you plan to do anything
apart from run the automated test. The Mininet
[walkthrough](http://mininet.org/walkthrough/) is a pretty good start.
One very useful thing to know is to use `mininet> host command` in the CLI to run
`command` on `host`. E.g. to run ifconfig on in1, use `mininet> in1 ifconfig`.

We could manually test the NAT by running these commands:
``` bash
$ sudo ./examples/Nat/nat_topo.py
mininet> out0 echo 'Hi from out0!' | netcat -l 12010 &
mininet> in1 netcat out0 12010
```
Note that on line 3, we specify `out0` instead of the IP of out0. We can do this
because the Mininet CLI replaces it with the IP. Be aware that this is the IP of the
default interface, which is fine here because out0 only has one, but on nat0
it might not be the IP you were expecting.

_

Feel free to look in [`examples/Nat/nat_topo.py`](Nat/nat_topo.py):
- The `NatTopo` class defines the network topology for Mininet
```
                  ┌──────┐     ┌─────┐
                  |      |-----│ in1 |
    ┌──────┐      |      |     └─────┘
    │ out0 |------| nat0 |
    └──────┘      |      |     ┌─────┐
                  |      |-----│ in2 |
                  └──────┘     └─────┘
```
- You might notice that `nat0` is specified as being a node of type `PaxNode`. You can
  look at the definition in [`pax_mininet_node.py`](pax_mininet_node.py). It is a host with firewall rules on
  each of the interfaces on nat0 to drop all incoming traffic. This is so that only
  the NAT process will respond to packets. Otherwise, the OS could reject or accept
  connections that are intended for internal hosts. We also disable ip_forward so that
  the OS doesn't forward packets that aren't addressed to it.
- The `createNetwork()` procedure instantiates the network topology and sets up
  the hosts. It sets the default gateway for the internal hosts to nat0 so that
  connections to outside the subnet go through the NAT.

  Take special note that the MAC address of out0 is manually set. This is so because
  the NAT implementation currently requires the next hop to be hardcoded in the config.
  Without this, out0 would ignore packets from the NAT, because the MAC would be wrong.
- The `run()` procedure provides a commandline-interface to the network.
- The `test()` procedure creates a network, tests the NAT implementation by
  creating a connection between in1 and out0, and then cleans up.

## Packet generator
The packet generator example emits packets on a specific interface at regular
intervals. It's a very simple affair, but can easily be extended for more
complex behaviour.

### Configuration
The generator emits TCP segments from (`src_port`,`src_ip`,`src_mac`) to
(`dst_port`,`dst_ip`,`dst_mac`) every `interval` milliseconds, on interface
`interface_name`. An example configuration can be seen in
[generator_wiring.json](generator_wiring.json):

```javascript
{
  "handlers": [
    {
      "class_name": "Generator",
      "args": {
        "interval": "100",
        "src_port": "10",
        "dst_port": "11",
        "src_ip": "10.0.0.4",
        "dst_ip": "10.0.0.5",
        "src_mac": "02-00-00-00-00-01",
        "dst_mac": "02-00-00-00-00-02"
      }
    }
  ],
  "interfaces": [
    {
      "interface_name" : "en3",
      "lead_handler" : "Generator"
    }
  ]
}
```

### Testing
I ran the generator by calling
```
$ sudo mono ./Bin/Pax.exe --config=examples/generator_wiring.json --code=examples/Bin/Examples.dll
```
and, in parallel used tcpdump  -- with a suitable filter -- to see what the generator is producing:
```
$ sudo tcpdump -nvvv "host 10.0.0.4"
tcpdump: data link type PKTAP
tcpdump: listening on pktap, link-type PKTAP (Packet Tap), capture size 65535 bytes
20:52:29.872721 IP (tos 0x0, ttl 64, id 0, offset 0, flags [none], proto TCP (6), length 40)
    10.0.0.4.10 > 10.0.0.5.11: Flags [none], cksum 0x9bc7 (correct), seq 0, win 0, length 0
20:52:29.966521 IP (tos 0x0, ttl 64, id 0, offset 0, flags [none], proto TCP (6), length 40)
    10.0.0.4.10 > 10.0.0.5.11: Flags [none], cksum 0x9bc7 (correct), seq 0, win 0, length 0
20:52:30.069319 IP (tos 0x0, ttl 64, id 0, offset 0, flags [none], proto TCP (6), length 40)
    10.0.0.4.10 > 10.0.0.5.11: Flags [none], cksum 0x9bc7 (correct), seq 0, win 0, length 0
20:52:30.169720 IP (tos 0x0, ttl 64, id 0, offset 0, flags [none], proto TCP (6), length 40)
    10.0.0.4.10 > 10.0.0.5.11: Flags [none], cksum 0x9bc7 (correct), seq 0, win 0, length 0
20:52:30.269609 IP (tos 0x0, ttl 64, id 0, offset 0, flags [none], proto TCP (6), length 40)
    10.0.0.4.10 > 10.0.0.5.11: Flags [none], cksum 0x9bc7 (correct), seq 0, win 0, length 0
```

## Ethernet Echo
[EthernetEcho.cs](EthernetEcho/EthernetEcho.cs) implements an element that swaps
the source and destination Ethernet addresses.
The goal of this example is to show the *byte-based* interface for packet
processors in Pax, i.e., it avoids dissecting and constructing packets, but
rather works at the lower level of byte arrays.

### Testing
This example was tested in Mininet using the [mn_ethernet_echo.py](EthernetEcho/mn_ethernet_echo.py)
script which automatically generates and tests for
[ECTP](https://en.wikipedia.org/wiki/Ethernet_Configuration_Testing_Protocol) [EtherType](https://en.wikipedia.org/wiki/EtherType)
frames.
When running Mininet in a VM, remember that to compile/run Pax elements in that
VM you must have Mono installed there too.


text:
using lessonweb.Data;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace lessonweb.web
{
    /// <summary>
    /// Summary description for deletetask
    /// </summary>
    public class JSONTasksList : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            /*Dictionary<String, object> res = new Dictionary<string, object>();
            List<Object> finalList = new List<object>();
            IEnumerable<RewardDefinition> rews = RewardDefinition.getAll();
            foreach (RewardDefinition r in rews)
            {
                List<string> obj = new List<string>();
                obj.Add("");
                obj.Add(r.RewardName);
                obj.Add(r.RewardType);
                obj.Add(r.getRewardDetail());
                finalList.Add(obj);
            }
            res.Add("data", finalList);
            string json = JsonConvert.SerializeObject(res);
            context.Response.Write(json);
            */

            Dictionary<int, String> TypeCodes = TaskDefinition.GetTaskTypeCodes();
            Dictionary<String, object> res = new Dictionary<string, object>();
            List<Object> finalList = new List<object>();
            IEnumerable<TaskDefinition> rews = TaskDefinition.getAllTaskDefinitions();
            foreach (TaskDefinition r in rews)
            {
                Dictionary<string, string> obj = new Dictionary<string, string>();
                obj.Add("TaskName", r.TaskName);
                obj.Add("TaskID", r.TaskID.ToString());
                obj.Add("actions", r.TaskID.ToString());
                obj.Add("TaskTypeName", TypeCodes[r.TaskType]);
                obj.Add("TaskType", r.TaskType.ToString());
                obj.Add("TaskDescription", r.TaskDescription);
                obj.Add("AircraftType", r.AircraftType);
                obj.Add("Airport", r.Airport);
                obj.Add("Course", r.Course);
                obj.Add("Detail", r.Detail);
                obj.Add("Distance", (r.Distance != null) ? r.Distance.ToString() : "");
                obj.Add("Hours", (r.Hours != null) ? r.Hours.ToString() : "");
                obj.Add("IsCrossCountry", (r.IsCrossCountry != null) ? r.IsCrossCountry.ToString() : "");
                obj.Add("IsDual", (r.IsDual != null) ? r.IsDual.ToString() : "");
                obj.Add("IsNight", (r.IsNight != null) ? r.IsNight.ToString() : "");
                obj.Add("IsWithPassenger", (r.IsWithPassenger != null) ? r.IsWithPassenger.ToString() : "");
                obj.Add("Lesson", r.Lesson);
                obj.Add("Rating", r.Rating);
                obj.Add("Maneuver", r.Maneuver);
                obj.Add("TailNo", r.TailNo);

                finalList.Add(obj);
            }
            res.Add("data", finalList);
            string json = JsonConvert.SerializeObject(res);
            context.Response.Write(json);

        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}


text:
Live Update Feed

						{{ feed.createdAt | date:'medium' }}

{{ feed.text }}


text:
var loadState = {

  preload: function () {
    game.stage.disableVisibilityChange = true

    /*
    Load all game assets
    Place your load bar, some messages.
    In this case of loading, only text is placed...
    */

    var loadingLabel = game.add.text(80, 150, 'loading...', {font: '20px press_start_2pregular', fill: '#fff'});

    //Load your images, spritesheets, bitmaps...
    game.load.image('ship', 'assets/img/nave 4.png')
    //background game
    game.load.image('starfield', 'assets/img/campo_de_estrellas.png');
    // homescreen background
    game.load.image('background-414x736', 'assets/img/menú inicio/Inicio_414x736.png');
    game.load.image('background-384x640', 'assets/img/menú inicio/Inicio_384x640.png');
    game.load.image('background-360x640', 'assets/img/menú inicio/Inicio_360x640.png');
    game.load.image('background-320x568', 'assets/img/menú inicio/Inicio_320x568.png');

    //buttons
    game.load.image('start', 'assets/img/start.png');
    game.load.image('highScore', 'assets/img/hight score.png');
    //sprites
    game.load.spritesheet('bala', 'assets/img/balas/balas_1.png', 15, 15);
    game.load.spritesheet('balaEnemigo', 'assets/img/balas/balas_4.png', 15, 15);
    game.load.spritesheet('enemy', 'assets/img/invader.png', 45, 36 );
    game.load.spritesheet('player', 'assets/img/nave4_explosión.png', 30, 15);

    //Load your sounds, efx, music...
    //Example: game.load.audio('rockas', 'assets/snd/rockas.wav');

    game.load.audio('laser1', 'assets/sound/laser4.wav');
    game.load.audio('laser2', 'assets/sound/laser5.wav');
    game.load.audio('music', 'assets/sound/high tech lab.wav');
    game.load.audio('explosion2', 'assets/sound/Explosion_02.wav');
    game.load.audio('explosion1', 'assets/sound/Explosion.wav')

    //Load your data, JSON, Querys...
    //Example: game.load.json('version', 'http://phaser.io/version.json');

  },

  create: function () {

    game.stage.setBackgroundColor('#000');
    game.scale.fullScreenScaleMode = Phaser.ScaleManager.EXACT_FIT;
    game.state.start('menu');
  }
};


text:
'use strict';

angular.module('twitterStreamApp')
    .controller('StreamCtrl', function ($scope, $http) {

      $scope.updateTwits = function(){
        $scope.twits = null;

        $http.get('/api/streams').success(function(data) {
          $scope.twits = data;
        });
      };

      $scope.storeTwit = function(item) {
        $http.post('/api/starred', { 'twit_id': item.id, twit: item }).success(function(){
          item.starred = true;
        });
      };

      $scope.deleteTwit = function(item) {
        $http.delete('/api/starred/' + item.id).success(function(){
          item.starred = null;
        });
      };

      $scope.updateTwits();

    });


text:
<?php
namespace Procure\Application\Service\Output\Formatter;

/**
 * Row Output Decorator
 *
 * @author Nguyen Mau Tri - ngmautri@gmail.com
 *
 */
abstract class RowFormatterDecorator extends AbstractRowFormatter
{

    protected $formatter;

    /**
     *
     * @param AbstractRowFormatter $formatter
     */
    public function __construct(AbstractRowFormatter $formatter)
    {
        $this->formatter = $formatter;
    }
}


text:
package org.hisp.dhis.android.core.user.internal;

import org.hisp.dhis.android.core.arch.modules.internal.TypedModuleDownloader;
import org.hisp.dhis.android.core.user.User;

import javax.inject.Inject;

import dagger.Reusable;
import io.reactivex.Single;

@Reusable
public class UserModuleDownloader implements TypedModuleDownloader<User> {

    private final UserCall userCall;
    private final AuthorityEndpointCallFactory authorityCallFactory;

    @Inject
    UserModuleDownloader(UserCall userCall, AuthorityEndpointCallFactory authorityCallFactory) {
        this.userCall = userCall;
        this.authorityCallFactory = authorityCallFactory;
    }

    @Override
    public Single<User> downloadMetadata() {
        return Single.fromCallable(() -> {
            User user = userCall.call();
            authorityCallFactory.create().call();
            return user;
        });
    }
}


text:
package com.github.weisj.darklaf.properties.icons;

import java.awt.*;

import org.jetbrains.annotations.NotNull;

import com.github.weisj.jsvg.parser.DomProcessor;
import com.github.weisj.jsvg.parser.ParsedElement;

public class DarkSVGIconDomProcessor<T extends DarkSVGIcon> implements DomProcessor {
    protected final @NotNull T icon;

    public DarkSVGIconDomProcessor(@NotNull T icon) {
        this.icon = icon;
    }

    @Override
    public void process(@NotNull ParsedElement root) {
        float[] visualPaddings = root.attributeNode().getFloatList("visualPadding");
        if (visualPaddings.length == 4) {
            icon.setVisualPadding(new Insets(
                    (int) visualPaddings[0],
                    (int) visualPaddings[1],
                    (int) visualPaddings[2],
                    (int) visualPaddings[3]));
        }
    }
}


text:
#ifndef MEMORY_FILE_SHM_BASE_HPP
#define MEMORY_FILE_SHM_BASE_HPP

/*  Titles			                                                     Authors	          Date
 *  -File shm base for mmap file.                                    R.Chatsiri         21/03/2014
 */
#include <boost/interprocess/managed_shared_memory.hpp>
#include <boost/interprocess/allocators/allocator.hpp>
#include <boost/interprocess/containers/string.hpp>

#include <boost/multi_index_container.hpp>
#include <boost/multi_index/member.hpp>
#include <boost/multi_index/ordered_index.hpp>

namespace memory
{
		namespace boostinp = boost::interprocess;
	  namespace boostbmi = boost::multi_index;

		typedef boostinp::managed_shared_memory::allocator<char>::type  char_allocator;
    typedef boostinp::basic_string<char, std::char_traits<char>, char_allocator> shm_string;

    struct file_shm_meta{

        uint64_t     file_name_md5;
        uint8_t      status;
        void        *mapped_addr;
        uint64_t     mapped_size;
        shm_string    name;
        file_shm_meta( uint64_t file_name_md5_,
                uint8_t  status_,
                void    *mapped_addr_,
                uint64_t mapped_size_,
                shm_string  name_,
                const char_allocator& ca)
            : file_name_md5(file_name_md5_),
              status(status_),
              mapped_addr(mapped_addr_),
              mapped_size(mapped_size_),name(name_, ca)
        { }
    };

    //Tags
    struct file_name_md5 {};
    struct status {};
    struct mapped_addr {};
    struct mapped_size {};
    struct name {};

    template<typename MAPPED_FILE>
    class file_shm_base
    {

        public:
            typedef boost::shared_ptr<struct file_shm_meta> fshm_meta_str;
            virtual fshm_meta_str get_file_shm_meta(uint64_t file_name_md5)  = 0;

    };

}

#endif /* MEMORY_FILE_SHM_BASE_HPP */


text:
package com.smartfoo.android.core.platform;

public class FooIncrementingIntegerValue
{
    private int mNextMessageCode = 0;

    public int getNextMessageCode()
    {
        return mNextMessageCode++;
    }
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>haskell.data</groupId>
  <artifactId>java-iteratee</artifactId>
  <version>0.1</version>
  <packaging>jar</packaging>

  <name>jittery</name>
  <url>https://github.com/kapilash/java-iteratee</url>
  <description>
    Implements Iteratee in java to explain the concept to those born and
brought up in the java land.
  </description>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <build>
      <plugins>
          <plugin>
              <groupId>org.apache.maven.plugins</groupId>
              <artifactId>maven-compiler-plugin</artifactId>
              <version>2.3.2</version>
              <configuration>
                  <source>1.6</source>
                  <target>1.6</target>
              </configuration>
          </plugin>
      </plugins>
   </build>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.8.2</version>
    </dependency>
    <dependency>
	<groupId>jdom</groupId>
	<artifactId>jdom</artifactId>
	<version>1.1</version>
    </dependency>
  </dependencies>
</project>


text:
'use strict';
/*global global, require, process, module, ccs, _restConfig*/

var fs = require('fs'),
    path = require('path'),
    zlib = require('zlib'),
    util = require('util'),
    http = require('http'),
    domain = require('domain'),
    serverDm = domain.create(),
    processPath = path.dirname(process.argv[1]);

global.ccs = {}; // 注册全局变量ccs
module.exports.conf = require('./config/config'); // 注册rrestjs配置文件
module.exports.conf_dev = require('./config/config_dev'); // 注册开发模式配置文件

serverDm.on('error', function (err) {
    delete err.domain;
    ccs.serverlog.error(err);
});
serverDm.run(function () {
    ccs.module = {};
    ccs.module.os = require('os');
    ccs.module.xss = require('xss');
    ccs.module.then = require('thenjs');
    ccs.module.marked = require('marked');
    ccs.module.rrestjs = require('rrestjs');
    ccs.module.mongoskin = require('mongoskin');
    ccs.module.nodemailer = require('nodemailer');
    ccs.serverlog = ccs.module.rrestjs.restlog;
    ccs.conf = ccs.module.rrestjs.config;
    ccs.lib = {};
    ccs.lib.msg = require('./lib/msg.js');
    ccs.lib.json = require('./lib/json.js');
    ccs.lib.tools = require('./lib/tools.js');
    ccs.lib.email = require('./lib/email.js');
    ccs.lib.redis = require('./lib/redis.js');
    ccs.lib.CacheLRU = require('./lib/cacheLRU.js');
    ccs.lib.converter = require('./lib/anyBaseConverter.js');
    ccs.Err = ccs.lib.tools.Err;
    ccs.dao = {};
    ccs.dao.db = require('./dao/mongoDao.js').db;
    ccs.dao.tag = require('./dao/tagDao.js');
    ccs.dao.test = require('./dao/testDao.js');//dw2014
    ccs.dao.user = require('./dao/userDao.js');
    ccs.dao.index = require('./dao/indexDao.js');
    ccs.dao.article = require('./dao/articleDao.js');
    ccs.dao.message = require('./dao/messageDao.js');
    ccs.dao.collection = require('./dao/collectionDao.js');
    ccs.thenErrLog = function (defer, err) {
        ccs.serverlog.error(err);
    };

    var redis = ccs.lib.redis,
        then = ccs.module.then,
        each = ccs.lib.tools.each,
        CacheLRU = ccs.lib.CacheLRU,
        extend = ccs.lib.tools.extend,
        resJson = ccs.lib.tools.resJson,
        TimeLimitCache = ccs.lib.redis.TimeLimitCache;

    redis.connect().then(function (defer) {
        redis.initConfig(ccs.lib.json.GlobalConfig, defer); // 初始化config缓存
    }).then(function (defer, config) {
        ccs.config = config;
        if (process.argv.indexOf('install') > 0) { // 带'install'参数启动则初始化MongoDB
            require('./api/install.js')().all(defer);
        } else { // Redis config缓存未赋值,则从MongoDB取值
            ccs.dao.index.getGlobalConfig(defer);
        }
    }).then(function (defer, config) {
        each(ccs.config, function (value, key, list) {
            if (key in config) {
                list[key] = config[key]; // 写入config缓存
                //console.log( "aaaaa" + list[key]);
                //console.log( "bbbbb" + key);
            }
        });
        defer(null, ccs.config);
    }).then(function (defer, config) {
        var api = ['index', 'user', 'article', 'tag', 'collection', 'message', 'rebuild','test'];
            //console.log(ccs.config.tagCache);
            //console.log(config.listCache);
        ccs.cache = {};
        ccs.cache.test = new CacheLRU(100);//dw2014
        ccs.cache.tag = new CacheLRU(config.tagCache);
        ccs.cache.user = new CacheLRU(config.userCache);
        ccs.cache.list = new CacheLRU(config.listCache);
        ccs.cache.article = new CacheLRU(config.articleCache);
        ccs.cache.comment = new CacheLRU(config.commentCache);
        ccs.cache.message = new CacheLRU(config.messageCache);
        ccs.cache.collection = new CacheLRU(config.collectionCache);
        ccs.cache.timeInterval = new TimeLimitCache(config.TimeInterval, 'string', 'interval', false);
        ccs.cache.pagination = new TimeLimitCache(config.paginationCache, 'array', 'pagination', true);
        ccs.robotReg = new RegExp(config.robots || 'Baiduspider|Googlebot|BingBot|Slurp!', 'i');
        ccs.api = {};

        each(api, function (x) {
            ccs.api[x] = {}; // 初始化api引用,从而各api内部可提前获取其它api引用
           // console.log(ccs.api[x]);
        });
        each(api, function (x) {
            extend(ccs.api[x], require('./api/' + x + '.js')); // 扩展各api的具体方法

        });

        fs.readFile(processPath + '/package.json', 'utf8', defer); // 读取软件信息

    }).then(function (defer, data) {
        data = JSON.parse(data);
        data.nodejs = process.versions.node;
        data.rrestjs = _restConfig._version;
        ccs.config.info = data;
        redis.userCache.index.total(defer); // 读取user缓存

    }).then(function (defer, users) {
        var rebuild = ccs.api.rebuild;
        if (!users) { // user缓存为空,则判断redis缓存为空,需要初始化
            // 初始化redis缓存
            then(function (defer2) {
                rebuild.user().all(defer2);
            }).then(function (defer2) {
                rebuild.tag().all(defer2);
            }).then(function (defer2) {
                rebuild.article().all(defer);
            }).then(function (defer2) {
                    rebuild.test().all(defer);
                }).fail(defer);
        } else {
            defer();
        }

    }).then(function (defer) {
        http.createServer(function (req, res) {
            var dm = domain.create();
            function errHandler(err, res, dm) {
                delete err.domain;

                try {
                    res.on('finish', function () {
                        //ccs.dao.db.close();
                        process.nextTick(function () {
                            dm.dispose();
                        });
                    });
                    if (err.hasOwnProperty('name')) {
                        res.sendjson(resJson(err));
                    } else {
                        ccs.serverlog.error(err);
                        res.sendjson(resJson(ccs.Err(ccs.lib.msg.MAIN.requestDataErr)));
                    }
                } catch (error) {
                    delete error.domain;
                    ccs.serverlog.error(error);
                    dm.dispose();
                }
            }

            function router(req, res) {
                if (req.path[0] === 'api' && ccs.api[req.path[1]]) {
                   // console.log("ffff"+req.path[0]+req.path[1]);
                    ccs.api[req.path[1]][req.method.toUpperCase()](req, res); // 处理api请求
                } else if (req.path[0].toLowerCase() === 'sitemap.xml') {
                    ccs.api.article.sitemap(req, res); // 响应搜索引擎sitemap,动态生成
                } else if (req.path[0].slice(-3).toLowerCase() === 'txt') {
                    // 直接响应static目录的txt文件,如robots.txt
                    then(function (defer) {
                        fs.readFile(processPath + ccs.conf.staticFolder + req.path[0], 'utf8', defer);
                    }).then(function (defer, txt) {
                        res.setHeader('Content-Type', 'text/plain');
                        res.send(txt);
                    }).fail(res.throwError);
                } else if (ccs.robotReg.test(req.useragent)) {
                    ccs.api.article.robot(req, res); // 处理搜索引擎请求
                } else {
                    ccs.config.visitors = 1; // 访问次数+1
                    res.setHeader('Content-Type', 'text/html');
                    if (ccs.cache.indexTpl) {
                        res.send(ccs.cache.indexTpl); // 响应首页index.html
                    } else {
                        then(function (defer) {
                            fs.readFile(processPath + ccs.conf.staticFolder + '/index.html', 'utf8', defer);
                        }).then(function (defer, tpl) {
                            ccs.cache.indexTpl = tpl;
                            res.send(ccs.cache.indexTpl);
                        }).fail(res.throwError);
                    }
                }
            }

            res.throwError = function (defer, err) { // 处理then.js捕捉的错误
                if (!util.isError(err)) {
                    err = ccs.Err(err);
                }
                errHandler(err, res, dm);
            };
            dm.on('error', function (err) { // 处理domain捕捉的错误
                errHandler(err, res, dm);
            });
            dm.run(function () {
                router(req, res); // 运行
            });
        }).listen(ccs.conf.listenPort);
        console.log('ccs start at ' + ccs.conf.listenPort);
    }).fail(function (defer, err) {
        throw err;
    });
});


text:
// RobotBuilder Version: 2.0
//
// This file was generated by RobotBuilder. It contains sections of
// code that are automatically generated and assigned by robotbuilder.
// These sections will be updated in the future when you export to
// Java from RobotBuilder. Do not put any code or make any change in
// the blocks indicating autogenerated code or it will be lost on an
// update. Deleting the comments indicating the section will prevent
// it from being updated in the future.

package org.usfirst.frc4579.Robot2017.commands;

import org.usfirst.frc4579.Robot2017.Robot;
import org.usfirst.frc4579.instrumentation.EventLogging;

import edu.wpi.first.wpilibj.command.Command;
import edu.wpi.first.wpilibj.Timer;

/**
 *
 */
public class AutonomousCommand extends Command {

    // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=VARIABLE_DECLARATIONS
	// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=VARIABLE_DECLARATIONS
	public Timer timer = new Timer();
	public String robotPosition;
	public double distanceTime = 0;
    // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTOR
    public AutonomousCommand() {
    // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTOR
    	requires(Robot.switches);
    	requires(Robot.driveTrain);
        // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=VARIABLE_SETTING

        // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=VARIABLE_SETTING
        // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=REQUIRES

    // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=REQUIRES
    }

    // Called just before this Command runs the first time
    protected void initialize() {
    	robotPosition = Robot.switches.getMode();
    	System.out.println("AUTOCOMM IS: "+ robotPosition);
    	timer.start();
    	if (robotPosition == "center") {

    		distanceTime = 2.8;
    	} else {
    		distanceTime = 2.8;
    	}
    }

    // Called repeatedly when this Command is scheduled to run
    protected void execute() {
    	if (robotPosition != "null") {
    		EventLogging.logNormalEvent(EventLogging.NORMALEVENTS.START_EXECUTE_COMMAND, "Autonomous");

        	// Update IMU data.
        	Robot.meas.measure();

        	// Add Autonoumous code here.
        	Robot.driveTrain.driveStraight(0.4);

        	EventLogging.logNormalEvent(EventLogging.NORMALEVENTS.END_EXECUTE_COMMAND, "Autonomous");
    	}
    }

    // Make this return true when this Command no longer needs to run execute()
    protected boolean isFinished() {
    	if (timer.get() >= distanceTime || robotPosition == "null") {
    		return true;
    	}
        return false;
    }

    // Called once after isFinished returns true
    protected void end() {
    	Robot.driveTrain.stop();
    	timer.stop();
    }

    // Called when another command which requires one or more of the same
    // subsystems is scheduled to run
    protected void interrupted() {
    	end();
    }
}


text:
package org.apache.pig.piggybank.test.evaluation;

import java.io.File;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.Properties;
import java.util.LinkedList;
import java.util.List;

import junit.framework.TestCase;

import org.junit.Test;

import org.apache.pig.data.Tuple;
import org.apache.pig.data.DefaultTupleFactory;
import org.apache.pig.impl.logicalLayer.schema.Schema;

import org.apache.pig.piggybank.evaluation.string.*;

// This class tests all string eval functions.

public class TestEvalString extends TestCase {

    @Test
    public void testUPPER() throws Exception {
        UPPER func = new UPPER();

        // test excution
        String in = "Hello World!";
        String expected = "HELLO WORLD!";

        Tuple input = DefaultTupleFactory.getInstance().newTuple(in);

        String output = func.exec(input);
        assertTrue(output.equals(expected));

        String in2 = null;
        Tuple input2 = DefaultTupleFactory.getInstance().newTuple(in2);
        assertEquals("upper null value",null, func.exec(input2));

        // test schema creation

        // FIXME
        //Schema outSchema = func.outputSchema(tupleSchema);
        //assertTrue(outSchema.toString().equals("upper_" + fieldName));

    }

    @Test
    public void testLOWER() throws Exception {
        LOWER func = new LOWER();

        // test excution
        String in = "Hello World!";
        String expected = "hello world!";

        Tuple input = DefaultTupleFactory.getInstance().newTuple(in);

        String output = func.exec(input);
        assertTrue(output.equals(expected));
    }

    @Test
    public void testINDEXOF() throws Exception {
        INDEXOF func = new INDEXOF();

        // test excution
        List l = new LinkedList();
        l.add("Hello World!");
        l.add("o");

        Tuple input = DefaultTupleFactory.getInstance().newTuple(l);

        Integer output = func.exec(input);
        assertTrue(output.intValue()==4);
    }

    @Test
    public void testLASTINDEXOF() throws Exception {
        LASTINDEXOF func = new LASTINDEXOF();

        // test excution
        List l = new LinkedList();
        l.add("Hello World!");
        l.add("o");

        Tuple input = DefaultTupleFactory.getInstance().newTuple(l);

        Integer output = func.exec(input);
        assertTrue(output.intValue()==7);
    }

    @Test
    public void testREPLACE() throws Exception {
        REPLACE func = new REPLACE();

        // test excution
        List l = new LinkedList();
        l.add("Hello World!");
        l.add("o");
        l.add("a");
        String expected = "Hella Warld!";

        Tuple input = DefaultTupleFactory.getInstance().newTuple(l);

        String output = func.exec(input);
        assertTrue(output.equals(expected));
    }

    @Test
    public void testSUBSTRING() throws Exception {
        SUBSTRING func = new SUBSTRING();

        // test excution
        List l = new LinkedList();
        l.add("Hello World!");
        l.add(1);
        l.add(5);
        String expected = "ello";

        Tuple input = DefaultTupleFactory.getInstance().newTuple(l);

        String output = func.exec(input);
        assertTrue(output.equals(expected));
    }

}


text:
package br.gov.siscomex.portalunico.rcnt.model;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

import com.fasterxml.jackson.annotation.JsonProperty;

import io.swagger.annotations.ApiModelProperty;

@XmlAccessorType(XmlAccessType.FIELD)
 @XmlType(name = "DadosDaCoordenadaDeAlerta", propOrder =
    { "idElemento", "x", "y", "x2", "y2"
})

@XmlRootElement(name="DadosDaCoordenadaDeAlerta")
public class DadosDaCoordenadaDeAlerta  {

  @XmlElement(name="idElemento")
  @ApiModelProperty(value = "Identificação de cada elemento da lista.
Tamanho: 40")
 /**
   * Identificação de cada elemento da lista.
Tamanho: 40
  **/
  private String idElemento = null;

  @XmlElement(name="x")
  @ApiModelProperty(example = "12", value = "Coordenada para marcar o alerta na posição X")
 /**
   * Coordenada para marcar o alerta na posição X
  **/
  private Integer x = null;

  @XmlElement(name="y")
  @ApiModelProperty(example = "7", value = "Coordenada para marcar o alerta na posição Y")
 /**
   * Coordenada para marcar o alerta na posição Y
  **/
  private Integer y = null;

  @XmlElement(name="x2")
  @ApiModelProperty(example = "0", value = "Coordenada para marcar o alerta na posição X2")
 /**
   * Coordenada para marcar o alerta na posição X2
  **/
  private Integer x2 = null;

  @XmlElement(name="y2")
  @ApiModelProperty(example = "8", value = "Coordenada para marcar o alerta na posição Y2")
 /**
   * Coordenada para marcar o alerta na posição Y2
  **/
  private Integer y2 = null;
 /**
   * Identificação de cada elemento da lista.<br/>Tamanho: 40
   * @return idElemento
  **/
  @JsonProperty("idElemento")
  public String getIdElemento() {
    return idElemento;
  }

  public void setIdElemento(String idElemento) {
    this.idElemento = idElemento;
  }

  public DadosDaCoordenadaDeAlerta idElemento(String idElemento) {
    this.idElemento = idElemento;
    return this;
  }

 /**
   * Coordenada para marcar o alerta na posição X
   * @return x
  **/
  @JsonProperty("x")
  public Integer getX() {
    return x;
  }

  public void setX(Integer x) {
    this.x = x;
  }

  public DadosDaCoordenadaDeAlerta x(Integer x) {
    this.x = x;
    return this;
  }

 /**
   * Coordenada para marcar o alerta na posição Y
   * @return y
  **/
  @JsonProperty("y")
  public Integer getY() {
    return y;
  }

  public void setY(Integer y) {
    this.y = y;
  }

  public DadosDaCoordenadaDeAlerta y(Integer y) {
    this.y = y;
    return this;
  }

 /**
   * Coordenada para marcar o alerta na posição X2
   * @return x2
  **/
  @JsonProperty("x2")
  public Integer getX2() {
    return x2;
  }

  public void setX2(Integer x2) {
    this.x2 = x2;
  }

  public DadosDaCoordenadaDeAlerta x2(Integer x2) {
    this.x2 = x2;
    return this;
  }

 /**
   * Coordenada para marcar o alerta na posição Y2
   * @return y2
  **/
  @JsonProperty("y2")
  public Integer getY2() {
    return y2;
  }

  public void setY2(Integer y2) {
    this.y2 = y2;
  }

  public DadosDaCoordenadaDeAlerta y2(Integer y2) {
    this.y2 = y2;
    return this;
  }

  @Override
  public String toString() {
    StringBuilder sb = new StringBuilder();
    sb.append("class DadosDaCoordenadaDeAlerta {\n");

    sb.append("    idElemento: ").append(toIndentedString(idElemento)).append("\n");
    sb.append("    x: ").append(toIndentedString(x)).append("\n");
    sb.append("    y: ").append(toIndentedString(y)).append("\n");
    sb.append("    x2: ").append(toIndentedString(x2)).append("\n");
    sb.append("    y2: ").append(toIndentedString(y2)).append("\n");
    sb.append("}");
    return sb.toString();
  }

  /**
   * Convert the given object to string with each line indented by 4 spaces
   * (except the first line).
   */
  private static String toIndentedString(java.lang.Object o) {
    if (o == null) {
      return "null";
    }
    return o.toString().replace("\n", "\n    ");
  }
}


text:
<!DOCTYPE html>

	<meta charset="UTF-8">
	<title>message</title>

	<input type="text">
	<input type="button" value="take a message">
	<input type="button" value="delete">


text:
package com.bstek.uflo.service;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.XmlAdapter;

public class MapAdapter<K, V> extends XmlAdapter<MapAdapter.Adapter<K, V>, Map<K, V>> {

	@Override
	public Map<K, V> unmarshal(Adapter<K, V> v) throws Exception {
		if (v == null) {
			return null;
		}
		Map<K, V> map = new HashMap<K, V>();
		for (MyEntry<K, V> mapEntryType : v.getEntries()) {
			map.put(rUnmarshal(mapEntryType.getKey()), rUnmarshal(mapEntryType.getValue()));
		}
		return map;
	}

	@Override
	public Adapter<K, V> marshal(Map<K, V> v) throws Exception {
		if (v == null) {
			return null;
		}
		return new Adapter<K, V>(v);
	}

	@SuppressWarnings("unchecked")
	private static <T> T rUnmarshal(T obj) throws Exception {
		if (obj instanceof Adapter) {
			return (T) new MapAdapter<Object, Object>().unmarshal((Adapter<Object, Object>) obj);
		}
		return obj;
	}

	@SuppressWarnings("unchecked")
	static <T> T rMarshal(T obj) throws Exception {
		if (obj instanceof Map) {
			return (T) new MapAdapter<Object, Object>().marshal((Map<Object, Object>) obj);
		}
		return obj;
	}

	@XmlType
	@XmlRootElement
	public final static class Adapter<K, V> {

		@XmlElement
		protected List<MyEntry<K, V>> fEntries = new LinkedList<MyEntry<K, V>>();

		// needed for JAXB
		@SuppressWarnings("unused")
		private Adapter() {
		}

		public Adapter(Map<K, V> original) throws Exception {
			for (Map.Entry<K, V> entry : original.entrySet()) {
				this.fEntries.add(new MyEntry<K, V>(entry));
			}
		}

		public List<MyEntry<K, V>> getEntries() {
			return this.fEntries;
		}

	}

	@XmlType
	@XmlRootElement
	public final static class MyEntry<K, V> {

		@XmlElement
		protected K fKey;

		@XmlElement
		protected V fValue;

		// needed for JAXB
		@SuppressWarnings("unused")
		private MyEntry() {
		}

		public MyEntry(Map.Entry<K, V> original) throws Exception {
			this.fKey = rMarshal(original.getKey());
			this.fValue = rMarshal(original.getValue());
		}

		public K getKey() {
			return this.fKey;
		}

		public V getValue() {
			return this.fValue;
		}

	}

}


text:
import AbstractLevelStrategy from './abstractLevelStrategy';
import TabNames from '../enums/tabNames';

export default class NestedLevelStrategy extends AbstractLevelStrategy {
    getTabs() {
        return [
            TabNames.overview,
            TabNames.pois,
            TabNames.hotels
        ];
    }
}


text:
""" --- Day 19: Medicine for Rudolph ---

Rudolph the Red-Nosed Reindeer is sick!
His nose isn't shining very brightly, and he needs medicine.

Red-Nosed Reindeer biology isn't similar to regular reindeer biology;
Rudolph is going to need custom-made medicine.
Unfortunately, Red-Nosed Reindeer chemistry isn't similar
to regular reindeer chemistry, either.

The North Pole is equipped with a Red-Nosed Reindeer
nuclear fusion/fission plant, capable of constructing any Red-Nosed Reindeer
molecule you need. It works by starting with some input molecule
and then doing a series of replacements, one per step,
until it has the right molecule.

However, the machine has to be calibrated before it can be used.
Calibration involves determining the number of molecules that can be
generated in one step from a given starting point.

For example, imagine a simpler machine that supports
only the following replacements:

H => HO
H => OH
O => HH

Given the replacements above and starting with HOH,
the following molecules could be generated:

HOOH (via H => HO on the first H).
HOHO (via H => HO on the second H).
OHOH (via H => OH on the first H).
HOOH (via H => OH on the second H).
HHHH (via O => HH).

So, in the example above, there are 4 distinct molecules
(not five, because HOOH appears twice) after one replacement from HOH.

Santa's favorite molecule, HOHOHO, can become 7 distinct molecules
(over nine replacements: six from H, and three from O).

The machine replaces without regard for the surrounding characters.
For example, given the string H2O, the transition
H => OO would result in OO2O.

Your puzzle input describes all of the possible replacements and,
at the bottom,the medicine molecule for which you need to calibrate
the machine. How many distinct molecules can be created after all the
different ways you can do one replacement on the medicine molecule?

--- Part Two ---

Now that the machine is calibrated,
you're ready to begin molecule fabrication.

Molecule fabrication always begins with just a single electron, e,
and applying replacements one at a time, just like the ones during calibration.

For example, suppose you have the following replacements:

e => H
e => O
H => HO
H => OH
O => HH

If you'd like to make HOH, you start with e,
and then make the following replacements:

e => O to get O
O => HH to get HH
H => OH (on the second H) to get HOH

So, you could make HOH after 3 steps.
Santa's favorite molecule, HOHOHO, can be made in 6 steps.

How long will it take to make the medicine?
Given the available replacements
and the medicine molecule in your puzzle input,
what is the fewest number of steps to go from e to the medicine molecule? """

# LOGIC
# Greedy approach
# Substitute the largest substitution first,
# then continue with largest substitutions in order,
# until we reach a string

# FOR SOME REASON, THE OUTPUT FLUCTUTATES
# BETWEEN TWO VALUES THAT SEEM TO NO STABILIZE

# read input
with open('./input.txt', 'r') as f:
    text = f.readlines()

# parsed substitution as tuples of form:
# (target_string, substitution)
substitutions = {}

# parse input to get substitutions
# stop at empty line
import re
pattern = re.compile(r'(\w+) => (\w+)')
for line in text:
    if len(line.strip()) == 0:
        break
    target, sub = pattern.match(line).groups()
    substitutions[sub] = target

# add string to be changed
target_string = text[-1]
target_string = target_string.strip()

# sort the substitutions by size
# this is useful to replace the biggest strings first
substitutions_by_size = sorted(substitutions.keys(), key=len, reverse=True)

def replace(string):

    if string == 'e':
        # nothing more to replace
        return 1

    # get all applicable substitutions,
    # and then get only the first one using next
    # this is the applicable substitution because it's the largest
    try:
        substitution = next(s for s in substitutions_by_size if s in string)
    except StopIteration:
        return 1

    # replace the substitution by its molecule
    # and replace only the first occurence
    # pass this string to the replace function
    # get the number of iterations
    iterations = replace(
        string.replace(
            substitution, substitutions[substitution], 1))

    # return this + other iterations
    return 1 + iterations

print(replace(target_string))


text:
<!DOCTYPE html>

        <meta name="viewport" content="width=device-width" />
        <title>TeamCity Builds</title>
		<link href="content/style.css" rel="stylesheet" />


text:
"""Support for XS1 switches."""
from __future__ import annotations

from typing import Any

from xs1_api_client.api_constants import ActuatorType

from homeassistant.components.switch import SwitchEntity
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType

from . import ACTUATORS, DOMAIN as COMPONENT_DOMAIN, XS1DeviceEntity

def setup_platform(
    hass: HomeAssistant,
    config: ConfigType,
    add_entities: AddEntitiesCallback,
    discovery_info: DiscoveryInfoType | None = None,
) -> None:
    """Set up the XS1 switch platform."""
    actuators = hass.data[COMPONENT_DOMAIN][ACTUATORS]

    switch_entities = []
    for actuator in actuators:
        if (actuator.type() == ActuatorType.SWITCH) or (
            actuator.type() == ActuatorType.DIMMER
        ):
            switch_entities.append(XS1SwitchEntity(actuator))

    add_entities(switch_entities)

class XS1SwitchEntity(XS1DeviceEntity, SwitchEntity):
    """Representation of a XS1 switch actuator."""

    @property
    def name(self):
        """Return the name of the device if any."""
        return self.device.name()

    @property
    def is_on(self):
        """Return true if switch is on."""
        return self.device.value() == 100

    def turn_on(self, **kwargs: Any) -> None:
        """Turn the device on."""
        self.device.turn_on()

    def turn_off(self, **kwargs: Any) -> None:
        """Turn the device off."""
        self.device.turn_off()


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <bool name="fitsSystemWindowForHeader">false</bool>
</resources>


text:
.class public Lcom/mixpanel/android/mpmetrics/Survey;
.super Ljava/lang/Object;
.source ""

# annotations
.annotation system Ldalvik/annotation/MemberClasses;
    value = {
        Lcom/mixpanel/android/mpmetrics/Survey$1;,
        Lcom/mixpanel/android/mpmetrics/Survey$Question;,
        Lcom/mixpanel/android/mpmetrics/Survey$QuestionType;,
        Lcom/mixpanel/android/mpmetrics/Survey$BadSurveyException;
    }
.end annotation

# instance fields
.field private final mCollectionId:I

.field private final mDescription:Lorg/json/JSONObject;

.field private final mId:I

.field private final mQuestions:Ljava/util/List;
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "Ljava/util/List<Lcom/mixpanel/android/mpmetrics/Survey$Question;>;"
        }
    .end annotation
.end field

# direct methods
.method constructor <init>(Lorg/json/JSONObject;)V
    .locals 5

    .line 45
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    .line 47
    :try_start_0
    iput-object p1, p0, Lcom/mixpanel/android/mpmetrics/Survey;->mDescription:Lorg/json/JSONObject;

    .line 48
    const-string v0, "id"

    invoke-virtual {p1, v0}, Lorg/json/JSONObject;->getInt(Ljava/lang/String;)I

    move-result v0

    iput v0, p0, Lcom/mixpanel/android/mpmetrics/Survey;->mId:I

    .line 49
    const-string v0, "collections"

    invoke-virtual {p1, v0}, Lorg/json/JSONObject;->getJSONArray(Ljava/lang/String;)Lorg/json/JSONArray;

    move-result-object v0

    .line 50
    const/4 v1, 0x0

    invoke-virtual {v0, v1}, Lorg/json/JSONArray;->getJSONObject(I)Lorg/json/JSONObject;

    move-result-object v2

    .line 51
    const-string v0, "id"

    invoke-virtual {v2, v0}, Lorg/json/JSONObject;->getInt(Ljava/lang/String;)I

    move-result v0

    iput v0, p0, Lcom/mixpanel/android/mpmetrics/Survey;->mCollectionId:I

    .line 53
    const-string v0, "questions"

    invoke-virtual {p1, v0}, Lorg/json/JSONObject;->getJSONArray(Ljava/lang/String;)Lorg/json/JSONArray;

    move-result-object v0

    .line 54
    move-object p1, v0

    invoke-virtual {v0}, Lorg/json/JSONArray;->length()I

    move-result v0

    if-nez v0, :cond_0

    .line 55
    new-instance v0, Lcom/mixpanel/android/mpmetrics/Survey$BadSurveyException;

    const-string v1, "Survey has no questions."

    invoke-direct {v0, v1}, Lcom/mixpanel/android/mpmetrics/Survey$BadSurveyException;-><init>(Ljava/lang/String;)V

    throw v0

    .line 57
    :cond_0
    new-instance v2, Ljava/util/ArrayList;

    invoke-virtual {p1}, Lorg/json/JSONArray;->length()I

    move-result v0

    invoke-direct {v2, v0}, Ljava/util/ArrayList;-><init>(I)V

    .line 58
    const/4 v3, 0x0

    :goto_0
    invoke-virtual {p1}, Lorg/json/JSONArray;->length()I

    move-result v0

    if-ge v3, v0, :cond_1

    .line 59
    invoke-virtual {p1, v3}, Lorg/json/JSONArray;->getJSONObject(I)Lorg/json/JSONObject;

    move-result-object v4

    .line 60
    new-instance v0, Lcom/mixpanel/android/mpmetrics/Survey$Question;

    const/4 v1, 0x0

    invoke-direct {v0, p0, v4, v1}, Lcom/mixpanel/android/mpmetrics/Survey$Question;-><init>(Lcom/mixpanel/android/mpmetrics/Survey;Lorg/json/JSONObject;Lcom/mixpanel/android/mpmetrics/Survey$1;)V

    invoke-interface {v2, v0}, Ljava/util/List;->add(Ljava/lang/Object;)Z

    .line 58
    add-int/lit8 v3, v3, 0x1

    goto :goto_0

    .line 62
    :cond_1
    invoke-static {v2}, Ljava/util/Collections;->unmodifiableList(Ljava/util/List;)Ljava/util/List;

    move-result-object v0

    iput-object v0, p0, Lcom/mixpanel/android/mpmetrics/Survey;->mQuestions:Ljava/util/List;
    :try_end_0
    .catch Lorg/json/JSONException; {:try_start_0 .. :try_end_0} :catch_0

    .line 65
    return-void

    .line 63
    :catch_0
    move-exception v2

    .line 64
    new-instance v0, Lcom/mixpanel/android/mpmetrics/Survey$BadSurveyException;

    const-string v1, "Survey JSON was unexpected or bad"

    invoke-direct {v0, v1, v2}, Lcom/mixpanel/android/mpmetrics/Survey$BadSurveyException;-><init>(Ljava/lang/String;Ljava/lang/Throwable;)V

    throw v0
.end method

# virtual methods
.method public getCollectionId()I
    .locals 1

    .line 77
    iget v0, p0, Lcom/mixpanel/android/mpmetrics/Survey;->mCollectionId:I

    return v0
.end method

.method public getId()I
    .locals 1

    .line 73
    iget v0, p0, Lcom/mixpanel/android/mpmetrics/Survey;->mId:I

    return v0
.end method

.method public getQuestions()Ljava/util/List;
    .locals 1
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "()Ljava/util/List<Lcom/mixpanel/android/mpmetrics/Survey$Question;>;"
        }
    .end annotation

    .line 81
    iget-object v0, p0, Lcom/mixpanel/android/mpmetrics/Survey;->mQuestions:Ljava/util/List;

    return-object v0
.end method

.method toJSON()Ljava/lang/String;
    .locals 1

    .line 69
    iget-object v0, p0, Lcom/mixpanel/android/mpmetrics/Survey;->mDescription:Lorg/json/JSONObject;

    invoke-virtual {v0}, Lorg/json/JSONObject;->toString()Ljava/lang/String;

    move-result-object v0

    return-object v0
.end method