text:
"""Run subprocess.
"""
import os
import platform
import subprocess
import distutils.spawn
from vex import exceptions

def get_environ(environ, defaults, ve_path):
    """Make an environment to run with.
    """
    # Copy the parent environment, add in defaults from .vexrc.
    env = environ.copy()
    env.update(defaults)

    # Leaving in existing PYTHONHOME can cause some errors
    if "PYTHONHOME" in env:
        del env["PYTHONHOME"]

    # Now we have to adjust PATH to find scripts for the virtualenv...
    # PATH being unset/empty is OK, but ve_path must be set
    # or there is nothing for us to do here and it's bad.
    if not ve_path:
        raise exceptions.BadConfig("ve_path must be set")
    if platform.system() == "Windows":
        ve_bin = os.path.join(ve_path, "Scripts")
    else:
        ve_bin = os.path.join(ve_path, "bin")

    # If user is currently in a virtualenv, DON'T just prepend
    # to its path (vex foo; echo $PATH -> " /foo/bin:/bar/bin")
    # but don't incur this cost unless we're already in one.
    # activate handles this by running "deactivate" first, we don't
    # have that so we have to use other ways.
    # This would not be necessary and things would be simpler if vex
    # did not have to interoperate with a ubiquitous existing tool.
    # virtualenv doesn't...
    current_ve = env.get("VIRTUAL_ENV", "")
    system_path = environ.get("PATH", "")
    segments = system_path.split(os.pathsep)
    if current_ve:
        # Since activate doesn't export _OLD_VIRTUAL_PATH, we are going to
        # manually remove the virtualenv's bin.
        # A virtualenv's bin should not normally be on PATH except
        # via activate or similar, so I'm OK with this solution.
        current_ve_bin = os.path.join(current_ve, "bin")
        try:
            segments.remove(current_ve_bin)
        except ValueError:
            raise exceptions.BadConfig(
                "something set VIRTUAL_ENV prior to this vex execution, "
                "implying that a virtualenv is already activated "
                "and PATH should contain the virtualenv's bin directory. "
                "Unfortunately, it doesn't: it's {0!r}. "
                "You might want to check that PATH is not "
                "getting clobbered somewhere, e.g. in your shell's configs."
                .format(system_path)
            )

    segments.insert(0, ve_bin)
    env["PATH"] = os.pathsep.join(segments)
    env["VIRTUAL_ENV"] = ve_path
    return env

def run(command, env, cwd):
    """Run the given command.
    """
    assert command
    if cwd:
        assert os.path.exists(cwd)
    if platform.system() == "Windows":
        exe = distutils.spawn.find_executable(command[0], path=env["PATH"])
        if exe:
            command[0] = exe
    _, command_name = os.path.split(command[0])
    if (command_name in ("bash", "zsh")
    and "VIRTUALENVWRAPPER_PYTHON" not in env):
        env["VIRTUALENVWRAPPER_PYTHON"] = ":"
    try:
        process = subprocess.Popen(command, env=env, cwd=cwd)
        process.wait()
    except exceptions.CommandNotFoundError as error:
        if error.errno != 2:
            raise
        return None
    return process.returncode


text:
package com.anysoftkeyboard.ime;

import android.content.SharedPreferences;
import android.support.annotation.NonNull;
import android.view.inputmethod.InputConnection;

