text:
package process

import (
	"bytes"
	"fmt"
	"os"
	"path"
	"strconv"
	"strings"

	linuxproc "github.com/c9s/goprocinfo/linux"

	"github.com/weaveworks/common/fs"
	"github.com/weaveworks/scope/probe/host"
)

type walker struct {
	procRoot string
}

// NewWalker creates a new process Walker.
func NewWalker(procRoot string) Walker {
	return &walker{procRoot: procRoot}
}

func readStats(path string) (ppid, threads int, jiffies, rss, rssLimit uint64, err error) {
	var (
		buf                               []byte
		userJiffies, sysJiffies, rssPages uint64
	)
	buf, err = fs.ReadFile(path)
	if err != nil {
		return
	}
	splits := strings.Fields(string(buf))
	if len(splits) < 25 {
		err = fmt.Errorf("Invalid /proc/PID/stat")
		return
	}
	ppid, err = strconv.Atoi(splits[3])
	if err != nil {
		return
	}
	threads, err = strconv.Atoi(splits[19])
	if err != nil {
		return
	}
	userJiffies, err = strconv.ParseUint(splits[13], 10, 64)
	if err != nil {
		return
	}
	sysJiffies, err = strconv.ParseUint(splits[14], 10, 64)
	if err != nil {
		return
	}
	jiffies = userJiffies + sysJiffies
	rssPages, err = strconv.ParseUint(splits[23], 10, 64)
	if err != nil {
		return
	}
	rss = rssPages * uint64(os.Getpagesize())
	rssLimit, err = strconv.ParseUint(splits[24], 10, 64)
	return
}

func readLimits(path string) (openFilesLimit uint64, err error) {
	buf, err := cachedReadFile(path)
	if err != nil {
		return 0, err
	}
	for _, line := range strings.Split(string(buf), "\n") {
		if strings.HasPrefix(line, "Max open files") {
			splits := strings.Fields(line)
			if len(splits) < 6 {
				return 0, fmt.Errorf("Invalid /proc/PID/limits")
			}
			openFilesLimit, err := strconv.Atoi(splits[3])
			return uint64(openFilesLimit), err
		}
	}
	return 0, nil
}

// Walk walks the supplied directory (expecting it to look like /proc)
// and marshalls the files into instances of Process, which it then
// passes one-by-one to the supplied function. Walk is only made public
// so that is can be tested.
func (w *walker) Walk(f func(Process, Process)) error {
	dirEntries, err := fs.ReadDirNames(w.procRoot)
	if err != nil {
		return err
	}

	for _, filename := range dirEntries {
		pid, err := strconv.Atoi(filename)
		if err != nil {
			continue
		}

		ppid, threads, jiffies, rss, rssLimit, err := readStats(path.Join(w.procRoot, filename, "stat"))
		if err != nil {
			continue
		}

		openFiles, err := fs.ReadDirNames(path.Join(w.procRoot, filename, "fd"))
		if err != nil {
			continue
		}

		openFilesLimit, err := readLimits(path.Join(w.procRoot, filename, "limits"))
		if err != nil {
			continue
		}

		cmdline, name := "", ""
		if cmdlineBuf, err := cachedReadFile(path.Join(w.procRoot, filename, "cmdline")); err == nil {
			// like proc, treat name as the first element of command line
			i := bytes.IndexByte(cmdlineBuf, '\000')
			if i == -1 {
				i = len(cmdlineBuf)
			}
			name = string(cmdlineBuf[:i])
			cmdlineBuf = bytes.Replace(cmdlineBuf, []byte{'\000'}, []byte{' '}, -1)
			cmdline = string(cmdlineBuf)
		}
		if name == "" {
			if commBuf, err := cachedReadFile(path.Join(w.procRoot, filename, "comm")); err == nil {
				name = "[" + strings.TrimSpace(string(commBuf)) + "]"
			} else {
				name = "(unknown)"
			}
		}
		f(Process{
			PID:            pid,
			PPID:           ppid,
			Name:           name,
			Cmdline:        cmdline,
			Threads:        threads,
			Jiffies:        jiffies,
			RSSBytes:       rss,
			RSSBytesLimit:  rssLimit,
			OpenFilesCount: len(openFiles),
			OpenFilesLimit: openFilesLimit,
		}, Process{})
	}

	return nil
}

var previousStat = linuxproc.CPUStat{}

// GetDeltaTotalJiffies returns the number of jiffies that have passed since it
// was last called.  In that respect, it is side-effect-ful.
func GetDeltaTotalJiffies() (uint64, float64, error) {
	stat, err := linuxproc.ReadStat(host.ProcStat)
	if err != nil {
		return 0, 0.0, err
	}

	var (
		currentStat = stat.CPUStatAll
		prevTotal   = (previousStat.Idle + previousStat.IOWait + previousStat.User +
			previousStat.Nice + previousStat.System + previousStat.IRQ +
			previousStat.SoftIRQ + previousStat.Steal)
		currentTotal = (currentStat.Idle + currentStat.IOWait + currentStat.User +
			currentStat.Nice + currentStat.System + currentStat.IRQ +
			currentStat.SoftIRQ + currentStat.Steal)
	)
	previousStat = currentStat
	return currentTotal - prevTotal, float64(len(stat.CPUStats)) * 100., nil
}


text:
namespace Ptakopysk
{

    BitFieldSerializer::BitFieldSerializer()
    {
    }

    BitFieldSerializer::BitFieldSerializer( const BitValues& bitvalues )
    : m_bitValues( bitvalues )
    {
    }

    BitFieldSerializer::~BitFieldSerializer()
    {
        m_bitValues.clear();
    }

    Json::Value BitFieldSerializer::serialize( const void* srcValue )
    {
        if( !srcValue )
            return Json::Value::null;
        int v = *(int*)srcValue;
        Json::Value a( Json::arrayValue );
        for( BitValues::iterator it = m_bitValues.begin(); it != m_bitValues.end(); it++ )
            if( it->second & v || it->second == v )
                a.append( Json::Value( it->first ) );
        return a;
    }

    void BitFieldSerializer::deserialize( const void* dstValue, const Json::Value& root )
    {
        if( !dstValue || !root.isArray() )
            return;
        int b = 0;
        Json::Value item;
        for( unsigned int i = 0; i < root.size(); i++ )
        {
            item = root[ i ];
            if( m_bitValues.count( item.asString() ) )
                b |= m_bitValues[ item.asString() ];
        }
        *(int*)dstValue = b;
    }

    void BitFieldSerializer::setup( const BitValues& bitvalues )
    {
        m_bitValues = bitvalues;
    }

}

redpajama_set_name: RedPajamaGithub


text:
using Microsoft.Bot.Builder.ConnectorEx;
using Microsoft.Bot.Connector;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Bot.Builder.ChannelConnector.Facebook;
using Xunit;

namespace BotBuilderChannelConectorTests
{
    public class ActivityTransformationTests
    {
        [Fact]
        public void CanConvertTextMessage()
        {
            var activity = new Activity
            {
                Recipient = new ChannelAccount
                {
                    Id = "4711"
                },
                Text = "hello world"
            };

            var fbMessages = activity.ToFacebookMessaging().ToList();

            Assert.Equal(1, fbMessages.Count);
            Assert.Equal("4711", fbMessages.First().Recipient.Id);
            Assert.Equal("hello world", fbMessages.First().Message.Text);
        }

        [Fact]
        public void CanConvertLocationQuickReply()
        {
            var activity = new Activity
            {
                Recipient = new ChannelAccount
                {
                    Id = "4711"
                },
                ChannelData = new FacebookMessage
                (
                    "Please enter your location",
                    new List<FacebookQuickReply>
                    {
                        new FacebookQuickReply
                        (
                            FacebookQuickReply.ContentTypes.Location,
                            default(string),
                            default(string)
                        )
                    }
                )
            };

            var fbMessages = activity.ToFacebookMessaging().ToList();
            var fbMessage = fbMessages.First();

            Assert.Equal(1, fbMessages.Count);
            Assert.Equal("4711", fbMessage.Recipient.Id);
            Assert.Equal("Please enter your location", fbMessage.Message.Text);
            Assert.Equal(FacebookQuickReply.ContentTypes.Location, fbMessage.Message.QuickReplies.First().ContentType);
        }

        [Fact]
        public void CanConvertTyping()
        {
            var activity = new Activity
            {
                Recipient = new ChannelAccount
                {
                    Id = "4711"
                },
                Type = ActivityTypes.Typing
            };

            var fbMessages = activity.ToFacebookMessaging().ToList();

            Assert.Equal(1, fbMessages.Count);
            Assert.Equal("4711", fbMessages.First().Recipient.Id);
            Assert.Equal("typing_on", fbMessages.First().SenderAction);
        }

        [Fact]
        public void CanConvertQuickReply()
        {
            var activity = new Activity
            {
                Recipient = new ChannelAccount
                {
                    Id = "4711"
                },
                ChannelData = new FacebookMessage("quickreplies")
                {
                    QuickReplies = new List<FacebookQuickReply>
                    {
                        new FacebookQuickReply("text", "hello", "hello"),
                        new FacebookQuickReply("text", "hello2", "hello2"),
                    }
                }
            };

            var fbMessages = activity.ToFacebookMessaging().ToList();
            var fbMessage = fbMessages.First();

            Assert.Equal(1, fbMessages.Count);
            Assert.Equal("4711", fbMessage.Recipient.Id);
            Assert.Equal("quickreplies", fbMessage.Message.Text);
            Assert.Equal(FacebookQuickReply.ContentTypes.Text, fbMessage.Message.QuickReplies.First().ContentType);
        }

        [Fact]
        public void CanConvertAttachment()
        {
            var activity = new Activity
            {
                Recipient = new ChannelAccount
                {
                    Id = "4711"
                },
                Attachments = new List<Attachment>
                {
                    new Attachment
                    {
                        ContentType = "image/png",
                        ContentUrl = "http://aihelpwebsite.com/portals/0/Images/AIHelpWebsiteLogo_Large.png",
                        Name = "AIHelpWebsiteLogo_Large.png"
                    }
                }
            };

            var fbMessages = activity.ToFacebookMessaging().ToList();

            Assert.Equal(1, fbMessages.Count);
            Assert.Equal("4711", fbMessages.First().Recipient.Id);
            Assert.Null(fbMessages.First().Message.Text);
        }

