text:
package squashfs_test

import (
	"fmt"
	"io"
	"os"
	"path"
	"strings"
	"testing"

	"github.com/diskfs/go-diskfs/filesystem"
	"github.com/diskfs/go-diskfs/filesystem/squashfs"
)

func getOpenMode(mode int) string {
	modes := make([]string, 0)
	if mode&os.O_CREATE == os.O_CREATE {
		modes = append(modes, "CREATE")
	}
	if mode&os.O_APPEND == os.O_APPEND {
		modes = append(modes, "APPEND")
	}
	if mode&os.O_RDWR == os.O_RDWR {
		modes = append(modes, "RDWR")
	} else {
		modes = append(modes, "RDONLY")
	}
	return strings.Join(modes, "|")
}

func tmpSquashfsFile() (*os.File, error) {
	filename := "squashfs_test.sqs"
	f, err := os.CreateTemp("", filename)
	if err != nil {
		return nil, fmt.Errorf("Failed to create tempfile %s :%v", filename, err)
	}
	return f, nil
}

func getValidSquashfsFSWorkspace() (*squashfs.FileSystem, error) {
	// create the filesystem
	f, err := tmpSquashfsFile()
	if err != nil {
		return nil, fmt.Errorf("Failed to create squashfs tmpfile: %v", err)
	}
	return squashfs.Create(f, 0, 0, 4096)
}

func getValidSquashfsFSReadOnly() (*squashfs.FileSystem, error) {
	f, err := os.Open(squashfs.Squashfsfile)
	if err != nil {
		return nil, fmt.Errorf("Failed to read squashfs testfile %s: %v", squashfs.Squashfsfile, err)
	}
	return squashfs.Read(f, 0, 0, 4096)
}

func TestSquashfsType(t *testing.T) {
	fs := &squashfs.FileSystem{}
	fstype := fs.Type()
	expected := filesystem.TypeSquashfs
	if fstype != expected {
		t.Errorf("Type() returns %v instead of expected %v", fstype, expected)
	}
}

func TestSquashfsMkdir(t *testing.T) {
	t.Run("read-only", func(t *testing.T) {
		fs, err := getValidSquashfsFSReadOnly()
		if err != nil {
			t.Fatalf("Failed to get read-only squashfs filesystem: %v", err)
		}
		err = fs.Mkdir("/abcdef")
		if err == nil {
			t.Errorf("received no error when trying to mkdir read-only filesystem")
		}
	})
	t.Run("workspace", func(t *testing.T) {
		fs, err := getValidSquashfsFSWorkspace()
		if err != nil {
			t.Fatalf("Failed to get workspace: %v", err)
		}
		existPath := "/abc"
		tests := []struct {
			fs   *squashfs.FileSystem
			path string
			err  error
		}{
			{fs, "/abcdef", nil},                          // new one
			{fs, existPath, nil},                          // already exists
			{fs, path.Join(existPath, "bar/def/la"), nil}, // already exists
			{fs, "/a/b/c", nil},                           // already exists
		}

		// for fsw, we want to work at least once with a path that exists
		existPathFull := path.Join(fs.Workspace(), existPath)
		err = os.MkdirAll(existPathFull, 0o755)
		if err != nil {
			t.Fatalf("could not create path %s in workspace as %s: %v", existPath, existPathFull, err)
		}
		for _, tt := range tests {
			fs := tt.fs
			ws := fs.Workspace()
			err := fs.Mkdir(tt.path)
			if (err == nil && tt.err != nil) || (err != nil && err == nil) {
				t.Errorf("unexpected error mismatch. Actual: %v, expected: %v", err, tt.err)
			}
			// did the path exist?
			if ws != "" {
				fullPath := path.Join(ws, tt.path)
				if _, err := os.Stat(fullPath); os.IsNotExist(err) {
					t.Errorf("path did not exist after creation base %s, in workspace %s", tt.path, fullPath)
				}
			}
		}
	})
}

func TestSquashfsReadDir(t *testing.T) {
	type testList struct {
		fs    *squashfs.FileSystem
		path  string
		count int
		first string
		last  string
		err   error
	}
	//nolint:thelper // this is not a helper function
	runTests := func(t *testing.T, tests []testList) {
		for _, tt := range tests {
			fi, err := tt.fs.ReadDir(tt.path)
			switch {
			case (err == nil && tt.err != nil) || (err != nil && tt.err == nil):
				t.Errorf("fs.ReadDir(%s): mismatched errors, actual %v expected %v", tt.path, err, tt.err)
			case len(fi) != tt.count:
				t.Errorf("fs.ReadDir(%s): mismatched directory received %d entries, expected %d", tt.path, len(fi), tt.count)
			case fi != nil && tt.count > 2 && fi[0].Name() != tt.first:
				t.Errorf("fs.ReadDir(%s): mismatched first non-self or parent entry, actual then expected", tt.path)
				t.Logf("%s", fi[0].Name())
				t.Logf("%s", tt.first)
			case fi != nil && tt.count > 0 && fi[len(fi)-1].Name() != tt.last:
				t.Errorf("fs.ReadDir(%s): mismatched last entry, actual then expected", tt.path)
				t.Logf("%s", fi[len(fi)-1].Name())
				t.Logf("%s", tt.last)
			}
		}
	}
	t.Run("read-only", func(t *testing.T) {
		fs, err := getValidSquashfsFSReadOnly()
		if err != nil {
			t.Errorf("Failed to get read-only squashfs filesystem: %v", err)
		}
		runTests(t, []testList{
			{fs, "/abcdef", 0, "", "", fmt.Errorf("directory does not exist")},      // does not exist
			{fs, "/", 9, "README.md", "zero", nil},                                  // exists
			{fs, "/foo", 501, "filename_0", "filename_99", nil},                     // exists
			{fs, "/abc", 0, "", "LARGEFIL", fmt.Errorf("directory does not exist")}, // should not find rock ridge name
		},
		)
	})
	t.Run("workspace", func(t *testing.T) {
		fs, err := getValidSquashfsFSWorkspace()
		if err != nil {
			t.Errorf("Failed to get workspace: %v", err)
		}
		// make sure existPath exists in the workspace
		ws := fs.Workspace()
		existPath := "/abc"
		existPathWs := path.Join(ws, existPath)
		_ = os.MkdirAll(existPathWs, 0o755)
		// create files
		for i := 0; i < 10; i++ {
			filename := path.Join(existPathWs, fmt.Sprintf("filename_%d", i))
			contents := fmt.Sprintf("abcdefg %d", i)
			_ = os.WriteFile(filename, []byte(contents), 0o600)
		}
		runTests(t, []testList{
			{fs, "/abcdef", 0, "", "", fmt.Errorf("directory does not exist")}, // does not exist
			{fs, existPath, 10, "filename_0", "filename_9", nil},               // exists
		},
		)
	})
}

func TestSquashfsOpenFile(t *testing.T) {
	// opening directories and files for reading
	type testStruct struct {
		path     string
		mode     int
		expected string
		err      error
	}

	t.Run("read", func(t *testing.T) {
		//nolint:thelper // this is not a helper function
		runTests := func(t *testing.T, fs *squashfs.FileSystem, tests []testStruct) {
			for _, tt := range tests {
				header := fmt.Sprintf("OpenFile(%s, %s)", tt.path, getOpenMode(tt.mode))
				reader, err := fs.OpenFile(tt.path, tt.mode)
				switch {
				case (err == nil && tt.err != nil) || (err != nil && tt.err == nil) || (err != nil && tt.err != nil && !strings.HasPrefix(err.Error(), tt.err.Error())):
					t.Errorf("%s: mismatched errors, actual: %v , expected: %v", header, err, tt.err)
				case reader == nil && (tt.err == nil || tt.expected != ""):
					t.Errorf("%s: Unexpected nil output", header)
				case reader != nil:
					b, err := io.ReadAll(reader)
					if err != nil {
						t.Errorf("%s: io.ReadAll(reader) unexpected error: %v", header, err)
					}
					if string(b) != tt.expected {
						t.Errorf("%s: mismatched contents, actual then expected", header)
						t.Log(string(b))
						t.Log(tt.expected)
					}
				}
			}
		}
		t.Run("read-only", func(t *testing.T) {
			fs, err := getValidSquashfsFSReadOnly()
			if err != nil {
				t.Errorf("Failed to get read-only squashfs filesystem: %v", err)
			}
			tests := []testStruct{
				// error opening a directory
				{"/", os.O_RDONLY, "", fmt.Errorf("cannot open directory %s as file", "/")},
				{"/abcdefg", os.O_RDONLY, "", fmt.Errorf("target file %s does not exist", "/abcdefg")},
				{"/foo/filename_10", os.O_RDONLY, "filename_10\n", nil},
				{"/foo/filename_75", os.O_RDONLY, "filename_75\n", nil},
				{"/README.MD", os.O_RDONLY, "", fmt.Errorf("target file %s does not exist", "/README.MD")},
				{"/README.md", os.O_RDONLY, "README\n", nil},
			}
			runTests(t, fs, tests)
		})
		t.Run("workspace", func(t *testing.T) {
			fs, err := getValidSquashfsFSWorkspace()
			if err != nil {
				t.Errorf("Failed to get workspace: %v", err)
			}
			// make sure our test files exist and have necessary content
			ws := fs.Workspace()
			subdir := "/FOO"
			_ = os.MkdirAll(path.Join(ws, subdir), 0o755)
			for i := 0; i <= 75; i++ {
				filename := fmt.Sprintf("FILENA%02d", i)
				content := fmt.Sprintf("filename_%d\n", i)
				_ = os.WriteFile(path.Join(ws, subdir, filename), []byte(content), 0o600)
			}
			tests := []testStruct{
				// error opening a directory
				{"/", os.O_RDONLY, "", fmt.Errorf("cannot open directory %s as file", "/")},
				// open non-existent file for read or read write
				{"/abcdefg", os.O_RDONLY, "", fmt.Errorf("target file %s does not exist", "/abcdefg")},
				// open file for read or read write and check contents
				{"/FOO/FILENA01", os.O_RDONLY, "filename_1\n", nil},
				{"/FOO/FILENA75", os.O_RDONLY, "filename_75\n", nil},
			}
			runTests(t, fs, tests)
		})
	})
}

func TestSquashfsRead(t *testing.T) {
	tests := []struct {
		blocksize  int64
		filesize   int64
		bytechange int64
		fs         *squashfs.FileSystem
		err        error
	}{
		{500, 6000, -1, nil, fmt.Errorf("blocksize %d too small, must be at least %d", 500, 4096)},
		{4097, squashfs.GB * squashfs.GB, -1, nil, fmt.Errorf("blocksize %d is not a power of 2", 4097)},
		{4096, 10000000, -1, &squashfs.FileSystem{}, nil},
	}
	for i, tt := range tests {
		tt := tt
		t.Run(fmt.Sprintf("blocksize %d filesize %d bytechange %d", tt.blocksize, tt.filesize, tt.bytechange), func(t *testing.T) {
			// get a temporary working file
			f, err := os.Open(squashfs.Squashfsfile)
			if err != nil {
				t.Fatal(err)
			}
			defer f.Close()
			// create the filesystem
			fs, err := squashfs.Read(f, tt.filesize, 0, tt.blocksize)
			switch {
			case (err == nil && tt.err != nil) || (err != nil && tt.err == nil) || (err != nil && tt.err != nil && !strings.HasPrefix(err.Error(), tt.err.Error())):
				t.Errorf("%d: Read(%s, %d, %d, %d): mismatched errors, actual %v expected %v", i, f.Name(), tt.filesize, 0, tt.blocksize, err, tt.err)
			case (fs == nil && tt.fs != nil) || (fs != nil && tt.fs == nil):
				t.Errorf("%d: Read(%s, %d, %d, %d): mismatched fs, actual then expected", i, f.Name(), tt.filesize, 0, tt.blocksize)
				t.Logf("%v", fs)
				t.Logf("%v", tt.fs)
			}
			// we do not match the filesystems here, only check functional accuracy
		})
	}
}