import com.anysoftkeyboard.dictionaries.TextEntryState;
import com.anysoftkeyboard.gesturetyping.GestureTypingDetector;
import com.menny.android.anysoftkeyboard.R;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public abstract class AnySoftKeyboardWithGestureTyping extends AnySoftKeyboardWithQuickText {

    private boolean mGestureTypingEnabled;
    private GestureTypingDetector mGestureTypingDetector;

    @Override
    protected void onLoadSettingsRequired(SharedPreferences sharedPreferences) {
        super.onLoadSettingsRequired(sharedPreferences);
        mGestureTypingEnabled = sharedPreferences.getBoolean(getString(R.string.settings_key_gesture_typing),
                getResources().getBoolean(R.bool.settings_default_gesture_typing));

        if (mGestureTypingDetector == null && mGestureTypingEnabled) {
            mGestureTypingDetector = new GestureTypingDetector();
            mGestureTypingDetector.loadResources(this);
        }
    }

    protected abstract void commitWordToInput(@NonNull CharSequence wordToCommit, boolean correcting);

    public abstract void setSuggestions(List<? extends CharSequence> suggestions,
                                        boolean completions, boolean typedWordValid,
                                        boolean haveMinimalSuggestion);

    @Override
    public boolean isValidGestureTypingStart(int x, int y) {
        if (!mGestureTypingEnabled) return false;
        mGestureTypingDetector.setKeys(getCurrentAlphabetKeyboard().getKeys(), this,
                getCurrentAlphabetKeyboard().getMinWidth(), getCurrentAlphabetKeyboard().getHeight());

        return mGestureTypingDetector.isValidStartTouch(x,y);
    }

    @Override
    public void onGestureTypingInputStart(int x, int y, long eventTime) {
        if (!mGestureTypingEnabled) return;
        mGestureTypingDetector.clearGesture();
        mGestureTypingDetector.addPoint(x,y,eventTime);
    }

    @Override
    public void onGestureTypingInput(int x, int y, long eventTime) {
        if (!mGestureTypingEnabled) return;
        mGestureTypingDetector.addPoint(x,y,eventTime);
    }

    @Override
    public void onGestureTypingInputDone() {
        if (!mGestureTypingEnabled) return;
        InputConnection ic = getCurrentInputConnection();

        if (mGestureTypingEnabled && ic != null) {
            ArrayList<String> gestureTypingPossibilities = mGestureTypingDetector.getCandidates();

            final boolean isShifted = mShiftKeyState.isActive();
            final boolean isCapsLocked = mShiftKeyState.isLocked();

            if (gestureTypingPossibilities.size() > 0) {
                ic.beginBatchEdit();
                final boolean alsoAddSpace = TextEntryState.getState() == TextEntryState.State.PERFORMED_GESTURE;
                abortCorrectionAndResetPredictionState(false);

                if (alsoAddSpace) {
                    //adding space automatically
                    ic.commitText(" ", 1);
                }

                CharSequence word = gestureTypingPossibilities.get(0);

                // This is used when correcting
                mWord.reset();
                mWord.setAutoCapitalized(isShifted || isCapsLocked);
                mWord.simulateTypedWord(word);

                commitWordToInput(mWord.getTypedWord(), false);

                TextEntryState.performedGesture();

                if (gestureTypingPossibilities.size() > 1) {
                    setCandidatesViewShown(true);
                    setSuggestions(gestureTypingPossibilities, false, true, true);
                } else {
                    //clearing any suggestion shown
                    setSuggestions(Collections.<CharSequence>emptyList(), false, false, false);
                }

                ic.endBatchEdit();
            }

            mGestureTypingDetector.clearGesture();
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
import time

from autosklearn.util.stopwatch import StopWatch

def test_stopwatch_overhead() -> None:
    wall_start = time.time()
    cpu_start = time.process_time()

    watch = StopWatch()
    for i in range(1, 1000):
        watch.start("task_%d" % i)
        watch.stop("task_%d" % i)

    cpu_end = time.process_time()
    wall_end = time.time()

    wall_duration = wall_end - wall_start
    cpu_duration = cpu_end - cpu_start

    cpu_overhead = cpu_duration - watch.total_cpu()
    wall_overhead = wall_duration - watch.total_wall()

    assert cpu_overhead < 1
    assert wall_overhead < 1
    assert watch.total_cpu() < 2 * watch.total_wall()

def test_contextmanager() -> None:
    watch = StopWatch()

    with watch.time("task"):
        assert watch["task"].started()

    assert "task" in watch
    assert watch["task"].finished()

    assert watch["task"].cpu_duration is not None
    assert watch["task"].wall_duration is not None


text:
import tokenize
import collections
import os
import funcy
import microcache
from io import StringIO

try:
    from urllib import parse as urlparse
except ImportError:
    import urlparse

SimplifiedToken = collections.namedtuple('SimplifiedToken', ('typenum', 'value'))

@microcache.this
def value_of_named_argument_in_function(argument_name, function_name, search_str,
                                        resolve_varname=False):
    """ Parse an arbitrary block of python code to get the value of a named argument
        from inside a function call
    """
    try:
        search_str = unicode(search_str)
    except NameError:
        pass
    readline = StringIO(search_str).readline
    try:
        token_generator = tokenize.generate_tokens(readline)
        tokens = [SimplifiedToken(toknum, tokval) for toknum, tokval, _, _, _ in token_generator]
    except tokenize.TokenError as e:
        raise ValueError('search_str is not parse-able python code: ' + str(e))
    in_function = False
    is_var = False
    for i in range(len(tokens)):
        if (
            not in_function and
            tokens[i].typenum == tokenize.NAME and tokens[i].value == function_name and
            tokens[i+1].typenum == tokenize.OP and tokens[i+1].value == '('
        ):
            in_function = True
            continue
        elif (
            in_function and
            tokens[i].typenum == tokenize.NAME and tokens[i].value == argument_name and
            tokens[i+1].typenum == tokenize.OP and tokens[i+1].value == '='
        ):
            # value is set to another variable which we are going to attempt to resolve
            if resolve_varname and tokens[i+2].typenum == 1:
                is_var = True
                argument_name = tokens[i+2].value
                break

            # again, for a very specific usecase -- get the whole value and concatenate it
            # this will match something like _version.__version__
            j = 3
            while True:
                if tokens[i+j].value in (',', ')') or tokens[i+j].typenum == 58:
                    break
                j += 1

            return ''.join([t.value for t in tokens[i+2:i+j]]).strip()

    # this is very dumb logic, and only works if the function argument is set to a variable
    # which is set to a string value
    if is_var:
        for i in range(len(tokens)):
            if (
                tokens[i].typenum == tokenize.NAME and tokens[i].value == argument_name and
                tokens[i+1].typenum == tokenize.OP and tokens[i+1].value == '='
            ):
                return tokens[i+2].value.strip()

    return None

@microcache.this
def get_file_content(file_path):
    """ Load the content of a text file into a string """
    with open(file_path) as f:
        ret = f.read()
    return ret

@microcache.this
def package_file_path(filename, package_name):
    """ Convenience function to get the path to a package's version file

    >>> package_file_path('mymodule.py', 'mypackage')
    'mypackage/mymodule.py'
    """
    return os.path.join(package_name, filename)

@microcache.this
def regex_in_file(regex, filepath, return_match=False):
    """ Search for a regex in a file

    If return_match is True, return the found object instead of a boolean
    """
    file_content = get_file_content(filepath)
    re_method = funcy.re_find if return_match else funcy.re_test
    return re_method(regex, file_content)

@microcache.this
def regex_in_package_file(regex, filename, package_name, return_match=False):
    """ Search for a regex in a file contained within the package directory

    If return_match is True, return the found object instead of a boolean
    """
    filepath = package_file_path(filename, package_name)
    return regex_in_file(regex, filepath, return_match=return_match)

@microcache.this
def string_is_url(test_str):
    """ Test to see if a string is a URL or not, defined in this case as a string for which
    urlparse returns a scheme component

    >>> string_is_url('somestring')
    False
    >>> string_is_url('https://some.domain.org/path')
    True
    """
    parsed = urlparse.urlparse(test_str)
    return parsed.scheme is not None and parsed.scheme != ''


text:
package router

import (
	"crypto/rand"
	"crypto/rsa"
	"crypto/tls"
	"crypto/x509"
	"encoding/asn1"
	"encoding/pem"
	"fmt"
	"io/ioutil"
	"log"
	"net"
	"net/http"
	"net/http/httptest"
	"net/url"
	"os"
	"sort"
	"strings"
	"sync"
	"testing"

	"golang.org/x/crypto/ssh"

	"github.com/gorilla/websocket"
	"github.com/miekg/dns"
	"github.com/stretchr/testify/assert"
)

func testSshClient(user string, r *proxyRouter) error {
	reader := rand.Reader
	bitSize := 2048

	key, err := rsa.GenerateKey(reader, bitSize)
	if err != nil {
		return err
	}
	signer, err := ssh.NewSignerFromKey(key)
	if err != nil {
		return err
	}
	config := &ssh.ClientConfig{
		User: user,
		Auth: []ssh.AuthMethod{
			ssh.PublicKeys(signer),
		},
		HostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error {
			return nil
		},
	}
	chunks := strings.Split(r.ListenSshAddress(), ":")
	l := fmt.Sprintf("127.0.0.1:%s", chunks[len(chunks)-1])
	client, err := ssh.Dial("tcp", l, config)
	if err != nil {
		return err
	}
	session, err := client.NewSession()
	if err != nil {
		return err
	}
	defer session.Close()

	return nil
}

func testSshServer(f func(user, pass, ctype string)) (string, error) {
	reader := rand.Reader
	bitSize := 2048

	key, err := rsa.GenerateKey(reader, bitSize)
	if err != nil {
		return "", err
	}
	signer, err := ssh.NewSignerFromKey(key)
	if err != nil {
		return "", err
	}

	var receivedUser string
	var receivedPass string
	var receivedChannelType string

	config := &ssh.ServerConfig{
		PasswordCallback: func(conn ssh.ConnMetadata, password []byte) (*ssh.Permissions, error) {
			receivedUser = conn.User()
			receivedPass = string(password)

			return nil, nil
		},
	}
	config.AddHostKey(signer)
	listener, err := net.Listen("tcp", "0.0.0.0:0")
	if err != nil {
		return "", err
	}

	go func() {
		defer listener.Close()
		nConn, err := listener.Accept()
		if err != nil {
			log.Println(err)
			return
		}
		conn, chans, reqs, err := ssh.NewServerConn(nConn, config)
		if err != nil {
			log.Println(err)
			return
		}
		go ssh.DiscardRequests(reqs)
		defer nConn.Close()
		defer conn.Close()

		ch := <-chans

		receivedChannelType = ch.ChannelType()

		f(receivedUser, receivedPass, receivedChannelType)
	}()

	return listener.Addr().String(), nil
}

func generateKeys() (string, string, string, error) {
	dir, err := ioutil.TempDir("", "pwd")
	if err != nil {
		return "", "", "", err
	}

	reader := rand.Reader
	bitSize := 2048

	key, err := rsa.GenerateKey(reader, bitSize)
	if err != nil {
		return "", "", "", err
	}

	privateFile, err := os.OpenFile(fmt.Sprintf("%s/id_rsa", dir), os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
	if err != nil {
		return "", "", "", err
	}
	defer privateFile.Close()

	var privateKey = &pem.Block{
		Type:  "RSA PRIVATE KEY",
		Bytes: x509.MarshalPKCS1PrivateKey(key),
	}

	err = pem.Encode(privateFile, privateKey)
	if err != nil {
		return "", "", "", err
	}

	publicFile, err := os.OpenFile(fmt.Sprintf("%s/id_rsa.pub", dir), os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
	if err != nil {
		return "", "", "", err
	}
	defer publicFile.Close()

	asn1Bytes, err := asn1.Marshal(key.PublicKey)
	if err != nil {
		return "", "", "", err
	}

	var publicKey = &pem.Block{
		Type:  "PUBLIC KEY",
		Bytes: asn1Bytes,
	}

	err = pem.Encode(publicFile, publicKey)
	if err != nil {
		return "", "", "", err
	}
	return dir, privateFile.Name(), publicFile.Name(), nil
}

func getRouterUrl(scheme string, r *proxyRouter) string {
	chunks := strings.Split(r.ListenHttpAddress(), ":")
	return fmt.Sprintf("%s://localhost:%s", scheme, chunks[len(chunks)-1])
}

func routerLookup(protocol, domain string, r *proxyRouter) ([]string, error) {
	c := dns.Client{Net: protocol}
	m := dns.Msg{}

	m.SetQuestion(fmt.Sprintf("%s.", domain), dns.TypeA)
	var l string
	if protocol == "udp" {
		chunks := strings.Split(r.ListenDnsUdpAddress(), ":")
		l = fmt.Sprintf("127.0.0.1:%s", chunks[len(chunks)-1])
	} else if protocol == "tcp" {
		chunks := strings.Split(r.ListenDnsTcpAddress(), ":")
		l = fmt.Sprintf("127.0.0.1:%s", chunks[len(chunks)-1])
	}
	res, _, err := c.Exchange(&m, l)

	if err != nil {
		return nil, err
	}

	if len(res.Answer) == 0 {
		return nil, fmt.Errorf("Didn't receive any answer")
	}
	addrs := []string{}
	for _, a := range res.Answer {
		if b, ok := a.(*dns.A); ok {
			addrs = append(addrs, b.A.String())
		} else if b, ok := a.(*dns.AAAA); ok {
			addrs = append(addrs, b.AAAA.String())
		}
	}

	return addrs, nil
}

func TestProxy_TLS(t *testing.T) {
	dir, private, _, _ := generateKeys()
	defer os.RemoveAll(dir)

	tr := &http.Transport{
		TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
	}
	client := &http.Client{Transport: tr}

	const msg = "It works!"

	var receivedHost string
	var receivedProtocol Protocol

	ts := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprint(w, msg)
	}))
	defer ts.Close()

	r := NewRouter(func(protocol Protocol, host string) (*DirectorInfo, error) {
		receivedHost = host
		receivedProtocol = protocol
		u, _ := url.Parse(ts.URL)
		a, _ := net.ResolveTCPAddr("tcp", u.Host)
		return &DirectorInfo{Dst: a}, nil
	}, private)
	r.Listen(":0", ":0", ":0")
	defer r.Close()

	req, err := http.NewRequest("GET", getRouterUrl("https", r), nil)
	assert.Nil(t, err)

	resp, err := client.Do(req)
	assert.Nil(t, err)

	body, err := ioutil.ReadAll(resp.Body)
	assert.Nil(t, err)
	assert.Equal(t, msg, string(body))
	assert.Equal(t, "localhost", receivedHost)
	assert.Equal(t, ProtocolHTTPS, receivedProtocol)
}

func TestProxy_Http(t *testing.T) {
	dir, private, _, _ := generateKeys()
	defer os.RemoveAll(dir)

	const msg = "It works!"

	var receivedHost string
	var receivedProtocol Protocol

	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprint(w, msg)
	}))
	defer ts.Close()

	r := NewRouter(func(protocol Protocol, host string) (*DirectorInfo, error) {
		receivedHost = host
		receivedProtocol = protocol
		u, _ := url.Parse(ts.URL)
		a, _ := net.ResolveTCPAddr("tcp", u.Host)
		return &DirectorInfo{Dst: a}, nil
	}, private)
	r.Listen(":0", ":0", ":0")
	defer r.Close()

	req, err := http.NewRequest("GET", getRouterUrl("http", r), nil)
	assert.Nil(t, err)

	resp, err := http.DefaultClient.Do(req)
	assert.Nil(t, err)

	body, err := ioutil.ReadAll(resp.Body)
	assert.Nil(t, err)
	assert.Equal(t, msg, string(body))

	u, _ := url.Parse(getRouterUrl("http", r))
	assert.Equal(t, u.Host, receivedHost)
	assert.Equal(t, ProtocolHTTP, receivedProtocol)
}

func TestProxy_WS(t *testing.T) {
	dir, private, _, _ := generateKeys()
	defer os.RemoveAll(dir)

	const msg = "It works!"

	var serverReceivedMessage string

	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		var upgrader = websocket.Upgrader{}
		c, err := upgrader.Upgrade(w, r, nil)
		if err != nil {
			log.Print("upgrade:", err)
			return
		}
		defer c.Close()
		mt, message, err := c.ReadMessage()
		if err != nil {
			log.Println("read:", err)
			return
		}
		serverReceivedMessage = string(message)
		err = c.WriteMessage(mt, message)
		if err != nil {
			log.Println("write:", err)
			return
		}
	}))
	defer ts.Close()

	r := NewRouter(func(protocol Protocol, host string) (*DirectorInfo, error) {
		u, _ := url.Parse(ts.URL)
		a, _ := net.ResolveTCPAddr("tcp", u.Host)
		return &DirectorInfo{Dst: a}, nil
	}, private)
	r.Listen(":0", ":0", ":0")
	defer r.Close()

	c, _, err := websocket.DefaultDialer.Dial(getRouterUrl("ws", r), nil)
	assert.Nil(t, err)
	defer c.Close()

	var clientReceivedMessage []byte
	wg := sync.WaitGroup{}
	wg.Add(1)
	go func() {
		_, clientReceivedMessage, _ = c.ReadMessage()
		wg.Done()
	}()
	err = c.WriteMessage(websocket.TextMessage, []byte(msg))
	assert.Nil(t, err)

	wg.Wait()

	assert.Equal(t, msg, string(clientReceivedMessage))
	assert.Equal(t, msg, serverReceivedMessage)
}