        [Fact]
        public void CanConvertHeroCard()
        {
            var activity = new Activity
            {
                Recipient = new ChannelAccount
                {
                    Id = "4711"
                },
                Attachments = new List<Attachment>
                {
                    new HeroCard
                    {
                        Title = "Deco!",
                        Subtitle = "I am Brasilian",
                        Images = new List<CardImage>
                        {
                            new CardImage(url: "https://upload.wikimedia.org/wikipedia/commons/5/5c/Chelsea_Deco.jpg")
                        },
                        Buttons = new List<CardAction>
                        {
                            new CardAction
                            {
                                Value = "https://de.wikipedia.org/wiki/Deco",
                                Type = ActionTypes.OpenUrl,
                                Title = "Get me to Deco"
                            },
                            new CardAction
                            {
                                Value = "Postback",
                                Type = ActionTypes.PostBack,
                                Title = "Get me to Deco"
                            }

                        }
                    }
                    .ToAttachment()
                }
            };

            var fbMessages = activity.ToFacebookMessaging().ToList();
            var fbMessage = fbMessages.First();
            var template = fbMessage.Message.Attachment.Payload.Elements.First();

            Assert.Equal(1, fbMessages.Count);
            Assert.Equal("4711", fbMessages.First().Recipient.Id);
            Assert.Null(fbMessage.Message.Text);
            Assert.Equal("postback", template.Buttons[1].Type);
        }

        [Fact]
        public void CanConvertThumbnailCard()
        {
            var activity = new Activity
            {
                Text = "Deco!",
                Recipient = new ChannelAccount
                {
                    Id = "4711"
                },
                Attachments = new List<Attachment>
                {
                    new ThumbnailCard
                    {
                        Subtitle = "Subtitle",
                        Images = new List<CardImage>
                        {
                            new CardImage(url: "https://upload.wikimedia.org/wikipedia/commons/5/5c/Chelsea_Deco.jpg")
                        },
                        Buttons = new List<CardAction>
                        {
                            new CardAction
                            {
                                Value = "https://de.wikipedia.org/wiki/Deco",
                                Type = ActionTypes.OpenUrl,
                                Title = "Get me to Deco"
                            },
                            new CardAction
                            {
                                Value = "Postback",
                                Type = ActionTypes.PostBack,
                                Title = "Get me to Deco"
                            }

                        }
                    }
                    .ToAttachment()
                }
            };

            var fbMessages = activity.ToFacebookMessaging().ToList();
            var fbMessage = fbMessages.First();
            var template = fbMessage.Message.Attachment.Payload.Elements.First();

            Assert.Equal(1, fbMessages.Count);
            Assert.Equal("4711", fbMessages.First().Recipient.Id);
            Assert.Equal("Deco!", fbMessages.First().Message.Attachment.Payload.Elements.First().Title);
            Assert.Null(fbMessage.Message.Text);
            Assert.Equal("postback", template.Buttons[1].Type);
        }
    }
}


text:
**[mmir-tooling 7.0.0-beta1](../README.md)**

> [Globals](../README.md) / [mmir-tooling](../modules/mmir_tooling.md) / SettingsBuildEntryMultiple

# Interface: SettingsBuildEntryMultiple

## Hierarchy

* [SettingsEntryOptionsMultiple](mmir_tooling.settingsentryoptionsmultiple.md)

* [BuildOptions](mmir_tooling.buildoptions.md)

  ↳ **SettingsBuildEntryMultiple**

## Index

### Properties