func TestSquashfsCreate(t *testing.T) {
	tests := []struct {
		blocksize int64
		filesize  int64
		fs        *squashfs.FileSystem
		err       error
	}{
		{500, 6000, nil, fmt.Errorf("blocksize %d too small, must be at least %d", 500, 4096)},
		{4097, squashfs.GB * squashfs.GB, nil, fmt.Errorf("blocksize %d is not a power of 2", 4097)},
		{4096, 10000000, &squashfs.FileSystem{}, nil},
	}
	for _, tt := range tests {
		tt := tt
		t.Run(fmt.Sprintf("blocksize %d filesize %d", tt.blocksize, tt.filesize), func(t *testing.T) {
			// create the filesystem
			f, err := tmpSquashfsFile()
			if err != nil {
				t.Errorf("Failed to create squashfs tmpfile: %v", err)
			}
			fs, err := squashfs.Create(f, tt.filesize, 0, tt.blocksize)
			defer os.Remove(f.Name())
			switch {
			case (err == nil && tt.err != nil) || (err != nil && tt.err == nil) || (err != nil && tt.err != nil && !strings.HasPrefix(err.Error(), tt.err.Error())):
				t.Errorf("Create(%s, %d, %d, %d): mismatched errors, actual %v expected %v", f.Name(), tt.filesize, 0, tt.blocksize, err, tt.err)
			case (fs == nil && tt.fs != nil) || (fs != nil && tt.fs == nil):
				t.Errorf("Create(%s, %d, %d, %d): mismatched fs, actual then expected", f.Name(), tt.filesize, 0, tt.blocksize)
				t.Logf("%v", fs)
				t.Logf("%v", tt.fs)
			}
			// we do not match the filesystems here, only check functional accuracy
		})
	}
}

func TestSquashfsReadDirXattr(t *testing.T) {
	fs, err := getValidSquashfsFSReadOnly()
	if err != nil {
		t.Errorf("Failed to get read-only squashfs filesystem: %v", err)
	}
	tests := []struct {
		path   string
		f      string
		xattrs map[string]string
	}{
		{"/", "attrfile", map[string]string{"abc": "def", "myattr": "hello"}},
		{"/", "README.md", map[string]string{}},
	}

	for _, tt := range tests {
		// read the directory
		list, err := fs.ReadDir(tt.path)
		if err != nil {
			t.Errorf("unexpected error reading dir %s: %v", tt.path, err)
			continue
		}
		// get the file we care about
		var (
			fi    os.FileInfo
			found bool
		)
		for _, f := range list {
			if f.Name() == tt.f {
				fi = f
				found = true
			}
		}
		if !found {
			t.Errorf("Did not find file named %s", tt.f)
			continue
		}
		sysbase := fi.Sys()
		sys, ok := sysbase.(squashfs.FileStat)
		if !ok {
			t.Errorf("could not convert fi.Sys() to FileStat")
			continue
		}
		xa := sys.Xattrs()
		if !squashfs.CompareEqualMapStringString(xa, tt.xattrs) {
			t.Errorf("Mismatched xattrs, actual then expected")
			t.Logf("%v", xa)
			t.Logf("%v", tt.xattrs)
		}
	}
}

func TestFinalize(t *testing.T) {

}


text:
package com.rejasupotaro.octodroid.http;

import android.support.test.runner.AndroidJUnit4;

import com.rejasupotaro.octodroid.http.Params;

import org.junit.Test;
import org.junit.runner.RunWith;

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

@RunWith(AndroidJUnit4.class)
public class ParamsTest {

    @Test
    public void buildEmptyQuery() {
        Params params = new Params();
        assertThat(params.toString()).isEqualTo("page=1");
    }

    @Test
    public void buildQuery() {
        {
            Params params = new Params()
                    .add("q", "Android Java");
            assertThat(params.toString()).isEqualTo("q=Android+Java&page=1");
        }
        {
            Params params = new Params()
                    .add("order", "desc")
                    .add("all", "true")
                    .add("sort", "stars")
                    .add("type", "owner");
            assertThat(params.toString()).isEqualTo("all=true&order=desc&sort=stars&type=owner&page=1");
        }
    }

    @Test
    public void incrementPage() {
        Params params = new Params();
        assertThat(params.toString()).isEqualTo("page=1");
        params.incrementPage();
        assertThat(params.toString()).isEqualTo("page=2");
    }
}

redpajama_set_name: RedPajamaGithub


text:
class VulkanDevice;

class VulkanCommandPool : public RHICommandPool
{
public:
	VulkanCommandPool(VulkanDevice* device);

	virtual ~VulkanCommandPool() = default;

	virtual bool Init() override;

	virtual void Destroy() override;

	Ptr<RHICommandBuffer> CreateCommandBuffer(const RHICommandBufferDesc& desc) override;

	bool Valid() const { return _vkCommandPool != VK_NULL_HANDLE; }

	VulkanDevice* VKDevice() const { return (VulkanDevice*)_device; }

	const VkCommandPool& HWCommandPool() const { return _vkCommandPool; }

private:
	VkCommandPool _vkCommandPool;
};

#endif


text:
using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;

namespace WinCity.Control.LayoutManager
{
    public class GridLayout : ILayoutManager
    {
        public GridLayout(int rows, int columns)
        {
            if (rows <= 0 || columns <= 0)
            {
                throw new ArgumentException("rows or columns should larger than zero");
            }
            this.rows = rows;
            this.columns = columns;
            this.widthPref = new int[columns];
            this.heightPref = new int[rows];
            this.xs = new int[columns];
            this.ys = new int[rows];
            this.components = new GridLayoutComponent[rows * columns];
        }

        #region ILayoutManager 成员

        public void AddLayoutComponent(object constraint, IRControl control)
        {
            if (control == null)
            {
                throw new ArgumentNullException();
            }
            if (count > Capacity)
            {
                throw new GridLayoutException("容器已满");
            }
            GridLayoutComponent glc = new GridLayoutComponent();
            glc.Control = control;
            glc.Index = count;
            if (constraint is GridLayoutEnum)
            {
                glc.Layout = (GridLayoutEnum)constraint;
                if (glc.Layout == GridLayoutEnum.None)
                {
                    throw new GridLayoutException("Unsupported Layout : GridLayoutEnum.None");
                }
            }
            else
            {
                glc.Layout = GridLayoutEnum.Default;
            }
            components[count] = glc;
            count++;
        }

        public void RemoveLayoutComponent(IRControl control)
        {
            if (control == null)
            {
                return;
            }
            for (int i = 0; i < count; i++)
            {
                if (components[i] != null &&
                    components[i].Control == control)
                {
                    components[i] = null;
                }
            }
        }

        public void Clear()
        {
            Fill(components, null);
            count = 0;
        }

        public void Layout(IRContainer container)
        {
            CalculateSize(container);

            // so for control of index = r * rows + c, it's rectangle is
            //  (x=xs[r], y=ys[c], width=widthPref[r], height=heightPref[c]).
            foreach (GridLayoutComponent comp in components)
            {
                Size size = comp.Control.PreferredSize;
                int index = comp.Index,
                    rowIndex = index / columns,
                    colIndex = index % columns;
                int x = xs[colIndex],
                    y = ys[rowIndex],
                    width = widthPref[colIndex],
                    height = heightPref[rowIndex];
                comp.Control.Bounds = new Rectangle(x, y, width, height);
            }
        }

        #endregion

        private int Capacity
        {
            get
            {
                return rows * columns - 1;
            }
        }

        private void Fill<T>(T[] array, T item)
        {
            for (int i = 0; i < array.Length; i++)
            {
                array[i] = item;
            }
        }

        private void CalculateSize(IRContainer container)
        {
            Fill(widthPref, 0);
            Fill(heightPref, 0);
            Fill(xs, 0);
            Fill(ys, 0);

            foreach (GridLayoutComponent comp in components)
            {
                int rowIdx = comp.Index / columns;
                int colIdx = comp.Index % columns;
                Size size = comp.Control.PreferredSize;
                heightPref[rowIdx] = Math.Max(size.Height, heightPref[rowIdx]);
                widthPref[colIdx] = Math.Max(size.Width, widthPref[colIdx]);
            }

            for (int i = 1; i < columns; i++)
            {
                xs[i] = xs[i - 1] + widthPref[i - 1];
            }
            for (int i = 1; i < rows; i++)
            {
                ys[i] = ys[i - 1] + heightPref[i - 1];
            }

            // zoom , not implemented.
            Rectangle destRect = container.Bounds;
            int totalWidth = xs[columns - 1] + widthPref[columns - 1],
                totalHeight = ys[rows - 1] + heightPref[rows - 1],
                deltaWidth = destRect.Width - totalWidth,
                deltaHeight = destRect.Height - totalHeight;

            if (deltaWidth > 0)
            {

            }
            else if(deltaWidth < 0)
            {

            }

            if (deltaHeight > 0)
            {

            }
            else if(deltaHeight < 0)
            {

            }
        }

        private GridLayoutComponent[] components;

        private int count, rows, columns;

        int[] heightPref;
        int[] widthPref;
        int[] xs;
        int[] ys;

        private class GridLayoutComponent
        {
            public IRControl Control;

            public int Index;

            public GridLayoutEnum Layout;
        }
    }

    [Flags]
    public enum GridLayoutEnum
    {
        None = 0x00,
        Default = 0x11,
        Left = 0x01,
        Right = 0x02,
        Top = 0x10,
        Bottom = 0x20,
        HCenter = 0x03,
        VCenter = 0x30,
        Center = 0x33
    }
}


text:
Want the *command-not-found* plugin from *oh-my-zsh* but not *oh-my-zsh* itself? Then you've found your repository!