func TestProxy_WSS(t *testing.T) {
	dir, private, _, _ := generateKeys()
	defer os.RemoveAll(dir)

	const msg = "It works!"

	var serverReceivedMessage string

	ts := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		var upgrader = websocket.Upgrader{}
		c, err := upgrader.Upgrade(w, r, nil)
		if err != nil {
			log.Print("upgrade:", err)
			return
		}
		defer c.Close()
		mt, message, err := c.ReadMessage()
		if err != nil {
			log.Println("read:", err)
			return
		}
		serverReceivedMessage = string(message)
		err = c.WriteMessage(mt, message)
		if err != nil {
			log.Println("write:", err)
			return
		}
	}))
	defer ts.Close()

	r := NewRouter(func(protocol Protocol, host string) (*DirectorInfo, error) {
		u, _ := url.Parse(ts.URL)
		a, _ := net.ResolveTCPAddr("tcp", u.Host)
		return &DirectorInfo{Dst: a}, nil
	}, private)
	r.Listen(":0", ":0", ":0")
	defer r.Close()

	d := websocket.Dialer{TLSClientConfig: &tls.Config{InsecureSkipVerify: true}}
	c, _, err := d.Dial(getRouterUrl("wss", r), nil)
	assert.Nil(t, err)
	defer c.Close()

	var clientReceivedMessage []byte

	wg := sync.WaitGroup{}
	wg.Add(1)
	go func() {
		_, clientReceivedMessage, _ = c.ReadMessage()
		wg.Done()
	}()

	err = c.WriteMessage(websocket.TextMessage, []byte(msg))
	assert.Nil(t, err)

	wg.Wait()

	assert.Equal(t, msg, string(clientReceivedMessage))
	assert.Equal(t, msg, serverReceivedMessage)
}

func TestProxy_DNS_UDP(t *testing.T) {
	dir, private, _, _ := generateKeys()
	defer os.RemoveAll(dir)

	var receivedHost string
	var receivedProtocol Protocol

	r := NewRouter(func(protocol Protocol, host string) (*DirectorInfo, error) {
		receivedHost = host
		receivedProtocol = protocol
		if host == "10_0_0_1.foo.bar" {
			a, _ := net.ResolveTCPAddr("tcp", "10.0.0.1:0")
			return &DirectorInfo{Dst: a}, nil
		} else {
			return nil, fmt.Errorf("Not recognized")
		}
	}, private)
	r.Listen(":0", ":0", ":0")
	defer r.Close()

	ips, err := routerLookup("udp", "10_0_0_1.foo.bar", r)
	assert.Nil(t, err)
	assert.Equal(t, "10_0_0_1.foo.bar", receivedHost)
	assert.Equal(t, ProtocolDNS, receivedProtocol)
	assert.Equal(t, []string{"10.0.0.1"}, ips)

	ips, err = routerLookup("udp", "www.google.com", r)
	assert.Nil(t, err)
	assert.Equal(t, "www.google.com", receivedHost)
	assert.Equal(t, ProtocolDNS, receivedProtocol)

	expectedIps, err := net.LookupHost("www.google.com")
	assert.Nil(t, err)

	sort.Strings(expectedIps)
	sort.Strings(ips)
	assert.Equal(t, expectedIps, ips)

	ips, err = routerLookup("udp", "localhost", r)
	assert.Nil(t, err)
	assert.NotEqual(t, "localhost", receivedHost)
	assert.Equal(t, ProtocolDNS, receivedProtocol)
	assert.Equal(t, []string{"127.0.0.1"}, ips)
}

func TestProxy_DNS_TCP(t *testing.T) {
	dir, private, _, _ := generateKeys()
	defer os.RemoveAll(dir)

	var receivedHost string

	r := NewRouter(func(protocol Protocol, host string) (*DirectorInfo, error) {
		receivedHost = host
		if host == "10_0_0_1.foo.bar" {
			a, _ := net.ResolveTCPAddr("tcp", "10.0.0.1:0")
			return &DirectorInfo{Dst: a}, nil
		} else {
			return nil, fmt.Errorf("Not recognized")
		}
	}, private)
	r.Listen(":0", ":0", ":0")
	defer r.Close()

	ips, err := routerLookup("tcp", "10_0_0_1.foo.bar", r)
	assert.Nil(t, err)
	assert.Equal(t, "10_0_0_1.foo.bar", receivedHost)
	assert.Equal(t, []string{"10.0.0.1"}, ips)

	ips, err = routerLookup("tcp", "www.google.com", r)
	assert.Nil(t, err)
	assert.Equal(t, "www.google.com", receivedHost)

	expectedIps, err := net.LookupHost("www.google.com")
	assert.Nil(t, err)

	sort.Strings(expectedIps)
	sort.Strings(ips)
	assert.Equal(t, expectedIps, ips)

	ips, err = routerLookup("tcp", "localhost", r)
	assert.Nil(t, err)
	assert.NotEqual(t, "localhost", receivedHost)
	assert.Equal(t, []string{"127.0.0.1"}, ips)
}

func TestProxy_SSH(t *testing.T) {
	dir, private, _, _ := generateKeys()
	defer os.RemoveAll(dir)

	var receivedUser string
	var receivedPass string
	var receivedChannelType string
	var receivedHost string
	var receivedProtocol Protocol

	wg := sync.WaitGroup{}
	wg.Add(1)
	laddr, err := testSshServer(func(user, pass, ctype string) {
		receivedUser = user
		receivedPass = pass
		receivedChannelType = ctype
		wg.Done()
	})
	assert.Nil(t, err)

	r := NewRouter(func(protocol Protocol, host string) (*DirectorInfo, error) {
		receivedHost = host
		receivedProtocol = protocol
		if host == "10-0-0-1-aaaabbbb" {
			chunks := strings.Split(laddr, ":")
			a, _ := net.ResolveTCPAddr("tcp", fmt.Sprintf("127.0.0.1:%s", chunks[len(chunks)-1]))
			return &DirectorInfo{Dst: a, SSHUser: "root", SSHAuthMethods: []ssh.AuthMethod{ssh.Password("root")}}, nil
		} else {
			return nil, fmt.Errorf("Not recognized")
		}
	}, private)
	r.Listen(":0", ":0", ":0")
	defer r.Close()

	err = testSshClient("10-0-0-1-aaaabbbb", r)
	assert.Nil(t, err)

	wg.Wait()

	assert.Equal(t, "root", receivedUser)
	assert.Equal(t, "root", receivedPass)
	assert.Equal(t, "session", receivedChannelType)
	assert.Equal(t, "10-0-0-1-aaaabbbb", receivedHost)
	assert.Equal(t, ProtocolSSH, receivedProtocol)
}


text:
Tokenizer
=========

Generate one-time use authenticated links to arbitrary rails resources. Used in mailer to give users single use updates.

## to get this running from within an app ##

    mount Tokenizer::Engine => "/tokenizer", :as => "tokenizer_engine"

    rake tokenizer:install:migrations

files will be copied, then run:

    rake db:migrate

    get "simulate/tokenized_thing"

go here: http://localhost:4000/tokenizer/

## Using in your app ##

add `acts_as_tokenized_thing` to a model.

that adds the the method your_resource.tokenize_me

    acts_as_tokenized_thing :default_lifespan => 1.day

if not specified 1 day will be used.

## example use in rails console ##

creating a user action without saving it
  an_action = UserAction.new(actual_value: 10, priority_id: 1, user_id: 1, done_at: Time.now)
  an_action.tokenize_me

you can find tokenized values

    Tokenizer::TokenizedThing.all

* There is no user_action id, because it doesn't exist yet.

## Engine Design ##

* Make engine

        rails plugin new tokenizer --mountable

* Mount the engine in your_app/config/routes

        mount Tokenizer::Engine => "/tokenizer"

* To access engine paths from within the parent app,

        mount Tokenizer::Engine => "/tokenizer", :as => "tokenizer_engine"

in a view `redirect_to tokenizer_engine.root_path`

* From within the engine

        <%= link_to "Simulate Tokenized Thing", main_app.simulate_tokenized_thing_path %>

* Generating the tokenized_thing

        rails g model tokenized_thing class_name:string token:string parameters:text redirect_url_success:string redirect_url_failure:string lifespan:datetime

* Run

        rake db:create
        rake db:migrate

* Make a test object

        Tokenizer::TokenizedThing.create!(:class_name => 'UserAction', :token => 'a_unique_token', :parameters => '{"this": "is", "a": "JSON", "string": "bitches"}', :lifespan => Time.now + 1.year)

## Tests ##

    cd tokenizer/test
    ruby -Itest test/unit/tokenizer/tokenized_thing_test.rb

## TODOs ##

* sweep through and delete old tokens

* test coverage

## Thanks ##

Thanks to Ryan Bates http://railscasts.com/episodes/277-mountable-engines

## MIT License


text:
//-----------------------------------NOTICE----------------------------------//
// Some of this file is automatically filled in by a Python script.  Only    //
// add custom code in the designated areas or it will be overwritten during  //
// the next update.                                                          //
//-----------------------------------NOTICE----------------------------------//

//--BEGIN FILE HEAD CUSTOM CODE--//
#include "../../include/Inertia.h"
//--END CUSTOM CODE--//

#include "../../include/FixLink.h"
#include "../../include/ObjectRegistry.h"
#include "../../include/NIF_IO.h"
#include "../../include/obj/bhkSphereRepShape.h"
using namespace Niflib;

//Definition of TYPE constant
const Type bhkSphereRepShape::TYPE("bhkSphereRepShape", &bhkShape::TYPE );

bhkSphereRepShape::bhkSphereRepShape() : material((HavokMaterial)0), skyrimMaterial((SkyrimHavokMaterial)0), radius(0.0f) {
	//--BEGIN CONSTRUCTOR CUSTOM CODE--//
	//--END CUSTOM CODE--//
}

bhkSphereRepShape::~bhkSphereRepShape() {
	//--BEGIN DESTRUCTOR CUSTOM CODE--//
	//--END CUSTOM CODE--//
}

const Type & bhkSphereRepShape::GetType() const {
	return TYPE;
}

NiObject * bhkSphereRepShape::Create() {
	return new bhkSphereRepShape;
}

void bhkSphereRepShape::Read( istream& in, list<unsigned int> & link_stack, const NifInfo & info ) {
	//--BEGIN PRE-READ CUSTOM CODE--//
	//--END CUSTOM CODE--//

	bhkShape::Read( in, link_stack, info );
	if ( (info.userVersion < 12) ) {
		NifStream( material, in, info );
	};
	if ( (info.userVersion >= 12) ) {
		NifStream( skyrimMaterial, in, info );
	};
	NifStream( radius, in, info );

	//--BEGIN POST-READ CUSTOM CODE--//
	//--END CUSTOM CODE--//
}