* [exclude](mmir_tooling.settingsbuildentrymultiple.md#exclude)
* [file](mmir_tooling.settingsbuildentrymultiple.md#file)
* [fileType](mmir_tooling.settingsbuildentrymultiple.md#filetype)
* [force](mmir_tooling.settingsbuildentrymultiple.md#force)
* [id](mmir_tooling.settingsbuildentrymultiple.md#id)
* [include](mmir_tooling.settingsbuildentrymultiple.md#include)
* [targetDir](mmir_tooling.settingsbuildentrymultiple.md#targetdir)
* [type](mmir_tooling.settingsbuildentrymultiple.md#type)
* [value](mmir_tooling.settingsbuildentrymultiple.md#value)

## Properties

### exclude

• `Optional` **exclude**: boolean

*Inherited from [SettingsBuildEntry](mmir_tooling.settingsbuildentry.md).[exclude](mmir_tooling.settingsbuildentry.md#exclude)*

if `true`, the corresponding resource will be excluded (when parsing `path`)

___

### file

• `Optional` **file**: string \| string[]

*Inherited from [SettingsBuildEntryMultiple](mmir_tooling.settingsbuildentrymultiple.md).[file](mmir_tooling.settingsbuildentrymultiple.md#file)*

for explicitly specifying the settings-resource directly (e.g. instead or in addition of parsing `path` for settings resource files)

___

### fileType

• `Optional` **fileType**: \"js\" \| \"json\"

*Inherited from [SettingsBuildEntry](mmir_tooling.settingsbuildentry.md).[fileType](mmir_tooling.settingsbuildentry.md#filetype)*

the settings-file-type _(should not be set manually)_:\
derived from the file-extension, either "json" or "js".

If .js file, it MUST be a CommonJS module that exports the settings object as its only/default export, i.e.\
```javascript
module.exports = settingsObject;
```
any dynamic code is evaluated at compile-time, i.e. the exported settings-object must not contain dynamic content

___

### force

• `Optional` **force**: boolean

*Inherited from [BuildOptions](mmir_tooling.buildoptions.md).[force](mmir_tooling.buildoptions.md#force)*

if TRUE the targets will be newly created and written to the targetDir,
even if the existence or up-to-date check returns `true`

___

### id

• `Optional` **id**: string

*Inherited from [SettingsBuildEntry](mmir_tooling.settingsbuildentry.md).[id](mmir_tooling.settingsbuildentry.md#id)*

the ID for the settings-resources _(should not be set manually)_

___

### include

• `Optional` **include**: \"inline\" \| \"file\"

*Inherited from [SettingsBuildEntry](mmir_tooling.settingsbuildentry.md).[include](mmir_tooling.settingsbuildentry.md#include)*

can be used to include the resource as separate file, instead of bundeling via webpack

**`default`** "inline"

___

### targetDir

• `Optional` **targetDir**: string

*Inherited from [BuildOptions](mmir_tooling.buildoptions.md).[targetDir](mmir_tooling.buildoptions.md#targetdir)*

directory to which the compiled resources like grammars (and checksum files) will be stored

by default, the relative paths are resolved against the app's root directory;
if the target directory is missing it will be newly created.

**`default`** [BuildAppConfig.targetDir](mmir_tooling.buildappconfig.md#targetdir) + [ResourceType](../modules/mmir_tooling.md#resourcetype)

___

### type

• `Optional` **type**: [SettingsType](../modules/mmir_tooling.md#settingstype)

*Inherited from [SettingsBuildEntry](mmir_tooling.settingsbuildentry.md).[type](mmir_tooling.settingsbuildentry.md#type)*

the settings-type _(should not be set manually)_

___

### value

• `Optional` **value**: any


text:
class DocumentCollectionGroup < ActiveRecord::Base
  belongs_to :document_collection, inverse_of: :groups, touch: true
  has_many :memberships,
           -> { order('document_collection_group_memberships.ordering') } ,
           class_name: 'DocumentCollectionGroupMembership',
           inverse_of: :document_collection_group,
           dependent: :destroy
  has_many :documents,
           -> { order('document_collection_group_memberships.ordering') },
           through: :memberships
  has_many :editions,
           -> { order('document_collection_group_memberships.ordering') },
           through: :documents

  validates :heading, presence: true, uniqueness: { scope: :document_collection_id }
  validates_associated :memberships

  before_create :assign_ordering

  def set_document_ids_in_order!(document_ids)
    self.document_ids = document_ids
    self.save!
    self.memberships.each do |membership|
      membership.update_attribute(:ordering, document_ids.index(membership.document_id))
    end
  end

  def self.visible
    includes(:editions).references(:editions).where(editions: { state: 'published'})
  end

  def self.default_attributes
    { heading: 'Documents' }
  end

  def published_editions
    editions.published
  end

  def latest_editions
    associations = { latest_edition: [:organisations, :translations] }
    editions = documents.includes(associations).map(&:latest_edition)
    editions.compact
  end

  def visible?
    published_editions.present?
  end

  def dup
    new_group = super
    new_group.memberships = memberships.map &:dup
    new_group
  end

  def slug
    heading.parameterize
  end

  private

  def assign_ordering
    peers = document_collection.present? ? document_collection.groups.maximum(:ordering).to_i : 0
    self.ordering = peers + 1
  end
end


text:
/*
 * @test
 * @bug 6332435
 * @summary Basic tests for CountDownLatch
 * @author Seetharam Avadhanam, Martin Buchholz
 */

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

interface AwaiterFactory {
    Awaiter getAwaiter();
}

abstract class Awaiter extends Thread {
    private volatile Throwable result = null;
    protected void result(Throwable result) { this.result = result; }
    public Throwable result() { return this.result; }
}

public class Basic {

    private void toTheStartingGate(CountDownLatch gate) {
        try {
            gate.await();
        }
        catch (Throwable t) { fail(t); }
    }

    private Awaiter awaiter(final CountDownLatch latch,
                            final CountDownLatch gate) {
        return new Awaiter() { public void run() {
            System.out.println("without millis: " + latch.toString());
            gate.countDown();

            try {
                latch.await();
                System.out.println("without millis - ComingOut");
            }
            catch (Throwable result) { result(result); }}};
    }

    private Awaiter awaiter(final CountDownLatch latch,
                            final CountDownLatch gate,
                            final long millis) {
        return new Awaiter() { public void run() {
            System.out.println("with millis: "+latch.toString());
            gate.countDown();

            try {
                latch.await(millis, TimeUnit.MILLISECONDS);
                System.out.println("with millis - ComingOut");
            }
            catch (Throwable result) { result(result); }}};
    }

    private AwaiterFactory awaiterFactories(final CountDownLatch latch,
                                            final CountDownLatch gate,
                                            final int i) {
        if (i == 1)
            return new AwaiterFactory() { public Awaiter getAwaiter() {
                return awaiter(latch, gate); }};

        return new AwaiterFactory() { public Awaiter getAwaiter() {
            return awaiter(latch, gate, 10000); }};
    }

    //----------------------------------------------------------------
    // Normal use
    //----------------------------------------------------------------
    public static void normalUse() throws Throwable {
        int count = 0;
        Basic test = new Basic();
        CountDownLatch latch = new CountDownLatch(3);
        Awaiter a[] = new Awaiter[12];

        for (int i = 0; i < 3; i++) {
            CountDownLatch gate = new CountDownLatch(4);
            AwaiterFactory factory1 = test.awaiterFactories(latch, gate, 1);
            AwaiterFactory factory2 = test.awaiterFactories(latch, gate, 0);
            a[count] = factory1.getAwaiter(); a[count++].start();
            a[count] = factory1.getAwaiter(); a[count++].start();
            a[count] = factory2.getAwaiter(); a[count++].start();
            a[count] = factory2.getAwaiter(); a[count++].start();
            test.toTheStartingGate(gate);
            System.out.println("Main Thread: " + latch.toString());
            latch.countDown();
            checkCount(latch, 2-i);
        }
        for (int i = 0; i < 12; i++)
            a[i].join();

        for (int i = 0; i < 12; i++)
            checkResult(a[i], null);
    }

    //----------------------------------------------------------------
    // One thread interrupted
    //----------------------------------------------------------------
    public static void threadInterrupted() throws Throwable{
        int count = 0;
        Basic test = new Basic();
        CountDownLatch latch = new CountDownLatch(3);
        Awaiter a[] = new Awaiter[12];

        for (int i = 0; i < 3; i++) {
            CountDownLatch gate = new CountDownLatch(4);
            AwaiterFactory factory1 = test.awaiterFactories(latch, gate, 1);
            AwaiterFactory factory2 = test.awaiterFactories(latch, gate, 0);
            a[count] = factory1.getAwaiter(); a[count++].start();
            a[count] = factory1.getAwaiter(); a[count++].start();
            a[count] = factory2.getAwaiter(); a[count++].start();
            a[count] = factory2.getAwaiter(); a[count++].start();
            a[count-1].interrupt();
            test.toTheStartingGate(gate);
            System.out.println("Main Thread: " + latch.toString());
            latch.countDown();
            checkCount(latch, 2-i);
        }
        for (int i = 0; i < 12; i++)
            a[i].join();

        for (int i = 0; i < 12; i++)
            checkResult(a[i],
                        (i % 4) == 3 ? InterruptedException.class : null);
    }

    //----------------------------------------------------------------
    // One thread timed out
    //----------------------------------------------------------------
    public static void timeOut() throws Throwable {
        int count =0;
        Basic test = new Basic();
        CountDownLatch latch = new CountDownLatch(3);
        Awaiter a[] = new Awaiter[12];

        long[] timeout = { 0L, 5L, 10L };

        for (int i = 0; i < 3; i++) {
            CountDownLatch gate = new CountDownLatch(4);
            AwaiterFactory factory1 = test.awaiterFactories(latch, gate, 1);
            AwaiterFactory factory2 = test.awaiterFactories(latch, gate, 0);
            a[count] = test.awaiter(latch, gate, timeout[i]); a[count++].start();
            a[count] = factory1.getAwaiter(); a[count++].start();
            a[count] = factory2.getAwaiter(); a[count++].start();
            a[count] = factory2.getAwaiter(); a[count++].start();
            test.toTheStartingGate(gate);
            System.out.println("Main Thread: " + latch.toString());
            latch.countDown();
            checkCount(latch, 2-i);
        }
        for (int i = 0; i < 12; i++)
            a[i].join();

        for (int i = 0; i < 12; i++)
            checkResult(a[i], null);
    }

    public static void main(String[] args) throws Throwable {
        normalUse();
        threadInterrupted();
        timeOut();
        if (failures.get() > 0L)
            throw new AssertionError(failures.get() + " failures");
    }

    private static final AtomicInteger failures = new AtomicInteger(0);

    private static void fail(String msg) {
        fail(new AssertionError(msg));
    }

    private static void fail(Throwable t) {
        t.printStackTrace();
        failures.getAndIncrement();
    }

    private static void checkCount(CountDownLatch b, int expected) {
        if (b.getCount() != expected)
            fail("Count = " + b.getCount() +
                 ", expected = " + expected);
    }

    private static void checkResult(Awaiter a, Class c) {
        Throwable t = a.result();
        if (! ((t == null && c == null) || c.isInstance(t))) {
            System.out.println("Mismatch: " + t + ", " + c.getName());
            failures.getAndIncrement();
        }
    }
}


text:
package models_test

import "testing"

func Test_Quote(t *testing.T) {
	t.Fatal("This test needs to be implemented!")
}


text:
# Database and REST (dare)

[![Coverage Status](https://coveralls.io/repos/github/5app/dare/badge.svg)](https://coveralls.io/github/5app/dare)
[![CircleCI](https://circleci.com/gh/5app/dare.svg?style=shield)](https://circleci.com/gh/5app/dare)
[![NPM Version](https://img.shields.io/npm/v/dare.svg)](https://www.npmjs.com/package/dare)
[![Known Vulnerabilities](https://snyk.io/test/github/5app/dare/badge.svg)](https://snyk.io/test/github/5app/dare)
[![semantic-release](https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--release-e10079.svg)](https://github.com/semantic-release/semantic-release)
[![codebeat badge](https://codebeat.co/badges/718b30e2-76fa-4c61-b770-751b22c5ea5e)](https://codebeat.co/projects/github-com-5app-dare-main)

Dare is a lovely API for generating SQL out of structured Javascript object. It's more than just sugar to querying a SQL database though, as you will discover.
# Example usage...

This is a simple setup to get started with, it'll make a basic SELECT query.

```js
// Require the module
import Dare from 'dare';
import sqlConn from './mySqlConn.js';

// Initiate it
const dare = new Dare();

// Define the handler dare.execute for handing database requests
await dare.execute = async ({sql, values}) => {
	// Execute query using prepared statements
	return sqlConn.execute(sql, values);
};

// Make a request
const resp = await dare.get('users', ['name'], {id: 1});
// SELECT id, name FROM users WHERE id = 1 LIMIT 1;

console.log(`Hi ${resp.name}');
```

## Install

```bash
npm i dare --save
```

# Methods

## dare.get(table[, fields][, filter][, options])

The `dare.get` method is used to build and execute a `SELECT ...` SQL statement.

| property | Type              | Description
|----------|-------------------|----------------
| table    | string            | Name of the table to access
| fields   | Array strings     | Fields Array
| filter   | Hash (key=>Value) | Query Object
| options  | Hash (key=>Value) | Additional Options

e.g.

```js
await dare.get('table', ['name'], {id: 1});
// SELECT name FROM table WHERE id = 1 LIMIT 1;
```

## dare.get(options Object)

Alternatively an options Object can be used instead.

e.g.

```js
await dare.get({
	table: 'users',
	fields: ['name'],
	filter: {
		id: 1
	}
});
```

### Fields Array `fields`

The `fields` property is the second argument in the shorthand request `dare.get(table,fields[], ...)`. It is an Array of the fields from the matching table to return.

In its simplest form `fields` it is an Array of Strings, e.g. `['id', 'name', 'created_date']`. This creates a very simple query.

```js
await dare.get('users', ['id', 'name', 'created_date'], ...);
// SELECT id, name, created_date FROM ....
```

The array items can also be Objects.

#### Aliased fields and Formatting (objects)

**Aliasing fields**

It's sometimes appropriate to return a field by another name, this is called *aliasing*.

To achieve that, instead of having a string item in the fields array, an object is provided instead. The object has one property where the key of that property defines the new name, and the value the db field.

e.g. here we rename email to emailAddress

```js
await dare.get('users',
	[
		'name', // also including a regular string field alongside for comparison
		{
			// label : db field
			'emailAddress': 'email'
		}
	]
);
// sql: SELECT email AS emailAddress FROM users ...
```

**Applying SQL Formatting**

The object structure used for **aliasing** can also be used to label a response including a SQL Function.

E.g. Below we're using the `DATE` function to format the `created_date`, and we're aliasing it so it will be returned with prop key `date`.

```js
await dare.get('users',
	[
	  {
	  	'date': 'DATE(created_date)'
	  }
	]
);
// sql: SELECT name, DATE(created_date) AS date ...
```

**Supported SQL Functions**:

SQL Functions have to adhere to a pattern.

*note*: It is currently limited to defining just one table field, we hope this will change

`FUNCTION_NAME([FIELD_PREFIX]? field_name [MATH_OPERATOR MATH_VALUE]?[, ADDITIONAL_PARAMETERS]*)`

- *FUNCTION_NAME*: uppercase, no spaces
- *FIELD_PREFIX*: optional, uppercase
- *field_name*: db field reference
- *MATH_OPERATOR* *MATH_VALUE*: optional
- *ADDITIONAL_PARAMETERS*: optional, prefixed with `,`, (uppercase, digit or quoted string)

*e.g.*

Field Defition | Description
--|--
`FORMAT(field, 2, 'de_DE')` | Rounding to 2 decimal places and convert to a string with German formatting.
`CONCAT(ROUND(field * 100), '%')` | Multiplying a number by 100. Rounding to 2 decimal places and appending a '%' to the end to convert a decimal value to a percentage.
`DATE_FORMAT(field, "%Y-%m-%dT%T.%fZ")` | Format date field
`!ISNULL(field)` | Function prefixed with negation operator `!`

#### Nesting Fields

Nesting can return data structures from across tables.

*note*: a **Model** Field Attribute `reference`, which defines the join between the two tables, is required to make nested joins.

Request nested data with an object; where the key is the name of the table to be joined, and the value is the Array of fields to return from the joined table.

```js
	// fields attribute...
	[
		'name',
		{
			'country': [
				'name'
			]
		}
	]

	// sql: SELECT name, county.name
```

The SQL this creates renames the fields and then recreates the structured format that was requested. So with the above request: a typical response would have the following structure...

```js
	// Example response
	{
		name: 'Andrew',
		country: {
			name: 'UK'
		}
	}
```

- At the moment this only supports *n:1* mapping.
- The relationship between the tables must be defined in a model field reference.

### Filter `filter`

The Filter Object is a Fields=>Value object literal, defining the SQL condition to attach to a statement.

e.g.

```js

	{
		id: 1,
		is_hidden: 0
	}

	// ... WHERE id = 1 AND is_hidden = 0 ...
```

The filter object can contain nested objects (Similar to the Fields Object). Nested objects define conditions on Relational tables.

*note*: a **Model** Field Attribute `reference`, which defines the join between the two tables, is required to make nested joins.

```js
	{
		country: {
			name: 'UK'
		}
	}
```

OR shorthand, nested subkeys are represented with a '.'

```
	{
		'country.name': 'UK'
	}
```

Creates the following SQL JOIN Condition

```sql
	... WHERE country.name = 'UK' ...
```

#### Filter Syntax

The type of value affects the choice of SQL Condition syntax to use. For example an array will create an `IN (...)` condition.

Prefixing the prop with:

- `%`: creates a `LIKE` comparison
- `-`: hyhen negates the value
- `~`: creates a range

| Key     | Value                     | Type           | = SQL Condition
|---------|---------------------------|----------------|----------------
| id      | 1                         | number         | `id = 1`
| name    | 'Andrew'                  | string         | `name = 'Andrew'`
| %name   | 'And%'                    | Pattern        | `name LIKE 'And%'`
| -%name  | 'And%'                    | Pattern        | `name NOT LIKE 'And%'`
| name$1  | any                  	  | any            | e.g. `name LIKE '%And%` $suffixing gives `name` alternative unique object key values, useful when writing `name LIKE %X% AND name LIKE %Y%`
| tag     | [1, 'a']                  | Array values   | `tag IN (1, 'a')`
| -tag    | [1, 'a']                  | Array values   | `tag NOT IN (1, 'a')`
| -status | ['deleted', null]         | Array values   | `(status NOT IN ('deleted') AND status IS NOT NULL)` Mixed type including `null`
| ~date   | '2016-03-04T16:08:32Z..'  | Greater than   | `date > '2016-03-04T16:08:32Z'`
| ~date   | '2016-03-04..2016-03-05'  | Between        | `date BETWEEN '2016-03-04' AND '2016-03-05'`
| -~date  | '2016-03-04..'            | !Greater than  | `(NOT date > '2016-03-04T00:00:00' OR date IS NULL)`
| flag    | null                      | null           | `flag IS NULL`
| -flag   | null                      | null           | `flag IS NOT NULL`

#### Negate entire joins (i.e. NOT EXISTS)

*note*: a **Model** Field Attribute `reference`, which defines the join between the two tables, is required to make nested joins.

If there is a nested section on a filter which should act to exclude items from the resultset. Then it can be appropriate to use `-` in front of the table name.

Example: Retrieve all users who are *not* in the 'admin' team....
```js
await dare.get({
	table: 'users',
	fields: ['name'],
	filter: {
		-team: {name: 'admin'}
	}
});

// SELECT u.name FROM users u WHERE NOT EXISTS (SELECT 1 FROM team t WHERE name = 'admin' AND t.user_id = u.id)...
```

note: this is very different from having the negation on the field definition, i.e.  `-name:'admin'`, which is described in Filter Syntax.

### Group by `groupby`

`groupby` accepts the same format as a single `field` expression. It can be a single value or an array of multiple expressions. I.e.

```js
groupby: [
	'type',
	'YEAR_MONTH(created_date)'
]
```

Generates
```sql
	GROUP BY type, YEAR_MONTH(created_date)
```

### Order By `orderby`

`orderby` accepts the same format as a single `field` expression. It can be a single value or an array of multiple expressions. I.e.

```js
orderby: [
	'type',
	'YEAR_MONTH(created_date)'
]
```

Generates
```sql
	ORDER BY type, YEAR_MONTH(created_date)
```

### Join

*note*: a **Model** Field Attribute `reference`, which defines the join between the two tables, is required to make nested joins.

The Join Object is a Fields=>Value object literal. It accepts the same syntax to the Filter Object, and defines those conditions on the SQL JOIN Condition.

e.g.

```js

	join: {
		county: {
			is_hidden: 0
		}
	}

	// ... LEFT JOIN county b ON (b.id = a.country_id AND b.is_hidden = 0)
```

The JOIN object is useful when restricting results in the join table without affecting the results returned in the primary table.

To facilitate scenarios where the optional JOIN tables records are dependent on another relationship we can define this also in the JOIN Object, by passing though a special prop `_required: true` (key=>value)

The following statement includes all rows as before, but the nested country data is filtered separatly.

```js

	join: {
		county: {
			continent: {
				_required: true,
				name: 'Europe'
			}
		}
	}

	// ...
	// LEFT JOIN county b ON (b.id = a.country_id)
	// LEFT JOIN continent c ON (c.id = b.continent_id)
	// WHERE (c.id = b.continent_id OR b.continent_id IS NULL)
	// ...
```

### Pagination `limit` and `start`

The `limit` and `start` properties are simply applied to the SQL query and can be used to paginate the resultset.

```js
await dare.get({
	table: 'table',
	fields: ['name'],
	limit: 10, // Return only 10 rows
	start: 20, // Start in the 20th
});
// SELECT name FROM table LIMIT 10 OFFSET 20;
```

### No `limit` set and `notfound`
Dare returns a single item when no `limit` is set. When the item is not found Dare rejects the request with `DareError.NOT_FOUND`. To override this default behaviour simply set the `notfound` to the value to respond with in the event of a notfound event being triggered. This can be a simple value or if a function is provided, then that function will be called e.g.

```js
const resp = await dare.get({
	table: 'table',
	fields: ['name'],
	filter: {name: 'Nameless'}
	notfound: null
});

// SELECT name FROM table WHERE name = 'Nameless' LIMIT 1;
// -- found 0 rows
console.log(resp); // null

```

## dare.getCount(table[, filter][, options])

The `dare.getCount` method like the `dare.get` method builds and executes a `SELECT ...` SQL statement. It differs from the `get` in that it does not operate on the `fields` option. It merely calculates and returns the number of results which match the request options. It is intended to be used when constructing pagination, or other summaries.

| property | Type              | Description
|----------|-------------------|----------------
| table    | string            | Name of the table to access
| filter   | Hash (key=>Value) | Query Object
| options  | Hash (key=>Value) | Additional Options

e.g.

```js
const count = await dare.getCount('profile', {first_name: 'Andrew'});
// SELECT COUNT(DISTINCT id) FROM profile WHERE name = 'Andrew' LIMIT 1;
```

## dare.getCount(options Object)

Using an options Object allows for  `date.getCount(options)` to be paired with a request to `dare.get(options)`.

e.g.

```js
const requestOptions = {
	table: 'profile',
	filter: {
		first_name: 'Andrew'
	},
	limit: 10
};

// Get the first 10 items, and the number of possible rows
const [items, foundRows] = await Promise.all([

	// Make a request for members matching the condition
	dare.get(requestOptions)

	// Get the number of possible results
	dare.getCount(requestOptions)
]);
```

## dare.post(table, body[, options])

The `dare.post` method is used to build and execute an `INSERT ...` SQL statement.

| property | Type              | Description
|----------|-------------------|----------------
| table    | string            | Name of the table to insert into
| body     | Object            | Post Object or Array of Post Objects
| options  | Hash (key=>Value) | Additional Options

e.g.

```js
await dare.post('user', {name: 'Andrew', profession: 'Mad scientist'});
// INSERT INTO table (name, profession) VALUES('Andrew', 'Mad scientist')
```

## dare.post(options Object)

Alternatively a options Object can be used instead.

e.g.

```js
await dare.post({
	table: 'user',
	body: {
		name: 'Andrew',
		profession: 'Mad scientist'
	}
});

```

## dare.post(options Object) with multiple values

The body can be an Array of objects.

e.g.

```js
await dare.post({
	table: 'user',
	body: [{
		name: 'Andrew',
		profession: 'Mad scientist'
	}, {
		name: 'Peppa'
	}]
});
```

This generates `INSERT INTO user (name, profession) VALUES ('Andrew', 'Mad Scientist'), ('Peppa', DEFAULT)`. Note where the key's differ between items in the Array the `DEFAULT` value is inserted instead.

### Post `options` (additional)

| Prop           | Type             | Description
|----------------|------------------|----------------
| duplicate_keys | 'ignore'         | Appends `ON DUPLICATE KEYS UPDATE _rowid=_rowid`
| duplicate_keys_update | Array(field1, field2, ...) | Appends `ON DUPLICATE KEYS UPDATE field1=VALUES(field1)`
| query          | Get Options		| See the dare.get options

#### query

The query is used to create an `INSERT...SELECT` statement in place of a `body` property. The object is the same as the Get options, see above.

e.g.

```js
/*
 * Run query to record all users with a session_date in the year 2021
 * INSERT INTO logs (id, name) SELECT id, name FROM user WHERE session_date BETWEEN '2021-01-01' AND '2021-12-31'
 */
await dare.post({
	table: 'log',
	query: {
		table: 'user',
		fields: ['id', 'name'],
		filter: {
			session_date: '2021-01-01..2021-12-31'
		}
	}]
});
```

## dare.patch(table, filter, body[, options])

Updates records within the `table` with the `body` object when they match `filter`.

| property | Type              | Description
|----------|-------------------|----------------
| table    | string            | Name of the table to insert into
| filter   | Object            | Filter object of the results
| body     | Object            | Post Object to apply
| options  | Hash (key=>Value) | Additional Options

### Patch `options` (additional)

| Prop          | Type      | Description
|---------------|-----------|----------------
| duplicate_keys | 'ignore' | Adds keyword `IGNORE`, e.g. `UPDATE IGNORE table ...`
| limit         | number    | Default: `1`. Limit the number of results which can be affected by patch
| notfound      | *         | Value to return when there are no affected rows. If it's a function the function will be called. Default throws `DareError.NOT_FOUND`

## dare.del(table, filter[, options])

Deletes records within the `table` when they match `filter`.

| property | Type              | Description
|----------|-------------------|----------------
| table    | string            | Name of the table to insert into
| filter   | Object            | Filter object of the results
| options  | Hash (key=>Value) | Additional Options

### Del `options` (additional)

| Prop          | Type      | Description
|---------------|-----------|----------------
| notfound      | *         | Value to return when there are no affected rows. If it's a function the function will be called. Default throws `DareError.NOT_FOUND`
| limit         | number    | Default: `1`. Limit the number of results which can be affected by delete

# `options` Object

The `options` Object is used to define properties on the current and descendent contexts. In other words, every method in Dare, creates a new instances inheritting its parent options as well as defining it's own. See `dare.use(options)` for more.

The `options` themselves are a set of properties used to interpret and manipulate the request.

```js
// Create an options Object
const options = {
	// Some options...
}

// Apply options at the point where Dare is invoked...
const dare = new Dare(options);

// OR Apply options when creating an instance off another instance...
const dare2 = dare.use(options);

// OR Apply options at the point of calling a method...
await dare.get({
	table: 'sometable',
	fields: ['id', 'name'],
	...options
})
```

As you can see, to apply `options` you have... um *options*.

# `options.models`

The `options.models` object, allows us to apply all our models to Dare. Where the object key is the label for which we'll refer to that model.

See next section **Model** for what a model looks like.

```js
// options Object containing a property called `models`
// Models is a key => model store, where the key is what we'll always refer to as the label for that model.
const options = {
	models: {
		// modelA,
		// modelB,
		// etc...
	}
}

// options applied to dare as before.
```

# Model

Perhaps the most important part of the **Dare** library is concept of a **model**.

A **model** defines:
- how data is interlinked, i.e. how one relational data table is joined to another via a key
- mutation handlers, for changing requests. This allows access permissions to be applied, to filter results, to restrict or mutate input data.

E.g. here are available properties which can be defined on a model,

```js
const myModel = {
	table, // this is the db table name, if omitted Dare will assume the models label instead
	schema, // A schema object defining fields, as well as their relationship to other models.
	get, // Function to modify the request when accessing data
	post, // Function to modify the request when posting data
	patch, // Function to modify the request when patching data
	del, // Function to modify the request when deleting data
}
```

## Model Table `table`

The underlying Database SQL Table to use when querying this model, if omitted Dare will assume the models label instead

```js
const myModel = {
	table: 't_mytable' // an example table name: some dba's do like to prefix table names, however it's not a convention which makes for a nice api.
	// ...
}
```
## Model Schema `schema`

The `schema` property defines an object, containing field attribute references in key=>value pair, i.e. `fieldName (key) => field attributes (value)`.

```js
const mySchema = {
	id, // id field attributes
	name, // name field attributes
	//etc...
}
```

### Field Attributes

Can define how a field corresponds to a DB table field, whether it's readable/writable, is it a generated field, as well as relationships between models.

Defining a field attribute, can be verbose using an object with special keys, or can be shorthanded with specific datatypes

Property | Attr Example | Shorthand DataType | ShortHand Example | Description
--|--|--|--|--
`references` | e.g. `{references: ['country.id']}` | `Array` | `county_id: ['country.id']` | Relationship with other models
`alias` | e.g. `{alias: 'email'}` | `String` | `emailAddress: 'email'` | Alias a field with a DB Table field
`handler` | e.g. `{handler: Function}` | `Function` | `url: urlFunction` | Generated Field
`type` | e.g. `{type: 'json'}` | na | na | Type of data in field, this has various uses.
`defaultValue` | e.g. `{defaultValue: 'active'}` | na | na | Default Value to insert during post, and filter with get/patch/del
`readable` | e.g. `{readable: false}` | na | na | Disables/Enables request access to a field
`writeable` | e.g. `{writeable: false}` | na | na | Disables/Enables write access to a field
na | e.g. `{writeable: false: readable: false}` | `Boolean` | `{password: false}` | Disables/Enables both write and read access to a field

Fields dont need to be explicitly defined in the `options.models.*tbl*.schema` where they map one to one with a DB table fields the request will just go through verbatim.

#### Field attribute: `reference`

In the example below the fields `users.country_id` defines a reference with `country.id` which is used to construct SQL JOIN Conditions.

```js
const dare = new Dare({
	models : {
		users: {
			schema: {
				// users fields...
				country_id: ['country.id']
			},
		},
		country: {
			schema: {
				// country fields...
				id: {}
			},
		}
	}
});
```

#### Field attribute: `type`

Defining the `type` introduces additional features.

**`datatime`**

Setting value to 'datetime', a conditional filter short hand for `created_time: 2017` would be expanded to `created_time BETWEEN '2017-01-01T00:00:00' AND '2017-12-31T23:59:59`

```js
const dare = new Dare({
	models: {
		users: {
			schema: {
				created_time: {
					type: 'datetime'
				}
			}
		}
	}
});
```

**`json`**

Serializes Objects and Deserializes JSON strings in `get`, `post` and `patch` operations.

e.g.

Schema: field definition...
```js
const dare = new Dare({
	models: {
		users: {
			schema: {
				meta: {
					// Define a field meta with data type of json
					type: 'json'
				}
			}
		}
	}
});
```

Example set and get
```js
	// Arbitary object...
	const meta = {
		prop1: 1,
		prop2: 2
	};

	// For a field named `meta`
	const {insertId: id} = await dare.post('users', {meta});
	// The value is run through JSON.stringify before insertion
	// INSERT INOT users (meta) VALUES('{"prop1": 1, "prop2": 2}')

	...

	// The value is desiralized, when accessed via get...
	const {meta} = await dare.get('users', ['meta'], {id});

	// e.g...
	console.log(meta);
	// Object({
	// 	prop1: 1,
	// 	prop2: 2
	// });

```

#### Field attribute: `handler`

When the value is a function, the function will be invoked when interpretting the request as part of a field value. The response of this function can either be a static value or it can be an additional function which is optionally run on all items in the response, to return a generated field.

E.g.

This will manipulate the request and response to create the property `avatar_url` on the fly.

```js
const dare = new Dare({
	models: {
		users: {
			schema: {
				avatar_url(fields) {

					fields.push('id'); // require additional field from users table.

					return (item) => `/images/avatars/${item.id}`;
				}
			}
		}
	}
});
```

#### Field attribute: `alias`

To alias a field, so that you can use a name different to the db column name, assign it a string name of the field in the current table. e.g. `emailAddress: 'email'`

```js
const dare = new Dare({
	models: {
		users: {
			schema: {
				emailAddress: 'email'
			}
		}
	}
});
```

For example this will enable the use of `emailAddress` in our api (see below), but the SQL generated will refer to it with it's true field name "`email`".

```js
await dare.get('users', ['emailAddress'], {emailAddress: 'andrew@%'});
// SELECT email AS emailAddress FROM users WHERE email LIKE 'andrew@%'

await dare.post('users', {emailAddress: 'andrew@example.com'});
// INSERT INTO users (email) VALUES ('andrew@example.com')

```

##### Nested and SQL `alias`'s

The aliasing can also be used for common functions and define fields on another table to abstract away some of the complexity in your relational schema and provide a cleaner api interface.

e.g.
```js
const dare = new Dare({
	models: {
		users: {
			schema: {
				emailAddress: {
					// Explicitly define the alias
					// Reference the email define on another table, we can also wrap in SQL functions.
					alias: 'LOWER(usersEmails.email)'
				},
			}
		},
		// Any cross table join needs fields to map
		usersEmails: {
			schema: {
				user_id: ['users.id']
			}
		}
	}
});
```

note: Defining an alias which includes SQL or points to another table will let it be used in a query filter and join conditions.
However an error will throw if attempting to set a value to such an alias.

#### Field attribute: `defaultValue`

Defining the `defaultValue` introduces default conditions or values when querying or inserting records respectively.

`defaultValue` can be any value supported by the context it is used. If `defaultValue` is not an object, it will be applied to all operations, "methods" (`get`, `post`, `patch` and `del`). However when `defaultValue` is defined as an object, then the properties of the object matching the method will be used.

e.g we can define what `defaultValue` is used in various scenarios:

```js
defaultValue: {
	get: 'active', // Includes `= 'active'` to `.get` filter conditions.
	post: 'active', // Inserts `active` into new records
	del: 'inactive', // Includes `= 'inactive'` to `.del` filter conditions.
	// patch: is undefined and wont apply any default values
}
```

**`defaultValue`**

In the example we're going to set the defaultValue for the `users.status` field to `"active"`.

```js
const dare = new Dare({
	models: {
		users: {
			schema: {
				status: {
					defaultValue: 'active'
				}
			}
		}
	}
});

// And now requests will by default include that value
await dare.post('users', {name: 'Andrew'}); // INSERT INTO users (name, status) VALUES ("Andrew", "active")
await dare.get('users', ['id'], {limit: 100}); // SELECT id FROM users WHERE status = 'active' LIMIT 100
// ... adds same condition for Del and Patch methods
```

#### Field attribute: `readable`/`writeable`

A flag to control access to a field

```js
const dare = new Dare({
	models: {
		users: {
			schema: {
				// Explicit object
				id: {
					readable: true,
					writeable: false // non-writeable
				},

				// Shorthand for non-readable + non-writeable
				password: false
			}
		}
	}
})
```

With the above `writeable`/`readable` field definitions an error is thrown whenever attempting to access the field e.g.

```js
await dare.get('users', ['password'], {id: 123});
// throws {code: INVALID_REFERENCE}
```

Or when trying to modify a field through `post` or `patch` methods, e.g.

```js
await dare.patch('users', {id: 321}, {id: 1337});
// throws {code: INVALID_REFERENCE}
```

## `model.get`

Here's an example of setting a model to be invoked whenever we access `users` model, we'll go into each of the properties afterwards.

```js
function get(options) {
	options.filter.deleted = null;
}

// For completeness we'll assume the new Dare instance approach for adding the options...
const dare = new Dare({
	models: {
		users: {
			get
		}
	}
});

// Here we're using `table:users`, so the model's `get` Function would be invoked
await dare.get({
	table: 'users',
	fields: ['name'],
	limit: 100
});

// SELECT name FROM users WHERE deleted = false LIMIT 100;
```

# Data validation

Dare has limited validation built in (see above). Set your own `validationInput` to check input values being applied in `patch` and `post` operation.

## validateInput(fieldAttributes, field, value)

The `validateInput` validation is called after any method model handlers. It contains the following parameters...

| property        | Type    | Description
|-----------------|---------|----------------
| fieldAttributes | Object  | Field Attributes
| field           | string  | Field Name
| value           | *       | Input value

e.g.

```js
dare.use({
	models: {
		// Member Model
		member: {
			schema: {
				username: {
					required: true,
					type: 'string',
					maxlength: 5,
					test(value) {
						if(!/\W/.test(value)) {
							throw new Error(`😞: username should only contain alphabetical characters`);
						}
					}
				},
				age: {
					// Another field
				}
			}
		}
	},

	validateInput(fieldAttributes, field, value) {
		if (!fieldAttribute) {
			throw new Error(`😞: ${field} field is unknown`);
		}
		if (fieldAttributes.required && value === undefined) {
			throw new Error(`😞: ${field} is missing`);
		}
		if (fieldAttributes.type && typeof (value) !== 'string') {
			throw new Error(`😞: ${field} should be a string`);
		}
		if (fieldAttributes.maxlength && value.length > fieldAttributes.maxlength) {
			throw new Error(`😞: ${field} should be less than ${fieldAttributes.maxlength} characters`);
		}
		fieldAttributes.test?.(value);
	}
});

// Then see what errors you'd get...

dare.post('member', {username: 'Fine', hello: "What's this?"});
// 😞: hello field is unknown

dare.post('member', {age: 5});
// 😞: username is missing

dare.post('member', {username: 123});
// 😞: username should be a string

dare.post('member', {username: 'Thisistoolong'});
// 😞: username should be less than 5 characters

dare.post('member', {username: 'No strange characters !@£$%^YU'});
// 😞: username should only contain alphabetical characters

```

### default attributes of model schema

The `default` field definition can be defined per model. This is useful to say when to be strict with unknown fields.

e.g.

```js
dare.use({
	models: {
		// Member Model
		member: {
			schema: {
				default: {
					// Be strict with the member model
					writeable: false
				},
				// ... other field definitions below
			}
		}
	},

	validateInput(fieldAttributes, field, value) {
		if (!fieldAttribute) {
			// Do nothing, We have no field definitions for this model
			console.log(`Someone should write field definitions for ${field} 👉`);
		}
		if (fieldAttributes.writeable === false) {
			throw new Error(`😞: ${field} field is un-writeable`);
		}
		// ... other validation rules below
	}
});

// So on the member table the default field would be replaced with an unknown field and would be caught
dare.post('member', {hello: "What's this?"});
// 😞: hello is un-writeable

// Whilst the same unknown field would be allowed through where the default field is not declared
dare.post('emails', {hello: "What's this?"});
// Someone should write field definitions for hello 👉`
```

# Additional Options

## Multiple joins/filters on the same table

In order to both: show all relationship on the join table AND filter the main results by the joined table. One can either create separate table aliases (as described above) using one for the field name, and one for the filter. Or alternatively append an arbitary label, a `$` sign followed by an string. E.g.

E.g. Include all the tags associated with users AND only show users whom include the tag "Andrew"

```js
await dare.get({
	table: 'users',
	fields: ['name', {'tags': ['name']}],
	filter: {
		tags$a: {
			name: 'Andrew'
		}
	}
});
```

This will get all users who contain atleast the tags 'Andrew', as well as returning all the other tags.

## After Handlers

An `dareInstance.after` handler is executed after the initial request has completed but before Dare has resolved the call. This makes it useful for logging as well as manipulating the response. If the handler returns `undefined` or `Promise<undefined>` then the original response is returned unaltered. And anything other than `undefined` will become the new response.

E.g. here is an example using the `after` handlers in the `users.patch` model to record a transaction.

```js
options.models.users = {
	async patch(options, dareInstance) {

		/**
		 * Check that the data to be modified
		 * By using the options to construct a SELECT request first
		 */

		// Clonse the options
		const opts = {
			...options,
			fields: ['id', 'name']
		};

		// Execute a dare.get with the cloned options
		const {id: ref_id, name: previous_name} = await dare.get(opts);

		// Set the after handler
		dareInstance.after = () => {
			dare.post('changelog', {
				message: 'User updated',
				type: 'users',
				ref_id,
				previous_name
			})

			// Returns undefined so no change
		};
	}
};

```

### Handling dates and date ranges

The library supports a number of user friendly ways of passing in dates and date ranges by constructing the formal timestamp implied in the data passed to Dare.

E.g. here is a list of supported syntaxes and the resulting timestamp.

```
2018-01-01..2018-01-02,
2018-01-01..02,
2018-1-1..2

=== 2018-01-01T00:00:00..2018-01-02T23:59:59

etc...
```

### Changing the default MAX_LIMIT

By default the maximum value for a `limit` option is set by `dare.MAX_LIMIT`, you can override this in an instance of Dare.

```js
import Dare from 'dare';

// Initiate it
const dare = new Dare();

await dare.MAX_LIMIT = 1000000;
```

### Disabling intermediate model joins `infer_intermediate_models`

By default `infer_intermediate_models = true`. This allows two models which share a common relationship with another model to be joined in a query directly. However sometimes this can be unpredictable if there are potentially more than one shared references between the models. In which case you would need to use explicit full paths, you then might like to disable `infer_intermediate_models` so that you catch anything which doesn't tow the line.

```js
// Disable intermediate models

// On new instance
const dare = new Dare({infer_intermediate_models: false});

// On extended instance
const dareInst = dare.use({infer_intermediate_models: false);

// On individual queries...
await dare.get({
	// ... other options
	infer_intermediate_models: false
});
```

### Infering conditional operators based on value `conditional_operators_in_value`

By default `conditional_operators_in_value = '!%'`. Which is a selection of special characters within the value to be compared.

- `%`: A string containing `%` within the value to be compared will indicate a wild character and the SQL `LIKE` conditional operator will be used.
- `!`: A string starting with `!` will negate the value using a SQL `LIKE` comparison operator.
- `..`: A string containing `..` will use a range `BETWEEN`, `<` or `>` comparison operator where a string value contains `..` or the value is an array with two values (dependending if the first or second value is empty it will use `<` or `>` respecfively). This denotes a range and is enabled using the `~` operator (because `.` within prop name has another meaning)

```js
// Enabling support for one or more of the above special characters...

// On new instance
const dare = new Dare({conditional_operators_in_value: '%!~'});

// On extended instance
const dareInst = dare.use({conditional_operators_in_value: '%!~');

// On individual queries...
await dare.get({
	table: 'mytable',
	fields: ['id'],
	filter: {name: '%compare%', created: '2022-01-01..'}
	conditional_operators_in_value: '%!~'
});

// ... SELECT id FROM mytable WHERE name LIKE '%compare%' AND created > '2022-01-01'

// The same query with the option disabled
await dare.get({
	table: 'mytable',
	fields: ['id'],
	filter: {name: '%compare%', created: '2022-01-01..'}
	conditional_operators_in_value: ''
});

// Fallbacks to the '=' conditional operator
// ... SELECT id FROM mytable WHERE name = '%compare%' AND created = '2022-01-01..'

```

### Post format the response

The `dare.response_row_handler` is a little helper to format or redirect the response data as it's being processed. Using this approach to post-processing should give better performance on large datasets.

E.g.

```js
// create a new dare instance to avoid polluting the others.
dare = dare.use();

// Define a response_row_handler on the new instance...
await dare.response_row_handler = (item) => {
	// rudimentary write out as CSV.
	res.write(Object.keys(item).join(',') + '\n');

	// Do not return anything unless you want to include it in `data` (see below)
};

// Execute the query
const data = await dare.get('users', ['name'], {limit: 10000000});

console.log(data.length === 0); // empty array
```

### Overriding table schema per operation

You can override the schema per operation using the `models` option:

E.g.

```js
// On an instance, or create new instance with newDareInstance = dare.use(options)
const dare = new Dare({
	models: {
		my_table: {
			schema: {
				a_write_protected_field: {
					type: 'datetime',
					writeable: false,
				}
			}
		},
	}
});

// On an individual request
await dare.patch({
	table: 'my_table',
	body: {
		a_write_protected_field: 'new value,
	},
	models: {
		my_table: {
			schema: {
				write_protected_field: {
					writeable: true,
				},
			}
		},
	},
});
```

# Caveats

## Only one column name may appear in a Field Expression

Dare can't have more than one model field/column names in the same field expression.

e.g. Fields array....
```js
[{
	// Both fist_name and last_name in the same field expression 💥
	`displayName`: 'CONCAT(first_name, last_name)' // ❌
}]
```

To work around this we'd simply use post-formatting. Either write one yourself or make a Generated Field (handler) in the Dare schema and request that by name in the field expression.


text:
package org.jkiss.dbeaver.registry.driver;

import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.Platform;
import org.jkiss.code.NotNull;
import org.jkiss.code.Nullable;
import org.jkiss.dbeaver.Log;
import org.jkiss.dbeaver.model.DBIcon;
import org.jkiss.dbeaver.model.connection.DBPDriverLibrary;
import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Collection;

/**
 * DriverLibraryLocal
 */
public class DriverLibraryLocal extends DriverLibraryAbstract
{
    private static final Log log = Log.getLog(DriverLibraryLocal.class);

    public DriverLibraryLocal(DriverDescriptor driver, FileType type, String path) {
        super(driver, type, path);
    }

    public DriverLibraryLocal(DriverDescriptor driver, IConfigurationElement config) {
        super(driver, config);
    }

    public DriverLibraryLocal(DriverDescriptor driverDescriptor, DriverLibraryLocal copyFrom) {
        super(driverDescriptor, copyFrom);
    }

    @Override
    public DBPDriverLibrary copyLibrary(DriverDescriptor driverDescriptor) {
        return new DriverLibraryLocal(driverDescriptor, this);
    }

    @Override
    public boolean isDownloadable()
    {
        return false;
    }

    @Override
    public void resetVersion() {
        // do nothing
    }

    @Override
    public boolean isSecureDownload(DBRProgressMonitor monitor) {
        return true;
    }

    protected String getLocalFilePath() {
        return path;
    }

    @Nullable
    @Override
    public String getExternalURL(DBRProgressMonitor monitor) {
        return null;
    }

    @Nullable
    @Override
    public File getLocalFile()
    {
        // Try to use direct path
        String localFilePath = this.getLocalFilePath();

        File libraryFile = new File(localFilePath);
        if (libraryFile.exists()) {
            return libraryFile;
        }

        // Try to get local file
        File platformFile = detectLocalFile();
        if (platformFile != null && platformFile.exists()) {
            // Relative file do not exists - use plain one
            return platformFile;
        }

        URL url = driver.getProviderDescriptor().getContributorBundle().getEntry(localFilePath);
        if (url == null) {
            // Find in external resources
            url = driver.getProviderDescriptor().getRegistry().findResourceURL(localFilePath);
        }
        if (url != null) {
            try {
                url = FileLocator.toFileURL(url);
            } catch (IOException ex) {
                log.warn(ex);
            }
            if (url != null) {
                return new File(url.getFile());
            }
        } else {
            try {
                url = FileLocator.toFileURL(new URL(localFilePath));
                File urlFile = new File(url.getFile());
                if (urlFile.exists()) {
                    platformFile = urlFile;
                }
            }
            catch (IOException ex) {
                // ignore
            }
        }

        // Nothing fits - just return plain url
        return platformFile;
    }

    @Nullable
    @Override
    public Collection<? extends DBPDriverLibrary> getDependencies(@NotNull DBRProgressMonitor monitor) throws IOException {
        return null;
    }

    protected File detectLocalFile()
    {
        String localPath = getLocalFilePath();

        // Try to use relative path from installation dir
        File file = new File(new File(Platform.getInstallLocation().getURL().getFile()), localPath);
        if (!file.exists()) {
            // Use custom drivers path
            file = new File(DriverDescriptor.getCustomDriversHome(), localPath);
        }
        return file;
    }

    @NotNull
    public String getDisplayName() {
        return path;
    }

    @Override
    public String getId() {
        return path;
    }

    @NotNull
    @Override
    public DBIcon getIcon() {
        File localFile = getLocalFile();
        if (localFile != null && localFile.isDirectory()) {
            return DBIcon.TREE_FOLDER;
        } else {
            switch (type) {
                case lib: return DBIcon.LIBRARY;
                case jar: return DBIcon.JAR;
                default: return DBIcon.TYPE_UNKNOWN;
            }
        }
    }

}


text:
class AdminQasController < AdminController
end


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Gram. unifl. sesquifl. 157. 1824

#### Original name
null

### Remarks
null


text:
package de.borellda.domain;

import javax.persistence.*;
import java.sql.Timestamp;

/**
 * Created by borellda on 2/24/2016.
 */
@Entity
@Table(name = "user_following_dataset", schema = "public", catalog = "ecodp")
@IdClass(UserFollowingDatasetEntityPK.class)
public class UserFollowingDatasetEntity {
    /* The Logger */
    private static final Logger log = LoggerFactory.getLogger(UserFollowingDatasetEntity.class);
    private String followerId;
    private String objectId;
    private Timestamp datetime;

    @Id
    @Column(name = "follower_id", nullable = false, length = -1)
    public String getFollowerId() {
        return followerId;
    }

    public void setFollowerId(String followerId) {
        this.followerId = followerId;
    }

    @Id
    @Column(name = "object_id", nullable = false, length = -1)
    public String getObjectId() {
        return objectId;
    }

    public void setObjectId(String objectId) {
        this.objectId = objectId;
    }

    @Basic
    @Column(name = "datetime", nullable = false)
    public Timestamp getDatetime() {
        return datetime;
    }

    public void setDatetime(Timestamp datetime) {
        this.datetime = datetime;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        UserFollowingDatasetEntity that = (UserFollowingDatasetEntity) o;

        if (followerId != null ? !followerId.equals(that.followerId) : that.followerId != null) return false;
        if (objectId != null ? !objectId.equals(that.objectId) : that.objectId != null) return false;
        if (datetime != null ? !datetime.equals(that.datetime) : that.datetime != null) return false;

        return true;
    }

    @Override
    public int hashCode() {
        int result = followerId != null ? followerId.hashCode() : 0;
        result = 31 * result + (objectId != null ? objectId.hashCode() : 0);
        result = 31 * result + (datetime != null ? datetime.hashCode() : 0);
        return result;
    }
}


text:
package com.joshng.util.concurrent;

import com.google.common.util.concurrent.AsyncFunction;
import com.google.common.util.concurrent.ListenableFuture;

import java.util.concurrent.Callable;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;

import static com.google.common.base.Preconditions.checkNotNull;

/**
 * User: josh
 * Date: 8/7/15
 * Time: 2:24 PM
 */
public class FutureChain<T> {
  private static final AtomicReferenceFieldUpdater<FutureChain, FunFuture> TAIL_UPDATER = AtomicReferenceFieldUpdater.newUpdater(FutureChain.class, FunFuture.class, "tail");
  private volatile FunFuture<T> tail;

  public FutureChain(FunFuture<T> initialValue) {
    this.tail = checkNotNull(initialValue, "initialValue");
  }

  public FutureChain(T initialValue) {
    this(FunFuture.immediateFuture(initialValue));
  }

  public FunFuture<T> getTail() {
    return tail;
  }

  public <R extends T> FunFuture<R> append(Callable<? extends ListenableFuture<R>> job) {
    return transform(prev -> job.call());
  }

  public <R extends T> FunFuture<R> transform(AsyncFunction<? super T, R> job) {
    return Promise.newPromise(promise -> {
              @SuppressWarnings("unchecked") FunFuture<T> prevTail = TAIL_UPDATER.getAndSet(this, promise);
              promise.completeWith(prevTail.flatMap(job));
            });
  }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project name="${project.name}" xmlns="http://maven.apache.org/DECORATION/1.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/DECORATION/1.0.0 http://maven.apache.org/xsd/decoration-1.0.0.xsd">
	<bannerLeft>
		<name>${project.name}</name>
		<href>#</href>
	</bannerLeft>

	<skin>
		<groupId>org.apache.maven.skins</groupId>
		<artifactId>maven-fluido-skin</artifactId>
		<version>1.3.0</version>
	</skin>
	<custom>
		<fluidoSkin>
			<topBarEnabled>false</topBarEnabled>
			<sideBarEnabled>true</sideBarEnabled>
			<gitHub>
				<projectId>${team.group.id}/${project.artifactId}</projectId>
				<ribbonOrientation>right</ribbonOrientation>
				<ribbonColor>black</ribbonColor>
			</gitHub>
		</fluidoSkin>
	</custom>

	<body>
		<head>
			<link rel="stylesheet" href="site.css" type="text/css" />
		</head>

		<menu name="${project.name}">
			<item name="About" href="about-basic.html" />
		</menu>
<!--
		<menu name="Other Information">
			<item name="Other" href="other.html" />
		</menu>
 -->
 		<menu ref="reports" />
	</body>
</project>


text:
class SourceParser # :nodoc:
  # == SourceParser::Ical
  #
  # Reads iCalendar events.
  #
  # Example:
  #   abstract_events = SourceParser::Ical.to_abstract_events('http://upcoming.yahoo.com/calendar/v2/event/349225')
  #
  # Sample sources:
  #   http://upcoming.yahoo.com/calendar/v2/event/349225
  #   webcal://appendix.23ae.com/calendars/AlternateHolidays.ics
  #   http://appendix.23ae.com/calendars/AlternateHolidays.ics
  class Ical < Base
    label :iCalendar

    # Override Base::read_url to handle "webcal" scheme addresses.
    def self.read_url(url)
      super(url.gsub(/^webcal:/, 'http:'))
    end

    CALENDAR_CONTENT_RE    = /^BEGIN:VCALENDAR.*?^END:VCALENDAR/m
    EVENT_CONTENT_RE       = /^BEGIN:VEVENT.*?^END:VEVENT/m
    EVENT_DTSTART_RE       = /^DTSTART.*?:([^\r\n$]+)/m
    EVENT_DTEND_RE         = /^DTEND.*?:([^\r\n$]+)/m
    VENUE_CONTENT_RE       = /^BEGIN:VVENUE$.*?^END:VVENUE$/m
    VENUE_CONTENT_BEGIN_RE = /^BEGIN:VVENUE$/m
    VENUE_CONTENT_END_RE   = /^END:VVENUE$/m
    IS_UPCOMING_RE         = /^PRODID:\W+Upcoming/m

    # Return an Array of AbstractEvent instances extracted from an iCalendar input.
    #
    # Options:
    # * :url -- URL of iCalendar data to import
    # * :content -- String of iCalendar data to import
    # * :skip_old -- Should old events be skipped? Default is true.
    def self.to_abstract_events(opts={})
      # Skip old events by default
      opts[:skip_old] = true unless opts[:skip_old] == false
      cutoff = Time.now.yesterday

      content = content_for(opts).gsub(/\r\n/, "\n")

      # Provide special handling for Upcoming's broken implementation of iCalendar
      if content.match(IS_UPCOMING_RE)
        # Strip out superflous self-referential Upcoming link
        content.sub!(%r{\s*\[\s*Full details at http://upcoming.yahoo.com/event/\d+/?\s*\]\s*}m, '')

        # Fix newlines in DESCRIPTION, replace them with escaped '\n' strings.
        matches = content.scan(/^(DESCRIPTION:.+?)(?:^\w+[:;])/m)
        matches.each do |match|
          content.sub!(match[0], match[0].strip.gsub(/\n/, '\n')+"\r\n")
        end
      end

      content_calendars = content.scan(CALENDAR_CONTENT_RE)

      [].tap do |events|
        for content_calendar in content_calendars
          content_venues = content_calendar.scan(VENUE_CONTENT_RE)

          content_calendar.scan(EVENT_CONTENT_RE).each_with_index do |content_event, index|
            # Skip old events before handing them to VPIM
            if opts[:skip_old]
              if start_match = content_event.match(EVENT_DTSTART_RE)
                start_time = Time.parse(start_match[1])

                end_match = content_event.match(EVENT_DTEND_RE)
                end_time = end_match ? Time.parse(end_match[1]) : nil

                next if (end_time || start_time) < cutoff
              end
            end

            components = Vpim::Icalendar.decode(%{BEGIN:VCALENDAR\n#{content_event}\nEND:VCALENDAR\n}).first.components
            raise TypeError, "Got multiple components for a single event" unless components.size == 1
            component = components.first

            event             = AbstractEvent.new
            event.start_time  = component.dtstart
            event.title       = component.summary
            event.description = component.description
            event.end_time    = component.dtend
            event.url         = component.url

            content_venue = \
              begin
                if content_calendar.match(%r{VALUE=URI:http://upcoming.yahoo.com/})
                  # Special handling for Upcoming, where each event maps 1:1 to a venue
                  content_venues[index]
                else
                  begin
                    location_field = component.fields.find{|t| t.respond_to?(:name) && t.name.upcase == "LOCATION"}
                    venue_values   = location_field ? location_field.pvalues("VVENUE") : nil
                    venue_uid      = venue_values ? venue_values.first : venue_values
                    venue_uid ? content_venues.find{|content_venue| content_venue.match(/^UID:#{venue_uid}$/m)} : nil
                  rescue Exception => e
                    # Ignore
                    RAILS_DEFAULT_LOGGER.info("SourceParser::Ical.to_abstract_events : Failed to parse content_venue for non-Upcoming event -- #{e}")
                    nil
                  end
                end
              end

            event.location = to_abstract_location(content_venue, :fallback => component.location)
            events << event
          end
        end
      end
    end

    # Return an AbstractLocation extracted from an iCalendar input.
    #
    # Arguments:
    # * value - String with iCalendar data to parse which contains a Vvenue item.
    #
    # Options:
    # * :fallback - String to use as the title for the location if the +value+ doesn't contain a Vvenue.
    def self.to_abstract_location(value, opts={})
      value = "" if value.nil?
      a = AbstractLocation.new

      # The Vpim libary doesn't understand that Vvenue entries are just Vcards,
      # so transform the content to trick it into treating them as such.
      if vcard_content = value.scan(VENUE_CONTENT_RE).first
        vcard_content.gsub!(VENUE_CONTENT_BEGIN_RE, 'BEGIN:VCARD')
        vcard_content.gsub!(VENUE_CONTENT_END_RE,   'END:VCARD')

        begin
          vcards = Vpim::Vcard.decode(vcard_content)
          raise ArgumentError, "Wrong number of vcards" unless vcards.size == 1
          vcard = vcards.first

          a.title          = vcard['name']
          a.street_address = vcard['address']
          a.locality       = vcard['city']
          a.region         = vcard['region']
          a.postal_code    = vcard['postalcode']
          a.country        = vcard['country']

          a.latitude, a.longitude = vcard['geo'].split(/;/).map(&:to_f)

          return a
        rescue Vpim::InvalidEncodingError, ArgumentError, RuntimeError
          # Exceptional state will be handled below
          :ignore # Leave this line in for rcov's code coverage
        end
      end

      if opts[:fallback].blank?
        return nil
      else
        a.title = opts[:fallback]
        return a
      end
    end
  end
end


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="HaarRectangle.cs" company="James South">
//   Copyright (c) James South.
//   Licensed under the Apache License, Version 2.0.
// </copyright>
// <summary>
//   Represents a rectangle which can be at any position and scale within the original image.
//   Based on original code found in the Accord Framework at <see href="https://github.com/accord-net/framework" />
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace ImageProcessor.Imaging.Filters.ObjectDetection
{
    using System;
    using System.Globalization;

    /// <summary>
    /// Represents a rectangle which can be at any position and scale within the original image.
    /// Based on original code found in the Accord Framework at <see href="https://github.com/accord-net/framework"/>
    /// </summary>
    [Serializable]
    public class HaarRectangle : ICloneable
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="HaarRectangle"/> class.
        /// </summary>
        /// <param name="values">
        /// The values for this rectangle.
        /// </param>
        public HaarRectangle(int[] values)
        {
            this.X = values[0];
            this.Y = values[1];
            this.Width = values[2];
            this.Height = values[3];
            this.Weight = values[4];
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="HaarRectangle"/> class.
        /// </summary>
        /// <param name="x">
        /// The x coordinate marking the top-left point to apply to this rectangle.
        /// </param>
        /// <param name="y">
        /// The y coordinate marking the top-left point to apply to this rectangle.
        /// </param>
        /// <param name="width">
        /// The width to apply to this rectangle.
        /// </param>
        /// <param name="height">
        /// The height to apply to this rectangle.
        /// </param>
        /// <param name="weight">
        /// The weight to apply to this rectangle.
        /// </param>
        public HaarRectangle(int x, int y, int width, int height, float weight)
        {
            this.X = x;
            this.Y = y;
            this.Width = width;
            this.Height = height;
            this.Weight = weight;
        }

        /// <summary>
        /// Prevents a default instance of the <see cref="HaarRectangle"/> class from being created.
        /// </summary>
        private HaarRectangle()
        {
        }

        /// <summary>
        /// Gets or sets the x-coordinate of this Haar feature rectangle.
        /// </summary>
        public int X { get; set; }

        /// <summary>
        /// Gets or sets the y-coordinate of this Haar feature rectangle.
        /// </summary>
        public int Y { get; set; }

        /// <summary>
        /// Gets or sets the width of this Haar feature rectangle.
        /// </summary>
        public int Width { get; set; }

        /// <summary>
        /// Gets or sets the height of this Haar feature rectangle.
        /// </summary>
        public int Height { get; set; }

        /// <summary>
        /// Gets or sets the weight of this Haar feature rectangle.
        /// </summary>
        public float Weight { get; set; }

        /// <summary>
        /// Gets or sets the scaled x-coordinate of this Haar feature rectangle.
        /// </summary>
        public int ScaledX { get; set; }

        /// <summary>
        /// Gets or sets the scaled y-coordinate of this Haar feature rectangle.
        /// </summary>
        public int ScaledY { get; set; }

        /// <summary>
        ///   Gets or sets the scaled width of this Haar feature rectangle.
        /// </summary>
        public int ScaledWidth { get; set; }

        /// <summary>
        ///   Gets or sets the scaled height of this Haar feature rectangle.
        /// </summary>
        public int ScaledHeight { get; set; }

        /// <summary>
        /// Gets or sets the scaled weight of this Haar feature rectangle.
        /// </summary>
        public float ScaledWeight { get; set; }

        /// <summary>
        /// Gets the area of this rectangle.
        /// </summary>
        public int Area
        {
            get { return this.ScaledWidth * this.ScaledHeight; }
        }

        /// <summary>
        /// Converts a <see cref="HaarRectangle"/> from a string representation.
        /// </summary>
        /// <param name="value">
        /// The value to parse.
        /// </param>
        /// <returns>
        /// The <see cref="HaarRectangle"/>.
        /// </returns>
        public static HaarRectangle Parse(string value)
        {
            string[] values = value.Trim().Split(' ');

            int x = int.Parse(values[0], CultureInfo.InvariantCulture);
            int y = int.Parse(values[1], CultureInfo.InvariantCulture);
            int w = int.Parse(values[2], CultureInfo.InvariantCulture);
            int h = int.Parse(values[3], CultureInfo.InvariantCulture);
            float weight = float.Parse(values[4], CultureInfo.InvariantCulture);

            return new HaarRectangle(x, y, w, h, weight);
        }

        /// <summary>
        /// Scales the values of this rectangle.
        /// </summary>
        /// <param name="scale">
        /// The scale.
        /// </param>
        public void ScaleRectangle(float scale)
        {
            this.ScaledX = (int)(this.X * scale);
            this.ScaledY = (int)(this.Y * scale);
            this.ScaledWidth = (int)(this.Width * scale);
            this.ScaledHeight = (int)(this.Height * scale);
        }

        /// <summary>
        /// Scales the weight of this rectangle.
        /// </summary>
        /// <param name="scale">
        /// The scale.
        /// </param>
        public void ScaleWeight(float scale)
        {
            this.ScaledWeight = this.Weight * scale;
        }

        /// <summary>
        /// Creates a new object that is a copy of the current instance.
        /// </summary>
        /// <returns>
        /// A new object that is a copy of this instance.
        /// </returns>
        public object Clone()
        {
            HaarRectangle r = new HaarRectangle
            {
                Height = this.Height,
                ScaledHeight = this.ScaledHeight,
                ScaledWeight = this.ScaledWeight,
                ScaledWidth = this.ScaledWidth,
                ScaledX = this.ScaledX,
                ScaledY = this.ScaledY,
                Weight = this.Weight,
                Width = this.Width,
                X = this.X,
                Y = this.Y
            };

            return r;
        }
    }
}


text:
VERBOSE = True

class Loading:
	""" Requirement! """
	controller = None
	def __init__( self, controller ):
		if VERBOSE:
			print "Loading module loaded with controller data (pin count is %d)." % controller.pin_count

		self.controller = controller

	current_channel = 0
	def work( self ):
		for i in range( 0, self.controller.pin_count ):
			self.controller.off( i )

		self.current_channel = self.current_channel + 1
		if self.current_channel >= self.controller.pin_count:
			self.current_channel = 0

		self.controller.on( self.current_channel )


text:
<?php

declare(strict_types=1);

namespace Eelly\SDK\Message\Api;

use Eelly\SDK\EellyClient;
use Eelly\SDK\Message\Service\MessageFormidInterface;

/**
 *
 * @author shadonTools<localhost.shell@gmail.com>
 */
class MessageFormid implements MessageFormidInterface
{
    /**
     * 发送订单取消通知消息.
     *
     * @param int $orderId 订单ID
     *
     * @author zhangyingdi<zhangyingdi@eelly.net>
     *
     * @since 2018.05.19
     */
    public function sendCancelOrder(int $orderId): bool
    {
        return EellyClient::request('message/messageFormid', 'sendCancelOrder', true, $orderId);
    }

    /**
     * 发送订单取消通知消息.
     *
     * @param int $orderId 订单ID
     *
     * @author zhangyingdi<zhangyingdi@eelly.net>
     *
     * @since 2018.05.19
     */
    public function sendCancelOrderAsync(int $orderId)
    {
        return EellyClient::request('message/messageFormid', 'sendCancelOrder', false, $orderId);
    }

    /**
     * 添加小程序表单id.
     *
     * @param string $formId 小程序表单id
     *
     * @return bool
     *
     * @author 肖俊明<xiaojunming@eelly.net>
     *
     * @since 2018年08月02日
     */
    public function addFormId(array $data): bool
    {
        return EellyClient::request('message/messageFormid', 'addFormId', true, $data);
    }

    /**
     * 添加小程序表单id.
     *
     * @param string $formId 小程序表单id
     *
     * @return bool
     *
     * @author 肖俊明<xiaojunming@eelly.net>
     *
     * @since 2018年08月02日
     */
    public function addFormIdAsync(array $data)
    {
        return EellyClient::request('message/messageFormid', 'addFormId', false, $data);
    }

    /**
     * 发送订单支付成功通知消息.
     *
     * @param int $orderId 订单ID
     *
     * @author zhangyingdi<zhangyingdi@eelly.net>
     *
     * @since 2018.05.21
     */
    public function sendSuccessOrder(int $orderId): bool
    {
        return EellyClient::request('message/messageFormid', 'sendSuccessOrder', true, $orderId);
    }

    /**
     * 发送订单支付成功通知消息.
     *
     * @param int $orderId 订单ID
     *
     * @author zhangyingdi<zhangyingdi@eelly.net>
     *
     * @since 2018.05.21
     */
    public function sendSuccessOrderAsync(int $orderId)
    {
        return EellyClient::request('message/messageFormid', 'sendSuccessOrder', false, $orderId);
    }

    /**
     * 发送订单发货通知.
     *
     * @param int $orderId 订单id
     *
     * @author zhangyingdi<zhangyingdi@eelly.net>
     *
     * @since 2018.05.30
     */
    public function sendOrderDelivery(int $orderId): bool
    {
        return EellyClient::request('message/messageFormid', 'sendOrderDelivery', true, $orderId);
    }

    /**
     * 发送订单发货通知.
     *
     * @param int $orderId 订单id
     *
     * @author zhangyingdi<zhangyingdi@eelly.net>
     *
     * @since 2018.05.30
     */
    public function sendOrderDeliveryAsync(int $orderId)
    {
        return EellyClient::request('message/messageFormid', 'sendOrderDelivery', false, $orderId);
    }

    /**
     * 发送领取优惠卷红包信息.
     *
     * @param  array $data 微信数据
     * @param  string $fromFlag 订单生成来源标识(单选):wechat|wechat_blty|wechat_lr
     * @param  int $userId 用户id
     *
     * @author zhangyingdi<zhangyingdi@eelly.net>
     * @author 肖俊明<xiaojunming@eelly.net>
     *
     * @since 2018.05.21
     */
    public function sendReceiveRedPackage(array $data, string $fromFlag, int $userId): bool
    {
        return EellyClient::request('message/messageFormid', 'sendReceiveRedPackage', true, $data, $fromFlag, $userId);
    }

    /**
     * 发送领取优惠卷红包信息.
     *
     * @param  array $data 微信数据
     * @param  string $fromFlag 订单生成来源标识(单选):wechat|wechat_blty|wechat_lr
     * @param  int $userId 用户id
     *
     * @author zhangyingdi<zhangyingdi@eelly.net>
     * @author 肖俊明<xiaojunming@eelly.net>
     *
     * @since 2018.05.21
     */
    public function sendReceiveRedPackageAsync(array $data, string $fromFlag, int $userId)
    {
        return EellyClient::request('message/messageFormid', 'sendReceiveRedPackage', false, $data, $fromFlag, $userId);
    }

    /**
     * @return self
     */
    public static function getInstance(): self
    {
        static $instance;
        if (null === $instance) {
            $instance = new self();
        }

        return $instance;
    }
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.analytics.synapse.artifacts.models;

import com.azure.core.annotation.Fluent;
import com.fasterxml.jackson.annotation.JsonProperty;

/** The LinkTableRequestTarget model. */
@Fluent
public final class LinkTableRequestTarget {
    /*
     * Target table table name
     */
    @JsonProperty(value = "tableName")
    private String tableName;

    /*
     * Target table schema name
     */
    @JsonProperty(value = "schemaName")
    private String schemaName;

    /*
     * Target table distribution options for link table request
     */
    @JsonProperty(value = "distributionOptions")
    private LinkTableRequestTargetDistributionOptions distributionOptions;

    /*
     * Target table structure options for link table request
     */
    @JsonProperty(value = "structureOptions")
    private LinkTableRequestTargetStructureOptions structureOptions;

    /**
     * Get the tableName property: Target table table name.
     *
     * @return the tableName value.
     */
    public String getTableName() {
        return this.tableName;
    }

    /**
     * Set the tableName property: Target table table name.
     *
     * @param tableName the tableName value to set.
     * @return the LinkTableRequestTarget object itself.
     */
    public LinkTableRequestTarget setTableName(String tableName) {
        this.tableName = tableName;
        return this;
    }

    /**
     * Get the schemaName property: Target table schema name.
     *
     * @return the schemaName value.
     */
    public String getSchemaName() {
        return this.schemaName;
    }

    /**
     * Set the schemaName property: Target table schema name.
     *
     * @param schemaName the schemaName value to set.
     * @return the LinkTableRequestTarget object itself.
     */
    public LinkTableRequestTarget setSchemaName(String schemaName) {
        this.schemaName = schemaName;
        return this;
    }

    /**
     * Get the distributionOptions property: Target table distribution options for link table request.
     *
     * @return the distributionOptions value.
     */
    public LinkTableRequestTargetDistributionOptions getDistributionOptions() {
        return this.distributionOptions;
    }

    /**
     * Set the distributionOptions property: Target table distribution options for link table request.
     *
     * @param distributionOptions the distributionOptions value to set.
     * @return the LinkTableRequestTarget object itself.
     */
    public LinkTableRequestTarget setDistributionOptions(
            LinkTableRequestTargetDistributionOptions distributionOptions) {
        this.distributionOptions = distributionOptions;
        return this;
    }

    /**
     * Get the structureOptions property: Target table structure options for link table request.
     *
     * @return the structureOptions value.
     */
    public LinkTableRequestTargetStructureOptions getStructureOptions() {
        return this.structureOptions;
    }

    /**
     * Set the structureOptions property: Target table structure options for link table request.
     *
     * @param structureOptions the structureOptions value to set.
     * @return the LinkTableRequestTarget object itself.
     */
    public LinkTableRequestTarget setStructureOptions(LinkTableRequestTargetStructureOptions structureOptions) {
        this.structureOptions = structureOptions;
        return this;
    }
}