text:
![Logo](websocket-sharp_logo.png)

## Welcome to websocket-sharp! ##

**websocket-sharp** supports:

- **[RFC 6455](#supported-websocket-specifications)**
- **[WebSocket Client](#websocket-client)** and **[Server](#websocket-server)**
- **[Per-message Compression](#per-message-compression)** extension
- **[Secure Connection](#secure-connection)**
- **[HTTP Authentication](#http-authentication)**
- **[Query String, Origin header and Cookies](#query-string-origin-header-and-cookies)**
- **[Connecting through the HTTP Proxy server](#connecting-through-the-http-proxy-server)**
- .NET **3.5** or later (includes compatible)

## Branches ##

- **[master]** for production releases.
- **[hybi-00]** for older [draft-ietf-hybi-thewebsocketprotocol-00]. No longer maintained.
- **[draft75]** for even more old [draft-hixie-thewebsocketprotocol-75]. No longer maintained.

## Build ##

websocket-sharp is built as a single assembly, **websocket-sharp.dll**.

websocket-sharp is developed with **[MonoDevelop]**. So the simple way to build is to open **websocket-sharp.sln** and run build for **websocket-sharp project** with any of the build configurations (e.g. `Debug`) in MonoDevelop.

## Install ##

### Self Build ###

You should add your **websocket-sharp.dll** (e.g. `/path/to/websocket-sharp/bin/Debug/websocket-sharp.dll`) to the library references of your project.

If you would like to use that dll in your **[Unity]** project, you should add it to any folder of your project (e.g. `Assets/Plugins`) in **Unity Editor**.

### NuGet Gallery ###

websocket-sharp is available on the **[NuGet Gallery]**, as still a **prerelease** version.

- **[NuGet Gallery: websocket-sharp]**

You can add websocket-sharp to your project with the **NuGet Package Manager**, by using the following command in the **Package Manager Console**.

    PM> Install-Package WebSocketSharp -Pre

### Unity Asset Store ###

websocket-sharp is available on the **Unity Asset Store**.

- **[WebSocket-Sharp for Unity]**

It works with **Unity Free**, but there are some limitations:

- **[Security Sandbox of the Webplayer]** (the server doesn't work in the webplayer)
- **[.NET Socket Support for iOS/Android][Unity Licenses Comparison]** (requires iOS/Android Pro)
- **Limited support for the System.IO.Compression** (the compression extension isn't available on Windows)
- **.NET API 2.0 compatibility level for iOS/Android**

Using **.NET API 2.0 compatibility level for iOS/Android** requires to fix lack of some features for later than .NET 2.0, such as the `System.Func<...>` delegates (so i've fixed it in the asset package).

And it's priced at **US$15**. I think your $15 makes this project more better and accelerated, **Thank you!**

## Usage ##

### WebSocket Client ###

```csharp
using System;
using WebSocketSharp;

namespace Example
{
  public class Program
  {
    public static void Main (string[] args)
    {
      using (var ws = new WebSocket ("ws://dragonsnest.far/Laputa")) {
        ws.OnMessage += (sender, e) =>
          Console.WriteLine ("Laputa says: " + e.Data);

        ws.Connect ();
        ws.Send ("BALUS");
        Console.ReadKey (true);
      }
    }
  }
}
```

#### Step 1 ####

Required namespace.

```csharp
using WebSocketSharp;
```

The `WebSocket` class exists in the `WebSocketSharp` namespace.

#### Step 2 ####

Creating a new instance of the `WebSocket` class with the WebSocket URL to connect.

```csharp
using (var ws = new WebSocket ("ws://example.com")) {
  ...
}
```

The `WebSocket` class inherits the `System.IDisposable` interface, so you can use the `using` statement. And the WebSocket connection will be closed with close status `1001` (going away) when the control leaves the `using` block.

#### Step 3 ####

Setting the `WebSocket` events.

##### WebSocket.OnOpen Event #####

A `WebSocket.OnOpen` event occurs when the WebSocket connection has been established.

```csharp
ws.OnOpen += (sender, e) => {
  ...
};
```

`e` has passed as the `System.EventArgs.Empty`, so you don't need to use it.

##### WebSocket.OnMessage Event #####

A `WebSocket.OnMessage` event occurs when the `WebSocket` receives a message.

```csharp
ws.OnMessage += (sender, e) => {
  ...
};
```

`e` has passed as a `WebSocketSharp.MessageEventArgs`.

`e.Type` property returns either `WebSocketSharp.Opcode.Text` or `WebSocketSharp.Opcode.Binary` that represents the type of the message. So by checking it, you can determine which item you should use.

If it returns `Opcode.Text`, you should use `e.Data` property that returns a `string` (represents the **Text** message).

Or if it returns `Opcode.Binary`, you should use `e.RawData` property that returns a `byte[]` (represents the **Binary** message).

```csharp
if (e.Type == Opcode.Text) {
  // Do something with e.Data.
  ...

  return;
}

if (e.Type == Opcode.Binary) {
  // Do something with e.RawData.
  ...

  return;
}
```

##### WebSocket.OnError Event #####

A `WebSocket.OnError` event occurs when the `WebSocket` gets an error.

```csharp
ws.OnError += (sender, e) => {
  ...
};
```

`e` has passed as a `WebSocketSharp.ErrorEventArgs`.

`e.Message` property returns a `string` that represents the error message.

If the error is due to an exception, `e.Exception` property returns a `System.Exception` instance that caused the error.

##### WebSocket.OnClose Event #####

A `WebSocket.OnClose` event occurs when the WebSocket connection has been closed.

```csharp
ws.OnClose += (sender, e) => {
  ...
};
```

`e` has passed as a `WebSocketSharp.CloseEventArgs`.

`e.Code` property returns a `ushort` that represents the status code indicating the reason for the close, and `e.Reason` property returns a `string` that represents the reason for the close.

#### Step 4 ####

Connecting to the WebSocket server.

```csharp
ws.Connect ();
```

If you would like to connect to the server asynchronously, you should use the `WebSocket.ConnectAsync ()` method.

#### Step 5 ####

Sending data to the WebSocket server.

```csharp
ws.Send (data);
```

The `WebSocket.Send` method is overloaded.

You can use the `WebSocket.Send (string)`, `WebSocket.Send (byte[])`, or `WebSocket.Send (System.IO.FileInfo)` method to send the data.

If you would like to send the data asynchronously, you should use the `WebSocket.SendAsync` method.

```csharp
ws.SendAsync (data, completed);
```

And also if you would like to do something when the send is complete, you should set `completed` to any `Action<bool>` delegate.

#### Step 6 ####

Closing the WebSocket connection.

```csharp
ws.Close (code, reason);
```

If you would like to close the connection explicitly, you should use the `WebSocket.Close` method.

The `WebSocket.Close` method is overloaded.

You can use the `WebSocket.Close ()`, `WebSocket.Close (ushort)`, `WebSocket.Close (WebSocketSharp.CloseStatusCode)`, `WebSocket.Close (ushort, string)`, or `WebSocket.Close (WebSocketSharp.CloseStatusCode, string)` method to close the connection.

If you would like to close the connection asynchronously, you should use the `WebSocket.CloseAsync` method.

### WebSocket Server ###

```csharp
using System;
using WebSocketSharp;
using WebSocketSharp.Server;

namespace Example
{
  public class Laputa : WebSocketBehavior
  {
    protected override void OnMessage (MessageEventArgs e)
    {
      var msg = e.Data == "BALUS"
                ? "I've been balused already..."
                : "I'm not available now.";

      Send (msg);
    }
  }

  public class Program
  {
    public static void Main (string[] args)
    {
      var wssv = new WebSocketServer ("ws://dragonsnest.far");
      wssv.AddWebSocketService<Laputa> ("/Laputa");
      wssv.Start ();
      Console.ReadKey (true);
      wssv.Stop ();
    }
  }
}
```

#### Step 1 ####

Required namespace.

```csharp
using WebSocketSharp.Server;
```

The `WebSocketBehavior` and `WebSocketServer` classes exist in the `WebSocketSharp.Server` namespace.

#### Step 2 ####

Creating the class that inherits the `WebSocketBehavior` class.

For example, if you would like to provide an echo service,

```csharp
using System;
using WebSocketSharp;
using WebSocketSharp.Server;

public class Echo : WebSocketBehavior
{
  protected override void OnMessage (MessageEventArgs e)
  {
    Send (e.Data);
  }
}
```

And if you would like to provide a chat service,

```csharp
using System;
using WebSocketSharp;
using WebSocketSharp.Server;

public class Chat : WebSocketBehavior
{
  private string _suffix;

  public Chat ()
    : this (null)
  {
  }

  public Chat (string suffix)
  {
    _suffix = suffix ?? String.Empty;
  }

  protected override void OnMessage (MessageEventArgs e)
  {
    Sessions.Broadcast (e.Data + _suffix);
  }
}
```

You can define the behavior of any WebSocket service by creating the class that inherits the `WebSocketBehavior` class.

If you override the `WebSocketBehavior.OnMessage (MessageEventArgs)` method, it's called when the `WebSocket` used in a session in the service receives a message.

And if you override the `WebSocketBehavior.OnOpen ()`, `WebSocketBehavior.OnError (ErrorEventArgs)`, and `WebSocketBehavior.OnClose (CloseEventArgs)` methods, each of them is called when each event of the `WebSocket` (the `OnOpen`, `OnError`, and `OnClose` events) occurs.

The `WebSocketBehavior.Send` method sends data to the client on a session in the service.

If you would like to access the sessions in the service, you should use the `WebSocketBehavior.Sessions` property (returns a `WebSocketSharp.Server.WebSocketSessionManager`).

The `WebSocketBehavior.Sessions.Broadcast` method sends data to every client in the service.

#### Step 3 ####

Creating a new instance of the `WebSocketServer` class.

```csharp
var wssv = new WebSocketServer (4649);
wssv.AddWebSocketService<Echo> ("/Echo");
wssv.AddWebSocketService<Chat> ("/Chat");
wssv.AddWebSocketService<Chat> ("/ChatWithNyan", () => new Chat (" Nyan!"));
```

You can add any WebSocket service to your `WebSocketServer` with the specified behavior and path to the service, by using the `WebSocketServer.AddWebSocketService<TBehaviorWithNew> (string)` or `WebSocketServer.AddWebSocketService<TBehavior> (string, Func<TBehavior>)` method.

The type of `TBehaviorWithNew` must inherit the `WebSocketBehavior` class, and must have a public parameterless constructor.

And also the type of `TBehavior` must inherit the `WebSocketBehavior` class.

So you can use the classes created in **Step 2** to add the service.

If you create a instance of the `WebSocketServer` class without a port number, the `WebSocketServer` class set the port number to **80** automatically. So it's necessary to run with root permission.

    $ sudo mono example2.exe

#### Step 4 ####

Starting the WebSocket server.

```csharp
wssv.Start ();
```

#### Step 5 ####

Stopping the WebSocket server.

```csharp
wssv.Stop (code, reason);
```

The `WebSocketServer.Stop` method is overloaded.

You can use the `WebSocketServer.Stop ()`, `WebSocketServer.Stop (ushort, string)`, or `WebSocketServer.Stop (WebSocketSharp.CloseStatusCode, string)` method to stop the server.

### HTTP Server with the WebSocket ###

I modified the `System.Net.HttpListener`, `System.Net.HttpListenerContext`, and some other classes of **[Mono]** to create the HTTP server that allows to accept the WebSocket connection requests.

So websocket-sharp provides the `WebSocketSharp.Server.HttpServer` class.

You can add any WebSocket service to your `HttpServer` with the specified behavior and path to the service, by using the `HttpServer.AddWebSocketService<TBehaviorWithNew> (string)` or `HttpServer.AddWebSocketService<TBehavior> (string, Func<TBehavior>)` method.

```csharp
var httpsv = new HttpServer (4649);
httpsv.AddWebSocketService<Echo> ("/Echo");
httpsv.AddWebSocketService<Chat> ("/Chat");
httpsv.AddWebSocketService<Chat> ("/ChatWithNyan", () => new Chat (" Nyan!"));
```

For more information, would you see **[Example3]**?

### WebSocket Extensions ###

#### Per-message Compression ####

websocket-sharp supports the **[Per-message Compression][compression]** extension. (But this doesn't support it with the [context take over].)

If you would like to enable this extension as a WebSocket client, you should set such as the following.

```csharp
ws.Compression = CompressionMethod.Deflate;
```

And then your client will send the following header with the connection request to the server.

    Sec-WebSocket-Extensions: permessage-deflate; server_no_context_takeover; client_no_context_takeover

If the server accepts this extension, it will return the same header which has the corresponding value. And when your client receives it, this extension will be available.

### Secure Connection ###

websocket-sharp supports the **Secure Connection** with **SSL/TLS**.

As a **WebSocket Client**, you should create a new instance of the `WebSocket` class with the **wss** scheme WebSocket URL.

```csharp
using (var ws = new WebSocket ("wss://example.com")) {
  ...
}
```

And if you would like to use the custom validation for the server certificate, you should set the `WebSocket.SslConfiguration.ServerCertificateValidationCallback` property.

```csharp
ws.SslConfiguration.ServerCertificateValidationCallback =
  (sender, certificate, chain, sslPolicyErrors) => {
    // Do something to validate the server certificate.
    ...

    return true; // If the server certificate is valid.
  };
```

If you set this property to nothing, the validation does nothing with the server certificate, and returns `true`.

As a **WebSocket Server**, you should create a new instance of the `WebSocketServer` or `HttpServer` class with some settings for secure connection, such as the following.

```csharp
var wssv = new WebSocketServer (5963, true);
wssv.SslConfiguration.ServerCertificate =
  new X509Certificate2 ("/path/to/cert.pfx", "password for cert.pfx");
```

### HTTP Authentication ###

websocket-sharp supports the **[HTTP Authentication (Basic/Digest)][rfc2617]**.

As a **WebSocket Client**, you should set a pair of user name and password for the HTTP authentication, by using the `WebSocket.SetCredentials (string, string, bool)` method before connecting.

```csharp
ws.SetCredentials ("nobita", "password", preAuth);
```

If `preAuth` is `true`, the `WebSocket` sends the Basic authentication credentials with the first connection request to the server.

Or if `preAuth` is `false`, the `WebSocket` sends either the Basic or Digest (determined by the unauthorized response to the first connection request) authentication credentials with the second connection request to the server.

As a **WebSocket Server**, you should set an HTTP authentication scheme, a realm, and any function to find the user credentials before starting, such as the following.

```csharp
wssv.AuthenticationSchemes = AuthenticationSchemes.Basic;
wssv.Realm = "WebSocket Test";
wssv.UserCredentialsFinder = id => {
  var name = id.Name;

  // Return user name, password, and roles.
  return name == "nobita"
         ? new NetworkCredential (name, "password", "gunfighter")
         : null; // If the user credentials aren't found.
};
```

If you would like to provide the Digest authentication, you should set such as the following.

```csharp
wssv.AuthenticationSchemes = AuthenticationSchemes.Digest;
```

### Query String, Origin header and Cookies ###

As a **WebSocket Client**, if you would like to send the **Query String** with the WebSocket connection request to the server, you should create a new instance of the `WebSocket` class with the WebSocket URL that includes the [Query] string parameters.

```csharp
using (var ws = new WebSocket ("ws://example.com/?name=nobita")) {
  ...
}
```

And if you would like to send the **Origin header** with the WebSocket connection request to the server, you should set the `WebSocket.Origin` property to an allowable value as the [Origin header] before connecting, such as the following.

```csharp
ws.Origin = "http://example.com";
```

And also if you would like to send the **Cookies** with the WebSocket connection request to the server, you should set any cookie by using the `WebSocket.SetCookie (WebSocketSharp.Net.Cookie)` method before connecting, such as the following.

```csharp
ws.SetCookie (new Cookie ("name", "nobita"));
```

As a **WebSocket Server**, if you would like to get the **Query String** included in each WebSocket connection request, you should access the `WebSocketBehavior.Context.QueryString` property, such as the following.

```csharp
public class Chat : WebSocketBehavior
{
  private string _name;
  ...

  protected override void OnOpen ()
  {
    _name = Context.QueryString["name"];
  }

  ...
}
```

And if you would like to validate the **Origin header**, **Cookies**, or both included in each WebSocket connection request, you should set each validation with your `WebSocketBehavior`, for example, by using the `AddWebSocketService<TBehavior> (string, Func<TBehavior>)` method with initializing, such as the following.

```csharp
wssv.AddWebSocketService<Chat> (
  "/Chat",
  () => new Chat () {
    OriginValidator = val => {
      // Check the value of the Origin header, and return true if valid.
      Uri origin;
      return !val.IsNullOrEmpty () &&
             Uri.TryCreate (val, UriKind.Absolute, out origin) &&
             origin.Host == "example.com";
    },
    CookiesValidator = (req, res) => {
      // Check the Cookies in 'req', and set the Cookies to send to the client with 'res'
      // if necessary.
      foreach (Cookie cookie in req) {
        cookie.Expired = true;
        res.Add (cookie);
      }

      return true; // If valid.
    }
  });
```

And also if you would like to get each value of the Origin header and cookies, you should access each of the `WebSocketBehavior.Context.Origin` and `WebSocketBehavior.Context.CookieCollection` properties.

### Connecting through the HTTP Proxy server ###

websocket-sharp supports to connect through the **HTTP Proxy** server.

If you would like to connect to a WebSocket server through the HTTP Proxy server, you should set the proxy server URL, and if necessary, a pair of user name and password for the proxy server authentication (Basic/Digest), by using the `WebSocket.SetProxy (string, string, string)` method before connecting.

```csharp
var ws = new WebSocket ("ws://example.com");
ws.SetProxy ("http://localhost:3128", "nobita", "password");
```

I tested this with the [Squid]. And it's necessary to disable the following configuration option in **squid.conf** (e.g. `/etc/squid/squid.conf`).

```
# Deny CONNECT to other than SSL ports
#http_access deny CONNECT !SSL_ports
```

### Logging ###

The `WebSocket` class includes the own logging function.

You can use it with the `WebSocket.Log` property (returns a `WebSocketSharp.Logger`).

So if you would like to change the current logging level (`WebSocketSharp.LogLevel.Error` as the default), you should set the `WebSocket.Log.Level` property to any of the `LogLevel` enum values.

```csharp
ws.Log.Level = LogLevel.Debug;
```

The above means a log with lower than `LogLevel.Debug` cannot be outputted.

And if you would like to output a log, you should use any of the output methods. The following outputs a log with `LogLevel.Debug`.

```csharp
ws.Log.Debug ("This is a debug message.");
```

The `WebSocketServer` and `HttpServer` classes include the same logging function.

## Examples ##

Examples using websocket-sharp.

### Example ###

**[Example]** connects to the **[Echo server]** with the WebSocket.

### Example1 ###

**[Example1]** connects to the **[Audio Data delivery server]** with the WebSocket. (But it's only implemented the chat feature, still unfinished.)

And Example1 uses **[Json.NET]**.

### Example2 ###

**[Example2]** starts a WebSocket server.

### Example3 ###

**[Example3]** starts an HTTP server that allows to accept the WebSocket connection requests.

Would you access to [http://localhost:4649](http://localhost:4649) to do **WebSocket Echo Test** with your web browser after Example3 running?

## Supported WebSocket Specifications ##

websocket-sharp supports **[RFC 6455][rfc6455]**, and it's based on the following WebSocket references:

- **[The WebSocket Protocol][rfc6455]**
- **[The WebSocket API][api]**
- **[Compression Extensions for WebSocket][compression]**

Thanks for translating to japanese.

- **[The WebSocket Protocol 日本語訳][rfc6455_ja]**
- **[The WebSocket API 日本語訳][api_ja]**

## License ##

websocket-sharp is provided under **[The MIT License]**.

[Audio Data delivery server]: http://agektmr.node-ninja.com:3000
[Echo server]: http://www.websocket.org/echo.html
[Example]: https://github.com/sta/websocket-sharp/tree/master/Example
[Example1]: https://github.com/sta/websocket-sharp/tree/master/Example1
[Example2]: https://github.com/sta/websocket-sharp/tree/master/Example2
[Example3]: https://github.com/sta/websocket-sharp/tree/master/Example3
[Json.NET]: http://james.newtonking.com/projects/json-net.aspx
[Mono]: http://www.mono-project.com
[MonoDevelop]: http://monodevelop.com
[NuGet Gallery]: http://www.nuget.org
[NuGet Gallery: websocket-sharp]: http://www.nuget.org/packages/WebSocketSharp
[Origin header]: http://tools.ietf.org/html/rfc6454#section-7
[Query]: http://tools.ietf.org/html/rfc3986#section-3.4
[Security Sandbox of the Webplayer]: http://docs.unity3d.com/Manual/SecuritySandbox.html
[Squid]: http://www.squid-cache.org
[The MIT License]: https://raw.github.com/sta/websocket-sharp/master/LICENSE.txt
[Unity]: http://unity3d.com
[Unity Licenses Comparison]: http://unity3d.com/unity/licenses
[WebSocket-Sharp for Unity]: http://u3d.as/content/sta-blockhead/websocket-sharp-for-unity
[api]: http://www.w3.org/TR/websockets
[api_ja]: http://www.hcn.zaq.ne.jp/___/WEB/WebSocket-ja.html
[compression]: http://tools.ietf.org/html/draft-ietf-hybi-permessage-compression-19
[context take over]: http://tools.ietf.org/html/draft-ietf-hybi-permessage-compression-19#section-8.1.1
[draft-hixie-thewebsocketprotocol-75]: http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-75
[draft-ietf-hybi-thewebsocketprotocol-00]: http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-00
[draft75]: https://github.com/sta/websocket-sharp/tree/draft75
[hybi-00]: https://github.com/sta/websocket-sharp/tree/hybi-00
[master]: https://github.com/sta/websocket-sharp/tree/master
[rfc2617]: http://tools.ietf.org/html/rfc2617
[rfc6455]: http://tools.ietf.org/html/rfc6455
[rfc6455_ja]: http://www.hcn.zaq.ne.jp/___/WEB/RFC6455-ja.html


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

import db.exception.NegocioException;
import db.exception.PersistenciaException;
import java.util.List;
import modelo.domain.Modulo;

/**
 *
 * @author DASJ
 */
public interface IManterModulo {

    public Integer cadastrar(Modulo modulo) throws PersistenciaException, NegocioException;
    public void atualizar(Modulo modulo) throws PersistenciaException, NegocioException;
    public void excluir(Modulo modulo) throws PersistenciaException, NegocioException;
    public List<Modulo> listarTodos() throws PersistenciaException, NegocioException;

}

redpajama_set_name: RedPajamaGithub


text:
ASDKEMULATORDIR=~/workshop/bin/android-sdk-linux_x86
ASDKSYSDIR=$ASDKEMULATORDIR/platforms/mitac/cust-image/android-sdk-2.3/images
ASDKDATADIR=$ASDKEMULATORDIR/platforms/mitac/cust-image/android-sdk-2.3/images
ASDKSKINDIR=$ASDKEMULATORDIR/platforms/mitac/cust-image/skins

../../tools/emulator -sysdir $ASDKSYSDIR -datadir $ASDKDATADIR -skindir $ASDKSKINDIR -sdcard $ASDKSKINDIR/FakeSDcard.iso -memory 256 -dpi-device 140 -skin WVGA800humpback -show-kernel -debug all


text:
// CSim - (c) 2017 Baltasar MIT License <jbgarcia@uvigo.es>

namespace CSim.Ui {
    using System;
    using System.IO;
    using System.Text;
    using System.Numerics;
    using System.Globalization;
    using System.Collections.Generic;

    using Core;

    ///
    /// Creates a Read - Eval - Loop for using the <see cref="Machine"/>.
    ///
    public class REL {
        /// The max number of bytes to dump.
        public const int DumpMaxBytes = 16;
        /// The prompt to use in the REL.
        public const string Prompt = "> ";
        /// Prefix for hex numbers.
        public const string HexPrefix = "0x";
        /// The prefix for all REL commands.
        public const string CmdPrefix = ".";
        /// The command to exit the REL.
        public const string CmdEnd = "exit";
        /// The command to show existing variables.
        public const string CmdDir = "dir";
        /// The command to show available commands.
        public const string CmdHelp = "help";
        /// The command to reset the machine.
        public const string CmdReset = "reset";
        /// The command to dump memory.
        public const string CmdDump = "dump";
        /// The command to load a program.
        public const string CmdLoad = "load";
        /// The argument to denote random.
        public const string ArgRandom = "rnd";
        /// Show the available commands.
        public const string ShowAssistance = "Type '"
                + CmdPrefix + CmdHelp + "' to show assistance.";
        /// Show the available commands.
        public const string Help = "Available commands:"
                + "\n\t" + CmdPrefix + CmdHelp + "\t\tThis help."
                + "\n\t" + CmdPrefix + CmdDir + "\t\tShow existing variables."
                + "\n\t" + CmdPrefix + CmdLoad + " /path/f\tLoads program f."
                + "\n\t" + CmdPrefix + CmdReset + "\t\tResets machine."
                + "\n\t" + CmdPrefix + CmdReset + " rnd\tResets machine with "
                                                + "random values in memory."
                + "\n\t" + CmdPrefix + CmdDump + " <addr>\tShow raw memory."
                + "\n\t" + CmdPrefix + CmdEnd + "\t\tExit this REL.";

        ///
        /// Initializes a new <see cref="T:REL"/>.
        ///
        public REL(Machine m)
        {
            this.Machine = m;

            this.Machine.Inputter = DoUserInput;
            this.Machine.Outputter = Console.Write;
        }

        private string DoUserInput(string msg)
        {
            Console.Write( msg );
            return Console.ReadLine();
        }

        private string PromptOrder()
        {
            Console.Write( "\n" + Prompt );
            return Console.ReadLine();
        }

        private string Dump(BigInteger address, int max = DumpMaxBytes)
        {
            BigInteger addr = address;
            var toret = new StringBuilder( max + ( max * 3 ) );
            byte[] rawBytes = this.Machine.Memory.Read( address, max );

            // The raw byte values
            foreach(byte b in rawBytes) {
                toret.Append( b.ToString( "x2" ) );
                toret.Append( ' ' );
            }

            // Bytes as chars
            foreach(byte b in rawBytes) {
                char ch = b.ToChar();

                if ( char.IsControl( ch ) ) {
                    ch = '.';
                }

                toret.Append( ch );
            }

            return toret.ToString();
        }

        private string GetVariableList()
        {
            IList<Variable> vbles = this.Machine.TDS.Variables;
            var toret = new StringBuilder( 15 * vbles.Count );

            foreach(Variable vble in vbles) {
                toret.Append( vble.Address );
                toret.Append( "\t\t" );
                toret.Append( vble.Type );
                toret.Append( "\t\t" );
                toret.Append( vble.Name );
                toret.Append( '\n' );
            }

            return toret.ToString().Trim();
        }

        private BigInteger ParseNumericArg(string arg)
        {
            BigInteger toret = 0;

            if ( arg.StartsWith( HexPrefix, StringComparison.InvariantCulture ) )
            {
                string hexValue = arg.Substring( HexPrefix.Length );

                if ( BigInteger.TryParse( hexValue,
                                          NumberStyles.HexNumber,
                                          NumberFormatInfo.InvariantInfo,
                                          out BigInteger x ) )
                {
                    toret = x;
                }
            } else {
                if ( BigInteger.TryParse( arg, out BigInteger x ) ) {
                    toret = x;
                }
            }

            return toret;
        }

        ///
        /// Loads the file from the second of the specified args.
        ///
        /// <param name="args">An array of string.</param>
        public void Load(string[] args)
        {
            if ( args.Length >= 2 ) {
               try {
                    this.Machine.Load( args[ 1 ], (line, vble) => {} );
               } catch(IOException exc) {
                    Console.Error.WriteLine( "I/O Error: " + exc.Message );
               } catch(EngineException exc) {
                    Console.Error.WriteLine( "Error: " + exc.Message );
               }
            } else {
                Console.WriteLine( CmdLoad + " <f>??" );
            }
        }

        ///
        /// Runs the command in the input.
        ///
        /// <param name="input">The user's input.</param>
        private void RunCommand(string input)
        {
            var InvCulture = StringComparison.InvariantCulture;

            if ( input.StartsWith( CmdPrefix, InvCulture ) ) {
                input = input.Remove( 0, CmdPrefix.Length );
                var parts = input.Split( ' ' );
                string cmd = parts[ 0 ];

                if ( cmd == CmdEnd ) {
                    Environment.Exit( 0 );
                }
                else
                if ( cmd == CmdHelp ) {
                    Console.WriteLine( Help );
                }
                else
                if ( cmd == CmdDir ) {
                    Console.WriteLine( this.GetVariableList() );
                }
                else
                if ( cmd == CmdDump ) {
                    BigInteger address = 0;

                    if ( parts.Length > 1 ) {
                        address = ParseNumericArg( parts[ 1 ]);
                    }

                    Console.WriteLine( Dump( address ) );
                }
                else
                if ( cmd == CmdReset ) {
                    MemoryManager.ResetType rt = MemoryManager.ResetType.Zero;

                    if ( parts.Length > 1
                      && parts[ 1 ] == ArgRandom )
                    {
                        rt = MemoryManager.ResetType.Random;
                    }

                    this.Machine.Reset( rt );
                }
                else
                if ( cmd == CmdLoad ) {
                   this.Load( parts );
                } else {
                    Console.WriteLine( input + "??" );
                }
            }

            return;
        }

        /// Run the REL.
        public void Run()
        {
            var InvCulture = StringComparison.InvariantCulture;
            string input;

            Console.WriteLine( AppInfo.Header );
            Console.WriteLine( ShowAssistance );

            try {
	            input = this.PromptOrder();
	            while( input != CmdEnd ) {
	                input = input.Trim();

	                if ( input.StartsWith( CmdPrefix, InvCulture ) ) {
                        this.RunCommand( input );
	                } else {
	                    try {
	                        this.Machine.Execute( input );
	                    } catch(EngineException exc)
	                    {
	                        Console.Error.WriteLine( "Error " + exc.Message );
                        }

	                }

	                input = this.PromptOrder();
	            }
            }
            catch(Exception exc)
            {
                Console.Error.WriteLine( "Internal error " + exc.Message );
            }

            return;
        }

        /// Gets the machine to use in the REL.
        /// <value>The <see cref="Machine"/>.</value>
        public Machine Machine {
            get; private set;
        }
    }
}


text:
package org.vngx.jsch.algorithm;

import org.vngx.jsch.exception.JSchException;

/**
 * An implementation of {@code JSchException} to use when an {@code Algorithm}
 * implementation is not supported.
 *
 * @see org.vngx.jsch.algorithm.AlgorithmFactory
 * @see org.vngx.jsch.algorithm.AlgorithmManager
 * @see org.vngx.jsch.exception.JSchException
 *
 * @author Michael Laudati
 */
public class UnsupportedAlgorithmException extends JSchException {

    /**
     * Creates a new instance of {@code UnsupportedAlgorithmException} without
	 * detail message.
     */
    public UnsupportedAlgorithmException() { }

    /**
     * Creates a new instance of {@code UnsupportedAlgorithmException} with the
	 * specified detail message.
	 *
     * @param msg the detail message
     */
    public UnsupportedAlgorithmException(String msg) {
        super(msg);
    }

	/**
	 * Creates a new instance of {@code UnsupportedAlgorithmException} with the
	 * specified detail message and cause.
	 *
     * @param msg the detail message
	 * @param cause of exception
	 */
	public UnsupportedAlgorithmException(String msg, Throwable cause) {
		super(msg, cause);
	}

}


text:
(function () {
  "use strict";

  angular
    .module('mnPluggableUiRegistry', [])
    .provider('mnPluggableUiRegistry', mnPluggableUiRegistryProvider)
    .factory('mnPluggableTabUtil', mnPluggableTabUtil)
    .directive('mnPluggableUiTabs', mnPluggableUiTabs);

  function mnPluggableTabUtil() {

    return {
      getTabTemplate: getTabTemplate
    };

    function getTabTemplate(tabBarName, index) {
      var configLocation = "::" + tabBarName + ".pluggableUiConfigs[" + index + "]";
      var defaultTemplate = "
{{ " + configLocation + ".name }}
"
      var tabTemplates = {
        adminTab: "
{{" + configLocation + ".name}}
",
        indexesTab:  "
{{" + configLocation + ".name}}
"
     };

      return tabTemplates[tabBarName] || defaultTemplate;
    }
  }

  function mnPluggableUiTabs(mnPluggableUiRegistry, mnPluggableTabUtil, $compile) {

    return {
      link: link
    };

    function link($scope, $element, $attrs) {
      var pluggableUiConfigs = mnPluggableUiRegistry.getConfigsByTabBarName($attrs.mnTabBarName);
      if (!pluggableUiConfigs.length) {
        return;
      }
      $scope[$attrs.mnTabBarName] = {
        pluggableUiConfigs: pluggableUiConfigs
      };
      angular.forEach(pluggableUiConfigs, function (config, index) {
        config.ngShow = config.ngShow == undefined ? true : config.ngShow;
        if (config.after) {
          var targetTab = $element[0].querySelector("[mn-tab='" + config.after + "']");
          if (!targetTab) {
            throw new Error("There is no tab with mn-tab=" + config.after + " in " + $attrs.mnTabBarName);
          }
          var compiled = $compile(mnPluggableTabUtil.getTabTemplate($attrs.mnTabBarName, index))($scope);
          angular.element(targetTab).after(compiled);
        } else {
          var compiled = $compile(mnPluggableTabUtil.getTabTemplate($attrs.mnTabBarName, index))($scope);
          $element.append(compiled);
        }
      });
    }
  }

  function mnPluggableUiRegistryProvider() {
    var _configs = [];

    this.registerConfig = registerConfig;
    this.$get = mnPluggableUiRegistryFactory;

    /**
     * Registers a UI component config with the pluggable UI registry service so that the
     * component can be displayed in the UI.
     *
     * The pluggable UI framework understands the following attributes of the config:
     * 1) name - the name of the UI component to be registered. This is used appropriately
     *    in the UI when the component is displayed. For instance, if the component is
     *    rendered in a tab, the value of name will be used in the tab name.
     * 2) state - the name of the ui.router state for this component. When the time comes to
     *    render the component this is what is used to find it.
     * 3) plugIn - where the component plugs-in to the UI. Currently only 2 values are supported.
     *    If a value other than these 2 is specified, the component won't be displayed.
     *    a) 'adminTab' - to be used in the case that the pluggable component wishes to plug-in to
     *        global nav bar
     *    b) 'settingsTab' - to be used in the case that the pluggable component wishes to
     *        plug in to the the settings tab bar
     *
     * Any attributes beyond these are not understood and are ignored.
     * @param config
     */
    function registerConfig(config) {
      _configs.push(config);
    }

    function mnPluggableUiRegistryFactory() {

      return {
        getConfigs: getConfigs,
        getConfigsByTabBarName: getConfigsByTabBarName
      };

      /**
       * Returns a list of the registered plugabble UI configs.
       * @returns {Array}
       */
      function getConfigs() {
        return _configs;
      }
      function getConfigsByTabBarName(tabBarName) {
        return _.filter(_configs, {plugIn: tabBarName});
      }
    }
  }
}());


text:
'use strict';

var fs = require('fs');

var homeController = require('./../controllers/home'),
  gameController = require('./../controllers/game'),
  debugController = require('./../controllers/debug');

module.exports = function routes(app) {

  // Handle flash.
  app.use(function (req, res, next) {
    res.locals.flash = req.flash();
    next();
  });

  // Handle i18n.
  app.use(function (req, res, next) {
    if (req.query.lng) {
      res.redirect('back');
    } else {
      next();
    }
  });

  app.use(function (req, res, next) {
    const currentVersion = app.locals.version;
    const previousVersion = req.cookies['changelog-version'];
    if (currentVersion !== previousVersion) res.locals.showChangelog = true;
    next();
  });

  // Handle home.
  app.route('/').get(homeController.index);

  // Handel debug.
  app.route('/debug').get(debugController.index);

  // Handle game pages.
  app.route('/game').get(gameController.index);
  app.route('/game/rules').get(gameController.rules);
  app.route('/game/add').get(gameController.add).post(gameController.add);
  app.route('/game/edit/:name').get(gameController.edit).post(gameController.edit);
  app.route('/game/save').post(gameController.save);
  app.route('/game/view/:name').get(gameController.view);
  app.route('/game/update').post(gameController.update);
  app.route('/game/delete').delete(gameController.delete);
  app.route('/game/delete/:name').delete(gameController.delete);
  app.route('/game/clone/:name').post(gameController.clone);
  app.route('/game/api').get(gameController.api);

  // Handle 404.
  app.use(function (req, res/*, next*/) {
    console.error('404', req.url);
    res.status(404);
    if (req.accepts('html')) {
      res.render('error', {
        title: req.i18n.t('error:404.title'),
        code: 404,
        message: req.i18n.t('error:404.message')
      });
    } else if (req.accepts('json')) {
      res.send({ error: 'Not found' });
    } else {
      res.type('txt').send('Not found');
    }
  });

  // Handle 500.
  app.use(function (err, req, res/*, next*/) {
    res.status(err.status || 500).render('error', {
      title: '500: Internal Server Error',
      code: 505,
      message: err
    });
  });

};


text:
ALTER TABLE support ADD `user_perspective` VARCHAR( 100 ) NULL DEFAULT NULL;
ALTER TABLE support ADD `user_perspective_other` VARCHAR( 200 ) NULL DEFAULT NULL;


text:
package me.dommi2212.BungeeBridge;

import java.util.logging.Level;
import java.util.logging.Logger;

import net.md_5.bungee.BungeeCord;

/**
 * The Class ConsolePrinter.
 */
public class ConsolePrinter {

	/** Specifies the prefix. */
	private static final String prefix = "[BungeeBridgeS] ";

	/** Logger used to send messages to the console. */
	private static Logger logger = BungeeCord.getInstance().getLogger();

	/**
	 * Log a message with a Level
	 *
	 * @param lvl the level
	 * @param msg the message
	 */
	public static void log(Level lvl, String msg) {
		logger.log(lvl, prefix + msg);
	}

	/**
	 * Print to the console (Level.INFO)
	 *
	 * @param msg the message
	 */
	public static void print(String msg) {
		log(Level.INFO, msg);
	}

	/**
	 * Print to console (Level.SEVERE)
	 *
	 * @param msg the msg
	 */
	public static void err(String msg) {
		log(Level.SEVERE, msg);
	}

	/**
	 * Print to the console (Level.WARNING)
	 *
	 * @param msg the msg
	 */
	public static void warn(String msg) {
		log(Level.WARNING, msg);
	}

}


text:
"""The gcloud app versions group."""
from googlecloudsdk.calliope import base

@base.Hidden
class Versions(base.Group):
  """View and manage your App Engine versions.

  This set of commands can be used to view and manage your existing App Engine
  versions. To create new deployments, use `{parent_command} deploy`.
  """

  detailed_help = {
      'DESCRIPTION': '{description}',
      'EXAMPLES': """\
          To list your deployed versions, run:

            $ {command} list
      """,
  }


text:
import { shallow } from "enzyme";
import { shallowToJson } from "enzyme-to-json";
import Layout from "../ResultLayout";
import { getSingleSpecWrapper } from "../../../../util/tests/data-spec.js";

const defaultProps = {
  groups: [],
  tags: ["test", "test"],
  loading: false,
  count: 12,
  query: "test",
  campuses: [],
  schedules: [1],
  showSearch: true,
  toggleSearch: true,
  showTags: true,
  toggleTags: true,
  onCardHover: jest.fn(),
  LoadingComponent: () =>
HARAMBE
,
};

const generateComponent = (additionalProps = {}) => {
  const newProps = {
    ...defaultProps,
    ...additionalProps,
  };
  return <Layout { ...newProps } />;
};

it("renders with props", () => {
  const wrapper = shallow(generateComponent());
  expect(shallowToJson(wrapper)).toMatchSnapshot();
});

it("renders spinner when loading is true", () => {
  const someProps = {
    loading: true,
  }
  const wrapper = shallow(generateComponent(someProps));
  expect(shallowToJson(wrapper)).toMatchSnapshot();
});

it("shows up arrow on filter tag when tags are shown", () => {
  const wrapper = shallow(generateComponent());
  expect(shallowToJson(wrapper)).toMatchSnapshot();

  const iconTag = getSingleSpecWrapper(wrapper, "iconTag").props();
  expect(iconTag.iconClass).toEqual("icon-arrow-up");
});

it("shows down arrow on filter tag when tag drawer is closed", () => {
  const wrapper = shallow(generateComponent({
    showTags: false,
  }));
  expect(shallowToJson(wrapper)).toMatchSnapshot();

  const iconTag = getSingleSpecWrapper(wrapper, "iconTag").props();
  expect(iconTag.iconClass).toEqual("icon-arrow-down");
});


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class My_brokerage extends MY_Controller {

	public function __construct() {

		parent::__construct();

		$this->load->model('basic_model');
		$this->load->model('finance_model');
	}

	public function list_brokerage($page=1) {

		$user_info = $this->session->userdata('user_info');
		$user_id = $user_info['id'];
		$data = $this->finance_model->list_brokerage($page, $user_id);
		$base_url = "/my_brokerage/list_brokerage";
		$pager = $this->pagination->getPageLink($base_url, $data['total'], $data['limit']);
		$this->assign('pager', $pager);
		$this->assign('data', $data);

		$houses = $this->basic_model->get_house_list();
		$this->assign('houses', $houses);

		$this->show('/mine/list_brokerage');
	}

	public function add_brokerage() {

		$houses = $this->basic_model->get_house_list();
		$this->assign('houses', $houses);

		$this->assign('house_id', null);
		$this->show('/mine/add_brokerage');
	}

	public function save_brokerage(){
		$rs = $this->finance_model->save_brokerage();
		if($rs == 1){
			$this->show_message('保存成功',site_url('my_brokerage/list_brokerage'));
		}else{
			$this->show_message('保存失败');
		}
	}

	public function del_brokerage($id) {
		$rs = $this->finance_model->del_brokerage($id);
		if($rs == 1){
			$this->show_message('删除成功',site_url('my_brokerage/list_brokerage'));
		}else{
			$this->show_message('删除失败');
		}
	}
}


text:
namespace InheritEmployee
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using NorthwindDataModel.Data;

    public class Program
    {
        public static void Main()
        {
            Employee extendedEmployee = new Employee();
            NorthwindEntities db = new NorthwindEntities();
            using (db)
            {
                extendedEmployee = db.Employees.Find(1);
                foreach (var item in extendedEmployee.Territories)
                {
                    Console.WriteLine("Territory description - {0}", item.TerritoryDescription);
                }
            }
        }
    }
}


text:
<?php
/*
	Date: 216-01
	Author: BlueSky
*/
defined('BASEPATH') OR exit('No direct script access allowed');

class Api extends CI_Controller {

	public function __construct(){

		parent::__construct();

		$this->load->helper('cookie');
		$this->load->helper('url');

		// load models
		$this->load->model('User');
		$this->load->model('News');
		$this->load->model('orders');
		$this->load->model('relations');
		$this->load->model('route');
		$this->load->model('topic');
		$this->load->model('comment');

		$this->load->model('store');
		$this->load->model('product');
		$this->load->model('category');

		$this->load->library('session');
		date_default_timezone_set('America/Chicago');
	}

	private function getValue($index){

		if(!isset($_POST[$index]))
			$_POST = json_decode(file_get_contents('php://input'), true);

		if(isset($_GET[$index]))
			return $_GET[$index];
		else if(isset($_POST[$index]))
			return $_POST[$index];
		else
			return '';
	}

	// ------- start User block -------//
	public function checkLogin(){

		$arrReturn = array();
		if( $this->session->has_userdata('userInfo') && !$this->getValue('email')){
			$arrReturn['status'] = "success";
			$arrReturn['userInfo'] = $this->session->userdata('userInfo');
			echo json_encode( $arrReturn );
		}
		else if( get_cookie('userInfo') ){
			$arrReturn['status'] = "success";
			$arrReturn['userInfo'] = json_decode( get_cookie('userInfo'));
			echo json_encode( $arrReturn );		}
		else
		{
			$user 	= new User();
			$email 		= $this->getValue('email');
			$password 	= $this->getValue('password');

			if( $email == "" || $password == "" )
			{
				echo json_encode(array("status"=>"error", "error_message"=>"Empty Email or Password!")); return;
			}

			$res = $user->checkLogin( $email, $password );
			if( isset($res->role) && $res->role != 3 )
			{
				if( $this->getValue('remeber_me') ){
					set_cookie('userInfo', json_encode($res), 60*60*24*15 );
				}

				$this->session->set_userdata( 'userInfo', $res );
				$arrReturn['status'] = "success";
				$arrReturn['userInfo'] = $this->session->userdata('userInfo');
				echo json_encode( $arrReturn );
			}
			else if(isset($res->role))
				echo json_encode(array("status"=>"error", "error_message"=>"Your account isn't Admin"));
			else
				echo json_encode(array("status"=>"error", "error_message"=>"Invalid Email or Password!"));
		}
		return;
	}

	public function getAllUsers(){

		$search = $this->getValue('search_text');
		$user = new User();
		$arrUsers = $user->getUsers( "`firstName` LIKE '%".$search."%' OR `lastName` LIKE '%".$search."%' OR `username` LIKE '%".$search."%' OR `email` LIKE '%".$search."%' " );
		echo json_encode( $arrUsers );
	}

	public function getUserById(){

		$userID = $this->getValue('userID');
		$user = new User();
		echo json_encode( $user->getUserById( $userID ));
	}

	public function saveUser(){

		$arrUser = array(
						"firstName" => $this->getValue("firstName"),
						"lastName"	=> $this->getValue("lastName"),
						"email"		=> $this->getValue("email"),
						"username"	=> $this->getValue("username"),
						"password"	=> $this->getValue("password"),
						"role"		=> $this->getValue("role")
					);

		if( $arrUser["firstName"] == "" || $arrUser["lastName"] == "" ||$arrUser["email"] == "" ||$arrUser["password"] == "" || $arrUser["username"]=="")
			return;

		$user = new User();
		if( $this->getValue("userID") ){
			$arrUser["userID"] = $this->getValue("userID");
			print_r( $user->updateUser( $arrUser ) );
		}
		else
			print_r( $user->addUser( $arrUser ) );
	}

	public function deleteUser(){

		$userID = $this->getValue('userID');
		$user = new User();
		echo $user->deleteUser( $userID );
	}

	public function logout(){
		delete_cookie('userInfo');
		$this->session->unset_userdata("userInfo");
	}

	public function checkExistEmail(){

		$email = $this->getValue('email');
		$user = new User();
		$arrUsers = $user->getUsers( "`email`='".$email."'" );
		echo json_encode( $arrUsers );
	}

	public function checkExistUsername(){

		$email = $this->getValue('username');
		$user = new User();
		$arrUsers = $user->getUsers( "`username`='".$email."'" );
		echo json_encode( $arrUsers );
	}
	// ------- end User block ------- //

	// ------- start News block -------//
	public function saveNews(){

		$arrNews = array(
						"newsTitle" => $this->getValue("newsTitle"),
						"imgPath"	=> $this->getValue("imgPath"),
						"newsContent" => $this->getValue("newsContent")
					);

		if( $arrNews["newsTitle"] == "" ||$arrNews["newsContent"] == "" )
			return;

		$news = new News();
		if( $this->getValue("newsID") ){
			$arrNews["newsID"] = $this->getValue("newsID");
			print_r( $news->updateNews( $arrNews ) );
		}
		else
			print_r( $news->addNews( $arrNews ) );
	}

	public function getNewsList(){

		$news = new News();
		$arrNews = $news->getNews( );
		echo json_encode( $arrNews );
	}

	public function getNewsById(){

		$newsID = $this->getValue('newsID');

		$news = new News();
		echo json_encode( $news->getNewsById( $newsID ));
	}

	public function deleteNews(){

		$newsID = $this->getValue('newsID');
		$news = new News();
		echo json_encode( $news->deleteNews( $newsID ));
	}
	// ------- end News block ------- //

	// ------- start Orders block ------- //
	public function getOrders(){

		/*
			$arrOrder Row Data fields
			array( 	"orderID"=>1,
					"firstName"=> "Jennifer",
					"lastName"=>"Minely",
					"orderDate"=>"23 Nov 2015",
					"orderQty"=>15,
					"storeName"=>"Store A,B" )
		*/
		$arrOrders = array();
		$arrOrders = $this->relations->getOrders();

		echo json_encode( $arrOrders );
	}

	public function getOrderDetails(){

		if( !$this->getValue("orderID") ){
			echo "error";
			die;
		}

		$arrOrderInfo 	= $this->relations->getOrders("orderID=".$this->getValue("orderID"));
		$arrProducts 	= $this->relations->getOrderDetailInfo(1);

		$arrReturn = array(
								"store_name" 	=> $arrOrderInfo[0]->storeName,
								"person_name" 	=> $arrOrderInfo[0]->firstName." ".$arrOrderInfo[0]->lastName,
								"order_date" 	=> $arrOrderInfo[0]->orderDate,
								"product_info" 	=> $arrProducts

							);

		echo json_encode( $arrReturn );
	}

	public function makeOrder(){

		if( !$this->getValue("orderData") ){
			echo "error";
			die;
		}
		//$orderData = json_decode( $this->getValue("orderData") );
		echo $this->relations->saveOrderData( $this->getValue("orderData") );
	}
	// ------- end Orders block ------- //

	// ------- start Report block ------- //
	public function calcCompletionRate( $userID, $date = NULL ){

		// get count of routes
		if( $date == NULL )
			$routes = $this->route->getRouteByUserId( $userID );
		else
			$routes = $this->route->getAllRoutes("routes.userID=".$userID." AND routes.routeDate='".$date."'");

		$num_routes = count( $routes );

		// get orders
		if( $date == NULL )
			$where = "userID=".$userID;
		else
			$where = "userID=".$userID." AND orderDate='".$date."'";

		$orders = $this->orders->getOrders( $where );
		$num_orders = sizeof( $orders );

		if( empty($routes) )
			return  "---";

		if( empty($orders) )
			return  "0%";

		return $num_orders / $num_routes * 100 ."%";
	}

	public function getReports(){

		$arrUsers = $this->User->getUsers();
		$arrReports = array();

		foreach( $arrUsers as $k => $val){
			$rate  = $this->calcCompletionRate( $val->userID );

			if( !strcmp($rate, "---") )
				continue;

			$val->completion = $rate;

			$arrReports[] = $val;
		}

		echo json_encode( $arrReports );
	}

	public function getPersonCompleteReports( ){

		if( !$this->getValue("userID") ){
			echo "error";
			die;
		}

		$userID = $this->getValue("userID");
		$routes = $this->route->getRouteByUserId( $userID );

		$arrPersonReports = array();
		if( count( $routes ) ){
			foreach( $routes as $k => $route )
			{
				$arrPersonReports[$k]['comp_date'] = $route->routeDate;
				$arrPersonReports[$k]['Area'] = "";
				$arrPersonReports[$k]['daily_completion'] = $this->calcCompletionRate( $userID, $route->routeDate );
			}
		}

		echo json_encode( $arrPersonReports );
	}
	// ------- end Reports block ------- //

	public function uploadFile(){

		if ( !empty( $_FILES ) ) {

			$file_name = date("Y-m-d").$_FILES[ 'file' ][ 'name' ];
		    $tempPath = $_FILES[ 'file' ][ 'tmp_name' ];
		    $uploadPath = dirname( __FILE__ ) . DIRECTORY_SEPARATOR . '../../uploads/news' . DIRECTORY_SEPARATOR . $file_name;

		    move_uploaded_file( $tempPath, $uploadPath );
		    $answer = array( 'answer' => 'success', 'Path' => "uploads/news". DIRECTORY_SEPARATOR .$file_name );
		    $json = json_encode( $answer );
		    echo $json;
		} else {
		    echo 'No files';
		}
	}

	// -- Part of Route -- //
	public function getAreaList(){

		$arrAreaList = array(
			array( "id"=>"1", "area_code"=>"", "name"=>"Scooby Doo" ),
			array( "id"=>"2", "area_code"=>"", "name"=>"Shaggy Rodgers" ),
			array( "id"=>"3", "area_code"=>"", "name"=>"Fred Jones" ),
			array( "id"=>"4", "area_code"=>"", "name"=>"Scooby" ),
			array( "id"=>"5", "area_code"=>"", "name"=>"Daphne Blake" ),
			array( "id"=>"6", "area_code"=>"", "name"=>"Velma Dinkley" ),
			array( "id"=>"7", "area_code"=>"", "name"=>"Fred Jones" ),
			array( "id"=>"8", "area_code"=>"", "name"=>"Daphne Blake" ),
			array( "id"=>"9", "area_code"=>"", "name"=>"Velma Dinkley" ),
		);
		echo json_encode( $arrAreaList );
	}

	public function getRoutes(){

		$userID = $this->getValue('userID');
		$where = '';
		if( $userID != "" && $userID != 0 )
				$where = "routes.userID=".$userID;

		$arrRoutes = $this->route->getAllRoutes( $where );
		echo json_encode( $arrRoutes );
	}

	// -- end of Route -- //
	public function uploadRoute(){

		if( $_FILES['file']['type'] != "text/csv" ){

		    $answer = array( 'answer' => 'error', 'message'=> 'Upload Correct File. File type is CSV' );
		    echo json_encode($answer);
		    exit;
		}

		$file_name = date("Y-m-d").$_FILES[ 'file' ][ 'name' ];
	    $tempPath = $_FILES[ 'file' ][ 'tmp_name' ];
	    $uploadPath = dirname( __FILE__ ) . DIRECTORY_SEPARATOR . '../../uploads/route' . DIRECTORY_SEPARATOR . $file_name;

	    move_uploaded_file( $tempPath, $uploadPath );

	    $answer = array( 'answer' => 'success', 'message' => $this->importDataFromCSV( $uploadPath ) );

	    echo json_encode($answer);
	    exit;
	}

	public function importDataFromCSV( $filePath = '' ){

		// read file content
        $arrRoutes = array();
        $arrKeys = array();

        $fp = fopen($filePath, 'rb');
        $index = -1;
        while (is_resource($fp) && !feof($fp)) {
            $row = fgets($fp, 16384);
            $arrTemp = explode( "," , $row );
            // set key
            if( empty($arrKeys)){
                foreach ( $arrTemp  as $key => $value)
                    $arrKeys[] = trim( $value );
            }
            else{
                if( sizeof($arrTemp) != sizeof($arrKeys) )
                    continue;
                foreach ( $arrTemp  as $key => $value) {
                    //if( $$arrKeys[$key] != "" )
                        $arrRoutes[$index][$arrKeys[$key]] = $value;
                }
            }
            $index++;
        }

        if( !in_array('salesCode', $arrKeys) || !in_array('customerCode', $arrKeys) || !in_array('routeDate', $arrKeys))
        	return  "Fields doesn't match";

        $counter = 0;
        try{
			foreach($arrRoutes as $key => $value){

				// get userID from salesCode(userCode)
				$userInfo = $this->User->getUsers("`salesCode`='".$value['salesCode']."'");
				if( is_array($userInfo))
					$userID = $userInfo[0]->userID;

				// get storeID from customerCode
				$storeInfo = $this->store->getStores("`storeCode`='".$value['customerCode']."'");
				if( is_array($storeInfo))
					$storeID = $storeInfo[0]->storeID;

				// check exists
				$routeInfo = $this->route->getAllRoutes("routes.userID=$userID AND routes.storeID=$storeID AND routes.routeDate='".$value['routeDate']."'");

				if( is_array($routeInfo) )
					continue;

				$data = array("userID" => $userID, "storeID" => $storeID, "routeDate" => $value['routeDate'], "active" => 1);
				$this->route->addRoute( $data);

				$counter++;
			}
			return $counter." Routes Imported";
		}
		catch( Exception $e){
			return "Importing Error!";
		}
	}

	public function getTopics(){

		$arrTopics = array();
		$arrTopics = $this->topic->getTopics();

		echo json_encode( $arrTopics );
	}

	public function getTopicByID(){

		$topicID = $this->getValue('topicID');

		$arrTopics = array();
		$arrTopics = $this->topic->getTopicById( $topicID );

		echo json_encode( $arrTopics);
	}

	public function getComments(){

		$topicID = $this->getValue('topicID');

		$arrComments = array();
		$arrComments = $this->comment->getComments("comments.topicID=".$topicID);

		echo json_encode( $arrComments );
	}

	public function getAllSyncData(){

		$userID = $this->getValue('userID');
		$date = date("Y-m-d");

		if( !$userID )
			return;

		// Get route data
		//$arrRoutes = $this->route->getRouteByUserId( $userID, $date );
		$arrRoutes = $this->route->getRouteByUserId( $userID );

//echo "
Routes ";
//print_r( $arrRoutes );
//echo "
";

		// Get Store Data
		$arrStores = array();
		if( is_array($arrRoutes) ){
			foreach( $arrRoutes as $route ){
				$temp = $this->store->getStoreById( $route->storeID );
				if( !in_array($temp, $arrStores))
					$arrStores[] = $temp;
			}
		}
//echo "
Stores ";
//print_r( $arrStores );
//echo "
";

		// Get Category Data
		$arrCategories = array();
		foreach($arrStores as $store) {
			$temp = $this->category->getCategories( "storeID=".$store->storeID );
			if( $temp ){
				for($i = 0; $i < count($temp); $i++) {
					$arrCategories[] = $temp[$i];
				}
			}
		}

//echo "
Categories ";
//print_r( $arrCategories );
//echo "
";

		// Get Product Data
		$arrProducts = array();
		foreach ($arrCategories as $category) {
			$temp = $this->product->getProducts( "categoryID=".$category->categoryID );
			if( $temp ){
				for($i = 0; $i < count($temp); $i++) {
					$arrProducts[] = $temp[$i];
				}
			}
		}
//echo "
Products ";
//print_r( $arrProducts );
//echo "
";

		// Get Topic Data
		$arrTopics = array();
		foreach($arrStores as $store) {
			$temp = $this->topic->getTopicsByStoreID( $store->storeID );
			if( $temp ){
				for($i = 0; $i < count($temp); $i++) {
					$arrTopics[] = $temp[$i];
				}
			}
		}
//echo "
Topics ";
//print_r( $arrTopics );
//echo "
";

		// Get Topic Data
		$arrComments = array();
		foreach($arrTopics as $topic) {
			$temp = $this->comment->getCommentsByTopicID( $topic->topicID );
			if( $temp ){
				for($i = 0; $i < count($temp); $i++) {
					$arrComments[] = $temp[$i];
				}
			}
		}
//echo "
Comments ";
//print_r( $arrComments );
//echo "
";

		// Get News Data
		$news = new News();
		$arrNews = $news->getNews( );
//echo "
News ";
//print_r( $arrNews );
//echo "
";

		// Get Order Data
		$arrOrders = array();
		if( is_array($arrRoutes) ){
			foreach( $arrRoutes as $route ){

				$temp = $this->orders->getOrders( "routeID=".$route->routeID );
				if( $temp ){
					for($i = 0; $i < count($temp); $i++) {
						$arrOrders[] = $temp[$i];
					}
				}
			}
		}
//echo "
Orders ";
//print_r( $arrOrders );
//echo "
";

		// Get OrderProducts Data
		$arrOrderProducts = array();
		if( is_array($arrOrders) ){
			foreach( $arrOrders as $order ){

				$temp = $this->relations->getOrderProducts( $order->orderID );
				if( $temp ){
					for($i = 0; $i < count($temp); $i++) {
						$arrOrderProducts[] = $temp[$i];
					}
				}
			}
		}

		$arrReturn = array(	"routes"  =>	$arrRoutes,
							"stores"	=>	$arrStores,
							"category"	=>	$arrCategories,
							"products"	=>	$arrProducts,
							"topics"	=>	$arrTopics,
							"comments"	=>	$arrComments,
							"news"		=>	$arrNews,
							"orders"	=>	$arrOrders,
							"order_products" => $arrOrderProducts
			);
/*echo "
";
print_r( $arrReturn );
echo "
";*/
		echo json_encode( $arrReturn );
	}

	public function addTopic(){

		$storeID = $this->getValue('storeID');
		$topicTitle = $this->getValue('topicTitle');
		$date_added = $this->getValue('date_added');

		if( !$storeID || $topicTitle == "" )
		{
			echo "error";
			exit;
		}

		$topicData = array(
			"storeID" 	=> $storeID,
			"topicTitle" 	=> $topicTitle,
			"date_added" 	=> $date_added,
			"active" 		=> 1
		);

		echo $this->topic->addTopic( $topicData );
	}

	public function addComment(){

		$topicID = $this->getValue('topicID');
		$userID = $this->getValue('userID');
		$contents = $this->getValue('contents');
		$date_added = $this->getValue('date_added');

		if( !$topicID || !$userID ){
			echo "error";
			exit;
		}
		$commentData = array(
			"topicID" 	=> $topicID,
			"userID" 	=> $userID,
			"contents" 	=> $contents,
			"date_added"=> $date_added,
			"active"	=> 1
		);

		echo $this->comment->addComment( $commentData );
	}

	public function uploadPhoto(){
		$routeID = $this->getValue('routeID');
		$filename = $this->getValue('file');

		return "success";
	}
}


text:
=begin
  This is a basic Ragdoll Sample
  The ragdoll currently shakes in rapid convultions. Not sure why yet.
=end
java_import "com.jme3.app.SimpleApplication"
java_import "com.jme3.bullet.BulletAppState"
java_import "com.jme3.bullet.PhysicsSpace"
java_import "com.jme3.bullet.collision.shapes.CapsuleCollisionShape"
java_import "com.jme3.bullet.control.RigidBodyControl"
java_import "com.jme3.bullet.joints.ConeJoint"
java_import "com.jme3.bullet.joints.PhysicsJoint"
java_import "com.jme3.input.controls.ActionListener"
java_import "com.jme3.input.controls.MouseButtonTrigger"
java_import "com.jme3.input.MouseInput"
java_import "com.jme3.math.Vector3f"
java_import "com.jme3.scene.Node"
java_import "com.jme3.light.AmbientLight"
java_import "com.jme3.font.BitmapText"
java_import "com.jme3.scene.shape.Box"
java_import "com.jme3.scene.Geometry"
java_import "com.jme3.math.ColorRGBA"
java_import "com.jme3.material.Material"

class Sample14 < SimpleApplication
  include ActionListener
  field_reader :cam, :settings
  field_accessor :flyCam
  attr_accessor :bullet_app_state, :upforce, :applyforce, :rag_doll, :shoulders

  def initialize
    self.bullet_app_state = BulletAppState.new
    self.rag_doll = Node.new
    self.upforce = Vector3f.new(0, 200, 0)
    self.applyforce = false
  end

  def simpleInitApp
    flyCam.move_speed = 30
    state_manager.attach(bullet_app_state)
    bullet_app_state.physics_space.enable_debug(asset_manager)
    input_manager.add_mapping("Pull ragdoll up", MouseButtonTrigger.new(MouseInput::BUTTON_LEFT))
    input_manager.add_listener(ControllerAction.new(self), "Pull ragdoll up")
    create_world
    create_rag_doll
  end

  def create_world
    light = AmbientLight.new
    light.color = ColorRGBA::LightGray
    root_node.add_light(light)

    material = Material.new(asset_manager, File.join("Common", "MatDefs", "Misc", "Unshaded.j3md"))
    material.set_texture("ColorMap", asset_manager.load_texture(File.join("Interface", "Logo", "Monkey.jpg")))

    box = Box.new(Vector3f.new(0, -4, -5), 100, 0.2, 100)
    floor = Geometry.new("the Floor", box)
    floor.material = material
    floor.set_local_translation(0, -0.1, 0)
    floor_phy = RigidBodyControl.new(0.0)
    floor.add_control(floor_phy)
    root_node.attach_child(floor)
    bullet_app_state.physics_space.add(floor)
  end

  def create_rag_doll
    head = create_limb(0.2, 0.5, Vector3f.new(0.0, 2.5, 0), false)
    self.shoulders = create_limb(0.2, 2.0, Vector3f.new(0.0, 1.5, 0), true)
    uArmL = create_limb(0.2, 0.5, Vector3f.new(-0.75, 0.8, 0), false)
    uArmR = create_limb(0.2, 0.5, Vector3f.new( 0.75, 0.8, 0), false)
    lArmL = create_limb(0.2, 0.5, Vector3f.new(-0.75,-0.2, 0), false)
    lArmR = create_limb(0.2, 0.5, Vector3f.new( 0.75,-0.2, 0), false)
    body = create_limb(0.2, 1.5, Vector3f.new( 0.0, 0.5, 0), false)
    hips = create_limb(0.2, 0.5, Vector3f.new( 0.0,-0.5, 0), true)
    uLegL = create_limb(0.2, 0.5, Vector3f.new(-0.25,-1.2, 0), false)
    uLegR = create_limb(0.2, 0.5, Vector3f.new( 0.25,-1.2, 0), false)
    lLegL = create_limb(0.2, 0.5, Vector3f.new(-0.25,-2.2, 0), false)
    lLegR = create_limb(0.2, 0.5, Vector3f.new( 0.25,-2.2, 0), false)
    join(shoulders,  head, Vector3f.new( 0.00,  1.8, 0))
    join(body,  shoulders, Vector3f.new( 0.00,  1.4, 0))
    join(body,       hips, Vector3f.new( 0.00, -0.5, 0))
    join(uArmL, shoulders, Vector3f.new(-0.75,  1.4, 0))
    join(uArmR, shoulders, Vector3f.new( 0.75,  1.4, 0))
    join(uArmL,     lArmL, Vector3f.new(-0.75,  0.4, 0))
    join(uArmR,     lArmR, Vector3f.new( 0.75,  0.4, 0))
    join(uLegL,      hips, Vector3f.new(-0.25, -0.5, 0))
    join(uLegR,      hips, Vector3f.new( 0.25, -0.5, 0))
    join(uLegL,     lLegL, Vector3f.new(-0.25, -1.7, 0))
    join(uLegR,     lLegR, Vector3f.new( 0.25, -1.7, 0))
    rag_doll.attach_child(head)
    rag_doll.attach_child(shoulders)
    rag_doll.attach_child(body)
    rag_doll.attach_child(hips)
    rag_doll.attach_child(uArmL)
    rag_doll.attach_child(uArmR)
    rag_doll.attach_child(lArmL)
    rag_doll.attach_child(lArmR)
    rag_doll.attach_child(uLegL)
    rag_doll.attach_child(uLegR)
    rag_doll.attach_child(lLegL)
    rag_doll.attach_child(lLegR)
    root_node.attach_child(rag_doll)
    bullet_app_state.physics_space.add_all(rag_doll)
  end

  def create_limb(width, height, location, rotate)
    axis = rotate ? PhysicsSpace::AXIS_X : PhysicsSpace::AXIS_Y
    shape = CapsuleCollisionShape.new(width, height, axis)
    node = Node.new("Limb")
    rigid_body_control = RigidBodyControl.new(shape, 1)
    node.local_translation = location
    node.add_control(rigid_body_control)
    node
  end

  def join(node_a, node_b, connection_point)
    pivot_a = node_a.world_to_local(connection_point, Vector3f.new)
    pivot_b = node_b.world_to_local(connection_point, Vector3f.new)
    joint = ConeJoint.new(node_a.get_control(RigidBodyControl.java_class),
                          node_b.get_control(RigidBodyControl.java_class),
                          pivot_a, pivot_b)
    joint.set_limit(1.0, 1.0, 0)
    joint
  end

  def simpleUpdate(tpf)
    if applyforce
      Waves.echo("APPLYING FORCE!", :yellow)
      shoulders.get_control(RigidBodyControl.java_class).apply_force(upforce, Vector3f::ZERO)
    end
  end

  class ControllerAction
    include ActionListener

    def initialize(obj)
      @parent = obj
    end

    def on_action(name, key_pressed, time_per_frame)
      if name.eql?("Pull ragdoll up")
        if key_pressed
          @parent.shoulders.get_control(RigidBodyControl.java_class).activate
          @parent.applyforce = true
        else
          @parent.applyforce = false
        end
      end
    end

  end

end


text:
'use strict';
/**
 * Created by garusis on 21/08/16.
 */

/**
 * Dependencies
 */
const gulp = require('gulp'),
    _ = require('lodash'),
    fs = require('fs'),
    path = require('path'),
    gutil = require('gulp-util'),
    yargs = require('yargs'),
    nconf = require('nconf');

/**
 * ErrorConstant Object
 *
 * @param {String} name constant's name
 * @param {String} [color] constant's color
 * @constructor
 */
function ErrorConstant(name, color) {
    this.name = name;
    this.color = color;
}

/**
 * This constant represents an Error that should be thrown
 * @type {ErrorConstant}
 */
ErrorConstant.THROW_ERROR = new ErrorConstant('THROW_ERROR', 'magenta');
/**
 * This constant represents an Error that should be shown as a Warning
 * @type {ErrorConstant}
 */
ErrorConstant.WARNING = new ErrorConstant('WARNING', 'yellow');
/**
 * This constant represents an Error that should not be shown
 * @type {ErrorConstant}
 */
ErrorConstant.SILENT_WARNING = new ErrorConstant('SILENT_WARNING', 'yellow');

const argv = yargs.argv;
const pkg = loadJsonFile('./package.json', ErrorConstant.THROW_ERROR);
const appName = (pkg.name || 'NODE').toUpperCase();

const defaults = {
    'localapi': false,
    'GULP_CONF_DIR': path.join(process.cwd(), 'gulp'),
    'GULP_TASKS_DIR': path.join(process.cwd(), 'gulp'),
    'availableEnvironments': [
        "development",
        "staging",
        "production"
    ]
};

let ENV = null;

/**
 *
 * @param {Object} error
 * @param {ErrorConstant} [typeError]
 */
function handleError(error, typeError) {
    typeError = typeError || ErrorConstant.WARNING;
    switch (typeError) {
        case ErrorConstant.THROW_ERROR:
            throw error;
            break;
        case ErrorConstant.WARNING:
            gutil.log(gutil.colors[ErrorConstant.WARNING.color](error.message));
            break;
        case ErrorConstant.SILENT_WARNING:
        default:
            break;
    }
}

/**
 *
 * @param {String} path
 * @param {ErrorConstant} [throwError]
 * @returns {Object}
 */
function loadJsonFile(path, throwError) {
    throwError = throwError || ErrorConstant.WARNING;

    try {
        let fileContent = loadFile(path, throwError);
        return JSON.parse(fileContent);
    } catch (err) {
        handleError(err, throwError);
        return {};
    }
}

/**
 *
 * @param {String} path
 * @param {ErrorConstant} [throwError]
 * @returns {String}
 */
function loadFile(path, throwError) {
    throwError = throwError || ErrorConstant.WARNING;
    try {
        return fs.readFileSync(path, {encoding: 'utf8'});
    } catch (err) {
        handleError(err, throwError);
        return "";
    }
}

/**
 *
 * @param {String} module
 * @param {ErrorConstant} [throwError]
 */
function loadTasks(module, throwError) {
    //throwError = throwError || ErrorConstant.WARNING;
    throwError = throwError || ErrorConstant.SILENT_WARNING;
    try {
        require(module)(ENV);
        gutil.log(`Loaded tasks in ${module}`);
    } catch (err) {
        handleError(err, throwError);
        return "";
    }
}

/**
 *
 * @param {String} path
 * @returns {Object}
 */
function loadConfFile(path) {
    try {
        let conf = require(path);
        gutil.log(`Loaded confs in ${path}`);
        return conf;
    } catch (err) {
        handleError(err, ErrorConstant.WARNING);
        return {};
    }
}

/*
 * You can emulate each env in local using file.{ENV_NAME}.local.
 * This allow you overwrite the loaded by file.{ENV_NAME} with file.{ENV_NAME}.local
 *
 * Order of precedence of load configs
 *
 * 1) config.json
 * 2) config.{APPNAME_ENV}.json
 * 3) config.local.json
 * 4) config.{APPNAME_ENV}.local.json
 */

/**
 *
 * @param {String} [env]
 */
function loadConfig(env) {
    let previousEnv = !!ENV;
    ENV = require('./env').loadEnv(env);

    let conf = loadConfFile(path.join(ENV.GULP_CONF_DIR, 'config'));
    let confLocal = loadConfFile(path.join(ENV.GULP_CONF_DIR, 'config.local'));
    let confEnv = loadConfFile(path.join(ENV.GULP_CONF_DIR, `config.${ENV[`${appName}_ENV`]}`));
    let confEnvLocal = loadConfFile(path.join(ENV.GULP_CONF_DIR, `config.${ENV[`${appName}_ENV`]}.local`));

    ENV = _.defaultsDeep(confEnvLocal, confLocal, confEnv, conf, ENV);

    loadTasks(path.join(ENV.GULP_TASKS_DIR, 'tasks.js'));
    loadTasks(path.join(ENV.GULP_TASKS_DIR, `tasks.${ENV[`${appName}_ENV`]}.js`));
    loadTasks(path.join(ENV.GULP_TASKS_DIR, 'tasks.local.js'));
    loadTasks(path.join(ENV.GULP_TASKS_DIR, `tasks.${ENV[`${appName}_ENV`]}.local.js`));

    /**
     * NOTE. Gulp have a limiting with load data in the async way.
     *
     * Step 1). Load Env Vars and Argvs. In gulp conf is possible that Argvs will be not required.
     * BUT can be used to send data to task.
     * Step 2). Using EnvVars, merge results with files by environments.
     * Step 3). Register default Tasks to all environments.
     * Step 4). Load task by environments
     * Note. Load data must be a method that can be called by others envVars
     */

    if (previousEnv) {
        gutil.log(`${ENV[`${appName}_ENV`]} environment started`);
    }
}
loadConfig();

/**
 * Default set env tasks
 */
_.forEach(ENV.availableEnvironments, function (envName) {
    let taskEnvName = `set${_.upperFirst(_.camelCase(envName))}Env`;
    gulp.task(taskEnvName, function () {
        loadConfig(envName);
    });
    gutil.log(gutil.colors.cyan(`${taskEnvName} task attached`));
});

/**
 * Utilities heroku tasks
 * https://github.com/bewest/heroku-buildpack-nodejs-bower-gulp-grunt
 *
 */
_.forEach(ENV.availableEnvironments, function (envName) {
    let taskEnvName = `set${_.upperFirst(_.camelCase(envName))}Env`;
    let herokuTaskEnvName = `heroku:${envName}`;
    gulp.task(herokuTaskEnvName, [taskEnvName, 'buildAssets']);
    gutil.log(gutil.colors.cyan(`${herokuTaskEnvName} task attached`));
});

gutil.log(`Default gulp config finished`);


text:
<?php

require_once 'PHPUnit/Util/Log/PMD/Rule/Function.php';
require_once 'PHPUnit/Util/Filter.php';

PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT');

/**
 *
 *
 * @category   Testing
 * @package    PHPUnit
 * @author     Sebastian Bergmann <sb@sebastian-bergmann.de>
 * @copyright  2002-2008 Sebastian Bergmann <sb@sebastian-bergmann.de>
 * @license    http://www.opensource.org/licenses/bsd-license.php  BSD License
 * @version    Release: 3.2.9
 * @link       http://www.phpunit.de/
 * @since      Class available since Release 3.2.0
 */
class PHPUnit_Util_Log_PMD_Rule_Function_CRAP extends PHPUnit_Util_Log_PMD_Rule_Function
{
    public function __construct($threshold = 30, $priority = 1)
    {
        parent::__construct($threshold);
    }

    public function apply(PHPUnit_Util_Metrics $metrics)
    {
        $crap = $metrics->getCrapIndex();

        if ($crap >= $this->threshold) {
            return sprintf(
              "The CRAP index is %d.\n" .
              'The Change Risk Analysis and Predictions (CRAP) index of a ' .
              'function or method uses cyclomatic complexity and code coverage ' .
              'from automated tests to help estimate the effort and risk ' .
              'associated with maintaining legacy code. A CRAP index over 30 ' .
              'is a good indicator of crappy code.',
              $crap
            );
        }
    }
}
?>


text:
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>W29157_text</title>
        <link rel="stylesheet" type="text/css" href="style.css" />

                «

    <p class="styleSans2.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">

    <p class="styleSans12000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">

    <p class="styleSans46.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Mil BAKER HUGHES

    <p class="styleSans8.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Dickinson, North Dakota District Laboratory 272 34th Avenue West
Dickinson, ND 58601
Phone (701) 227-5500 Fax (701) 227-5502

    <p class="styleSans12.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Dickinson, North Dakota District Laboratory CEMENTING REPORT
Prepared for:

    <p class="styleSans11.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Prepared Ibr: Newfield Exploration Company
Rolfsrud 152-96-29-32-13HLW

    <p class="styleSans11.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Dickinson, North Dakota District Laboratory
A... A _ _ -1 u.nnAAFAn-'—l-

    <p class="styleSans26.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Proposal FIUJUlDUUIOE
Rig #: Patterson 335

    <p class="styleSans12.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Dickinson, North Dakota District Laboratory

    <p class="styleSans11.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">272 34th Avenue West
Dickinson, ND 58601 Mom (701) 227-5500

    <p class="styleSans7.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">ANALYST: Dickinson District Lab

    <p class="styleSans10.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">BAKER HUGHES TECHNICAL REPRESENTATIVE Monica Wiberg

    <p class="styleSans8.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Submitted by: Casey J Scharenbroich

    <p class="styleSans8.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">August 28, 2014


text:
namespace network {
    namespace node {
        namespace protocol {
            class interest_packet : public packet {
            private:
                std::string m_packet_id;

            public:
                interest_packet(int originator_id, std::string packet_id) : packet(originator_id) {
                    this->m_packet_id = packet_id;
                }

                virtual ~interest_packet() {};

                std::string const& packet_id() const { return this->m_packet_id; }
            };
        }
    }
}

#endif


text:
UI.InfoPanel = function(){

    var me = UI.element();
    var text = "";
    var source = "";
    var status = "";
    var moreInfoUrl;

    var infoButton = UI.Assets.generate("buttonDark");
    infoButton.setLabel("More info ");
    infoButton.onClick = function(){
        if (moreInfoUrl) window.open(moreInfoUrl);
    };
    me.addChild(infoButton);

    var spinner = UI.animsprite(5,7,20,18,"boing",11);
    me.addChild(spinner);
    spinner.hide();

    EventBus.on(EVENT.statusChange,function(context){
        if (context){
            if (typeof context.status !== "undefined") status = context.status;
            if (typeof context.info !== "undefined"){
                text = context.info;
                source = context.source;
                moreInfoUrl = context.url;
            }
            if (typeof context.showSpinner !== "undefined"){
                spinner.toggle(!!context.showSpinner)
            }
        }
        me.refresh();
    });

    var properties = ["left","top","width","height","name","type","zIndex"];
    me.setProperties = function(p){

        properties.forEach(function(key){
            if (typeof p[key] !== "undefined") me[key] = p[key];
        });

        me.setSize(me.width,me.height);
        me.setPosition(me.left,me.top);

        if (me.setLayout) me.setLayout(me.left,me.top,me.width, me.height);
    };

    me.setLayout = function(){

        var width = Layout.col1W;
        var label = "More Info";
        if (width<100) label = "info";
        if (width<45) label = "i";

        infoButton.setProperties({
            width: Layout.col1W,
            height: 24,
            top: 2,
            left:Layout.col5X - 2 - me.left,
            label: label,
            font: fontFT
        });

    };

    me.render = function(internal){
        if (!me.isVisible()) return;

        internal = !!internal;

        if (this.needsRendering){
            me.clearCanvas();

            if (moreInfoUrl) infoButton.render();

            var fText = text;
            if (status) fText = status + ": " + fText;

            var textX = 6;
            if (spinner.isVisible()){
                spinner.render();
                textX += 20;
            }

            window.fontFT.write(me.ctx,fText,textX,11,0);

        }

        this.needsRendering = false;
        if (internal){
            return me.canvas;
        }else{
            me.parentCtx.drawImage(me.canvas,me.left,me.top,me.width,me.height);
        }

    };

    return me;

};


text:
- Changes default server port from 8080 to 8081 to avoil conflict with RethinkDB
- Changes styles for table rows and connection settings window
- Adds highlighting styles for columns with sort order
- Adds git sha into program version output
- Add new endpoint /api/info to get build details

## 0.5.2 - 2015-04-13

- Adds a new endpoint /activity that retuns active queries
- Adds tab to view active queries
- Adds column sorting when browsing table contents
- Fixes SQL query view when switching to table structure view

## 0.5.1 - 2015-02-23

- Upgrades Gin framework dependency to 0.5.0
- Fixes server crash if another pgweb server is running

## 0.5.0 - 2015-01-13

- Adds Go 1.4 support
- Adds connection string printing in debug mode
- Adds initial bookmarks support
- Adds /api prefix for all API calls
- Adds makefile usage task
- Adds windows CI to verify build process
- Adds example sql database to codebase
- Adds timestamped filenames when exporting results to CSV [GH-75]
- Adds connection checking on each request to prevent api panics
- Adds timestamps to query history records
- Adds current database name to the sidebar
- Adds button to refresh tables list to the sidebar
- Updates all application dependencies
- Changes /api/info endpoint to /api/connection
- Fixes issues with connection string/options parsing
- Fixes capitalized column names in table view
- Fixes connection string validation in /api/connect endpoint

## 0.4.1 - 2014-12-01

- Adds pgweb version on start [GH-65]
- Adds user detection from OS environment
- Adds simple memory profiles with --debug option
- Adds the session user and search path in connection info [GH-67]
- Adds table list reloading after CREATE/DROP TABLE queries [GH-69]
- Adds font awesome icons for the sidebar
- Removes query recording for internal queries [GH-67]
- Fixes default sslmode. Its not longer set to "disable"
- Fixes cells cropping on table indexes view
- Fixes connection URL generation using web interface
- Fixes SQL statements for table row count [GH-67]
- Fixes /tables JSON response if database does not have any tables

## 0.4.0 - 2014-11-11

- Adds query escaping when exporting results to CSV [GH-38]
- Adds keyboard shortcut (ctrl+e, command+e on mac) for query explain action
- Adds HTTP basic authentication with --auth-user and --auth-pass flags
- Adds -skip-open/-s flag to disable automatic browser launch
- Adds --bind option to specify server listen hostname/ip
- Adds ssl mode parameters to url if ssl flag is set and not defined in the url
- Adds dependency management with Godep
- Adds Docker support
- Adds Heroku support
- Adds ability to connect to databases with no tables
- Adds precompiled assets into repository to simplify development
- Adds a connection details view
- Adds a new interface to specify connection settings or make a new connection
- Adds page favicon
- Adds ability to present cell data as text area by double clicking on it
- Fixes styles for query explain results
- Fixes sidebar navigation scrolling styles [GH-12]
- Fixes sidebar table name styles to support long names

## 0.3.1 - 2014-10-28

- Adds proper exit code when printing version via -v/--version flag
- Adds --version and --debug long flag names
- Adds double quotes for table name when fetching table contents
- Adds support for DATABASE_URL environment variable if no --url is set
- Adds proper usage of jQuery .prop method
- Adds --pass flag to specify connection password
- Fixes --ssl flag usage, previous value was hardcoded

## 0.3.0 - 2014-10-26

- Renamed `make deps` to `make setup` and fix issues with bootstrapping
- Removed hardcoded url for CSV export, it now detects application host:port
- Improved query history view table styles
- Moved table information view to the sidebar
- Added --listen flag to specify web server port, still defaults to 8080

## 0.2.0 - 2014-10-23

- Design tweaks
- Automatically opens browser on OSX systems
- Adds query explain functionality
- Adds export to CSV

## 0.1.0 - 2014-10-14

- Initial release


text:
package org.docksidestage.dbflute.bsbhv.loader;

import java.util.List;

import org.dbflute.bhv.*;
import org.docksidestage.dbflute.exbhv.*;
import org.docksidestage.dbflute.exentity.*;

/**
 * The referrer loader of (会員退会情報)MEMBER_WITHDRAWAL as TABLE.

 *

 * [primary key]
 *     MEMBER_ID
 *
 * [column]
 *     MEMBER_ID, WITHDRAWAL_REASON_CODE, WITHDRAWAL_REASON_INPUT_TEXT, WITHDRAWAL_DATETIME, REGISTER_DATETIME, REGISTER_USER, UPDATE_DATETIME, UPDATE_USER
 *
 * [sequence]
 *
 *
 * [identity]
 *
 *
 * [version-no]
 *
 *
 * [foreign table]
 *     MEMBER, WITHDRAWAL_REASON
 *
 * [referrer table]
 *
 *
 * [foreign property]
 *     member, withdrawalReason
 *
 * [referrer property]
 *
 *

 * @author DBFlute(AutoGenerator)
 */
public class LoaderOfMemberWithdrawal {

    // ===================================================================================
    //                                                                           Attribute
    //                                                                           =========
    protected List<MemberWithdrawal> _selectedList;
    protected BehaviorSelector _selector;
    protected MemberWithdrawalBhv _myBhv; // lazy-loaded

    // ===================================================================================
    //                                                                   Ready for Loading
    //                                                                   =================
    public LoaderOfMemberWithdrawal ready(List<MemberWithdrawal> selectedList, BehaviorSelector selector)
    { _selectedList = selectedList; _selector = selector; return this; }

    protected MemberWithdrawalBhv myBhv()
    { if (_myBhv != null) { return _myBhv; } else { _myBhv = _selector.select(MemberWithdrawalBhv.class); return _myBhv; } }

    // ===================================================================================
    //                                                                    Pull out Foreign
    //                                                                    ================
    protected LoaderOfMember _foreignMemberLoader;
    public LoaderOfMember pulloutMember() {
        if (_foreignMemberLoader == null)
        { _foreignMemberLoader = new LoaderOfMember().ready(myBhv().pulloutMember(_selectedList), _selector); }
        return _foreignMemberLoader;
    }

    protected LoaderOfWithdrawalReason _foreignWithdrawalReasonLoader;
    public LoaderOfWithdrawalReason pulloutWithdrawalReason() {
        if (_foreignWithdrawalReasonLoader == null)
        { _foreignWithdrawalReasonLoader = new LoaderOfWithdrawalReason().ready(myBhv().pulloutWithdrawalReason(_selectedList), _selector); }
        return _foreignWithdrawalReasonLoader;
    }

    // ===================================================================================
    //                                                                            Accessor
    //                                                                            ========
    public List<MemberWithdrawal> getSelectedList() { return _selectedList; }
    public BehaviorSelector getSelector() { return _selector; }
}


text:
/* Generated SBE (Simple Binary Encoding) message codec */

using System;
using Adaptive.SimpleBinaryEncoding;

namespace Adaptive.SimpleBinaryEncoding.PerfTests.Bench.SBE.FIX
{
    [Flags]
    public enum QuoteCondition : byte
    {
        Implied = 1,
        ExchangeBest = 2,
    }
}


text:
namespace TestCases.SS.Formula.Functions {
    using NPOI.SS.Formula;
    using NPOI.SS.Formula.Eval;
    using NPOI.SS.Formula.Functions;
    using NUnit.Framework;

    /**
     * Test cases for AVERAGEIFS()
     *
     * @author Denilson Rodrigues
     */
    [TestFixture]
    public class TestAverageifs
    {
        private static OperationEvaluationContext EC = new OperationEvaluationContext(null, null, 0, 1, 0, null);

        private static ValueEval InvokeAverageifs(ValueEval[] args, OperationEvaluationContext ec)
        {
            return new AverageIfs().Evaluate(args, EC);
        }

        private static void ConfirmDouble(double expected, ValueEval actualEval)
        {
            if (!(actualEval is NumericValueEval))
            {
                throw new AssertionException("Expected numeric result");
            }
            NumericValueEval nve = (NumericValueEval)actualEval;
            Assert.AreEqual(expected, nve.NumberValue, 0);
        }

        private static void Confirm(double expectedResult, ValueEval[] args)
        {
            ConfirmDouble(expectedResult, InvokeAverageifs(args, EC));
        }

        /**
         *  Example 1 from
         *  https://support.office.com/en-us/article/averageifs-function-48910c45-1fc0-4389-a028-f7c5c3001690
         */
        [Test]
        public void TestExample1()

        {
            // mimic test sample from https://support.office.com/en-us/article/averageifs-function-48910c45-1fc0-4389-a028-f7c5c3001690

            ValueEval[] b2b5 = new ValueEval[]
            {
                new StringEval("Quiz"),
                new StringEval("Grade"),
                new NumberEval(75),
                new NumberEval(94),
            };

            ValueEval[] c2c5 = new ValueEval[]
            {
                new StringEval("Quiz"),
                new StringEval("Grade"),
                new NumberEval(85),
                new NumberEval(80),
            };

            ValueEval[] d2d5 = new ValueEval[]
            {
                new StringEval("Exam"),
                new StringEval("Grade"),
                new NumberEval(87),
                new NumberEval(88),
            };

            // "=AVERAGEIFS(B2:B5, B2:B5, ">70", B2:B5, "<90")"
            ValueEval[] args = new ValueEval[]
            {
                EvalFactory.CreateAreaEval("B2:B5", b2b5),
                EvalFactory.CreateAreaEval("B2:B5", b2b5),
                new StringEval(">70"),
                EvalFactory.CreateAreaEval("B2:B5", b2b5),
                new StringEval("<90")
            };
            Confirm(75, args);

            // "=AVERAGEIFS(C2:C5, C2:C5, ">95")"
            args = new ValueEval[]
            {
                EvalFactory.CreateAreaEval("C2:C5", c2c5),
                EvalFactory.CreateAreaEval("C2:C5", c2c5),
                new StringEval(">95"),
            };
            Assert.AreEqual(ErrorEval.VALUE_INVALID, InvokeAverageifs(args, EC));

            // "=AVERAGEIFS(D2:D5, D2:D5, "<>Incomplete", D2:D5, ">80")"
            args = new ValueEval[]
            {
                EvalFactory.CreateAreaEval("D2:D5", d2d5),
                EvalFactory.CreateAreaEval("D2:D5", d2d5),
                new StringEval("<>Imcomplete"),
                EvalFactory.CreateAreaEval("D2:D5", d2d5),
                new StringEval(">80"),
            };
            Confirm(87.5, args);
        }

        /**
         *  Example 2 from
         *  https://support.office.com/en-us/article/averageifs-function-48910c45-1fc0-4389-a028-f7c5c3001690
         */
        [Test]
        public void TestExample2()
        {
            System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.CreateSpecificCulture("en-US");

            ValueEval[] b2b7 = new ValueEval[]
            {
                new StringEval(""),
                new NumberEval(230000),
                new NumberEval(197000),
                new NumberEval(345678),
                new NumberEval(321900),
                new NumberEval(450000),
            };

            ValueEval[] c2c7 = new ValueEval[]
            {
                new StringEval(""),
                new StringEval("Issaquah"),
                new StringEval("Bellevue"),
                new StringEval("Bellevue"),
                new StringEval("Issaquah"),
                new StringEval("Bellevue"),
            };

            ValueEval[] d2d7 = new ValueEval[]
            {
                new StringEval(""),
                new NumberEval(3),
                new NumberEval(2),
                new NumberEval(4),
                new NumberEval(2),
                new NumberEval(5),
            };

            ValueEval[] e2e7 = new ValueEval[]
            {
                new StringEval(""),
                new StringEval("No"),
                new StringEval("Yes"),
                new StringEval("Yes"),
                new StringEval("Yes"),
                new StringEval("Yes"),
            };

            // "= AVERAGEIFS(B2: B7, C2: C7, "Bellevue", D2: D7, ">2", E2: E7, "Yes")"
            ValueEval[] args = new ValueEval[]
            {
                EvalFactory.CreateAreaEval("B2:B7", b2b7),
                EvalFactory.CreateAreaEval("C2:C7", c2c7),
                new StringEval("Bellevue"),
                EvalFactory.CreateAreaEval("D2:D7", d2d7),
                new StringEval(">2"),
                EvalFactory.CreateAreaEval("E2:E7", e2e7),
                new StringEval("Yes"),
            };
            Confirm(397839, args);

            // "= AVERAGEIFS(B2: B7, C2: C7, "Issaquah", D2: D7, "<=3", E2: E7, "No")"
            args = new ValueEval[]
            {
                EvalFactory.CreateAreaEval("B2:B7", b2b7),
                EvalFactory.CreateAreaEval("C2:C7", c2c7),
                new StringEval("Issaquah"),
                EvalFactory.CreateAreaEval("D2:D7", d2d7),
                new StringEval("<=3"),
                EvalFactory.CreateAreaEval("E2:E7", e2e7),
                new StringEval("No"),
            };
            Confirm(230000, args);
        }
    }
}


text:
@interface CLLocationManager (Enhancements)

- (void)simx_didUpdateLocation:(CLLocation *)locations;
- (void)fakeLocation:(CLLocation *)fakeLocation;

@end


text:
package hydrograph.ui.validators.impl;

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

import org.apache.commons.lang.StringUtils;

import hydrograph.ui.datastructure.property.FixedWidthGridRow;
import hydrograph.ui.datastructure.property.DatabaseSelectionConfig;

/**
 * ToggleSelectionValidationRule validates the selected option for database components
 * @author Bitwise
 *
 */
public class ToggleSelectionValidationRule implements IValidator {
	private String errorMessage;

	@Override
	public String getErrorMessage() {
		// TODO Auto-generated method stub
		return errorMessage;
	}

	@Override
	public boolean validateMap(Object object, String propertyName,
			Map<String, List<FixedWidthGridRow>> inputSchemaMap) {
		Map<String, Object> propertyMap = (Map<String, Object>) object;
		if (propertyMap != null && !propertyMap.isEmpty()) {
			return validate(propertyMap.get(propertyName), propertyName, inputSchemaMap,false);
		}
		return false;
	}

	@Override
	public boolean validate(Object object, String propertyName, Map<String, List<FixedWidthGridRow>> inputSchemaMap,
			boolean isJobFileImported) {

		DatabaseSelectionConfig databaseSelectionConfig = (DatabaseSelectionConfig) object;

		if (databaseSelectionConfig != null) {
			if (databaseSelectionConfig.isTableName()) {
				if (StringUtils.isNotBlank(databaseSelectionConfig.getTableName())) {
					return true;
				} else {
					errorMessage = propertyName + " can not be blank";
					return false;
				}
			} else {
				if ((StringUtils.isNotBlank(databaseSelectionConfig.getSqlQuery()))) {
					return true;
				}
				else {
					errorMessage = propertyName + " can not be blank";
					return false;
				}
			}
		}

		return false;
	}

}


text:
"""Tests for target_sas.py."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import os
import tempfile

from absl import flags
from absl.testing import flagsaver

import tensorflow.compat.v1 as tf
from tensorflow.compat.v1 import gfile
from mol_dqn.chemgraph import target_sas
from mol_dqn.chemgraph.dqn import deep_q_networks
from mol_dqn.chemgraph.dqn.tensorflow_core import core

class OptimizeQedTest(tf.test.TestCase):

  def setUp(self):
    super(OptimizeQedTest, self).setUp()
    self.mount_point = tempfile.mkdtemp(dir=flags.FLAGS.test_tmpdir)
    self.model_dir = os.path.join(self.mount_point, 'model_dir')
    gfile.MakeDirs(self.model_dir)

  def test_run(self):
    hparams = deep_q_networks.get_hparams(
        replay_buffer_size=100,
        num_episodes=10,
        batch_size=10,
        update_frequency=1,
        save_frequency=1,
        dense_layers=[32],
        fingerprint_length=128,
        fingerprint_radius=2,
        num_bootstrap_heads=12,
        prioritized=True,
        double_q=True)
    hparams_file = os.path.join(self.mount_point, 'config.json')
    core.write_hparams(hparams, hparams_file)

    with flagsaver.flagsaver(model_dir=self.model_dir, hparams=hparams_file):
      target_sas.main(None)

if __name__ == '__main__':
  tf.test.main()