void bhkSphereRepShape::Write( ostream& out, const map<NiObjectRef,unsigned int> & link_map, list<NiObject *> & missing_link_stack, const NifInfo & info ) const {
	//--BEGIN PRE-WRITE CUSTOM CODE--//
	//--END CUSTOM CODE--//

	bhkShape::Write( out, link_map, missing_link_stack, info );
	if ( (info.userVersion < 12) ) {
		NifStream( material, out, info );
	};
	if ( (info.userVersion >= 12) ) {
		NifStream( skyrimMaterial, out, info );
	};
	NifStream( radius, out, info );

	//--BEGIN POST-WRITE CUSTOM CODE--//
	//--END CUSTOM CODE--//
}

std::string bhkSphereRepShape::asString( bool verbose ) const {
	//--BEGIN PRE-STRING CUSTOM CODE--//
	//--END CUSTOM CODE--//

	stringstream out;
	out << bhkShape::asString();
	out << "  Material:  " << material << endl;
	out << "  Skyrim Material:  " << skyrimMaterial << endl;
	out << "  Radius:  " << radius << endl;
	return out.str();

	//--BEGIN POST-STRING CUSTOM CODE--//
	//--END CUSTOM CODE--//
}

void bhkSphereRepShape::FixLinks( const map<unsigned int,NiObjectRef> & objects, list<unsigned int> & link_stack, list<NiObjectRef> & missing_link_stack, const NifInfo & info ) {
	//--BEGIN PRE-FIXLINKS CUSTOM CODE--//
	//--END CUSTOM CODE--//

	bhkShape::FixLinks( objects, link_stack, missing_link_stack, info );

	//--BEGIN POST-FIXLINKS CUSTOM CODE--//
	//--END CUSTOM CODE--//
}

std::list<NiObjectRef> bhkSphereRepShape::GetRefs() const {
	list<Ref<NiObject> > refs;
	refs = bhkShape::GetRefs();
	return refs;
}

std::list<NiObject *> bhkSphereRepShape::GetPtrs() const {
	list<NiObject *> ptrs;
	ptrs = bhkShape::GetPtrs();
	return ptrs;
}

/***Begin Example Naive Implementation****

HavokMaterial bhkSphereRepShape::GetMaterial() const {
	return material;
}

void bhkSphereRepShape::SetMaterial( const HavokMaterial & value ) {
	material = value;
}

SkyrimHavokMaterial bhkSphereRepShape::GetSkyrimMaterial() const {
	return skyrimMaterial;
}

void bhkSphereRepShape::SetSkyrimMaterial( const SkyrimHavokMaterial & value ) {
	skyrimMaterial = value;
}

float bhkSphereRepShape::GetRadius() const {
	return radius;
}

void bhkSphereRepShape::SetRadius( float value ) {
	radius = value;
}

****End Example Naive Implementation***/

//--BEGIN MISC CUSTOM CODE--//

HavokMaterial bhkSphereRepShape::GetMaterial() const {
	return material;
}

void bhkSphereRepShape::SetMaterial( HavokMaterial value ) {
	material = value;
}

SkyrimHavokMaterial bhkSphereRepShape::GetSkyrimMaterial() const {
	return skyrimMaterial;
}

void bhkSphereRepShape::SetSkyrimMaterial(SkyrimHavokMaterial value) {
	skyrimMaterial = value;
}

float bhkSphereRepShape::GetRadius() const {
	return radius;
}

void bhkSphereRepShape::SetRadius( float value ) {
	radius = value;
}

void bhkSphereRepShape::CalcMassProperties(float density, bool solid, float &mass, float &volume, Vector3 &center, InertiaMatrix& inertia)
{
	center = Vector3(0,0,0);
	mass = 0.0f, volume = 0.0f;
	inertia = InertiaMatrix::IDENTITY;
	Inertia::CalcMassPropertiesSphere(radius, density, solid, mass, volume, center, inertia);

}
//--END CUSTOM CODE--//


text:
using System.Diagnostics;
using System.IO;

namespace FTTLib
{
    /// <summary>
    /// Methods for translating between mime-types and file extensions
    /// </summary>
    public sealed partial class FTT
    {
        /// <summary>
        /// Returns the mime type for the given file name
        /// </summary>
        /// <param name="fileName">A file name, file extension or file path specification</param>
        /// <returns></returns>
        [DebuggerStepThrough]
        public static string GetMimeType(string fileName)
        {
            string extension = GetExtension(fileName);

            return GetMimeTypeInternal(extension.ToLowerInvariant().Replace(".", ""));
        }

        /// <summary>
        /// Returns a list of possible file extensions for the given mime type
        /// </summary>
        /// <param name="mimeType">A mime type</param>
        /// <returns></returns>
        [DebuggerStepThrough]
        public static string[] GetMimeTypeFileExtensions(string mimeType)
        {
            return GetMimeTypeFileExtensionsInternal(mimeType.ToLowerInvariant());
        }

        /// <summary>
        /// Returns a file category for the given file name
        /// </summary>
        /// <param name="fileName">A file name, file extension or file path specification</param>
        /// <returns></returns>
        [DebuggerStepThrough]
        public static FileCategory GetFileCategory(string fileName)
        {
            string extension = GetExtension(fileName);

            return GetFileCategoryInternal(extension.ToLowerInvariant().Replace(".", ""));
        }

        private static string GetExtension(string fileName)
        {
            return fileName.Contains(".") ? Path.GetExtension(fileName) : fileName;
        }
    }
}


text:
layout: page
title: Coast Silver Enterprises Party
date: 2016-05-24
author: Stephen Powers
tags: weekly links, java
status: published
summary: Cras ut dictum sapien. Mauris enim ligula.
banner: images/banner/leisure-02.jpg
booking:
  startDate: 08/23/2017
  endDate: 08/28/2017
  ctyhocn: ANBHSHX
  groupCode: CSEP
published: true
---
Praesent eu nibh eget lorem rutrum mattis. Vivamus accumsan lorem sed quam tristique tempus. Ut nec imperdiet ante. Nunc ut pellentesque metus. Nam ultrices luctus velit. Pellentesque vehicula semper facilisis. Proin semper dui id dolor vehicula cursus. Cras sapien tellus, ullamcorper ac odio eget, volutpat gravida magna. Nullam eget est sed ligula feugiat vehicula. Maecenas cursus interdum quam, vitae rutrum est pretium sed.
Etiam convallis ac risus vel viverra. Morbi dictum ipsum in facilisis dignissim. Donec elementum ac elit ac lobortis. Nam consequat nec nibh at sodales. Nunc enim dui, iaculis nec euismod ac, facilisis vel felis. Curabitur quis luctus arcu, vitae ultrices lectus. Nulla tempor efficitur tellus sed ullamcorper. Vivamus sed elit arcu. Curabitur luctus tincidunt lacinia. Nunc id arcu blandit nulla lacinia accumsan.

* Aenean viverra metus eget orci tristique efficitur
* Aenean placerat mauris id nulla ullamcorper porta.

Aliquam consectetur cursus ipsum ac tristique. Aenean lobortis porta nisi nec porttitor. Duis nec justo nec quam pretium imperdiet ut eu ante. Phasellus sit amet suscipit tortor. Vestibulum vitae quam odio. Nullam ullamcorper cursus iaculis. Duis vel leo non nulla pulvinar tincidunt. Cras quis sem est. Donec ac pulvinar dolor. Maecenas facilisis arcu id odio ornare, at consequat nibh faucibus. Vestibulum ante libero, malesuada vel malesuada a, fermentum nec eros.


text:
package cli

import (
	"context"

	"github.com/pkg/errors"

	"github.com/kopia/kopia/repo"
	"github.com/kopia/kopia/repo/maintenance"
)

func maybeAutoUpgradeRepository(ctx context.Context, r repo.Repository) error {
	// only upgrade repository when it's directly connected, not via API.
	dr, _ := r.(repo.DirectRepository)
	if dr == nil {
		return nil
	}

	has, err := maintenance.HasParams(ctx, r)
	if err != nil {
		return errors.Wrap(err, "error looking for maintenance parameters")
	}

	if has {
		return nil
	}

	log(ctx).Debugf("Setting default maintenance parameters...")

	//nolint:wrapcheck
	return repo.DirectWriteSession(ctx, dr, repo.WriteSessionOptions{
		Purpose: "setDefaultMaintenanceParameters",
	}, func(ctx context.Context, w repo.DirectRepositoryWriter) error {
		return setDefaultMaintenanceParameters(ctx, w)
	})
}

func setDefaultMaintenanceParameters(ctx context.Context, rep repo.RepositoryWriter) error {
	p := maintenance.DefaultParams()
	p.Owner = rep.ClientOptions().UsernameAtHost()

	if dw, ok := rep.(repo.DirectRepositoryWriter); ok {
		_, ok, err := dw.ContentReader().EpochManager()
		if err != nil {
			return errors.Wrap(err, "epoch manager")
		}

		if ok {
			// disable quick maintenance cycle
			p.QuickCycle.Enabled = false
		}
	}

	if err := maintenance.SetParams(ctx, rep, &p); err != nil {
		return errors.Wrap(err, "unable to set maintenance params")
	}

	log(ctx).Infof(`
NOTE: Kopia will perform quick maintenance of the repository automatically every %v
and full maintenance every %v when running as %v.

See https://kopia.io/docs/advanced/maintenance/ for more information.
`, p.QuickCycle.Interval, p.FullCycle.Interval, p.Owner)

	return nil
}