Status: As of August 2016 I still use this and it works for me on Ubuntu 14.04LTS! :) (so don't worry about ancient commit dates)


text:
import { SkillAction } from './action-types-skill';
import { DeepClone } from './deep-clone';
import { Skills } from './skills';
import { SkillsStatus } from '../status/status';
import { ChatMessage, ChatSession } from '../test.component';
import { Tool } from './tool';
import { Validations } from './validations';

const INITIAL_TOOL_STATE: Tool = new Tool();

export function toolReducer(state: Tool = INITIAL_TOOL_STATE, action: any) {
    let newTool: Tool;
    let oldChatMessages: ChatMessage[] = state.chatSession.messages;
    newTool = DeepClone.cloneTool(state); // for some reason this doesn't work for the array
    let newChatMessages: ChatMessage[] = [];
    if (oldChatMessages) {
        oldChatMessages.forEach((message) => {
            newChatMessages.push(message);
        })
    }
    newTool.chatSession.messages = newChatMessages;

    switch (action.type) {
        case ToolAction.ADD_MESSAGE:
            newTool.chatSession.messages.push(action.payload.message);
            if (action.payload.message.incoming == false) {
                newTool.utterances = addUtterances(newTool.utterances, [action.payload.message.text]);
            }
            else {
                newTool.watsonConfigStatus = Tool.WATSON_CONFIG_STATUS_SYNTAX_CORRECT_AND_VALID;
            }
            newTool.selectedMessage = action.payload.message;
            return newTool;

        case ToolAction.DELETE_CHAT:
            let messageToBeDeleted: ChatMessage = action.payload;
            let messages: ChatMessage[] = newTool.chatSession.messages;
            newTool.chatSession = new ChatSession();
            newTool.chatSession.messages = [];
            let lastMessageIndex: number = -1;
            messages.forEach((message: ChatMessage, index: number) => {
                if (message.date == messageToBeDeleted.date) {
                    lastMessageIndex = index;
                }
            });
            if (lastMessageIndex > -1) {
                messages.forEach((message: ChatMessage, index: number) => {
                if (index < lastMessageIndex) {
                    newTool.chatSession.messages.push(message);
                    newTool.selectedMessage = message;
                }
            });
            }
            return newTool;

        case ToolAction.RESET_SESSION:
            newTool.chatSession = new ChatSession();
            newTool.selectedMessage = null;
            return newTool;

        case ToolAction.ADD_UTTERANCES:
            newTool.utterances = addUtterances(newTool.utterances, action.payload.utterances);
            return newTool;

        case ToolAction.SET_SELECTED_MESSAGE:
            newTool.selectedMessage = action.payload.message;
            if (newTool.selectedMessage.incoming == false) {
                newTool.stateType = 'All';
            }
            return newTool;

        case ToolAction.SET_STATE_TYPE:
            newTool.stateType = action.payload;
            return newTool;

        case ToolAction.SET_WATSON_USER_NAME:
            newTool.watsonUserName = action.payload;
            Validations.validate(newTool);
            return newTool;

        case ToolAction.SET_WATSON_USER_PASSWORD:
            newTool.watsonPassword = action.payload;
            Validations.validate(newTool);
            return newTool;

        case ToolAction.SET_WATSON_WORKSPACE:
            newTool.watsonWorkspace = action.payload;
            newTool.chatSession = new ChatSession();
            newTool.selectedMessage = null;
            Validations.validate(newTool);
            return newTool;

        case ToolAction.CONFIG_READ_FROM_FILE:
            newTool.configReadFromFile = true;
            Validations.validate(newTool);
            return newTool;

        case ToolAction.SET_WATSON_CONFIG_INVALID:
            newTool.watsonConfigStatus = Tool.WATSON_CONFIG_STATUS_SYNTAX_CORRECT_AND_INVALID;
            return newTool;

        case ToolAction.SET_WATSON_CREDENTIALS_VALID:
            newTool.watsonConfigStatus = Tool.WATSON_CONFIG_STATUS_SYNTAX_CORRECT_AND_VALID;
            return newTool;

        case ToolAction.SET_WATSON_CREDENTIALS_INVALID:
            newTool.watsonConfigStatus = Tool.WATSON_CONFIG_STATUS_CREDENTIALS_NOT_CORRECT;
            return newTool;

        case ToolAction.SET_WATSON_WORKSPACE_STATUS:
            newTool.workspaceStatus = action.payload;
            return newTool;

        case ToolAction.SET_OVERWRITTEN_PAYLOAD:
            newTool.overwrittenPayload = action.payload;
            Validations.validate(newTool);
            return newTool;

        case ToolAction.SET_WORKSPACES:
            newTool.workspaces = action.payload;
            return newTool;

        case ToolAction.SET_VCAP_CREDENTIALS_READ:
            newTool.vcapCredentialsRead = true;
            Validations.validate(newTool);
            return newTool;

        case ToolAction.SET_VCAP_CREDENTIALS_EXIST:
            newTool.vcapCredentialsExist = action.payload;
            Validations.validate(newTool);
            return newTool;

        default:
            return state;
    }
}

function addUtterances(previousUtterances: string[], newUtterances: string[]): string[] {
    previousUtterances.forEach((utterance) => {
        if (newUtterances.indexOf(utterance) < 0) {
            newUtterances.push(utterance);
        }
    })
    return newUtterances;
}

export class ToolAction {
    static SET_WATSON_USER_NAME: string = 'SET_WATSON_USER_NAME';
    static SET_WATSON_USER_PASSWORD: string = 'SET_WATSON_USER_PASSWORD';
    static SET_WATSON_WORKSPACE: string = 'SET_WATSON_WORKSPACE';
    static ADD_MESSAGE: string = 'ADD_CHAT_MESSAGE';
    static SET_SELECTED_MESSAGE: string = 'SET_SELECTED_CHAT_MESSAGE';
    static RESET_SESSION: string = 'RESET_SESSION';
    static ADD_UTTERANCES: string = 'ADD_UTTERANCES';
    static SET_CLIENT: string = 'SET_CLIENT';
    static SET_STATE_TYPE: string = 'SET_STATE_TYPE';
    static DELETE_CHAT: string = 'DELETE_CHAT';
    static CONFIG_READ_FROM_FILE: string = 'CONFIG_READ_FROM_FILE';
    static SET_WATSON_CONFIG_INVALID: string = 'SET_WATSON_CONFIG_INVALID';
    static SET_WATSON_CREDENTIALS_INVALID: string = 'SET_WATSON_CREDENTIALS_INVALID';
    static SET_WATSON_CREDENTIALS_VALID: string = 'SET_WATSON_CREDENTIALS_VALID';
    static SET_WATSON_WORKSPACE_STATUS: string = 'SET_WATSON_WORKSPACE_STATUS';
    static SET_OVERWRITTEN_PAYLOAD: string = 'SET_OVERWRITTEN_PAYLOAD';
    static SET_WORKSPACES: string = 'SET_WORKSPACES';
    static SET_VCAP_CREDENTIALS_READ: string = 'SET_VCAP_CREDENTIALS_READ';
    static SET_VCAP_CREDENTIALS_EXIST: string = 'SET_VCAP_CREDENTIALS_EXIST';
}


text:
import BarcodeReader from './barcode_reader';
import ArrayHelper from '../common/array_helper';

function Code93Reader() {
    BarcodeReader.call(this);
}

const ALPHABETH_STRING = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. $/+%abcd*";

var properties = {
    ALPHABETH_STRING: {value: ALPHABETH_STRING},
    ALPHABET: {value: ALPHABETH_STRING.split('').map(char => char.charCodeAt(0))},
    CHARACTER_ENCODINGS: {value: [
        0x114, 0x148, 0x144, 0x142, 0x128, 0x124, 0x122, 0x150, 0x112, 0x10A,
        0x1A8, 0x1A4, 0x1A2, 0x194, 0x192, 0x18A, 0x168, 0x164, 0x162, 0x134,
        0x11A, 0x158, 0x14C, 0x146, 0x12C, 0x116, 0x1B4, 0x1B2, 0x1AC, 0x1A6,
        0x196, 0x19A, 0x16C, 0x166, 0x136, 0x13A, 0x12E, 0x1D4, 0x1D2, 0x1CA,
        0x16E, 0x176, 0x1AE, 0x126, 0x1DA, 0x1D6, 0x132, 0x15E
    ]},
    ASTERISK: {value: 0x15E},
    FORMAT: {value: "code_93", writeable: false}
};

Code93Reader.prototype = Object.create(BarcodeReader.prototype, properties);
Code93Reader.prototype.constructor = Code93Reader;

Code93Reader.prototype._decode = function() {
    var self = this,
        counters = [0, 0, 0, 0, 0, 0],
        result = [],
        start = self._findStart(),
        decodedChar,
        lastStart,
        pattern,
        nextStart;

    if (!start) {
        return null;
    }
    nextStart = self._nextSet(self._row, start.end);

    do {
        counters = self._toCounters(nextStart, counters);
        pattern = self._toPattern(counters);
        if (pattern < 0) {
            return null;
        }
        decodedChar = self._patternToChar(pattern);
        if (decodedChar < 0){
            return null;
        }
        result.push(decodedChar);
        lastStart = nextStart;
        nextStart += ArrayHelper.sum(counters);
        nextStart = self._nextSet(self._row, nextStart);
    } while (decodedChar !== '*');
    result.pop();

    if (!result.length) {
        return null;
    }

    if (!self._verifyEnd(lastStart, nextStart, counters)) {
        return null;
    }

    if (!self._verifyChecksums(result)) {
        return null;
    }

    result = result.slice(0, result.length - 2);
    if ((result = self._decodeExtended(result)) === null) {
        return null;
    };

    return {
        code: result.join(""),
        start: start.start,
        end: nextStart,
        startInfo: start,
        decodedCodes: result
    };
};

Code93Reader.prototype._verifyEnd = function(lastStart, nextStart) {
    if (lastStart === nextStart || !this._row[nextStart]) {
        return false;
    }
    return true;
};

Code93Reader.prototype._patternToChar = function(pattern) {
    var i,
        self = this;

    for (i = 0; i < self.CHARACTER_ENCODINGS.length; i++) {
        if (self.CHARACTER_ENCODINGS[i] === pattern) {
            return String.fromCharCode(self.ALPHABET[i]);
        }
    }
    return -1;
};

Code93Reader.prototype._toPattern = function(counters) {
    const numCounters = counters.length;
    let pattern = 0;
    let sum = 0;
    for (let i = 0; i < numCounters; i++) {
        sum += counters[i];
    }

    for (let i = 0; i < numCounters; i++) {
        let normalized = Math.round(counters[i] * 9 / sum);
        if (normalized < 1 || normalized > 4) {
            return -1;
        }
        if ((i & 1) === 0) {
            for (let j = 0; j < normalized; j++) {
                pattern = (pattern << 1) | 1;
            }
        } else {
            pattern <<= normalized;
        }
    }

    return pattern;
};

Code93Reader.prototype._findStart = function() {
    var self = this,
        offset = self._nextSet(self._row),
        patternStart = offset,
        counter = [0, 0, 0, 0, 0, 0],
        counterPos = 0,
        isWhite = false,
        i,
        j,
        whiteSpaceMustStart;

    for ( i = offset; i < self._row.length; i++) {
        if (self._row[i] ^ isWhite) {
            counter[counterPos]++;
        } else {
            if (counterPos === counter.length - 1) {
                // find start pattern
                if (self._toPattern(counter) === self.ASTERISK) {
                    whiteSpaceMustStart = Math.floor(Math.max(0, patternStart - ((i - patternStart) / 4)));
                    if (self._matchRange(whiteSpaceMustStart, patternStart, 0)) {
                        return {
                            start: patternStart,
                            end: i
                        };
                    }
                }

                patternStart += counter[0] + counter[1];
                for ( j = 0; j < 4; j++) {
                    counter[j] = counter[j + 2];
                }
                counter[4] = 0;
                counter[5] = 0;
                counterPos--;
            } else {
                counterPos++;
            }
            counter[counterPos] = 1;
            isWhite = !isWhite;
        }
    }
    return null;
};

Code93Reader.prototype._decodeExtended = function(charArray) {
    const length = charArray.length;
    const result = [];
    for (let i = 0; i < length; i++) {
        const char = charArray[i];
        if (char >= 'a' && char <= 'd') {
            if (i > (length - 2)) {
                return null;
            }
            const nextChar = charArray[++i];
            const nextCharCode = nextChar.charCodeAt(0);
            let decodedChar;
            switch (char) {
            case 'a':
                if (nextChar >= 'A' && nextChar <= 'Z') {
                    decodedChar = String.fromCharCode(nextCharCode - 64);
                } else {
                    return null;
                }
                break;
            case 'b':
                if (nextChar >= 'A' && nextChar <= 'E') {
                    decodedChar = String.fromCharCode(nextCharCode - 38);
                } else if (nextChar >= 'F' && nextChar <= 'J') {
                    decodedChar = String.fromCharCode(nextCharCode - 11);
                } else if (nextChar >= 'K' && nextChar <= 'O') {
                    decodedChar = String.fromCharCode(nextCharCode + 16);
                } else if (nextChar >= 'P' && nextChar <= 'S') {
                    decodedChar = String.fromCharCode(nextCharCode + 43);
                } else if (nextChar >= 'T' && nextChar <= 'Z') {
                    decodedChar = String.fromCharCode(127);
                } else {
                    return null;
                }
                break;
            case 'c':
                if (nextChar >= 'A' && nextChar <= 'O') {
                    decodedChar = String.fromCharCode(nextCharCode - 32);
                } else if (nextChar === 'Z') {
                    decodedChar = ':';
                } else {
                    return null;
                }
                break;
            case 'd':
                if (nextChar >= 'A' && nextChar <= 'Z') {
                    decodedChar = String.fromCharCode(nextCharCode + 32);
                } else {
                    return null;
                }
                break;
            }
            result.push(decodedChar);
        } else {
            result.push(char);
        }
    }
    return result;
};

Code93Reader.prototype._verifyChecksums = function(charArray) {
    return this._matchCheckChar(charArray, charArray.length - 2, 20)
        && this._matchCheckChar(charArray, charArray.length - 1, 15);
};

Code93Reader.prototype._matchCheckChar = function(charArray, index, maxWeight) {
    const arrayToCheck = charArray.slice(0, index);
    const length = arrayToCheck.length;
    const weightedSums = arrayToCheck.reduce((sum, char, i) => {
        const weight = (((i * -1) + (length - 1)) % maxWeight) + 1;
        const value = this.ALPHABET.indexOf(char.charCodeAt(0));
        return sum + (weight * value);
    }, 0);

    const checkChar = this.ALPHABET[(weightedSums % 47)];
    return checkChar === charArray[index].charCodeAt(0);
};

export default Code93Reader;


text:
class FormOfWork < ApplicationRecord
  include MasterModel
  has_many :works, class_name: 'Manifestation' #, dependent: :restrict_with_exception
end

# == Schema Information
#
# Table name: form_of_works
#
#  id           :bigint           not null, primary key
#  name         :string           not null
#  display_name :text
#  note         :text
#  position     :integer
#  created_at   :datetime         not null
#  updated_at   :datetime         not null
#


text:
module Facter
  module Resolvers
    class Networking < BaseResolver
      init_resolver

      class << self
        private

        def post_resolve(fact_name, _options)
          @fact_list.fetch(fact_name) { read_facts(fact_name) }
        end

        def read_facts(fact_name)
          interfaces_data
          primary_interface
          Facter::Util::Resolvers::Networking.expand_main_bindings(@fact_list)
          @fact_list[fact_name]
        end

        def primary_interface
          primary_helper = Facter::Util::Resolvers::Networking::PrimaryInterface
          primary_interface ||= primary_helper.read_from_route

          primary_interface ||= primary_helper.find_in_interfaces(@fact_list[:interfaces])

          @fact_list[:primary_interface] = primary_interface
        end

        def interfaces_data
          command_response = Facter::Core::Execution.execute('ifconfig -a', logger: log)

          clean_up_interfaces_response(command_response)
          parse_interfaces_response(command_response)
        end

        def clean_up_interfaces_response(response)
          # convert ip ranges into single ip. eg. 10.16.132.213 -->  10.16.132.213 is converted to 10.16.132.213
          # convert ip6 ranges into single ip. eg. 2001:db8:cafe::132:213 -->
          # 2001:db8:cafe::132:213 is converted to 2001:db8:cafe::132:213
          response.gsub!(/([\da-fA-F]+([\.:]+[\da-fA-F]+)*)\s+-->\s+[\da-fA-F]+([\.:]+[\da-fA-F]+)*/, '\\1')
        end

        def parse_interfaces_response(response)
          parsed_interfaces_data = {}
          interfaces_data = Hash[*response.split(/^([A-Za-z0-9_\.]+): /)[1..-1]]

          interfaces_data.each do |interface_name, raw_data|
            parsed_interface_data = {}

            extract_mtu(raw_data, parsed_interface_data)
            extract_mac(raw_data, parsed_interface_data)
            extract_dhcp(interface_name, raw_data, parsed_interface_data)
            extract_ip_data(raw_data, parsed_interface_data)

            parsed_interfaces_data[interface_name] = parsed_interface_data
          end
          @fact_list[:interfaces] = parsed_interfaces_data unless parsed_interfaces_data.empty?
        end

        def extract_mtu(raw_data, parsed_interface_data)
          mtu = raw_data.match(/mtu\s+(\d+)/)&.captures&.first&.to_i
          parsed_interface_data[:mtu] = mtu unless mtu.nil?
        end

        def extract_mac(raw_data, parsed_interface_data)
          mac = raw_data.match(/(?:ether|lladdr)\s+((?:\w?\w:){5}\w?\w)|(?:infiniband)\s+((?:\w?\w:){19}\w?\w)/)
                       &.captures&.compact&.first
          parsed_interface_data[:mac] = mac unless mac.nil?
        end

        def extract_dhcp(interface_name, raw_data, parsed_interface_data)
          return unless raw_data =~ /status:\s+active/

          result = Facter::Core::Execution.execute("ipconfig getoption #{interface_name} " \
                                                     'server_identifier', logger: log)

          parsed_interface_data[:dhcp] = result.match(/^[\d.a-f:\s]+$/)&.to_s&.strip unless result.empty?
        end

        def extract_ip_data(raw_data, parsed_interface_data)
          ip = extract_values(raw_data, /inet (\S+)/)
          mask = extract_values(raw_data, /netmask (\S+)/).map { |val| val.hex.to_s(2).count('1') }

          ip6 = extract_values(raw_data, /inet6 (\S+)/).map { |val| val.gsub(/%.+/, '') }
          mask6 = extract_values(raw_data, /prefixlen (\S+)/)

          parsed_interface_data[:bindings] = create_bindings(ip, mask) unless ip.empty?
          parsed_interface_data[:bindings6] = create_bindings(ip6, mask6) unless ip6.empty?
        end

        def extract_values(data, regex)
          results = []
          data.scan(regex).flatten.each do |val|
            results << val
          end
          results
        end

        def create_bindings(ips, masks)
          bindings = []
          ips.zip(masks).each do |ip, mask|
            bindings << Facter::Util::Resolvers::Networking.build_binding(ip, mask)
          end
          bindings
        end
      end
    end
  end
end


text:
default['dnsmasq']['dhcp']['dhcp_range'] = ''

# An array of static hosts to be assigned
# specific IP addresses via DHCP. This uses the
# dnsmasq format for dhcp_hosts. For example:
# [
#  "11:22:33:44:55:66,192.168.0.60"
# ]
#
default['dnsmasq']['dhcp']['dhcp_hosts'] = []

# The default route provided by the DHCP server. This defaults
# to the machine running dnsmasq.
default['dnsmasq']['dhcp']['default_route'] = nil

# An array of hashes that represent the tags used to
# in conjunction with certain dhcp options. For
# instances, the following will set a tag to machines with
# the mac address specified, and assign those machines a
# different default route.
# [
#   {
#     :tag_name => "alternate_internet",
#     :dhcp_hosts => [
#       "11:22:33:44:55:66,192.168.0.70"
#     ],
#     :dhcp_range => "192.168.0.100,192.168.0.150,12h",
#     :mac_addresses => [
#       "00:60:8C:*:*:*"
#     ],
#     :route => "192.168.0.2"
#   }
# ]
default['dnsmasq']['dhcp']['tags'] = []


text:
extern crate byteorder;

// This is a helper macro that helps us validate results in our tests. It has
// to be defined before the mod definitions below so that it's visible in those
// mods.
// Thank you bluss and durka42!
#[cfg(test)]
macro_rules! assert_matches {
    ($expected:pat $(if $guard:expr)*, $value:expr) => {
        match $value {
            $expected $(if $guard)* => {},
            ref actual => {
                panic!("assertion failed: `(left matches right)` (left: `{}`, right: `{:?}`",
                    stringify!($expected), actual);
            },
        }
    };
}

mod reader;
mod writer;

pub use self::reader::{ReadError, ReadErrorKind, ReadResult, WaveReader};
pub use self::writer::{WaveWriter, WriteError, WriteResult};

pub const FORMAT_UNCOMPRESSED_PCM: u16 = 1;
pub const FORMAT_EXTENDED: u16 = 65534;

pub const MIN_I24_VALUE: i32 = -8388608;
pub const MAX_I24_VALUE: i32 = 8388607;

#[derive(Debug)]
pub enum Format {
    UncompressedPcm,
    Extended,
}

#[derive(Debug)]
pub struct PcmFormat {
    pub num_channels: u16,
    pub sample_rate: u32,
    pub bits_per_sample: u16,
}


text:
from docutils import nodes, utils
from docutils.parsers.rst import Directive, directives, docutils
from docutils.parsers.rst.directives.body import LineBlock

import sphinx.roles
from sphinx.domains import Domain

def setup(app):
    app.add_domain(HtmlDomain)
    app.add_node(div, html=(
        lambda self, node: self.body.append(self.starttag(node, 'div')),
        lambda self, node: self.body.append('
\n')))
    app.add_node(address, html=(
        lambda self, node: self.body.append(self.starttag(node, 'address')),
        lambda self, node: self.body.append('</address>\n')
    ))
    app.add_node(cite, html=(visit_cite, depart_cite))
    for name, node in [('mark', mark), ('ins', insert), ('del', delete),
                       ('s', strikethrough), ('u', underline), ('small', small),
                       ('kbd', kbd), ('var', var), ('samp', samp)]:
        addnode(app, node, name)

class div(nodes.General, nodes.Element): pass
class Div(Directive):
    optional_arguments = 1
    final_argument_whitespace = 1
    has_content = True

    def run(self):
        self.assert_has_content()
        text = '\n'.join(self.content)
        try:
            if self.arguments:
                classes = directives.class_option(self.arguments[0])
            else:
                classes = []
        except ValueError:
            raise self.error(
                'Invalid class attribute value for "%s" directive: "%s".'
                % (self.name, self.arguments[0]))
        node = div(text)
        node['classes'].extend(classes)
        self.add_name(node)
        self.state.nested_parse(self.content, self.content_offset, node)
        return [node]

class address(nodes.General, nodes.Element): pass
class Address(LineBlock):
    def run(self):
        [node] = super(Address, self).run()
        ad = address(node.rawsource, *node.children)
        return [ad]

class mark(nodes.Inline, nodes.TextElement): pass
class insert(nodes.Inline, nodes.TextElement): pass
class delete(nodes.Inline, nodes.TextElement): pass
class strikethrough(nodes.Inline, nodes.TextElement): pass
class underline(nodes.Inline, nodes.TextElement): pass
class small(nodes.Inline, nodes.TextElement): pass
class kbd(nodes.Inline, nodes.FixedTextElement): pass
class var(nodes.Inline, nodes.FixedTextElement): pass
class samp(nodes.Inline, nodes.FixedTextElement): pass

def makerole(node):
    return lambda name, rawtext, text, lineno, inliner, options=None, content=None:\
        ([node(rawtext.strip(), text.strip())], [])
def addnode(app, node, nodename):
    app.add_node(node, html=(
        lambda self, n: self.body.append(self.starttag(n, nodename)),
        lambda self, n: self.body.append('</%s>' % nodename)
    ))
def initialism(*args, **kwargs):
    nodes, _ = sphinx.roles.abbr_role(*args, **kwargs)
    [abbr] = nodes
    abbr.attributes.setdefault('classes', []).append('initialism')
    return [abbr], []

def cite_role(typ, rawtext, text, lineno, inliner, options=None, content=None):
    text = utils.unescape(text)
    m = sphinx.roles._abbr_re.search(text)
    if m is None:
        return [cite(text, text, **(options or {}))], []
    content = text[:m.start()].strip()
    source = m.group(1)
    return [cite(content, content, source=source)], []
class cite(nodes.Inline, nodes.TextElement): pass
def visit_cite(self, node):
    attrs = {}
    if node.hasattr('source'):
        attrs['title'] = node['source']
    self.body.append(self.starttag(node, 'cite', '', **attrs))
def depart_cite(self, node):
    self.body.append('')

class HtmlDomain(Domain):
    name = 'h'
    label = 'HTML'
    directives = {
        'div': Div,
        'address': Address,
    }
    roles = {
        'mark': makerole(mark),
        'ins': makerole(insert),
        'del': makerole(delete),
        's': makerole(strikethrough),
        'u': makerole(underline),
        'small': makerole(small),
        'initialism': initialism,
        'cite': cite_role,
        'kbd': makerole(kbd),
        'var': makerole(var),
        'samp': makerole(samp),
    }


text:
package ru.job4j.calculator;

/**
 * Calculator.
 * result - result of calculation.
 *
 * @author Kuzmin Danila (mailto:bus1d0@mail.ru)
 * @version $Id$
 * @since 0.1
 */
public class Calculator {
    /**
     * result of operation.
     */
    private double result;

    /**
     * Method add.
     *
     * @param first  number.
     * @param second number.
     */
    public void add(double first, double second) {
        this.result = first + second;
    }

    /**
     * Method subtract.
     *
     * @param first  number.
     * @param second number.
     */
    public void subtract(double first, double second) {
        this.result = first - second;
    }

    /**
     * Method div.
     *
     * @param first  number.
     * @param second number.
     */

    public void div(double first, double second) {
        this.result = first / second;
    }

    /**
     * Method multiple.
     *
     * @param first  number.
     * @param second number.
     */
    public void multiple(double first, double second) {
        this.result = first * second;
    }

    /**
     * Method getResult.
     *
     * @return Calculator operation
     */

    public double getResult() {
        return this.result;
    }
}


text:
Public Class frmCalc
    Dim dblNum1 As Double
    Dim dblNum2 As Double
    Dim Answer As Double
    Dim dblSet As Double
    Dim dblMem As Double
    Dim shtUse As Short
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btn1.Click
        calcDisplay.Text = calcDisplay.Text + "1" 'adds the said number to the display for use in problems
    End Sub

    Private Sub btn2_Click(sender As Object, e As EventArgs) Handles btn2.Click
        calcDisplay.Text = calcDisplay.Text + "2" 'adds the said number to the display for use in problems
    End Sub

    Private Sub btn3_Click(sender As Object, e As EventArgs) Handles btn3.Click
        calcDisplay.Text = calcDisplay.Text + "3" 'adds the said number to the display for use in problems
    End Sub

    Private Sub btn4_Click(sender As Object, e As EventArgs) Handles btn4.Click
        calcDisplay.Text = calcDisplay.Text + "4" 'adds the said number to the display for use in problems
    End Sub

    Private Sub btn5_Click(sender As Object, e As EventArgs) Handles btn5.Click
        calcDisplay.Text = calcDisplay.Text + "5" 'adds the said number to the display for use in problems
    End Sub

    Private Sub btn6_Click(sender As Object, e As EventArgs) Handles btn6.Click
        calcDisplay.Text = calcDisplay.Text + "6" 'adds the said number to the display for use in problems
    End Sub

    Private Sub btn7_Click(sender As Object, e As EventArgs) Handles btn7.Click
        calcDisplay.Text = calcDisplay.Text + "7" 'adds the said number to the display for use in problems
    End Sub

    Private Sub btn8_Click(sender As Object, e As EventArgs) Handles btn8.Click
        calcDisplay.Text = calcDisplay.Text + "8" 'adds the said number to the display for use in problems
    End Sub

    Private Sub btn9_Click(sender As Object, e As EventArgs) Handles btn9.Click
        calcDisplay.Text = calcDisplay.Text + "9" 'adds the said number to the display for use in problems
    End Sub

    Private Sub btn0_Click(sender As Object, e As EventArgs) Handles btn0.Click
        calcDisplay.Text = calcDisplay.Text + "0" 'adds the said number to the display for use in problems
    End Sub

    Private Sub btnMinus_Click(sender As Object, e As EventArgs) Handles btnMinus.Click
        If calcDisplay.Text = "" Then 'allows negative numbers
            calcDisplay.Text = "-"
        Else
            dblNum1 = calcDisplay.Text
            calcDisplay.Text = ""
            dblSet = 2
        End If

    End Sub

    Private Sub btnPlus_Click(sender As Object, e As EventArgs) Handles btnPlus.Click
        dblNum1 = calcDisplay.Text 'initiates addition
        calcDisplay.Text = ""
        dblSet = 1
    End Sub

    Private Sub btnDecimal_Click(sender As Object, e As EventArgs) Handles btnDecimal.Click
        If calcDisplay.Text.Contains(".") Then 'adds a decimal, no chance of two decimals (idiot proofing xD)
            calcDisplay.Text = calcDisplay.Text
        Else
            calcDisplay.Text = calcDisplay.Text & "."
        End If
    End Sub

    Private Sub btnMultiply_Click(sender As Object, e As EventArgs) Handles btnMultiply.Click
        dblNum1 = calcDisplay.Text 'multiplication
        calcDisplay.Text = ""
        dblSet = 3
    End Sub

    Private Sub btnDivide_Click(sender As Object, e As EventArgs) Handles btnDivide.Click
        dblNum1 = calcDisplay.Text 'division
        calcDisplay.Text = ""
        dblSet = 4
    End Sub

    Private Sub Button1_Click_1(sender As Object, e As EventArgs) Handles btnExp.Click
        dblNum1 = calcDisplay.Text 'exponents
        calcDisplay.Text = ""
        dblSet = 5
    End Sub

    Private Sub btnSqrt_Click(sender As Object, e As EventArgs) Handles btnSqrt.Click
        dblNum1 = calcDisplay.Text 'squareroot by exponent of 1/2
        Answer = dblNum1 ^ 0.5
        calcDisplay.Text = Answer
    End Sub

    Private Sub btnDelete_Click(sender As Object, e As EventArgs) Handles btnClear.Click
        calcDisplay.Text = "" 'clear display
    End Sub

    Private Sub btnDel_Click(sender As Object, e As EventArgs) Handles btnDel.Click
        If Len(calcDisplay.Text) > 1 Then 'delete last character
            calcDisplay.Text = Mid(calcDisplay.Text, 1, Len(calcDisplay.Text) - 1)
        Else
            calcDisplay.Text = ""
        End If
    End Sub

    Private Sub btnMem1_Click(sender As Object, e As EventArgs) Handles btnMS.Click
        dblMem = calcDisplay.Text 'memory store
        calcDisplay.Text = ""
    End Sub

    Private Sub Button1_Click_2(sender As Object, e As EventArgs) Handles btnMR.Click
        calcDisplay.Text = dblMem 'memory show
    End Sub

    Private Sub btnMPlus_Click(sender As Object, e As EventArgs) Handles btnMPlus.Click
        dblMem = calcDisplay.Text + dblMem 'memory add to
        calcDisplay.Text = ""
    End Sub

    Private Sub btnMClear_Click(sender As Object, e As EventArgs) Handles btnMClear.Click
        dblMem = 0 'clear memory
    End Sub

    Private Sub btnEqual_Click(sender As Object, e As EventArgs) Handles btnEqual.Click
        If calcDisplay.Text = "" Then 'idiot proofing once again
            dblNum2 = 0
        Else dblNum2 = calcDisplay.Text

        End If
        If dblSet = 1 Then 'executes the problem based on last operation selected
            Answer = dblNum1 + dblNum2
            calcDisplay.Text = ""
            calcDisplay.Text = Answer
        ElseIf dblSet = 2 Then
            Answer = dblNum1 - dblNum2
            calcDisplay.Text = ""
            calcDisplay.Text = Answer
        ElseIf dblSet = 3 Then
            Answer = dblNum1 * dblNum2
            calcDisplay.Text = ""
            calcDisplay.Text = Answer
        ElseIf dblSet = 4 Then
            Answer = dblNum1 / dblNum2
            calcDisplay.Text = ""
            calcDisplay.Text = Answer
        ElseIf dblSet = 5 Then
            Answer = dblNum1 ^ dblNum2
            calcDisplay.Text = ""
            calcDisplay.Text = Answer
        Else
            calcDisplay.Text = "0"
        End If
    End Sub

    Private Sub btnUse_Click_3(sender As Object, e As EventArgs) Handles btnUse.Click
        shtUse = calcDisplay.Text 'you can use the answer on the screen in the hard level's textbox!
        My.Forms.frmHard.txtAnswer.Text = shtUse
    End Sub
End Class


text:
import {Reader} from './reader';
import {ReaderErrors} from './reader-errors';
import {Settings} from '../../settings/settings';
import {APP_DATA, CATALOG_IMAGES, CATALOG_JSONL, TEMP} from '../../export/catalog/catalog-exporter';

const fs = typeof window !== 'undefined' ? window.require('fs') : require('fs');
const extract = typeof window !== 'undefined' ? window.require('extract-zip') : require('extract-zip');
const remote = typeof window !== 'undefined' ? window.require('@electron/remote') : undefined;

const UTF8 = 'utf-8';

/**
 * @author Daniel de Oliveira
 */
export class CatalogFilesystemReader implements Reader {

    constructor(private file: any, private settings: Settings) {}

    public go(): Promise<string> {

        return new Promise(async (resolve, reject) => {

            const tmpBaseDir = remote.app.getPath(APP_DATA) + '/' + remote.app.getName() + '/' + TEMP + '/';
            const tmpDir = tmpBaseDir + 'catalog-import/';
            const imgDir = tmpDir + CATALOG_IMAGES + '/';
            fs.rmdirSync(tmpDir, { recursive: true });
            fs.mkdirSync(imgDir, { recursive: true });
            const targetDir = this.settings.imagestorePath
                + this.settings.selectedProject
                + '/';
            if (!fs.existsSync(targetDir)) fs.mkdirSync(targetDir);

            try {
                await extract(this.file.path, { dir: tmpDir });

                for (let imageFile of fs.readdirSync(imgDir)) {
                    if (!fs.existsSync(targetDir + imageFile)) {
                        fs.copyFileSync(
                            imgDir + imageFile,
                            targetDir + imageFile
                        );
                    }
                }

                resolve(fs.readFileSync(tmpDir + CATALOG_JSONL, UTF8));
            } catch (err) {
                reject([ReaderErrors.CATALOG_GENERIC]);
            } finally {
                fs.rmdirSync(tmpDir, { recursive: true });
            }
        });
    }
}


text:
/* @flow strict */

import React, { Component } from 'react';
import PropTypes from 'prop-types';

import BpkInput from '../../bpk-component-input';
import { cssModules } from '../../bpk-react-utils';

import STYLES from './BpkInputField.module.scss';

const getClassName = cssModules(STYLES);

class BpkInputField extends Component {
  componentDidUpdate(prevProps) {
    const { focus } = this.props;
    if (prevProps.focus !== focus && this.input && focus) {
      this.input.focus();
      this.input.select();
    }
  }

  render() {
    const { focus, id, index, label, value, ...rest } = this.props;
    return (
      <div key={index} className={getClassName('bpk-input-field')}>
        <BpkInput
          id={id}
          autoComplete="off"
          maxLength="1"
          aria-label={`${label} ${index}`}
          inputRef={(input) => {
            this.input = input;
          }}
          value={value || ''}
          {...rest}
        />
      </div>
    );
  }
}

BpkInputField.propTypes = {
  id: PropTypes.string.isRequired,
  label: PropTypes.string.isRequired,
  value: PropTypes.string,
  focus: PropTypes.bool.isRequired,
  index: PropTypes.number.isRequired,
};

BpkInputField.defaultProps = {
  value: '',
};

export default BpkInputField;


text:
try {
    var back = document.getElementById('backbutton');
    back.addEventListener('click', function() {
        backButton();
    });
} catch (err) {
}

// link che effettuano il submit
var a_link = document.getElementsByClassName('submit-link');
for (var i = 0; i < a_link.length; i++) {
    a_link[i].addEventListener('click', function() {
        parentSubmit(this);
    });
}


text:
local assert, pairs, ipairs, setmetatable, table, rawget, type
   = assert, pairs, ipairs, setmetatable, table, rawget, type
local lgi = require 'lgi'
local cairo = lgi.cairo

local core = require 'lgi.core'
local ffi = require 'lgi.ffi'
local component = require 'lgi.component'
local record = require 'lgi.record'
local enum = require 'lgi.enum'
local ti = ffi.types

cairo._module = core.module('cairo', 2)
local module_gobject = core.gi.cairo.resolve

-- Versioning support.
function cairo.version_encode(major, minor, micro)
   return 10000 * major + 100 * minor + micro
end
cairo.version = core.callable.new {
   addr = cairo._module.cairo_version, ret = ti.int } ()
cairo.version_string = core.callable.new {
   addr = cairo._module.cairo_version_string, ret = ti.utf8 } ()

-- Load some constants.
cairo._constant = {
   MIME_TYPE_JP2 = 'image/jp2',
   MIME_TYPE_JPEG = 'image/jpeg',
   MIME_TYPE_PNG = 'image/png',
   MIME_TYPE_URI = 'text/x-uri',
}

-- Load definitions of all enums.
cairo._enum = cairo._enum or {}
for _, name in pairs {
   'Status', 'Content', 'Operator', 'Antialias', 'FillRule', 'LineCap',
   'LineJoin', 'TextClusterFlags', 'FontSlant', 'FontWeight', 'SubpixelOrder',
   'HintStyle', 'HintMetrics', 'FontType', 'PathDataType', 'DeviceType',
   'SurfaceType', 'Format', 'PatternType', 'Extend', 'Filter', 'RegionOverlap',
   'PdfVersion', 'PsLevel', 'SvgVersion',
} do
   local gtype = ffi.load_gtype(
      module_gobject, 'cairo_gobject_' .. core.uncamel(name) .. '_get_type')
   if gtype then
      cairo._enum[name] = ffi.load_enum(gtype, 'cairo.' .. name)
   else
      cairo._enum[name] = component.create(nil, enum.enum_mt, 'cairo.' .. name)
   end
end

-- Load definitions of all boxed records.
cairo._struct = cairo._struct or {}
for index, struct in pairs {
   'Context', 'Device', 'Surface', 'Rectangle', 'ScaledFont', 'FontFace',
   'FontOptions', 'Region', 'RectangleInt', 'Path', 'TextExtents',
   'FontExtents', 'Matrix', 'ImageSurface', 'PdfSurface', 'PsSurface',
   'RecordingSurface', 'SvgSurface', 'ToyFontFace', 'RectangleList',
   'SolidPattern', 'SurfacePattern', 'GradientPattern', 'LinearPattern',
   'RadialPattern',
   MeshPattern = cairo.version_encode(1, 12, 0),
} do
   local since = 0
   if type(index) == 'string' then
      since = struct
      struct = index
   end
   if cairo.version >= since then
      local gtype = ffi.load_gtype(
	 module_gobject,
	 'cairo_gobject_' .. core.uncamel(struct) .. '_get_type')
      local obj = component.create(gtype, record.struct_mt, 'cairo.' .. struct)
      cairo._struct[struct] = obj
   end
end

local path_data_header = component.create(nil, record.struct_mt)
ffi.load_fields(path_data_header, { { 'type', cairo.PathDataType },
				    { 'length', ti.int } })
local path_data_point = component.create(nil, record.struct_mt)
ffi.load_fields(path_data_point, { { 'x', ti.double }, { 'y', ti.double } })
cairo._union = rawget(cairo, '_union') or {}
cairo._union.PathData = component.create(nil, record.union_mt, 'cairo.PathData')

-- Populate methods into records.
for _, info in ipairs {
   {  'Status',
      methods = {
	 to_string = { static = true, ret = ti.utf8, cairo.Status }
      },
   },

   {  'Rectangle',
      fields = {
	 { 'x', ti.double }, { 'y', ti.double },
	 { 'width', ti.double }, { 'height', ti.double },
      },
   },

   {  'RectangleList',
      fields = {
	 { 'status', cairo.Status },
	 { 'rectangles', cairo.Rectangle, ptr = true },
	 { 'num_rectangles', ti.int },
      },
   },

   {  'RectangleInt',
      fields = {
	 { 'x', ti.int }, { 'y', ti.int },
	 { 'width', ti.int }, { 'height', ti.int },
      },
   },

   {  'Matrix',
      fields = {
	 { 'xx', ti.double }, { 'yx', ti.double },
	 { 'xy', ti.double }, { 'yy', ti.double },
	 { 'x0', ti.double }, { 'y0', ti.double },
      },
      methods = {
	 init = { ti.double, ti.double, ti.double,
		  ti.double, ti.double, ti.double },
	 init_identity = {},
	 init_translate = { ti.double, ti.double },
	 init_scale = { ti.double, ti.double },
	 init_rotate = { ti.double },
	 translate = { ti.double, ti.double },
	 scale = { ti.double, ti.double },
	 rotate = { ti.double },
	 invert = { ret = cairo.Status },
	 multiply = { cairo.Matrix, cairo.Matrix },
	 transform_distance = { { ti.double, dir = 'inout' },
				{ ti.double, dir = 'inout' } },
	 transform_point = { { ti.double, dir = 'inout' },
			     { ti.double, dir = 'inout' } },
      },
   },

   {  'PathData',
      fields = {
	 { 'header', path_data_header },
	 { 'point', path_data_point },
      },
   },

   {  'Path',
      fields = {
	 { 'status', cairo.Status },
	 { 'data', cairo.PathData, ptr = true },
	 { 'num_data', ti.int },
      },
   },

   {  'FontExtents',
      fields = {
	 { 'ascent', ti.double },
	 { 'descent', ti.double },
	 { 'height', ti.double },
	 { 'max_x_advance', ti.double },
	 { 'max_y_advance', ti.double },
      },
   },

   {  'TextExtents',
      fields = {
	 { 'x_bearing', ti.double },
	 { 'y_bearing', ti.double },
	 { 'width', ti.double },
	 { 'height', ti.double },
	 { 'x_advance', ti.double },
	 { 'y_advance', ti.double },
      },
   },

   {  'Context',
      cprefix = '',
      methods = {
	 create = { static = true, ret = { cairo.Context, xfer = true },
		    cairo.Surface },
	 status = { ret = cairo.Status },
	 save = {},
	 restore = {},
	 get_target = { ret = cairo.Surface},
	 push_group = {},
	 push_group_with_content = { cairo.Content },
	 pop_group = { ret = { cairo.Pattern, xfer = true } },
	 pop_group_to_source = {},
	 get_group_target = { ret = cairo.Surface },
	 set_source_rgb = { ti.double, ti.double, ti.double },
	 set_source_rgba = { ti.double, ti.double, ti.double, ti.double },
	 set_source = { cairo.Pattern },
	 set_source_surface = { cairo.Surface, ti.double, ti.double },
	 get_source = { ret = cairo.Pattern },
	 set_antialias = { cairo.Antialias },
	 get_antialias = { ret = cairo.Antialias },
	 get_dash_count = { ret = ti.int },
	 set_fill_rule = { cairo.FillRule },
	 get_fill_rule = { ret = cairo.FillRule },
	 set_line_cap = { cairo.LineCap },
	 get_line_cap = { ret = cairo.LineCap },
	 set_line_join = { cairo.LineJoin },
	 get_line_join = { ret = cairo.LineJoin },
	 set_line_width = { ti.double },
	 get_line_width = { ret = ti.double },
	 set_miter_limit = { ti.double },
	 get_miter_limit = { ret = ti.double },
	 set_operator = { cairo.Operator },
	 get_operator = { ret = cairo.Operator },
	 set_tolerance = { ti.double },
	 get_tolerance = { ret = ti.double },
	 clip = {},
	 clip_preserve = {},
	 clip_extents = { { ti.double, dir = 'out' },
			  { ti.double, dir = 'out' },
			  { ti.double, dir = 'out' },
			  { ti.double, dir = 'out' } },
	 in_clip = { ret = ti.boolean, ti.double, ti.double },
	 reset_clip = {},
	 copy_clip_rectangle_list = {
	    ret = { cairo.RectangleList, xfer = true } },
	 fill = {},
	 fill_preserve = {},
	 fill_extents = { { ti.double, dir = 'out' },
			  { ti.double, dir = 'out' },
			  { ti.double, dir = 'out' },
			  { ti.double, dir = 'out' } },
	 in_fill = { ret = ti.boolean, ti.double, ti.double },
	 mask = { cairo.Pattern },
	 mask_surface = { cairo.Surface, ti.double, ti.double },
	 paint = {},
	 paint_with_alpha = { ti.double },
	 stroke = {},
	 stroke_preserve = {},
	 stroke_extents = { { ti.double, dir = 'out' },
			    { ti.double, dir = 'out' },
			    { ti.double, dir = 'out' },
			    { ti.double, dir = 'out' } },
	 in_stroke = { ret = ti.boolean, ti.double, ti.double },
	 copy_page = {},
	 show_page = {},

	 copy_path = { ret = { cairo.Path, xfer = true } },
	 copy_path_flat = { ret = { cairo.Path, xfer = true } },
	 append_path = { cairo.Path },
	 has_current_point = { ret = ti.boolean },
	 get_current_point = { { ti.double, dir = 'out' },
			       { ti.double, dir = 'out' } },
	 new_path = {},
	 new_sub_path = {},
	 close_path = {},
	 arc = { ti.double, ti.double, ti.double, ti.double, ti.double },
	 arc_negative = { ti.double, ti.double, ti.double,
			  ti.double, ti.double },
	 curve_to = { ti.double, ti.double, ti.double,
		      ti.double, ti.double, ti.double },
	 line_to = { ti.double, ti.double },
	 move_to = { ti.double, ti.double },
	 rectangle = { ti.double, ti.double, ti.double, ti.double },
	 -- glyph_path,
	 text_path = { ti.utf8 },
	 rel_curve_to = { ti.double, ti.double, ti.double,
			  ti.double, ti.double, ti.double },
	 rel_line_to = { ti.double, ti.double },
	 rel_move_to = { ti.double, ti.double },
	 path_extents = { { ti.double, dir = 'out' },
			  { ti.double, dir = 'out' },
			  { ti.double, dir = 'out' },
			  { ti.double, dir = 'out' } },

	 translate = { ti.double, ti.double },
	 scale = { ti.double, ti.double },
	 rotate = { ti.double },
	 transform = { cairo.Matrix },
	 set_matrix = { cairo.Matrix },
	 get_matrix = { cairo.Matrix },
	 identity_matrix = {},
	 user_to_device = { { ti.double, dir = 'inout' },
			    { ti.double, dir = 'inout' } },
	 user_to_device_distance = { { ti.double, dir = 'inout' },
				     { ti.double, dir = 'inout' } },
	 device_to_user = { { ti.double, dir = 'inout' },
			    { ti.double, dir = 'inout' } },
	 device_to_user_distance = { { ti.double, dir = 'inout' },
				     { ti.double, dir = 'inout' } },

	 select_font_face = { ti.utf8, cairo.FontSlant, cairo.FontWeight },
	 set_font_size = { ti.double },
	 set_font_matrix = { cairo.Matrix },
	 get_font_matrix = { cairo.Matrix },
	 set_font_options = { cairo.FontOptions },
	 get_font_options = { cairo.FontOptions },
	 set_font_face = { cairo.FontFace },
	 get_font_face = { ret = cairo.FontFace },
	 set_scaled_font = { cairo.ScaledFont },
	 get_scaled_font = { ret = cairo.ScaledFont },
	 show_text = { ti.utf8 },
	 -- show_glyphs, show_text_glyphs
	 font_extents = { cairo.FontExtents },
	 text_extents = { ti.utf8, cairo.TextExtents },
	 -- glyph extents
      },

      properties = {
	 'status', 'target', 'group_target', 'source', 'antialias', 'fill_rule',
	 'line_cap', 'line_join', 'line_width', 'miter_limit', 'operator',
	 'tolerance', 'font_size', 'font_face', 'font_matrix', 'scaled_font',
	 'matrix',
      },
   },

   {  'Pattern',
      methods = {
	 status = { ret = cairo.Status },
	 set_extend = { cairo.Extend },
	 get_extend = { ret = cairo.Extend },
	 set_filter = { cairo.Filter },
	 get_filter = { ret = cairo.Filter },
	 set_matrix = { cairo.Matrix },
	 get_matrix = { cairo.Matrix },
	 get_type = { ret = cairo.PatternType },
      },
      properties = { 'status', 'extend', 'filter', 'type' },
   },

   {  'SolidPattern', parent = cairo.Pattern,
      cprefix = 'pattern_',
      methods = {
	 create_rgb = { static = true, ret = { cairo.Pattern, xfer = true },
			ti.double, ti.double, ti.double },
	 create_rgba = { static = true, ret = { cairo.Pattern, xfer = true },
			 ti.double, ti.double, ti.double, ti.double },
	 get_rgba = { ret = cairo.Status,
		      { ti.double, dir = 'out' },
		      { ti.double, dir = 'out' },
		      { ti.double, dir = 'out' },
		      { ti.double, dir = 'out' } },
      },
   },

   {  'SurfacePattern', parent = cairo.Pattern,
      cprefix = 'pattern_',
      methods = {
	 create = {
	    cname = 'cairo_pattern_create_for_surface', static = true,
	    ret = { cairo.Pattern, xfer = true },
	    cairo.Surface },
	 get_surface = { ret = cairo.Status, { cairo.Surface, dir = 'out' } },
      },
   },

   {  'GradientPattern', parent = cairo.Pattern,
      cprefix = 'pattern_',
      methods = {
	 add_color_stop_rgb = { ti.double, ti.double, ti.double, ti.double },
	 add_color_stop_rgba = { ti.double, ti.double, ti.double,
				 ti.double, ti.double },
	 get_color_stop_count = { ret = cairo.Status, { ti.int, dir = 'out' } },
	 get_color_stop_rgba = { ret = cairo.Status, ti.int,
				 { ti.double, dir = 'out' },
				 { ti.double, dir = 'out' },
				 { ti.double, dir = 'out' },
				 { ti.double, dir = 'out' },
				 { ti.double, dir = 'out' } },
      },
   },

   {  'LinearPattern', parent = cairo.GradientPattern,
      cprefix = 'pattern_',
      methods = {
	 create = { cname = 'cairo_pattern_create_linear', static = true,
		    ret = { cairo.Pattern, xfer = true },
		    ti.double, ti.double, ti.double, ti.double },
	 get_linear_points = { ret = cairo.Status,
			       { ti.double, dir = 'out' },
			       { ti.double, dir = 'out' },
			       { ti.double, dir = 'out' },
			       { ti.double, dir = 'out' } },
      }
   },

   {  'RadialPattern', parent = cairo.GradientPattern,
      cprefix = 'pattern_',
      methods = {
	 create = { cname = 'cairo_pattern_create_radial', static = true,
		    ret = { cairo.Pattern, xfer = true },
		    ti.double, ti.double, ti.double, ti.double,
		    ti.double, ti.double },
	 get_radial_circles = { ret = cairo.Status,
				{ ti.double, dir = 'out' },
				{ ti.double, dir = 'out' },
				{ ti.double, dir = 'out' },
				{ ti.double, dir = 'out' },
				{ ti.double, dir = 'out' },
				{ ti.double, dir = 'out' } },
      },
   },

   {  'MeshPattern', parent = cairo.Pattern,
      since = cairo.version_encode(1, 12, 0),
      methods = {
	 create = { cname = 'cairo_pattern_create_mesh', static = true,
		    ret = { cairo.Pattern, xfer = true } },
	 begin_patch = {},
	 end_patch = {},
	 move_to = { ti.double, ti.double },
	 line_to = { ti.double, ti.double },
	 curve_to = { ti.double, ti.double, ti.double, ti.double,
		      ti.double, ti.double },
	 set_control_point = { ti.int, ti.double, ti.double },
	 set_corner_color_rgb = { ti.int, ti.double, ti.double, ti.double },
	 set_corner_color_rgba = { ti.int, ti.double, ti.double, ti.double,
				   ti.double },
	 get_patch_count = { ret = cairo.Status, { ti.int, dir = 'out' } },
	 get_path = { ret = { cairo.Path, xfer = true }, ti.int },
	 get_control_point = { ret = cairo.Status, ti.int, ti.int,
			       { ti.double, dir = 'out' },
			       { ti.double, dir = 'out' },
			       { ti.double, dir = 'out' } },
	 get_corner_color_rgba = { ret = cairo.Status, ti.int, ti.int,
				   { ti.double, dir = 'out' },
				   { ti.double, dir = 'out' },
				   { ti.double, dir = 'out' },
				   { ti.double, dir = 'out' } },
      },
   },

   {  'Device',
      methods = {
	 status = { ret = cairo.Status },
	 finish = {},
	 flush = {},
	 get_type = { ret = cairo.DeviceType },
	 acquire = { ret = cairo.Status },
	 release = {},
      },
      properties = { 'status' },
   },

   {  'Format',
      methods = {
	 stride_for_width = { ret = ti.int, ti.int },
      },
   },

   {  'Surface',
      methods = {
	 create_similar = { ret = { cairo.Surface, xfer = true },
			    cairo.Content, ti.int, ti.int },
	 create_for_rectangle = { ret = { cairo.Surface, xfer = true },
				  ti.double, ti.double, ti.double, ti.double },
	 status = { ret = cairo.Status },
	 finish = {},
	 flush = {},
	 get_device = { ret = cairo.Device },
	 get_font_options = { cairo.FontOptions },
	 get_content = { ret = cairo.Content },
	 mark_dirty = {},
	 mark_dirty_rectangle = { ti.int, ti.int, ti.int, ti.int },
	 set_device_offset = { ti.double, ti.double },
	 get_device_offset = { { ti.double, dir = 'out' },
			       { ti.double, dir = 'out' } },
	 set_fallback_resolution = { ti.double, ti.double },
	 get_fallback_resolution = { { ti.double, dir = 'out' },
				     { ti.double, dir = 'out' } },
	 get_type = { ret = cairo.SurfaceType },
	 copy_page = {},
	 show_page = {},
	 has_show_text_glyphs = { ret = ti.boolean },
	 -- set_mime_data, get_mime_data
	 write_to_png = { ret = cairo.Status, ti.filename },
      },

      properties = { 'status', 'device', 'content', 'type' },
   },

   {  'ImageSurface', parent = cairo.Surface,
      methods = {
	 create = { static = true, ret = { cairo.Surface, xfer = true },
		    cairo.Format, ti.int, ti.int },
	 create_for_data = { static = true,
			     ret = { cairo.Surface, xfer = true },
			     ti.ptr, cairo.Format, ti.int, ti.int, ti.int },
	 create_from_png = { static = true,
			     ret = { cairo.Surface, xfer = true },
			     ti.filename },
	 get_data = { ret = ti.ptr },
	 get_format = { ret = cairo.Format },
	 get_width = { ret = ti.int },
	 get_height = { ret = ti.int },
	 get_stride = { ret = ti.int },
      },
      properties = { 'data', 'format', 'width', 'height', 'stride' },
   },

   {  'PdfVersion',
      values = {
	 ['1_4'] = 0,
	 ['1_5'] = 1,
      },
   },

   {  'PdfSurface', parent = cairo.Surface,
      methods = {
	 create = { static = true, ret = { cairo.Surface, xfer = true },
		    ti.filename, ti.double, ti.double },
	 restrict_to_version = { cairo.PdfVersion },
	 set_size = { ti.double, ti.double },
      },
   },

   {  'PsLevel',
      values = {
	 ['2'] = 0,
	 ['3'] = 1,
      },
   },

   {  'PsSurface', parent = cairo.Surface,
      methods = {
	 create = { static = true, ret = { cairo.Surface, xfer = true },
		    ti.filename, ti.double, ti.double },
	 restrict_to_level = { cairo.PsLevel },
	 set_eps = { ti.boolean },
	 get_eps = { ret = ti.boolean },
	 set_size = { ti.double, ti.double },
	 dsc_begin_setup = {},
	 dsc_begin_page_setup = {},
	 dsc_comment = { ti.utf8 },
      },
      properties = { 'eps' },
   },

   {  'RecordingSurface', parent = cairo.Surface,
      methods = {
	 create = { static = true, ret = { cairo.Surface, xfer = true },
		    cairo.Content, cairo.Rectangle },
	 ink_extents = {
	    { ti.double, dir = 'out' }, { ti.double, dir = 'out' },
	    { ti.double, dir = 'out' }, { ti.double, dir = 'out' } },
	 get_extents = { since = cairo.version_encode(1, 12, 0),
			 ret = ti.boolean, cairo.Rectangle },
      },
   },

   {  'SvgVersion',
      values = {
	 ['1_1'] = 0,
	 ['1_2'] = 1,
      },
   },

   {  'SvgSurface', parent = cairo.Surface,
      methods = {
	 create = { static = true, ret = { cairo.Surface, xfer = true },
		    ti.filename, ti.double, ti.double },
	 restrict_to_version = { cairo.SvgVersion },
      },
   },

   {  'FontFace',
      methods = {
	 status = { ret = cairo.Status },
	 get_type = { ret = cairo.FontType },
      },
      properties = { 'status', 'type' },
   },

   {  'ToyFontFace', parent = cairo.FontFace,
      methods = {
	 create = { static = true, ret = { cairo.ToyFontFace, xfer = true },
		    ti.utf8, cairo.FontSlant, cairo.FontWeight },
	 get_family = { ret = ti.utf8 },
	 get_slant = { ret = cairo.Slant },
	 get_weight = { ret = cairo.Weight },
      },
      properties = { 'family', 'slant', 'weight' },
   },

   {  'FontOptions',
      methods = {
	 create = { static = true, ret = { cairo.FontOptions, xfer = true } },
	 copy = { ret = { cairo.FontOptions, xfer = true } },
	 status = { ret = cairo.Status },
	 merge = { cairo.FontOptions },
	 hash = { ret = ti.ulong },
	 equal = { ret = ti.boolean, cairo.FontOptions },
	 set_antialias = { cairo.Antialias },
	 get_antialias = { ret = cairo.Antialias },
	 set_subpixel_order = { cairo.SubpixelOrder },
	 get_subpixel_order = { ret = cairo.SubpixelOrder },
	 set_hint_style = { cairo.HintStyle },
	 get_hint_style = { ret = cairo.HintStyle },
	 set_hint_metrics = { cairo.HintMetrics },
	 get_hint_metrics = { ret = cairo.HintMetrics },
      },
      properties = { 'status', 'antialias', 'subpixel_order',
		     'hint_style', 'hint_metrics' },
   },

   {  'ScaledFont',
      methods = {
	 create = { static = true, ret = { cairo.ScaledFont, xfer = true },
		    cairo.FontFace, cairo.Matrix, cairo.Matrix,
		    cairo.FontOptions },
	 status = { ret = cairo.Status },
	 extents = { cairo.FontExtents },
	 text_extents = { ti.utf8, cairo.TextExtents },
	 -- glyph_extents, text_to_glyphs
	 get_font_face = { ret = cairo.FontFace },
	 get_font_options = { cairo.FontOptions },
	 get_font_matrix = { cairo.Matrix },
	 get_ctm = { cairo.Matrix },
	 get_scale_matrix = { cairo.Matrix },
	 get_type = { ret = cairo.FontType },
      },
      properties = { 'status', 'font_face' },
   },

   {  'Region',
      methods = {
	 create = { static = true, ret = { cairo.Region, xfer = true } },
	 create_rectangle = { static = true,
			      ret = { cairo.Region, xfer = true },
			      cairo.RectangleInt },
	 copy = { ret = cairo.Region },
	 status = { ret = cairo.Status },
	 get_extents = { cairo.RectangleInt },
	 num_rectangles = { ret = ti.int },
	 get_rectangle = { ti.int, cairo.RectangleInt },
	 is_empty = { ret = ti.boolean },
	 contains_point = { ret = ti.boolean, ti.int, ti.int },
	 contains_rectangle = { ret = cairo.RegionOverlap, cairo.RectangleInt },
	 equal = { ret = ti.boolean, cairo.Region },
	 translate = { ti.int, ti.int },
	 intersect = { ret = cairo.Status, cairo.Region },
	 intersect_rectangle = { ret = cairo.Status, cairo.RectangleInt },
	 subtract = { ret = cairo.Status, cairo.Region },
	 subtract_rectangle = { ret = cairo.Status, cairo.RectangleInt },
	 union = { ret = cairo.Status, cairo.Region },
	 union_rectangle = { ret = cairo.Status, cairo.RectangleInt },
	 xor = { ret = cairo.Status, cairo.Region },
	 xor_rectangle = { ret = cairo.Status, cairo.RectangleInt },
      },
      properties = { 'status', 'extents', },
   },
} do
   if cairo.version >= (info.since or 0) then
      local name = info[1]
      local obj = assert(cairo[name], name)
      obj._parent = info.parent
      if info.methods then
	 -- Go through description of the methods and create functions
	 -- from them.
	 obj._method = {}
	 local cprefix = 'cairo_' .. (info.cprefix or core.uncamel(name) .. '_')
	 local self_arg = { obj }
	 for method_name, method_info in pairs(info.methods) do
	    if cairo.version >= (method_info.since or 0) then
	       method_info.name = 'cairo.' .. name .. '.' .. method_name
	       method_info.addr = assert(
		  cairo._module[
		     method_info.cname or (cprefix .. method_name)])
	       if not method_info.static then
		  table.insert(method_info, 1, self_arg)
	       end
	       method_info.ret = method_info.ret or ti.void
	       obj._method[method_name] = core.callable.new(method_info)
	    end
	 end
      end
      if info.values then
	 -- Fill in addition enum/bitflag values.
	 for n, v in pairs(info.values) do
	    obj[n] = v
	 end
      end
      if info.properties then
	 -- Aggregate getters/setters into pseudoproperties
	 -- implemented as attributes.
	 obj._attribute = {}
	 for _, attr in pairs(info.properties) do
	    obj._attribute[attr] = {
	       get = obj._method['get_' .. attr] or obj._method[attr],
	       set = obj._method['set_' .. attr],
	    }
	 end
      end
      if info.fields then
	 -- Load record fields definition
	 ffi.load_fields(obj, info.fields)
      end
   end
end

-- Teach non-boxed structs how to destroy itself.
cairo.RectangleList._free = cairo._module.cairo_rectangle_list_destroy
cairo.Path._free = cairo._module.cairo_path_destroy
cairo.FontOptions._free = cairo._module.cairo_font_options_destroy

-- Add Matrix creation routines.
for _, name in pairs { 'identity', 'scale', 'rotate', 'translate' } do
   local init = cairo.Matrix._method['init_' .. name]
   cairo.Matrix._method['create_' .. name] = function(...)
      local matrix = core.record.new(cairo.Matrix)
      init(matrix, ...)
      return matrix
   end
end

-- FontOptions can be created only by 'create' method.
function cairo.FontOptions._method:_new(props)
   local font_options = self.create()
   for k, v in pairs(props or {}) do
      font_options[k] = v
   end
   return font_options
end

-- Fix all methods using caller-alloc attribute, which is not
-- supported by ffi.  Emulate it 'by-hand', creating Lua wrapper for
-- them.
for _, info in pairs {
   { cairo.Context, 'matrix', cairo.Matrix },
   { cairo.Context, 'font_matrix', cairo.Matrix },
   { cairo.Context, 'font_options', cairo.FontOptions },
   { cairo.Context, 'font_extents', cairo.FontExtents },
   { cairo.Context, 'text_extents', cairo.TextExtents, args = 1 },
   { cairo.Pattern, 'matrix', cairo.Matrix },
   { cairo.Surface, 'font_options', cairo.FontOptions },
   { cairo.ScaledFont, 'font_matrix', cairo.Matrix },
   { cairo.ScaledFont, 'ctm', cairo.Matrix },
   { cairo.ScaledFont, 'scale_matrix', cairo.Matrix },
   { cairo.ScaledFont, 'font_options', cairo.FontOptions },
   { cairo.ScaledFont, 'extents', cairo.FontExtents },
   { cairo.ScaledFont, 'text_extents', cairo.TextExtents, args = 1 },
   { cairo.RecordingSurface, 'extents', cairo.Rectangle },
   { cairo.Region, 'extents', cairo.RectangleInt },
   { cairo.Region, 'get_rectangle', cairo.RectangleInt, args = 1 },
} do
   local getter_name = 'get_' ..info[2]
   local raw_getter = info[1]._method[getter_name]
   if not raw_getter then
      getter_name = info[2]
      raw_getter = info[1]._method[getter_name]
   end
   if raw_getter then
      if info.args == 1 then
	 info[1]._method[getter_name] = function(self, arg1)
	    local ret = info[3]()
	    local res = raw_getter(self, arg1, ret)
	    return (res == nil or res) and ret or nil
	 end
      else
	 info[1]._method[getter_name] = function(self)
	    local ret = info[3]()
	    local res = raw_getter(self, ret)
	    return (res == nil or res) and ret or nil
	 end
	 info[1]._attribute[info[2]] = {
	    get = info[1][getter_name],
	    set = info[1]['set_' .. info[2]],
	 }
      end
   end
end

-- Choose correct 'subclass' of surface on attaching to surface instances.
local surface_type_map = {
   IMAGE = cairo.ImageSurface,
   PDF = cairo.PdfSurface,
   PS = cairo.PsSurface,
   SVG = cairo.SvgSurface,
   RECORDING = cairo.RecordingSurface,
}
function cairo.Surface:_attach(surface)
   local type = cairo.Surface._method.get_type(surface)
   local repotype = surface_type_map[type]
   if repotype then
      core.record.set(surface, repotype)
   end
end

-- Also choose correct 'subclass' for patterns.
local pattern_type_map = {
   SOLID = cairo.SolidPattern,
   SURFACE = cairo.SurfacePattern,
   LINEAR = cairo.LinearPattern,
   RADIAL = cairo.RadialPattern,
   MESH = cairo.MeshPattern
}
function cairo.Pattern:_attach(pattern)
   local type = cairo.Pattern._method.get_type(pattern)
   local repotype = pattern_type_map[type]
   if repotype then
      core.record.set(pattern, repotype)
   end
end

-- Solid pattern constructor, calling either rgb or rgba variant
-- according to the number of arguments.
function cairo.SolidPattern._method.create(red, green, blue, alpha)
   if alpha then
      return cairo.SolidPattern._method.create_rgba(red, green, blue, alpha)
   else
      return cairo.SolidPattern._method.create_rgb(red, green, blue)
   end
end

-- For backward compatibility, propagate pattern creation methods from
-- specific subpattern types into base cairo.Pattern class.
cairo.Pattern._method.create_rgb = cairo.SolidPattern.create_rgb
cairo.Pattern._method.create_rgba = cairo.SolidPattern.create_rgba
cairo.Pattern._method.create_for_surface = cairo.SurfacePattern.create
cairo.Pattern._method.create_linear = cairo.LinearPattern.create
cairo.Pattern._method.create_radial = cairo.RadialPattern.create
if cairo.MeshPattern then
   cairo.Pattern._method.create_mesh = cairo.MeshPattern.create
end

-- Map all 'create' methods to constructors.
for _, struct in pairs(cairo._struct) do
   local create = struct._method and struct._method.create
   if create then
      function struct._new(typetable, ...)
	 return create(...)
      end
   end
end

-- Implementation of Context.dash operations.  Since ffi does not
-- support arrays of doubles, we cheat here and use array of structs
-- containing only single 'double' field.
local wrapped_double = component.create(nil, record.struct_mt)
ffi.load_fields(wrapped_double, { { 'v', ti.double } })
local raw_set_dash = core.callable.new {
   addr = cairo._module.cairo_set_dash, ret = ti.void,
   cairo.Context, wrapped_double, ti.int, ti.double }
local raw_get_dash = core.callable.new {
   addr = cairo._module.cairo_get_dash, ret = ti.void,
   cairo.Context, wrapped_double, { ti.double, dir = 'out' } }
function cairo.Context:set_dash(dashes, offset)
   local count, array = 0
   if dashes and #dashes > 0 then
      -- Convert 'dashes' array into the native array of wrapped_double
      -- records.
      count = #dashes
      array = core.record.new(wrapped_double, nil, count)
      for i = 1, count do
	 core.record.fromarray(array, i - 1).v = dashes[i]
      end
   end
   raw_set_dash(self, array, count, offset)
end

function cairo.Context:get_dash()
   local dashes, offset = {}, 0
   local count = self:get_dash_count()
   if count > 0 then
      -- Prepare native array of wrapped doubles of specified size.
      local array = core.record.new(wrapped_double, nil, count)

      -- Get the dashes.
      offset = raw_get_dash(self, array)

      -- Convert output to the table.
      for i = 1, count do
	 dashes[i] = core.record.fromarray(array, i - 1).v
      end
   end
   return dashes, offset
end

-- Implementation of iteration protocol over the cairo.Path
function cairo.Path:pairs()
   local index = 0
   return function()
      -- Bounds check, and get appropriate header PathData element.
      if index >= self.num_data then return nil end
      local path_data = core.record.fromarray(self.data, index)
      local type, length = path_data.header.type, path_data.header.length

      -- Create 'points' table.
      local points = {}
      if type ~= 'CLOSE_PATH' then
	 points[1] = core.record.fromarray(self.data, index + 1).point
	 if type == 'CURVE_TO' then
	    points[2] = core.record.fromarray(self.data, index + 2).point
	    points[3] = core.record.fromarray(self.data, index + 3).point
	 end
      end

      -- Skip this logical item.
      index = index + length
      return type, points
   end
end


text:
- Package config callbacks that return nothing are NOW handled correctly. Really.

## 0.2.1 (March 21, 2017)
### Fixed
- Package config callbacks that return nothing (i.e. are acting as disabled) are now handled correctly.

## 0.2.0 (March 20, 2017)

Addon authors, note that this release impacts behavior when your addon is included as a transitive dependency! See the notes for the beta releases below.

### Fixed
- The `engines` entry in `package.json` now reflects that this addon requires Node 4+.

## 0.2.0-beta.2 (February 1, 2017)
### Fixed
- Dynamic configuration functions are called with the correct `this` value ([#8](https://github.com/dfreeman/ember-cli-node-assets/issues/8))

## 0.2.0-beta.1 (January 31, 2017)
### Added
- Users can now specify `vendor` configuration to funnel files into the vendor tree without implicitly importing anything.

### Changed
- Documentation has been updated to encourage thinking primarily in terms of funneling files from an npm package into `vendor` and/or `public`. Importing specific files (while still possible), is now presented as a simple shorthand for funneling those files into `vendor` and then importing them explicitly.
- When operating on behalf of a nested addon, in the past ember-cli-node-assets would short circuit and do nothing. This forced addons that depended on others using ember-cli-node-assets (e.g. ember-shepherd -> ember-tether -> ember-cli-node-assets) to either declare them as `peerDependencies` or add a blueprint to make sure there upstream dependencies were installed in the parent application.

  As of this release, ember-cli-node-assets will now operate regardless of the level of nesting. This is motivated by a desire to avoid forcing `peerDependencies` or installation blueprints, and by a [change in `import` behavior](https://github.com/ember-cli/ember-cli/pull/6603) in the upcoming Ember CLI 2.12.

### Deprecated
- Specifying complex import configuration e.g. `import: [{ path: 'foo', type: 'test' }]` is now deprecated. Instead, use `vendor` configuration (see above) and call `app.import` with the additional options explicitly.


text:
package main

import (
	"flag"
	"net"
	"strconv"

	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials"
	"google.golang.org/grpc/grpclog"
	"google.golang.org/grpc/interop"
	testpb "google.golang.org/grpc/interop/grpc_testing"
)

var (
	useTLS   = flag.Bool("use_tls", false, "Connection uses TLS if true, else plain TCP")
	certFile = flag.String("tls_cert_file", "testdata/server1.pem", "The TLS cert file")
	keyFile  = flag.String("tls_key_file", "testdata/server1.key", "The TLS key file")
	port     = flag.Int("port", 10000, "The server port")
)

func main() {
	flag.Parse()
	p := strconv.Itoa(*port)
	lis, err := net.Listen("tcp", ":"+p)
	if err != nil {
		grpclog.Fatalf("failed to listen: %v", err)
	}
	var opts []grpc.ServerOption
	if *useTLS {
		creds, err := credentials.NewServerTLSFromFile(*certFile, *keyFile)
		if err != nil {
			grpclog.Fatalf("Failed to generate credentials %v", err)
		}
		opts = []grpc.ServerOption{grpc.Creds(creds)}
	}
	server := grpc.NewServer(opts...)
	testpb.RegisterTestServiceServer(server, interop.NewTestServer())
	server.Serve(lis)
}


text:
package org.apache.camel.component.kafka.serde;

import java.nio.ByteBuffer;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class DefaultKafkaHeaderSerializer implements KafkaHeaderSerializer {

    private static final Logger LOG = LoggerFactory.getLogger(DefaultKafkaHeaderSerializer.class);

    @Override
    public byte[] serialize(final String key, final Object value) {
        if (value instanceof String) {
            return ((String) value).getBytes();
        } else if (value instanceof Long) {
            ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES);
            buffer.putLong((Long) value);
            return buffer.array();
        } else if (value instanceof Integer) {
            ByteBuffer buffer = ByteBuffer.allocate(Integer.BYTES);
            buffer.putInt((Integer) value);
            return buffer.array();
        } else if (value instanceof Double) {
            ByteBuffer buffer = ByteBuffer.allocate(Double.BYTES);
            buffer.putDouble((Double) value);
            return buffer.array();
        } else if (value instanceof Boolean) {
            return value.toString().getBytes();
        } else if (value instanceof byte[]) {
            return (byte[]) value;
        }
        LOG.debug("Cannot propagate header value of type[{}], skipping... "
                + "Supported types: String, Integer, Long, Double, byte[].", value != null ? value.getClass() : "null");
        return null;
    }
}