text:
<!doctype html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0">
  <title>Import test - three.js, bundled, tree-shaking (using rollup)</title>


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

    angular
        .module('myApp')
        .config(config)
        .run(runBlock);

    // TODO: Move config out to route.config.js
    config.$inject = [
        '$stateProvider',
        '$urlRouterProvider',
        '$authProvider',
        '$httpProvider',
        '$provide'
    ];

    function config($stateProvider, $urlRouterProvider, $authProvider, $httpProvider, $provide) {

        $httpProvider.interceptors.push(authCheckInterceptor);

        $authProvider.loginUrl = '/api/account/login';

        $urlRouterProvider.otherwise('/auth');

        $stateProvider
            .state('main', {
                abstract: true,
                views: {
                    main : {templateUrl: '/assets/partials/shared/appTemplate.html'}
                }
            })
            .state('auth', {
                abstract: true,
                views: {
                    main : {templateUrl: '/assets/partials/shared/authTemplate.html'}
                }
            })
            .state('main.layout', {
                abstract: true,
                views: {
                    'header@main' : { templateUrl: '/assets/partials/components/app/headerView.html' },
                    'content@main' : {},
                    'footer@main' : {}
                }
            })
            .state('main.auth', {
                parent: 'auth',
                url: '/auth',
                views: {
                    "content@auth": { template: "<my-auth></my-auth>" }
                }
            })
            .state('main.home', {
                parent: 'main.layout',
                url: '/home',
                views: {
                    "content@main": { template: "<my-home></my-home>"}
                },
                resolve: {
                    auth: authStateResolve
                }
            });
    }

    authStateResolve.$inject = ['$q', 'authFactory', '$state'];
    function authStateResolve($q, authFactory, $state) {

        if(! authFactory.isAuthenticated()) {
            authFactory.logout();
            return $q.reject({ authenticated: false });
        }

        return $q.when(authFactory.getUser());
    }

    authCheckInterceptor.$inject = ['$q', '$injector'];
    function authCheckInterceptor($q, $injector) {

        return {
            responseError: function(rejection) {

                var $state = $injector.get('$state');
                var authFactory = $injector.get('authFactory');

                var rejectionReasons = ['token_not_provided', 'token_expired', 'token_absent', 'token_invalid'];

                angular.forEach(rejectionReasons, function(value, key) {

                    if(rejection.data.error == value || rejection.data == value) {
                        authFactory.logout();
                    }
                });

                return $q.reject(rejection);
            }
        };
    }

    runBlock.$inject = ['$rootScope', '$state', 'authFactory'];
    function runBlock($rootScope, $state, authFactory) {
        $rootScope.authLogout = function() { authFactory.logout(); };

        $rootScope.$on("$stateChangeStart", function(event, next) {

            var user = authFactory.getUser();

            // TODO: Refactor
            if(user) {
                authFactory.setAuthenticated(true);
                authFactory.setUser(user);

                if(next.name == "main.auth") {
                    event.preventDefault();
                    $state.go('main.home');
                }
            } else {
                if(next.name !== "main.auth") {
                    authFactory.logout();
                }
            }
        });

    }

})();


text:
module ParseFasta
  module CoreExt
    module String

      # Removes all gap chars from the string.
      #
      # @example Remove all '-' from string
      #   # First inclued the methods
      #   String.include ParseFasta::CoreExt::String
      #
      #   # The default gap char is '-'
      #   "--A-C-t-g".remove_gaps #=> "ACtg"
      #
      # @example Change the gap character to 'n'
      #   # First inclued the methods
      #   String.include ParseFasta::CoreExt::String
      #
      #   "-N-nACTG".remove_gaps "N" #=> "--nACTG"
      #
      # @example Passing multiple gap chars
      #   # First inclued the methods
      #   String.include ParseFasta::CoreExt::String
      #
      #   ".A----C_t~~~~g^G3".remove_gaps '^._-~3' #=> "ACtgG"
      #
      # @param gap_char [String] the character(s) to treat as a gap
      #
      # @return [String] a string with all instances of
      #   gap_char_removed
      def remove_gaps gap_char="-"

        if gap_char.length > 1
          if gap_char.include? "^"
            gap_char.sub! '^', '\\^'
          end

          if gap_char.include? "-"
            gap_char.sub! '-', '\\-'
          end
        end

        self.tr gap_char, ""
      end
    end
  end
end


text:
'use strict';

const msRest = require('ms-rest');
const msRestAzure = require('ms-rest-azure');
const WebResource = msRest.WebResource;

/**
 * Gets a list of workflow versions.
 *
 * @param {string} resourceGroupName The resource group name.
 *
 * @param {string} workflowName The workflow name.
 *
 * @param {object} [options] Optional Parameters.
 *
 * @param {number} [options.top] The number of items to be included in the
 * result.
 *
 * @param {object} [options.customHeaders] Headers that will be added to the
 * request
 *
 * @param {function} callback - The callback.
 *
 * @returns {function} callback(err, result, request, response)
 *
 *                      {Error}  err        - The Error object if an error occurred, null otherwise.
 *
 *                      {object} [result]   - The deserialized result object if an error did not occur.
 *                      See {@link WorkflowVersionListResult} for more
 *                      information.
 *
 *                      {object} [request]  - The HTTP Request object if an error did not occur.
 *
 *                      {stream} [response] - The HTTP Response stream if an error did not occur.
 */
function _list(resourceGroupName, workflowName, options, callback) {
   /* jshint validthis: true */
  let client = this.client;
  if(!callback && typeof options === 'function') {
    callback = options;
    options = null;
  }
  if (!callback) {
    throw new Error('callback cannot be null.');
  }
  let top = (options && options.top !== undefined) ? options.top : undefined;
  // Validate
  try {
    if (this.client.subscriptionId === null || this.client.subscriptionId === undefined || typeof this.client.subscriptionId.valueOf() !== 'string') {
      throw new Error('this.client.subscriptionId cannot be null or undefined and it must be of type string.');
    }
    if (resourceGroupName === null || resourceGroupName === undefined || typeof resourceGroupName.valueOf() !== 'string') {
      throw new Error('resourceGroupName cannot be null or undefined and it must be of type string.');
    }
    if (workflowName === null || workflowName === undefined || typeof workflowName.valueOf() !== 'string') {
      throw new Error('workflowName cannot be null or undefined and it must be of type string.');
    }
    if (this.client.apiVersion === null || this.client.apiVersion === undefined || typeof this.client.apiVersion.valueOf() !== 'string') {
      throw new Error('this.client.apiVersion cannot be null or undefined and it must be of type string.');
    }
    if (top !== null && top !== undefined && typeof top !== 'number') {
      throw new Error('top must be of type number.');
    }
    if (this.client.acceptLanguage !== null && this.client.acceptLanguage !== undefined && typeof this.client.acceptLanguage.valueOf() !== 'string') {
      throw new Error('this.client.acceptLanguage must be of type string.');
    }
  } catch (error) {
    return callback(error);
  }

  // Construct URL
  let baseUrl = this.client.baseUri;
  let requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Logic/workflows/{workflowName}/versions';
  requestUrl = requestUrl.replace('{subscriptionId}', encodeURIComponent(this.client.subscriptionId));
  requestUrl = requestUrl.replace('{resourceGroupName}', encodeURIComponent(resourceGroupName));
  requestUrl = requestUrl.replace('{workflowName}', encodeURIComponent(workflowName));
  let queryParameters = [];
  queryParameters.push('api-version=' + encodeURIComponent(this.client.apiVersion));
  if (top !== null && top !== undefined) {
    queryParameters.push('$top=' + encodeURIComponent(top.toString()));
  }
  if (queryParameters.length > 0) {
    requestUrl += '?' + queryParameters.join('&');
  }

  // Create HTTP transport objects
  let httpRequest = new WebResource();
  httpRequest.method = 'GET';
  httpRequest.headers = {};
  httpRequest.url = requestUrl;
  // Set Headers
  if (this.client.generateClientRequestId) {
      httpRequest.headers['x-ms-client-request-id'] = msRestAzure.generateUuid();
  }
  if (this.client.acceptLanguage !== undefined && this.client.acceptLanguage !== null) {
    httpRequest.headers['accept-language'] = this.client.acceptLanguage;
  }
  if(options) {
    for(let headerName in options['customHeaders']) {
      if (options['customHeaders'].hasOwnProperty(headerName)) {
        httpRequest.headers[headerName] = options['customHeaders'][headerName];
      }
    }
  }
  httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8';
  httpRequest.body = null;
  // Send Request
  return client.pipeline(httpRequest, (err, response, responseBody) => {
    if (err) {
      return callback(err);
    }
    let statusCode = response.statusCode;
    if (statusCode !== 200) {
      let error = new Error(responseBody);
      error.statusCode = response.statusCode;
      error.request = msRest.stripRequest(httpRequest);
      error.response = msRest.stripResponse(response);
      if (responseBody === '') responseBody = null;
      let parsedErrorResponse;
      try {
        parsedErrorResponse = JSON.parse(responseBody);
        if (parsedErrorResponse) {
          if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error;
          if (parsedErrorResponse.code) error.code = parsedErrorResponse.code;
          if (parsedErrorResponse.message) error.message = parsedErrorResponse.message;
        }
        if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) {
          let resultMapper = new client.models['CloudError']().mapper();
          error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body');
        }
      } catch (defaultError) {
        error.message = `Error "${defaultError.message}" occurred in deserializing the responseBody ` +
                         `- "${responseBody}" for the default response.`;
        return callback(error);
      }
      return callback(error);
    }
    // Create Result
    let result = null;
    if (responseBody === '') responseBody = null;
    // Deserialize Response
    if (statusCode === 200) {
      let parsedResponse = null;
      try {
        parsedResponse = JSON.parse(responseBody);
        result = JSON.parse(responseBody);
        if (parsedResponse !== null && parsedResponse !== undefined) {
          let resultMapper = new client.models['WorkflowVersionListResult']().mapper();
          result = client.deserialize(resultMapper, parsedResponse, 'result');
        }
      } catch (error) {
        let deserializationError = new Error(`Error ${error} occurred in deserializing the responseBody - ${responseBody}`);
        deserializationError.request = msRest.stripRequest(httpRequest);
        deserializationError.response = msRest.stripResponse(response);
        return callback(deserializationError);
      }
    }

    return callback(null, result, httpRequest, response);
  });
}

/**
 * Gets a workflow version.
 *
 * @param {string} resourceGroupName The resource group name.
 *
 * @param {string} workflowName The workflow name.
 *
 * @param {string} versionId The workflow versionId.
 *
 * @param {object} [options] Optional Parameters.
 *
 * @param {object} [options.customHeaders] Headers that will be added to the
 * request
 *
 * @param {function} callback - The callback.
 *
 * @returns {function} callback(err, result, request, response)
 *
 *                      {Error}  err        - The Error object if an error occurred, null otherwise.
 *
 *                      {object} [result]   - The deserialized result object if an error did not occur.
 *                      See {@link WorkflowVersion} for more information.
 *
 *                      {object} [request]  - The HTTP Request object if an error did not occur.
 *
 *                      {stream} [response] - The HTTP Response stream if an error did not occur.
 */
function _get(resourceGroupName, workflowName, versionId, options, callback) {
   /* jshint validthis: true */
  let client = this.client;
  if(!callback && typeof options === 'function') {
    callback = options;
    options = null;
  }
  if (!callback) {
    throw new Error('callback cannot be null.');
  }
  // Validate
  try {
    if (this.client.subscriptionId === null || this.client.subscriptionId === undefined || typeof this.client.subscriptionId.valueOf() !== 'string') {
      throw new Error('this.client.subscriptionId cannot be null or undefined and it must be of type string.');
    }
    if (resourceGroupName === null || resourceGroupName === undefined || typeof resourceGroupName.valueOf() !== 'string') {
      throw new Error('resourceGroupName cannot be null or undefined and it must be of type string.');
    }
    if (workflowName === null || workflowName === undefined || typeof workflowName.valueOf() !== 'string') {
      throw new Error('workflowName cannot be null or undefined and it must be of type string.');
    }
    if (versionId === null || versionId === undefined || typeof versionId.valueOf() !== 'string') {
      throw new Error('versionId cannot be null or undefined and it must be of type string.');
    }
    if (this.client.apiVersion === null || this.client.apiVersion === undefined || typeof this.client.apiVersion.valueOf() !== 'string') {
      throw new Error('this.client.apiVersion cannot be null or undefined and it must be of type string.');
    }
    if (this.client.acceptLanguage !== null && this.client.acceptLanguage !== undefined && typeof this.client.acceptLanguage.valueOf() !== 'string') {
      throw new Error('this.client.acceptLanguage must be of type string.');
    }
  } catch (error) {
    return callback(error);
  }

  // Construct URL
  let baseUrl = this.client.baseUri;
  let requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Logic/workflows/{workflowName}/versions/{versionId}';
  requestUrl = requestUrl.replace('{subscriptionId}', encodeURIComponent(this.client.subscriptionId));
  requestUrl = requestUrl.replace('{resourceGroupName}', encodeURIComponent(resourceGroupName));
  requestUrl = requestUrl.replace('{workflowName}', encodeURIComponent(workflowName));
  requestUrl = requestUrl.replace('{versionId}', encodeURIComponent(versionId));
  let queryParameters = [];
  queryParameters.push('api-version=' + encodeURIComponent(this.client.apiVersion));
  if (queryParameters.length > 0) {
    requestUrl += '?' + queryParameters.join('&');
  }

  // Create HTTP transport objects
  let httpRequest = new WebResource();
  httpRequest.method = 'GET';
  httpRequest.headers = {};
  httpRequest.url = requestUrl;
  // Set Headers
  if (this.client.generateClientRequestId) {
      httpRequest.headers['x-ms-client-request-id'] = msRestAzure.generateUuid();
  }
  if (this.client.acceptLanguage !== undefined && this.client.acceptLanguage !== null) {
    httpRequest.headers['accept-language'] = this.client.acceptLanguage;
  }
  if(options) {
    for(let headerName in options['customHeaders']) {
      if (options['customHeaders'].hasOwnProperty(headerName)) {
        httpRequest.headers[headerName] = options['customHeaders'][headerName];
      }
    }
  }
  httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8';
  httpRequest.body = null;
  // Send Request
  return client.pipeline(httpRequest, (err, response, responseBody) => {
    if (err) {
      return callback(err);
    }
    let statusCode = response.statusCode;
    if (statusCode !== 200) {
      let error = new Error(responseBody);
      error.statusCode = response.statusCode;
      error.request = msRest.stripRequest(httpRequest);
      error.response = msRest.stripResponse(response);
      if (responseBody === '') responseBody = null;
      let parsedErrorResponse;
      try {
        parsedErrorResponse = JSON.parse(responseBody);
        if (parsedErrorResponse) {
          if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error;
          if (parsedErrorResponse.code) error.code = parsedErrorResponse.code;
          if (parsedErrorResponse.message) error.message = parsedErrorResponse.message;
        }
        if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) {
          let resultMapper = new client.models['CloudError']().mapper();
          error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body');
        }
      } catch (defaultError) {
        error.message = `Error "${defaultError.message}" occurred in deserializing the responseBody ` +
                         `- "${responseBody}" for the default response.`;
        return callback(error);
      }
      return callback(error);
    }
    // Create Result
    let result = null;
    if (responseBody === '') responseBody = null;
    // Deserialize Response
    if (statusCode === 200) {
      let parsedResponse = null;
      try {
        parsedResponse = JSON.parse(responseBody);
        result = JSON.parse(responseBody);
        if (parsedResponse !== null && parsedResponse !== undefined) {
          let resultMapper = new client.models['WorkflowVersion']().mapper();
          result = client.deserialize(resultMapper, parsedResponse, 'result');
        }
      } catch (error) {
        let deserializationError = new Error(`Error ${error} occurred in deserializing the responseBody - ${responseBody}`);
        deserializationError.request = msRest.stripRequest(httpRequest);
        deserializationError.response = msRest.stripResponse(response);
        return callback(deserializationError);
      }
    }

    return callback(null, result, httpRequest, response);
  });
}

/**
 * Gets a list of workflow versions.
 *
 * @param {string} nextPageLink The NextLink from the previous successful call
 * to List operation.
 *
 * @param {object} [options] Optional Parameters.
 *
 * @param {object} [options.customHeaders] Headers that will be added to the
 * request
 *
 * @param {function} callback - The callback.
 *
 * @returns {function} callback(err, result, request, response)
 *
 *                      {Error}  err        - The Error object if an error occurred, null otherwise.
 *
 *                      {object} [result]   - The deserialized result object if an error did not occur.
 *                      See {@link WorkflowVersionListResult} for more
 *                      information.
 *
 *                      {object} [request]  - The HTTP Request object if an error did not occur.
 *
 *                      {stream} [response] - The HTTP Response stream if an error did not occur.
 */
function _listNext(nextPageLink, options, callback) {
   /* jshint validthis: true */
  let client = this.client;
  if(!callback && typeof options === 'function') {
    callback = options;
    options = null;
  }
  if (!callback) {
    throw new Error('callback cannot be null.');
  }
  // Validate
  try {
    if (nextPageLink === null || nextPageLink === undefined || typeof nextPageLink.valueOf() !== 'string') {
      throw new Error('nextPageLink cannot be null or undefined and it must be of type string.');
    }
    if (this.client.acceptLanguage !== null && this.client.acceptLanguage !== undefined && typeof this.client.acceptLanguage.valueOf() !== 'string') {
      throw new Error('this.client.acceptLanguage must be of type string.');
    }
  } catch (error) {
    return callback(error);
  }

  // Construct URL
  let requestUrl = '{nextLink}';
  requestUrl = requestUrl.replace('{nextLink}', nextPageLink);

  // Create HTTP transport objects
  let httpRequest = new WebResource();
  httpRequest.method = 'GET';
  httpRequest.headers = {};
  httpRequest.url = requestUrl;
  // Set Headers
  if (this.client.generateClientRequestId) {
      httpRequest.headers['x-ms-client-request-id'] = msRestAzure.generateUuid();
  }
  if (this.client.acceptLanguage !== undefined && this.client.acceptLanguage !== null) {
    httpRequest.headers['accept-language'] = this.client.acceptLanguage;
  }
  if(options) {
    for(let headerName in options['customHeaders']) {
      if (options['customHeaders'].hasOwnProperty(headerName)) {
        httpRequest.headers[headerName] = options['customHeaders'][headerName];
      }
    }
  }
  httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8';
  httpRequest.body = null;
  // Send Request
  return client.pipeline(httpRequest, (err, response, responseBody) => {
    if (err) {
      return callback(err);
    }
    let statusCode = response.statusCode;
    if (statusCode !== 200) {
      let error = new Error(responseBody);
      error.statusCode = response.statusCode;
      error.request = msRest.stripRequest(httpRequest);
      error.response = msRest.stripResponse(response);
      if (responseBody === '') responseBody = null;
      let parsedErrorResponse;
      try {
        parsedErrorResponse = JSON.parse(responseBody);
        if (parsedErrorResponse) {
          if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error;
          if (parsedErrorResponse.code) error.code = parsedErrorResponse.code;
          if (parsedErrorResponse.message) error.message = parsedErrorResponse.message;
        }
        if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) {
          let resultMapper = new client.models['CloudError']().mapper();
          error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body');
        }
      } catch (defaultError) {
        error.message = `Error "${defaultError.message}" occurred in deserializing the responseBody ` +
                         `- "${responseBody}" for the default response.`;
        return callback(error);
      }
      return callback(error);
    }
    // Create Result
    let result = null;
    if (responseBody === '') responseBody = null;
    // Deserialize Response
    if (statusCode === 200) {
      let parsedResponse = null;
      try {
        parsedResponse = JSON.parse(responseBody);
        result = JSON.parse(responseBody);
        if (parsedResponse !== null && parsedResponse !== undefined) {
          let resultMapper = new client.models['WorkflowVersionListResult']().mapper();
          result = client.deserialize(resultMapper, parsedResponse, 'result');
        }
      } catch (error) {
        let deserializationError = new Error(`Error ${error} occurred in deserializing the responseBody - ${responseBody}`);
        deserializationError.request = msRest.stripRequest(httpRequest);
        deserializationError.response = msRest.stripResponse(response);
        return callback(deserializationError);
      }
    }

    return callback(null, result, httpRequest, response);
  });
}

/**
 * @class
 * WorkflowVersions
 * __NOTE__: An instance of this class is automatically created for an
 * instance of the LogicManagementClient.
 * Initializes a new instance of the WorkflowVersions class.
 * @constructor
 *
 * @param {LogicManagementClient} client Reference to the service client.
 */
class WorkflowVersions {
  constructor(client) {
    this.client = client;
    this._list = _list;
    this._get = _get;
    this._listNext = _listNext;
  }

  /**
   * Gets a list of workflow versions.
   *
   * @param {string} resourceGroupName The resource group name.
   *
   * @param {string} workflowName The workflow name.
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {number} [options.top] The number of items to be included in the
   * result.
   *
   * @param {object} [options.customHeaders] Headers that will be added to the
   * request
   *
   * @returns {Promise} A promise is returned
   *
   * @resolve {HttpOperationResponse<WorkflowVersionListResult>} - The deserialized result object.
   *
   * @reject {Error} - The error object.
   */
  listWithHttpOperationResponse(resourceGroupName, workflowName, options) {
    let client = this.client;
    let self = this;
    return new Promise((resolve, reject) => {
      self._list(resourceGroupName, workflowName, options, (err, result, request, response) => {
        let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
        httpOperationResponse.body = result;
        if (err) { reject(err); }
        else { resolve(httpOperationResponse); }
        return;
      });
    });
  }

  /**
   * Gets a list of workflow versions.
   *
   * @param {string} resourceGroupName The resource group name.
   *
   * @param {string} workflowName The workflow name.
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {number} [options.top] The number of items to be included in the
   * result.
   *
   * @param {object} [options.customHeaders] Headers that will be added to the
   * request
   *
   * @param {function} [optionalCallback] - The optional callback.
   *
   * @returns {function|Promise} If a callback was passed as the last parameter
   * then it returns the callback else returns a Promise.
   *
   * {Promise} A promise is returned
   *
   *                      @resolve {WorkflowVersionListResult} - The deserialized result object.
   *
   *                      @reject {Error} - The error object.
   *
   * {function} optionalCallback(err, result, request, response)
   *
   *                      {Error}  err        - The Error object if an error occurred, null otherwise.
   *
   *                      {object} [result]   - The deserialized result object if an error did not occur.
   *                      See {@link WorkflowVersionListResult} for more
   *                      information.
   *
   *                      {object} [request]  - The HTTP Request object if an error did not occur.
   *
   *                      {stream} [response] - The HTTP Response stream if an error did not occur.
   */
  list(resourceGroupName, workflowName, options, optionalCallback) {
    let client = this.client;
    let self = this;
    if (!optionalCallback && typeof options === 'function') {
      optionalCallback = options;
      options = null;
    }
    if (!optionalCallback) {
      return new Promise((resolve, reject) => {
        self._list(resourceGroupName, workflowName, options, (err, result, request, response) => {
          if (err) { reject(err); }
          else { resolve(result); }
          return;
        });
      });
    } else {
      return self._list(resourceGroupName, workflowName, options, optionalCallback);
    }
  }

  /**
   * Gets a workflow version.
   *
   * @param {string} resourceGroupName The resource group name.
   *
   * @param {string} workflowName The workflow name.
   *
   * @param {string} versionId The workflow versionId.
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {object} [options.customHeaders] Headers that will be added to the
   * request
   *
   * @returns {Promise} A promise is returned
   *
   * @resolve {HttpOperationResponse<WorkflowVersion>} - The deserialized result object.
   *
   * @reject {Error} - The error object.
   */
  getWithHttpOperationResponse(resourceGroupName, workflowName, versionId, options) {
    let client = this.client;
    let self = this;
    return new Promise((resolve, reject) => {
      self._get(resourceGroupName, workflowName, versionId, options, (err, result, request, response) => {
        let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
        httpOperationResponse.body = result;
        if (err) { reject(err); }
        else { resolve(httpOperationResponse); }
        return;
      });
    });
  }

  /**
   * Gets a workflow version.
   *
   * @param {string} resourceGroupName The resource group name.
   *
   * @param {string} workflowName The workflow name.
   *
   * @param {string} versionId The workflow versionId.
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {object} [options.customHeaders] Headers that will be added to the
   * request
   *
   * @param {function} [optionalCallback] - The optional callback.
   *
   * @returns {function|Promise} If a callback was passed as the last parameter
   * then it returns the callback else returns a Promise.
   *
   * {Promise} A promise is returned
   *
   *                      @resolve {WorkflowVersion} - The deserialized result object.
   *
   *                      @reject {Error} - The error object.
   *
   * {function} optionalCallback(err, result, request, response)
   *
   *                      {Error}  err        - The Error object if an error occurred, null otherwise.
   *
   *                      {object} [result]   - The deserialized result object if an error did not occur.
   *                      See {@link WorkflowVersion} for more information.
   *
   *                      {object} [request]  - The HTTP Request object if an error did not occur.
   *
   *                      {stream} [response] - The HTTP Response stream if an error did not occur.
   */
  get(resourceGroupName, workflowName, versionId, options, optionalCallback) {
    let client = this.client;
    let self = this;
    if (!optionalCallback && typeof options === 'function') {
      optionalCallback = options;
      options = null;
    }
    if (!optionalCallback) {
      return new Promise((resolve, reject) => {
        self._get(resourceGroupName, workflowName, versionId, options, (err, result, request, response) => {
          if (err) { reject(err); }
          else { resolve(result); }
          return;
        });
      });
    } else {
      return self._get(resourceGroupName, workflowName, versionId, options, optionalCallback);
    }
  }

  /**
   * Gets a list of workflow versions.
   *
   * @param {string} nextPageLink The NextLink from the previous successful call
   * to List operation.
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {object} [options.customHeaders] Headers that will be added to the
   * request
   *
   * @returns {Promise} A promise is returned
   *
   * @resolve {HttpOperationResponse<WorkflowVersionListResult>} - The deserialized result object.
   *
   * @reject {Error} - The error object.
   */
  listNextWithHttpOperationResponse(nextPageLink, options) {
    let client = this.client;
    let self = this;
    return new Promise((resolve, reject) => {
      self._listNext(nextPageLink, options, (err, result, request, response) => {
        let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
        httpOperationResponse.body = result;
        if (err) { reject(err); }
        else { resolve(httpOperationResponse); }
        return;
      });
    });
  }

  /**
   * Gets a list of workflow versions.
   *
   * @param {string} nextPageLink The NextLink from the previous successful call
   * to List operation.
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {object} [options.customHeaders] Headers that will be added to the
   * request
   *
   * @param {function} [optionalCallback] - The optional callback.
   *
   * @returns {function|Promise} If a callback was passed as the last parameter
   * then it returns the callback else returns a Promise.
   *
   * {Promise} A promise is returned
   *
   *                      @resolve {WorkflowVersionListResult} - The deserialized result object.
   *
   *                      @reject {Error} - The error object.
   *
   * {function} optionalCallback(err, result, request, response)
   *
   *                      {Error}  err        - The Error object if an error occurred, null otherwise.
   *
   *                      {object} [result]   - The deserialized result object if an error did not occur.
   *                      See {@link WorkflowVersionListResult} for more
   *                      information.
   *
   *                      {object} [request]  - The HTTP Request object if an error did not occur.
   *
   *                      {stream} [response] - The HTTP Response stream if an error did not occur.
   */
  listNext(nextPageLink, options, optionalCallback) {
    let client = this.client;
    let self = this;
    if (!optionalCallback && typeof options === 'function') {
      optionalCallback = options;
      options = null;
    }
    if (!optionalCallback) {
      return new Promise((resolve, reject) => {
        self._listNext(nextPageLink, options, (err, result, request, response) => {
          if (err) { reject(err); }
          else { resolve(result); }
          return;
        });
      });
    } else {
      return self._listNext(nextPageLink, options, optionalCallback);
    }
  }

}

module.exports = WorkflowVersions;


text:
package com.microsoft.azure.management.netapp.v2020_06_01.implementation;

import retrofit2.Retrofit;
import com.google.common.reflect.TypeToken;
import com.microsoft.azure.CloudException;
import com.microsoft.rest.ServiceCallback;
import com.microsoft.rest.ServiceFuture;
import com.microsoft.rest.ServiceResponse;
import java.io.IOException;
import okhttp3.ResponseBody;
import retrofit2.http.GET;
import retrofit2.http.Header;
import retrofit2.http.Headers;
import retrofit2.http.HTTP;
import retrofit2.http.Path;
import retrofit2.http.Query;
import retrofit2.Response;
import rx.functions.Func1;
import rx.Observable;

/**
 * An instance of this class provides access to all the operations defined
 * in AccountBackups.
 */
public class AccountBackupsInner {
    /** The Retrofit service to perform REST calls. */
    private AccountBackupsService service;
    /** The service client containing this operation class. */
    private AzureNetAppFilesManagementClientImpl client;

    /**
     * Initializes an instance of AccountBackupsInner.
     *
     * @param retrofit the Retrofit instance built from a Retrofit Builder.
     * @param client the instance of the service client containing this operation class.
     */
    public AccountBackupsInner(Retrofit retrofit, AzureNetAppFilesManagementClientImpl client) {
        this.service = retrofit.create(AccountBackupsService.class);
        this.client = client;
    }

    /**
     * The interface defining all the services for AccountBackups to be
     * used by Retrofit to perform actually REST calls.
     */
    interface AccountBackupsService {
        @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.netapp.v2020_06_01.AccountBackups list" })
        @GET("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetApp/netAppAccounts/{accountName}/accountBackups")
        Observable<Response<ResponseBody>> list(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("accountName") String accountName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);

        @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.netapp.v2020_06_01.AccountBackups get" })
        @GET("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetApp/netAppAccounts/{accountName}/accountBackups/{backupName}")
        Observable<Response<ResponseBody>> get(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("accountName") String accountName, @Path("backupName") String backupName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);

        @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.netapp.v2020_06_01.AccountBackups delete" })
        @HTTP(path = "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetApp/netAppAccounts/{accountName}/accountBackups/{backupName}", method = "DELETE", hasBody = true)
        Observable<Response<ResponseBody>> delete(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("accountName") String accountName, @Path("backupName") String backupName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);

        @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.netapp.v2020_06_01.AccountBackups beginDelete" })
        @HTTP(path = "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetApp/netAppAccounts/{accountName}/accountBackups/{backupName}", method = "DELETE", hasBody = true)
        Observable<Response<ResponseBody>> beginDelete(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("accountName") String accountName, @Path("backupName") String backupName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);

    }

    /**
     * List Backups for a Netapp Account.
     * List all Backups for a Netapp Account.
     *
     * @param resourceGroupName The name of the resource group.
     * @param accountName The name of the NetApp account
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @throws CloudException thrown if the request is rejected by server
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
     * @return the BackupsListInner object if successful.
     */
    public BackupsListInner list(String resourceGroupName, String accountName) {
        return listWithServiceResponseAsync(resourceGroupName, accountName).toBlocking().single().body();
    }

    /**
     * List Backups for a Netapp Account.
     * List all Backups for a Netapp Account.
     *
     * @param resourceGroupName The name of the resource group.
     * @param accountName The name of the NetApp account
     * @param serviceCallback the async ServiceCallback to handle successful and failed responses.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the {@link ServiceFuture} object
     */
    public ServiceFuture<BackupsListInner> listAsync(String resourceGroupName, String accountName, final ServiceCallback<BackupsListInner> serviceCallback) {
        return ServiceFuture.fromResponse(listWithServiceResponseAsync(resourceGroupName, accountName), serviceCallback);
    }

    /**
     * List Backups for a Netapp Account.
     * List all Backups for a Netapp Account.
     *
     * @param resourceGroupName The name of the resource group.
     * @param accountName The name of the NetApp account
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the observable to the BackupsListInner object
     */
    public Observable<BackupsListInner> listAsync(String resourceGroupName, String accountName) {
        return listWithServiceResponseAsync(resourceGroupName, accountName).map(new Func1<ServiceResponse<BackupsListInner>, BackupsListInner>() {
            @Override
            public BackupsListInner call(ServiceResponse<BackupsListInner> response) {
                return response.body();
            }
        });
    }

    /**
     * List Backups for a Netapp Account.
     * List all Backups for a Netapp Account.
     *
     * @param resourceGroupName The name of the resource group.
     * @param accountName The name of the NetApp account
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the observable to the BackupsListInner object
     */
    public Observable<ServiceResponse<BackupsListInner>> listWithServiceResponseAsync(String resourceGroupName, String accountName) {
        if (this.client.subscriptionId() == null) {
            throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
        }
        if (resourceGroupName == null) {
            throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
        }
        if (accountName == null) {
            throw new IllegalArgumentException("Parameter accountName is required and cannot be null.");
        }
        if (this.client.apiVersion() == null) {
            throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.");
        }
        return service.list(this.client.subscriptionId(), resourceGroupName, accountName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent())
            .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<BackupsListInner>>>() {
                @Override
                public Observable<ServiceResponse<BackupsListInner>> call(Response<ResponseBody> response) {
                    try {
                        ServiceResponse<BackupsListInner> clientResponse = listDelegate(response);
                        return Observable.just(clientResponse);
                    } catch (Throwable t) {
                        return Observable.error(t);
                    }
                }
            });
    }

    private ServiceResponse<BackupsListInner> listDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException {
        return this.client.restClient().responseBuilderFactory().<BackupsListInner, CloudException>newInstance(this.client.serializerAdapter())
                .register(200, new TypeToken<BackupsListInner>() { }.getType())
                .registerError(CloudException.class)
                .build(response);
    }

    /**
     * Get Backup for a Netapp Account.
     * Get Backup for a Netapp Account.
     *
     * @param resourceGroupName The name of the resource group.
     * @param accountName The name of the NetApp account
     * @param backupName The name of the backup
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @throws CloudException thrown if the request is rejected by server
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
     * @return the BackupInner object if successful.
     */
    public BackupInner get(String resourceGroupName, String accountName, String backupName) {
        return getWithServiceResponseAsync(resourceGroupName, accountName, backupName).toBlocking().single().body();
    }

    /**
     * Get Backup for a Netapp Account.
     * Get Backup for a Netapp Account.
     *
     * @param resourceGroupName The name of the resource group.
     * @param accountName The name of the NetApp account
     * @param backupName The name of the backup
     * @param serviceCallback the async ServiceCallback to handle successful and failed responses.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the {@link ServiceFuture} object
     */
    public ServiceFuture<BackupInner> getAsync(String resourceGroupName, String accountName, String backupName, final ServiceCallback<BackupInner> serviceCallback) {
        return ServiceFuture.fromResponse(getWithServiceResponseAsync(resourceGroupName, accountName, backupName), serviceCallback);
    }

    /**
     * Get Backup for a Netapp Account.
     * Get Backup for a Netapp Account.
     *
     * @param resourceGroupName The name of the resource group.
     * @param accountName The name of the NetApp account
     * @param backupName The name of the backup
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the observable to the BackupInner object
     */
    public Observable<BackupInner> getAsync(String resourceGroupName, String accountName, String backupName) {
        return getWithServiceResponseAsync(resourceGroupName, accountName, backupName).map(new Func1<ServiceResponse<BackupInner>, BackupInner>() {
            @Override
            public BackupInner call(ServiceResponse<BackupInner> response) {
                return response.body();
            }
        });
    }

    /**
     * Get Backup for a Netapp Account.
     * Get Backup for a Netapp Account.
     *
     * @param resourceGroupName The name of the resource group.
     * @param accountName The name of the NetApp account
     * @param backupName The name of the backup
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the observable to the BackupInner object
     */
    public Observable<ServiceResponse<BackupInner>> getWithServiceResponseAsync(String resourceGroupName, String accountName, String backupName) {
        if (this.client.subscriptionId() == null) {
            throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
        }
        if (resourceGroupName == null) {
            throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
        }
        if (accountName == null) {
            throw new IllegalArgumentException("Parameter accountName is required and cannot be null.");
        }
        if (backupName == null) {
            throw new IllegalArgumentException("Parameter backupName is required and cannot be null.");
        }
        if (this.client.apiVersion() == null) {
            throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.");
        }
        return service.get(this.client.subscriptionId(), resourceGroupName, accountName, backupName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent())
            .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<BackupInner>>>() {
                @Override
                public Observable<ServiceResponse<BackupInner>> call(Response<ResponseBody> response) {
                    try {
                        ServiceResponse<BackupInner> clientResponse = getDelegate(response);
                        return Observable.just(clientResponse);
                    } catch (Throwable t) {
                        return Observable.error(t);
                    }
                }
            });
    }

    private ServiceResponse<BackupInner> getDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException {
        return this.client.restClient().responseBuilderFactory().<BackupInner, CloudException>newInstance(this.client.serializerAdapter())
                .register(200, new TypeToken<BackupInner>() { }.getType())
                .registerError(CloudException.class)
                .build(response);
    }

    /**
     * Delete Backup for a Netapp Account.
     * Delete Backup for a Netapp Account.
     *
     * @param resourceGroupName The name of the resource group.
     * @param accountName The name of the NetApp account
     * @param backupName The name of the backup
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @throws CloudException thrown if the request is rejected by server
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
     */
    public void delete(String resourceGroupName, String accountName, String backupName) {
        deleteWithServiceResponseAsync(resourceGroupName, accountName, backupName).toBlocking().last().body();
    }

    /**
     * Delete Backup for a Netapp Account.
     * Delete Backup for a Netapp Account.
     *
     * @param resourceGroupName The name of the resource group.
     * @param accountName The name of the NetApp account
     * @param backupName The name of the backup
     * @param serviceCallback the async ServiceCallback to handle successful and failed responses.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the {@link ServiceFuture} object
     */
    public ServiceFuture<Void> deleteAsync(String resourceGroupName, String accountName, String backupName, final ServiceCallback<Void> serviceCallback) {
        return ServiceFuture.fromResponse(deleteWithServiceResponseAsync(resourceGroupName, accountName, backupName), serviceCallback);
    }

    /**
     * Delete Backup for a Netapp Account.
     * Delete Backup for a Netapp Account.
     *
     * @param resourceGroupName The name of the resource group.
     * @param accountName The name of the NetApp account
     * @param backupName The name of the backup
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the observable for the request
     */
    public Observable<Void> deleteAsync(String resourceGroupName, String accountName, String backupName) {
        return deleteWithServiceResponseAsync(resourceGroupName, accountName, backupName).map(new Func1<ServiceResponse<Void>, Void>() {
            @Override
            public Void call(ServiceResponse<Void> response) {
                return response.body();
            }
        });
    }

    /**
     * Delete Backup for a Netapp Account.
     * Delete Backup for a Netapp Account.
     *
     * @param resourceGroupName The name of the resource group.
     * @param accountName The name of the NetApp account
     * @param backupName The name of the backup
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the observable for the request
     */
    public Observable<ServiceResponse<Void>> deleteWithServiceResponseAsync(String resourceGroupName, String accountName, String backupName) {
        if (this.client.subscriptionId() == null) {
            throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
        }
        if (resourceGroupName == null) {
            throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
        }
        if (accountName == null) {
            throw new IllegalArgumentException("Parameter accountName is required and cannot be null.");
        }
        if (backupName == null) {
            throw new IllegalArgumentException("Parameter backupName is required and cannot be null.");
        }
        if (this.client.apiVersion() == null) {
            throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.");
        }
        Observable<Response<ResponseBody>> observable = service.delete(this.client.subscriptionId(), resourceGroupName, accountName, backupName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent());
        return client.getAzureClient().getPostOrDeleteResultAsync(observable, new TypeToken<Void>() { }.getType());
    }

    /**
     * Delete Backup for a Netapp Account.
     * Delete Backup for a Netapp Account.
     *
     * @param resourceGroupName The name of the resource group.
     * @param accountName The name of the NetApp account
     * @param backupName The name of the backup
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @throws CloudException thrown if the request is rejected by server
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
     */
    public void beginDelete(String resourceGroupName, String accountName, String backupName) {
        beginDeleteWithServiceResponseAsync(resourceGroupName, accountName, backupName).toBlocking().single().body();
    }

    /**
     * Delete Backup for a Netapp Account.
     * Delete Backup for a Netapp Account.
     *
     * @param resourceGroupName The name of the resource group.
     * @param accountName The name of the NetApp account
     * @param backupName The name of the backup
     * @param serviceCallback the async ServiceCallback to handle successful and failed responses.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the {@link ServiceFuture} object
     */
    public ServiceFuture<Void> beginDeleteAsync(String resourceGroupName, String accountName, String backupName, final ServiceCallback<Void> serviceCallback) {
        return ServiceFuture.fromResponse(beginDeleteWithServiceResponseAsync(resourceGroupName, accountName, backupName), serviceCallback);
    }

    /**
     * Delete Backup for a Netapp Account.
     * Delete Backup for a Netapp Account.
     *
     * @param resourceGroupName The name of the resource group.
     * @param accountName The name of the NetApp account
     * @param backupName The name of the backup
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the {@link ServiceResponse} object if successful.
     */
    public Observable<Void> beginDeleteAsync(String resourceGroupName, String accountName, String backupName) {
        return beginDeleteWithServiceResponseAsync(resourceGroupName, accountName, backupName).map(new Func1<ServiceResponse<Void>, Void>() {
            @Override
            public Void call(ServiceResponse<Void> response) {
                return response.body();
            }
        });
    }

    /**
     * Delete Backup for a Netapp Account.
     * Delete Backup for a Netapp Account.
     *
     * @param resourceGroupName The name of the resource group.
     * @param accountName The name of the NetApp account
     * @param backupName The name of the backup
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the {@link ServiceResponse} object if successful.
     */
    public Observable<ServiceResponse<Void>> beginDeleteWithServiceResponseAsync(String resourceGroupName, String accountName, String backupName) {
        if (this.client.subscriptionId() == null) {
            throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
        }
        if (resourceGroupName == null) {
            throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
        }
        if (accountName == null) {
            throw new IllegalArgumentException("Parameter accountName is required and cannot be null.");
        }
        if (backupName == null) {
            throw new IllegalArgumentException("Parameter backupName is required and cannot be null.");
        }
        if (this.client.apiVersion() == null) {
            throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.");
        }
        return service.beginDelete(this.client.subscriptionId(), resourceGroupName, accountName, backupName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent())
            .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Void>>>() {
                @Override
                public Observable<ServiceResponse<Void>> call(Response<ResponseBody> response) {
                    try {
                        ServiceResponse<Void> clientResponse = beginDeleteDelegate(response);
                        return Observable.just(clientResponse);
                    } catch (Throwable t) {
                        return Observable.error(t);
                    }
                }
            });
    }

    private ServiceResponse<Void> beginDeleteDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException {
        return this.client.restClient().responseBuilderFactory().<Void, CloudException>newInstance(this.client.serializerAdapter())
                .register(200, new TypeToken<Void>() { }.getType())
                .register(202, new TypeToken<Void>() { }.getType())
                .register(204, new TypeToken<Void>() { }.getType())
                .registerError(CloudException.class)
                .build(response);
    }

}


text:
class CreateStrains < ActiveRecord::Migration
  def change
    create_table :strains do |t|
      t.string :name

      t.timestamps
    end
  end
end