text:
<?php

namespace Caxy\HtmlDiff;

/**
 * Class HtmlDiffConfig.
 */
class HtmlDiffConfig
{
    /**
     * @var array
     */
    protected $specialCaseTags = array('strong', 'b', 'i', 'big', 'small', 'u', 'sub', 'sup', 'strike', 's', 'p');

    /**
     * @var array
     */
    protected $specialCaseChars = array('.', ',', '(', ')', '\'');

    /**
     * @var bool
     */
    protected $groupDiffs = true;

    /**
     * @var bool
     */
    protected $insertSpaceInReplace = false;

    /**
     * @var string
     */
    protected $encoding = 'UTF-8';

    /**
     * @var array
     */
    protected $isolatedDiffTags = array(
        'ol' => '[[REPLACE_ORDERED_LIST]]',
        'ul' => '[[REPLACE_UNORDERED_LIST]]',
        'sub' => '[[REPLACE_SUB_SCRIPT]]',
        'sup' => '[[REPLACE_SUPER_SCRIPT]]',
        'dl' => '[[REPLACE_DEFINITION_LIST]]',
        'table' => '[[REPLACE_TABLE]]',
        'strong' => '[[REPLACE_STRONG]]',
        'b' => '[[REPLACE_STRONG]]',
        'em' => '[[REPLACE_EM]]',
        'i' => '[[REPLACE_EM]]',
        'a' => '[[REPLACE_A]]',
        'img' => '[[REPLACE_IMG]]',
    );

    /**
     * @var int
     */
    protected $matchThreshold = 80;
    /**
     * @var array
     */
    protected $specialCaseOpeningTags = array();
    /**
     * @var array
     */
    protected $specialCaseClosingTags = array();

    /**
     * @var bool
     */
    protected $useTableDiffing = true;

    /**
     * @var null|\Doctrine\Common\Cache\Cache
     */
    protected $cacheProvider;

    /**
     * @var null|string
     */
    protected $purifierCacheLocation = null;

    /**
     * @return HtmlDiffConfig
     */
    public static function create()
    {
        return new self();
    }

    /**
     * HtmlDiffConfig constructor.
     */
    public function __construct()
    {
        $this->setSpecialCaseTags($this->specialCaseTags);
    }

    /**
     * @return int
     */
    public function getMatchThreshold()
    {
        return $this->matchThreshold;
    }

    /**
     * @param int $matchThreshold
     *
     * @return AbstractDiff
     */
    public function setMatchThreshold($matchThreshold)
    {
        $this->matchThreshold = $matchThreshold;

        return $this;
    }

    /**
     * @param array $chars
     */
    public function setSpecialCaseChars(array $chars)
    {
        $this->specialCaseChars = $chars;
    }

    /**
     * @return array|null
     */
    public function getSpecialCaseChars()
    {
        return $this->specialCaseChars;
    }

    /**
     * @param string $char
     *
     * @return $this
     */
    public function addSpecialCaseChar($char)
    {
        if (!in_array($char, $this->specialCaseChars)) {
            $this->specialCaseChars[] = $char;
        }

        return $this;
    }

    /**
     * @param string $char
     *
     * @return $this
     */
    public function removeSpecialCaseChar($char)
    {
        $key = array_search($char, $this->specialCaseChars);
        if ($key !== false) {
            unset($this->specialCaseChars[$key]);
        }

        return $this;
    }

    /**
     * @param array $tags
     *
     * @return $this
     */
    public function setSpecialCaseTags(array $tags = array())
    {
        $this->specialCaseTags = $tags;
        $this->specialCaseOpeningTags = array();
        $this->specialCaseClosingTags = array();

        foreach ($this->specialCaseTags as $tag) {
            $this->addSpecialCaseTag($tag);
        }

        return $this;
    }

    /**
     * @param string $tag
     *
     * @return $this
     */
    public function addSpecialCaseTag($tag)
    {
        if (!in_array($tag, $this->specialCaseTags)) {
            $this->specialCaseTags[] = $tag;
        }

        $opening = $this->getOpeningTag($tag);
        $closing = $this->getClosingTag($tag);

        if (!in_array($opening, $this->specialCaseOpeningTags)) {
            $this->specialCaseOpeningTags[] = $opening;
        }
        if (!in_array($closing, $this->specialCaseClosingTags)) {
            $this->specialCaseClosingTags[] = $closing;
        }

        return $this;
    }

    /**
     * @param string $tag
     *
     * @return $this
     */
    public function removeSpecialCaseTag($tag)
    {
        if (($key = array_search($tag, $this->specialCaseTags)) !== false) {
            unset($this->specialCaseTags[$key]);

            $opening = $this->getOpeningTag($tag);
            $closing = $this->getClosingTag($tag);

            if (($key = array_search($opening, $this->specialCaseOpeningTags)) !== false) {
                unset($this->specialCaseOpeningTags[$key]);
            }
            if (($key = array_search($closing, $this->specialCaseClosingTags)) !== false) {
                unset($this->specialCaseClosingTags[$key]);
            }
        }

        return $this;
    }

    /**
     * @return array|null
     */
    public function getSpecialCaseTags()
    {
        return $this->specialCaseTags;
    }

    /**
     * @return bool
     */
    public function isGroupDiffs()
    {
        return $this->groupDiffs;
    }

    /**
     * @param bool $groupDiffs
     *
     * @return HtmlDiffConfig
     */
    public function setGroupDiffs($groupDiffs)
    {
        $this->groupDiffs = $groupDiffs;

        return $this;
    }

    /**
     * @return string
     */
    public function getEncoding()
    {
        return $this->encoding;
    }

    /**
     * @param string $encoding
     *
     * @return HtmlDiffConfig
     */
    public function setEncoding($encoding)
    {
        $this->encoding = $encoding;

        return $this;
    }

    /**
     * @return bool
     */
    public function isInsertSpaceInReplace()
    {
        return $this->insertSpaceInReplace;
    }

    /**
     * @param bool $insertSpaceInReplace
     *
     * @return HtmlDiffConfig
     */
    public function setInsertSpaceInReplace($insertSpaceInReplace)
    {
        $this->insertSpaceInReplace = $insertSpaceInReplace;

        return $this;
    }

    /**
     * @return array
     */
    public function getIsolatedDiffTags()
    {
        return $this->isolatedDiffTags;
    }

    /**
     * @param array $isolatedDiffTags
     *
     * @return HtmlDiffConfig
     */
    public function setIsolatedDiffTags($isolatedDiffTags)
    {
        $this->isolatedDiffTags = $isolatedDiffTags;

        return $this;
    }

    /**
     * @param string      $tag
     * @param null|string $placeholder
     *
     * @return $this
     */
    public function addIsolatedDiffTag($tag, $placeholder = null)
    {
        if (null === $placeholder) {
            $placeholder = sprintf('[[REPLACE_%s]]', strtoupper($tag));
        }

        if ($this->isIsolatedDiffTag($tag) && $this->isolatedDiffTags[$tag] !== $placeholder) {
            throw new \InvalidArgumentException(
                sprintf('Isolated diff tag "%s" already exists using a different placeholder', $tag)
            );
        }

        $matchingKey = array_search($placeholder, $this->isolatedDiffTags, true);
        if (false !== $matchingKey && $matchingKey !== $tag) {
            throw new \InvalidArgumentException(
                sprintf('Placeholder already being used for a different tag "%s"', $tag)
            );
        }

        if (!array_key_exists($tag, $this->isolatedDiffTags)) {
            $this->isolatedDiffTags[$tag] = $placeholder;
        }

        return $this;
    }

    /**
     * @param string $tag
     *
     * @return $this
     */
    public function removeIsolatedDiffTag($tag)
    {
        if ($this->isIsolatedDiffTag($tag)) {
            unset($this->isolatedDiffTags[$tag]);
        }

        return $this;
    }

    /**
     * @param string $tag
     *
     * @return bool
     */
    public function isIsolatedDiffTag($tag)
    {
        return array_key_exists($tag, $this->isolatedDiffTags);
    }

    /**
     * @param string $text
     *
     * @return bool
     */
    public function isIsolatedDiffTagPlaceholder($text)
    {
        return in_array($text, $this->isolatedDiffTags, true);
    }

    /**
     * @param string $tag
     *
     * @return null|string
     */
    public function getIsolatedDiffTagPlaceholder($tag)
    {
        return $this->isIsolatedDiffTag($tag) ? $this->isolatedDiffTags[$tag] : null;
    }

    /**
     * @return array
     */
    public function getSpecialCaseOpeningTags()
    {
        return $this->specialCaseOpeningTags;
    }

    /**
     * @return array
     */
    public function getSpecialCaseClosingTags()
    {
        return $this->specialCaseClosingTags;
    }

    /**
     * @return bool
     */
    public function isUseTableDiffing()
    {
        return $this->useTableDiffing;
    }

    /**
     * @param bool $useTableDiffing
     *
     * @return HtmlDiffConfig
     */
    public function setUseTableDiffing($useTableDiffing)
    {
        $this->useTableDiffing = $useTableDiffing;

        return $this;
    }

    /**
     * @param null|\Doctrine\Common\Cache\Cache $cacheProvider
     *
     * @return $this
     */
    public function setCacheProvider(\Doctrine\Common\Cache\Cache $cacheProvider = null)
    {
        $this->cacheProvider = $cacheProvider;

        return $this;
    }

    /**
     * @return null|\Doctrine\Common\Cache\Cache
     */
    public function getCacheProvider()
    {
        return $this->cacheProvider;
    }

    /**
     * @param null|string
     *
     * @return $this
     */
    public function setPurifierCacheLocation($purifierCacheLocation = null)
    {
        $this->purifierCacheLocation = $purifierCacheLocation;

        return $this;
    }

    /**
     * @return null|string
     */
    public function getPurifierCacheLocation()
    {
        return $this->purifierCacheLocation;
    }

    /**
     * @param string $tag
     *
     * @return string
     */
    protected function getOpeningTag($tag)
    {
        return '/<'.$tag.'[^>]*/i';
    }

    /**
     * @param string $tag
     *
     * @return string
     */
    protected function getClosingTag($tag)
    {
        return '</'.$tag.'>';
    }
}


text:
/** @file QQRect.h
*	Declaration of QQRect class for DDT core library
*
*	@author	Dynamic DeZigns Technology
*/

#pragma once
#include <qglobal.h>

#include <QRect>

class  QQRect : public QRect
{
public:
    QQRect(const QRect & r=QRect())
        : QRect(r) {};
    QQRect(QSize sz)
        : QRect(QPoint(0,0), sz) {}
    QQRect(QSize sz, QPoint ctr)
        : QRect(QPoint(ctr.x() - sz.width()/2, ctr.y() - sz.height()/2), sz) {};
    qreal aspect(void) const { return (qreal)width() / (qreal)height(); }
    int area(void) const { return width() * height(); }
    int overlapArea(QRect other);
    bool isNeighbor(QRect other, qreal factor);
    void matchAspect(const QSize sz);
    QQRect scaled(const qreal scale) const;
    QQRect operator*(const qreal scale) const;
}; // class QQRect

redpajama_set_name: RedPajamaGithub


text:
package org.apache.arrow.memory.util.hash;

import org.apache.arrow.memory.ArrowBuf;
import org.apache.arrow.memory.util.MemoryUtil;

/**
 * A simple hasher that calculates the hash code of integers as is,
 * and does not perform any finalization. So the computation is extremely
 * efficient.
 *

 *   This algorithm only provides the most basic semantics for the hash code. That is,
 *   if two objects are equal, they must have equal hash code. However, the quality of the
 *   produced hash code may not be good. In other words, the generated hash codes are
 *   far from being uniformly distributed in the universe.
 *

 *

 *   Therefore, this algorithm is suitable only for scenarios where the most basic semantics
 *   of the hash code is required (e.g. in scenarios that require fast and proactive data pruning)
 *

 *

 *   An object of this class is stateless, so it can be shared between threads.
 *

 */
public class SimpleHasher implements ArrowBufHasher {

  public static SimpleHasher INSTANCE = new SimpleHasher();

  protected SimpleHasher() {
  }

  /**
   * Calculates the hash code for a memory region.
   * @param address start address of the memory region.
   * @param length length of the memory region.
   * @return the hash code.
   */
  public int hashCode(long address, long length) {
    int hashValue = 0;
    int index = 0;
    while (index + 8 <= length) {
      long longValue = MemoryUtil.UNSAFE.getLong(address + index);
      int longHash = getLongHashCode(longValue);
      hashValue = combineHashCode(hashValue, longHash);
      index += 8;
    }

    if (index + 4 <= length) {
      int intValue = MemoryUtil.UNSAFE.getInt(address + index);
      int intHash = intValue;
      hashValue = combineHashCode(hashValue, intHash);
      index += 4;
    }

    while (index < length) {
      byte byteValue = MemoryUtil.UNSAFE.getByte(address + index);
      int byteHash = byteValue;
      hashValue = combineHashCode(hashValue, byteHash);
      index += 1;
    }

    return finalizeHashCode(hashValue);
  }

  /**
   * Calculates the hash code for a memory region.
   * @param buf the buffer for the memory region.
   * @param offset offset within the buffer for the memory region.
   * @param length length of the memory region.
   * @return the hash code.
   */
  @Override
  public int hashCode(ArrowBuf buf, long offset, long length) {
    buf.checkBytes(offset, offset + length);
    return hashCode(buf.memoryAddress() + offset, length);
  }

  protected int combineHashCode(int currentHashCode, int newHashCode) {
    return currentHashCode * 37 + newHashCode;
  }

  protected int getLongHashCode(long longValue) {
    return Long.hashCode(longValue);
  }

  protected int finalizeHashCode(int hashCode) {
    return hashCode;
  }

  @Override
  public int hashCode() {
    return 123;
  }

  @Override
  public boolean equals(Object obj) {
    return obj != null && (obj instanceof SimpleHasher);
  }
}


text:
package file

import (
	"fmt"
	"log"
	"os"
	"path"
	"strings"
	"sync"

	"github.com/miekg/coredns/middleware/file/tree"
	"github.com/miekg/coredns/request"

	"github.com/fsnotify/fsnotify"
	"github.com/miekg/dns"
)

// Zone defines a structure that contains all data related to a DNS zone.
type Zone struct {
	origin  string
	origLen int
	file    string
	*tree.Tree
	Apex Apex

	TransferTo   []string
	StartupOnce  sync.Once
	TransferFrom []string
	Expired      *bool

	NoReload       bool
	reloadMu       sync.RWMutex
	ReloadShutdown chan bool
}

// Apex contains the apex records of a zone: SOA, NS and their potential signatures.
type Apex struct {
	SOA    *dns.SOA
	NS     []dns.RR
	SIGSOA []dns.RR
	SIGNS  []dns.RR
}

// NewZone returns a new zone.
func NewZone(name, file string) *Zone {
	z := &Zone{
		origin:         dns.Fqdn(name),
		origLen:        dns.CountLabel(dns.Fqdn(name)),
		file:           path.Clean(file),
		Tree:           &tree.Tree{},
		Expired:        new(bool),
		ReloadShutdown: make(chan bool),
	}
	*z.Expired = false

	return z
}

// Copy copies a zone *without* copying the zone's content. It is not a deep copy.
func (z *Zone) Copy() *Zone {
	z1 := NewZone(z.origin, z.file)
	z1.TransferTo = z.TransferTo
	z1.TransferFrom = z.TransferFrom
	z1.Expired = z.Expired
	z1.Apex = z.Apex
	return z1
}

// Insert inserts r into z.
func (z *Zone) Insert(r dns.RR) error {
	r.Header().Name = strings.ToLower(r.Header().Name)

	switch h := r.Header().Rrtype; h {
	case dns.TypeNS:
		r.(*dns.NS).Ns = strings.ToLower(r.(*dns.NS).Ns)

		if r.Header().Name == z.origin {
			z.Apex.NS = append(z.Apex.NS, r)
			return nil
		}
	case dns.TypeSOA:
		r.(*dns.SOA).Ns = strings.ToLower(r.(*dns.SOA).Ns)
		r.(*dns.SOA).Mbox = strings.ToLower(r.(*dns.SOA).Mbox)

		z.Apex.SOA = r.(*dns.SOA)
		return nil
	case dns.TypeNSEC3, dns.TypeNSEC3PARAM:
		return fmt.Errorf("NSEC3 zone is not supported, dropping RR: %s for zone: %s", r.Header().Name, z.origin)
	case dns.TypeRRSIG:
		x := r.(*dns.RRSIG)
		switch x.TypeCovered {
		case dns.TypeSOA:
			z.Apex.SIGSOA = append(z.Apex.SIGSOA, x)
			return nil
		case dns.TypeNS:
			if r.Header().Name == z.origin {
				z.Apex.SIGNS = append(z.Apex.SIGNS, x)
				return nil
			}
		}
	case dns.TypeCNAME:
		r.(*dns.CNAME).Target = strings.ToLower(r.(*dns.CNAME).Target)
	case dns.TypeMX:
		r.(*dns.MX).Mx = strings.ToLower(r.(*dns.MX).Mx)
	case dns.TypeSRV:
		r.(*dns.SRV).Target = strings.ToLower(r.(*dns.SRV).Target)
	}

	z.Tree.Insert(r)
	return nil
}

// Delete deletes r from z.
func (z *Zone) Delete(r dns.RR) { z.Tree.Delete(r) }

// TransferAllowed checks if incoming request for transferring the zone is allowed according to the ACLs.
func (z *Zone) TransferAllowed(req request.Request) bool {
	for _, t := range z.TransferTo {
		if t == "*" {
			return true
		}
	}
	// TODO(miek): future matching against IP/CIDR notations
	return false
}

// All returns all records from the zone, the first record will be the SOA record,
// otionally followed by all RRSIG(SOA)s.
func (z *Zone) All() []dns.RR {
	if !z.NoReload {
		z.reloadMu.RLock()
		defer z.reloadMu.RUnlock()
	}

	records := []dns.RR{}
	allNodes := z.Tree.All()
	for _, a := range allNodes {
		records = append(records, a.All()...)
	}

	if len(z.Apex.SIGNS) > 0 {
		records = append(z.Apex.SIGNS, records...)
	}
	records = append(z.Apex.NS, records...)

	if len(z.Apex.SIGSOA) > 0 {
		records = append(z.Apex.SIGSOA, records...)
	}
	return append([]dns.RR{z.Apex.SOA}, records...)
}

// Reload reloads a zone when it is changed on disk. If z.NoRoload is true, no reloading will be done.
func (z *Zone) Reload() error {
	if z.NoReload {
		return nil
	}
	watcher, err := fsnotify.NewWatcher()
	if err != nil {
		return err
	}
	err = watcher.Add(path.Dir(z.file))
	if err != nil {
		return err
	}

	go func() {
		// TODO(miek): needs to be killed on reload.
		for {
			select {
			case event := <-watcher.Events:
				if path.Clean(event.Name) == z.file {

					reader, err := os.Open(z.file)
					if err != nil {
						log.Printf("[ERROR] Failed to open `%s' for `%s': %v", z.file, z.origin, err)
						continue
					}
					zone, err := Parse(reader, z.origin, z.file)
					if err != nil {
						log.Printf("[ERROR] Failed to parse `%s': %v", z.origin, err)
						continue
					}

					// copy elements we need
					z.reloadMu.Lock()
					z.Apex = zone.Apex
					z.Tree = zone.Tree
					z.reloadMu.Unlock()

					log.Printf("[INFO] Successfully reloaded zone `%s'", z.origin)
					z.Notify()
				}
			case <-z.ReloadShutdown:
				watcher.Close()
				return
			}
		}
	}()
	return nil
}

// Print prints the zone's tree to stdout.
func (z *Zone) Print() {
	z.Tree.Print()
}

// NameFromRight returns the labels from the right, staring with the
// origin and then i labels extra. When we are overshooting the name
// the returned boolean is set to true.
func (z *Zone) nameFromRight(qname string, i int) (string, bool) {
	if i <= 0 {
		return z.origin, false
	}

	for j := 1; j <= z.origLen; j++ {
		if _, shot := dns.PrevLabel(qname, j); shot {
			return qname, shot
		}
	}

	k := 0
	shot := false
	for j := 1; j <= i; j++ {
		k, shot = dns.PrevLabel(qname, j+z.origLen)
		if shot {
			return qname, shot
		}
	}
	return qname[k:], false
}


text:
/*
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/*
 *    UnsupervisedAttributeEvaluator.java
 *    Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand
 *
 */

package weka.attributeSelection;

/**
 * Abstract unsupervised attribute evaluator.
 *
 * @author Mark Hall (mhall@cs.waikato.ac.nz)
 * @version $Revision: 8034 $
 */
public abstract class UnsupervisedAttributeEvaluator
  extends ASEvaluation
          implements AttributeEvaluator {

  /** for serialization */
  private static final long serialVersionUID = -4100897318675336178L;

}


text:
import { DIR_TARGET, Platform } from "electron-builder"
import { outputFile } from "fs-extra"
import * as path from "path"
import { CheckingWinPackager } from "../helpers/CheckingPackager"
import { app, appThrows } from "../helpers/packTester"
import { parseDn } from "builder-util-runtime"
import { load } from "js-yaml"

test("parseDn", () => {
  expect(parseDn("CN=7digital Limited, O=7digital Limited, L=London, C=GB")).toMatchSnapshot()

  expect(load("publisherName:\n  - 7digital Limited")).toMatchObject({ publisherName: ["7digital Limited"] })
})

const windowsDirTarget = Platform.WINDOWS.createTarget(["dir"])

test.ifNotCiMac(
  "sign nested asar unpacked executables",
  appThrows(
    {
      targets: Platform.WINDOWS.createTarget(DIR_TARGET),
      config: {
        publish: "never",
        asarUnpack: ["assets"],
      },
    },
    {
      signedWin: true,
      projectDirCreated: async projectDir => {
        await outputFile(path.join(projectDir, "assets", "nested", "nested", "file.exe"), "invalid PE file")
      },
    },
    error => expect(error.message).toContain("Unrecognized file type:")
  )
)

function testCustomSign(sign: any) {
  return app({
    targets: Platform.WINDOWS.createTarget(DIR_TARGET),
    platformPackagerFactory: (packager, platform) => new CheckingWinPackager(packager),
    config: {
      win: {
        certificatePassword: "pass",
        certificateFile: "secretFile",
        sign,
        signingHashAlgorithms: ["sha256"],
        // to be sure that sign code will be executed
        forceCodeSigning: true,
      },
    },
  })
}

test.ifAll.ifNotCiMac(
  "certificateFile/password - sign as async/await",
  testCustomSign(async () => {
    return
  })
)
test.ifAll.ifNotCiMac(
  "certificateFile/password - sign as Promise",
  testCustomSign(() => Promise.resolve())
)
test.ifAll.ifNotCiMac("certificateFile/password - sign as function", testCustomSign(require("../helpers/customWindowsSign").default))
test.ifAll.ifNotCiMac("certificateFile/password - sign as path", testCustomSign(path.join(__dirname, "../helpers/customWindowsSign")))

test.ifAll.ifNotCiMac("custom sign if no code sign info", () => {
  let called = false
  return app(
    {
      targets: Platform.WINDOWS.createTarget(DIR_TARGET),
      platformPackagerFactory: (packager, platform) => new CheckingWinPackager(packager),
      config: {
        win: {
          // to be sure that sign code will be executed
          forceCodeSigning: true,
          sign: async () => {
            called = true
          },
        },
      },
    },
    {
      packed: async () => {
        expect(called).toBe(true)
      },
    }
  )()
})

test.ifAll.ifNotCiMac(
  "forceCodeSigning",
  appThrows({
    targets: windowsDirTarget,
    config: {
      forceCodeSigning: true,
    },
  })
)

test.ifAll.ifNotCiMac(
  "electronDist",
  appThrows({
    targets: Platform.WINDOWS.createTarget(DIR_TARGET),
    config: {
      electronDist: "foo",
    },
  })
)


text:
package org.aludratest.testcase;

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

/**
 * Annotates a test method to be evaluated as ignored.
 * @author Volker Bergmann
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Ignored {

    /** The optional reason why the test method has been marked as ignored.
     *
     * @return The optional reason why the test method has been marked as ignored. */
    public String value() default "";

}


text:
Data/Types version 0.09
=======================

This module exports a number of functions that are useful for validating and
converting data types. It is intended for use in applications where data types
are more important than they typically are in Perl -- e.g., for database
applications.

Installation
------------

To install this module, type the following:

    perl Build.PL
    ./Build
    ./Build test
    ./Build install

Or, if you don't have Module::Build installed, type the following:

    perl Makefile.PL
    make
    make test
    make install

Dependencies
------------

This module requires no modules or libraries not already included with Perl.

COPYRIGHT AND LICENCE

Copyright (c) 2002-2011, David E. Wheeler. Some Rights Reserved.

This module is free software; you can redistribute it and/or modify it under
the same terms as Perl itself.


text:
from immobilus.logic import immobilus, _datetime_to_utc_timestamp

import time
from datetime import datetime

def test_without_offset():
    with immobilus('1970-01-01 00:00:00'):
        timestamp = _datetime_to_utc_timestamp(datetime.utcnow())

        timetuple = datetime.utcnow().timetuple()
        mktime = time.mktime(timetuple)

        assert mktime == timestamp

def test_with_positive_offset():
    # UTC (gmt+0) 03:00, Moscow (gmt+3) 06:00
    with immobilus('1970-01-01 03:00:00', tz_offset=3):
        timestamp = _datetime_to_utc_timestamp(datetime.utcnow())  # utc time, 03:00

        timetuple = datetime.now().timetuple()  # local time, 06:00
        mktime = time.mktime(timetuple)

        assert mktime == timestamp == 3 * 3600

def test_with_negative_offset():
    # UTC (gmt+0) 06:00, EST (gmt-5) 01:00
    with immobilus('1970-01-01 06:00:00', tz_offset=-5):
        timestamp = _datetime_to_utc_timestamp(datetime.utcnow())  # utc time, 06:00

        timetuple = datetime.now().timetuple()  # local time, 01:00
        mktime = time.mktime(timetuple)

        assert mktime == timestamp == 6 * 3600


text:
package net.chwthewke.hamcrest.annotations;

import static net.chwthewke.hamcrest.matchers.Equivalences.asSpecifiedBy;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import net.chwthewke.hamcrest.annotations.ApproximateEquality;
import net.chwthewke.hamcrest.annotations.EquivalenceSpecificationOn;
import net.chwthewke.hamcrest.matchers.EquivalenceSpecification;

import org.hamcrest.Matcher;
import org.junit.Test;

public class ApproximateEqualityMatchersTest {

    @Test
    public void matchApproximateEqualityOnDouble( ) throws Exception {
        // Setup
        final Matcher<Matched> matcher =
                asSpecifiedBy( DoubleMatcherSpecification.class )
                    .equivalentTo( new Matched( 1.25d, 0f ) );
        final Matched actual = new Matched( 1.2500005d, 0f );
        // Exercise

        // Verify
        assertThat( matcher.matches( actual ), is( true ) );
    }

    @Test
    public void matchApproximateEqualityOnFloat( ) throws Exception {
        // Setup
        final Matcher<Matched> matcher =
                asSpecifiedBy( FloatMatcherSpecification.class )
                    .equivalentTo( new Matched( 0d, 1.1f ) );
        final Matched actual = new Matched( 0d, 1.0999999f );
        // Exercise

        // Verify
        assertThat( matcher.matches( actual ), is( true ) );
    }

    public static class Matched {

        Matched( final double doubleValue, final float floatValue ) {
            this.doubleValue = doubleValue;
            this.floatValue = floatValue;
        }

        public double getDoubleValue( ) {
            return doubleValue;
        }

        public float getFloatValue( ) {
            return floatValue;
        }

        private final double doubleValue;
        private final float floatValue;
    }

    @EquivalenceSpecificationOn( Matched.class )
    public static interface DoubleMatcherSpecification extends EquivalenceSpecification<Matched> {
        @ApproximateEquality( tolerance = 0.000001d )
        double getDoubleValue( );
    }

    @EquivalenceSpecificationOn( Matched.class )
    public static interface FloatMatcherSpecification extends EquivalenceSpecification<Matched> {
        @ApproximateEquality( tolerance = 0.000001d )
        float getFloatValue( );
    }
}


text:
package ach

import (
	"strconv"
)

// BatchCTX holds the BatchHeader and BatchControl and all EntryDetail for CTX Entries.
//
// The Corporate Trade Exchange (CTX) application provides the ability to collect and disburse
// funds and information between companies. Generally it is used by businesses paying one another
// for goods or services. These payments replace checks with an electronic process of debiting and
// crediting invoices between the financial institutions of participating companies.
type BatchCTX struct {
	Batch
}

// NewBatchCTX returns a *BatchCTX
func NewBatchCTX(bh *BatchHeader) *BatchCTX {
	batch := new(BatchCTX)
	batch.SetControl(NewBatchControl())
	batch.SetHeader(bh)
	batch.SetID(bh.ID)
	return batch
}

// Validate checks properties of the ACH batch to ensure they match NACHA guidelines.
// This includes computing checksums, totals, and sequence orderings.
//
// Validate will never modify the batch.
func (batch *BatchCTX) Validate() error {
	// basic verification of the batch before we validate specific rules.
	if err := batch.verify(); err != nil {
		return err
	}

	// Add configuration and type specific validation for this type.
	if batch.Header.StandardEntryClassCode != CTX {
		return batch.Error("StandardEntryClassCode", ErrBatchSECType, CTX)
	}

	for _, entry := range batch.Entries {

		// Trapping this error, as entry.CTXAddendaRecordsField() can not be greater than 9999
		if len(entry.Addenda05) > 9999 {
			return batch.Error("AddendaCount", NewErrBatchAddendaCount(len(entry.Addenda05), 9999))
		}

		// validate CTXAddendaRecord Field is equal to the actual number of Addenda records
		// use 0 value if there is no Addenda records
		addendaRecords, _ := strconv.Atoi(entry.CATXAddendaRecordsField())
		if len(entry.Addenda05) != addendaRecords {
			return batch.Error("AddendaCount", NewErrBatchExpectedAddendaCount(len(entry.Addenda05), addendaRecords))
		}
		// Verify TransactionCode for prenotes and regular entries
		switch entry.TransactionCode {
		case CheckingPrenoteCredit, CheckingPrenoteDebit,
			SavingsPrenoteCredit, SavingsReturnNOCDebit,
			GLPrenoteCredit, GLPrenoteDebit, LoanPrenoteCredit:
			if entry.Amount != 0 {
				return batch.Error("TransactionCode", ErrBatchTransactionCode, entry.TransactionCode)
			}
		}
		// Verify the TransactionCode is valid for a ServiceClassCode
		if err := batch.ValidTranCodeForServiceClassCode(entry); err != nil {
			return err
		}
		// Verify Addenda* FieldInclusion based on entry.Category and batchHeader.StandardEntryClassCode
		if err := batch.addendaFieldInclusion(entry); err != nil {
			return err
		}
	}
	return nil
}

// Create will tabulate and assemble an ACH batch into a valid state. This includes
// setting any posting dates, sequence numbers, counts, and sums.
//
// Create implementations are free to modify computable fields in a file and should
// call the Batch's Validate function at the end of their execution.
func (batch *BatchCTX) Create() error {
	// generates sequence numbers and batch control
	if err := batch.build(); err != nil {
		return err
	}
	// Additional steps specific to batch type
	// ...
	return batch.Validate()
}


text:
package com.google.api.core;

/**
 * An {@link ApiFuture} whose result can be set. Similar to Guava's {@code SettableFuture}, but
 * redeclared so that Guava could be shaded.
 */
public final class SettableApiFuture<V> extends AbstractApiFuture<V> {

  private SettableApiFuture() {}

  public static <V> SettableApiFuture<V> create() {
    return new SettableApiFuture<>();
  }

  @Override
  public boolean set(V value) {
    return super.set(value);
  }

  @Override
  public boolean setException(Throwable throwable) {
    return super.setException(throwable);
  }
}


text:
#import <CoreGraphics/CGGeometry.h>
#import <CoreGraphics/CGAffineTransform.h>

typedef struct O2PDFPage *CGPDFPageRef;

typedef enum {
    kCGPDFMediaBox = 0,
    kCGPDFCropBox = 1,
    kCGPDFBleedBox = 2,
    kCGPDFTrimBox = 3,
    kCGPDFArtBox = 4,
} CGPDFBox;

COREGRAPHICS_EXPORT CGPDFPageRef CGPDFPageRetain(CGPDFPageRef self);
COREGRAPHICS_EXPORT void CGPDFPageRelease(CGPDFPageRef self);
COREGRAPHICS_EXPORT CGRect CGPDFPageGetBoxRect(CGPDFPageRef self, CGPDFBox box);
COREGRAPHICS_EXPORT CGAffineTransform CGPDFPageGetDrawingTransform(CGPDFPageRef self, CGPDFBox box, CGRect rect, int clockwiseDegrees, bool preserveAspectRatio);


text:
package main

import (
	"fmt"
)

var currentId int
var todos Todos

func init(){
	RepoCreateTodo(Todo{Name: "Learn Golang!"})
	RepoCreateTodo(Todo{Name: "Find remote!"})
	RepoCreateTodo(Todo{Name: "Move to Japan!"})
}

func RepoFindTodo(id int) Todo {
	for _, t := range todos{
		if t.Id == id {
			return t
		}
	}
	return Todo{}
}

func RepoCreateTodo(t Todo) Todo{
	currentId += 1
	t.Id = currentId
	todos = append(todos, t)
	return t
}

func RepoDestroyID(id int) error{
	for i, t := range todos{
		if t.Id == id {
			todos = append(todos[:i], todos[:i+1]...)
			return nil
		}
	}
	return fmt.Errorf("Couldnt find Todo with id %d  in database", id)
}


text:
package org.jhove2.config.spring;

import org.jhove2.core.JHOVE2Exception;
import org.jhove2.persist.PersistenceManager;
import org.jhove2.persist.PersistenceManagerFactory;
import org.jhove2.persist.inmemory.InMemoryPersistenceManager;

/**
 * @author smorrissey
 *
 */
public class SpringInMemoryPersistenceManagerFactory implements
		PersistenceManagerFactory {

	private static final String PM_CLASSNAME =
		"org.jhove2.persist.inmemory.InMemoryPersistenceManager";
	private static final String PM_BEANNAME = "InMemoryPersistenceManager";

	private static InMemoryPersistenceManager inMemoryPersistenceManager = null;

	/* (non-Javadoc)
	 * @see org.jhove2.persist.PersistenceManagerFactory#getInstance()
	 */
	@SuppressWarnings("unchecked")
	@Override
	public PersistenceManager getInstance() throws JHOVE2Exception {
		if (inMemoryPersistenceManager==null){
			Class<InMemoryPersistenceManager> pClass = null;
			try {
				pClass =
					(Class<InMemoryPersistenceManager>) Class.forName(PM_CLASSNAME);
			} catch (ClassNotFoundException e) {
				throw new JHOVE2Exception ("Unable to create Class object for "
						+ PM_CLASSNAME, e);
			}
			inMemoryPersistenceManager =
				SpringPersistenceManagerFactoryUtil.getInstance(pClass, PM_BEANNAME);
		}
		return inMemoryPersistenceManager;
	}

}


text:
#ifndef HTMLBlockquoteElement_h
#define HTMLBlockquoteElement_h

#include "HTMLElement.h"

namespace WebCore {

class HTMLBlockquoteElement : public HTMLElement {
public:
    static PassRefPtr<HTMLBlockquoteElement> create(Document*);
    static PassRefPtr<HTMLBlockquoteElement> create(const QualifiedName&, Document*);

private:
    HTMLBlockquoteElement(const QualifiedName&, Document*);

    virtual bool isURLAttribute(Attribute*) const;
};

} // namespace WebCore

#endif // HTMLBlockquoteElement_h


text:
class 'Boost'

function Boost:__init()
	Events:Subscribe("KeyDown", self, self.Input)
	Events:Subscribe("ModulesLoad", self, self.ModulesLoad)
	Events:Subscribe("ModuleUnload", self, self.ModuleUnload)
end

function Boost:Input(args)
	if args.key == 16 then

		Network:Send("BoostAccelerate")

		return false

	elseif args.key == 17 then

		Network:Send("BoostBrake")

		return false

	else
		return true
	end
end

function Boost:ModulesLoad()
	Events:FireRegisteredEvent("HelpAddItem",
		{
			name = 	"Boost",
			text =
					"The Boost script is used to accerlerate a registered players vehicle beyond the normal limit.\n\n" ..

					"Keys:\n"..
					"LSHIFT: Accerlerate your vehicle - Requires you to be registered.\n\n"..

					"Commands:\n"..
					"/boost\n"..
					"Enable or disable your boost key if you are in the list of registered players.\n\n"..

					"Admin commands:\n"..
					"/bost add <player>\n"..
					"Add a player to the list of registered players. Leave the argument empty to add yourself.\n\n"..

					"/boost remove <player>\n"..
					"Remove a player from the list of registered players. Leave the argument empty to remove yourself.\n\n"..

					"/boost players\n"..
					"Prints all registered player's names into the chat."
		})
end

function Boost:ModuleUnload()
	Events:FireRegisteredEvent("HelpRemoveItem", {name = "Boost"})
end

local boost = Boost()


text:
<?php
namespace app\models;

use Yii;
use yii\web\UploadedFile;

class Userinfo extends \yii\db\ActiveRecord
{
    public $imageFile;

    public static function tableName()
    {
        return 'userinfo';
    }
    public function rules()
    {
        return [
            [['user_id', 'date_birth', 'address', 'phone', 'avatar', 'name'], 'required'],
            [['user_id', 'date_birth'], 'integer'],
            [['address'], 'string'],
            [['phone', 'avatar', 'name'], 'string', 'max' => 255]
        ];
    }

    public function attributeLabels()
    {
        return [
            'user_id' => 'id',
            'date_birth' => 'День народження',
            'address' => 'Адреса',
            'phone' => 'Телефон',
            'avatar' => 'Аватар',
            'name' => 'Імя',
        ];
    }

    public static function getAll($user_id)
    {
        $query = Userinfo::find();
        $departments = $query->where([ 'user_id' => $user_id])->asArray()->all();
        return $departments;
    }
    public static function savedate($data)
    {
        $customer = Userinfo::findOne(['user_id' => Yii::$app->user->identity->id,]);
        if($customer == ''){
            $customer = new Userinfo();
            $customer->user_id = Yii::$app->user->identity->id;
            $customer->date_birth = $data['Userinfo']['date_birth'];
            $customer->address = $data['Userinfo']['address'];
            $customer->phone = $data['Userinfo']['phone'];
            $customer->avatar = $data['Userinfo']['avatar'];
            $customer->name = $data['Userinfo']['name'];
            $customer->save();
        }else{
            $customer->date_birth = $data['Userinfo']['date_birth'];
            $customer->address = $data['Userinfo']['address'];
            $customer->phone = $data['Userinfo']['phone'];
            $customer->avatar = $data['Userinfo']['avatar'];
            $customer->name = $data['Userinfo']['name'];
            $customer->save();
        }
    }
}


text:
using UnityEngine;
using UnityEditor;
using System;

namespace A3Utility.CustomTemplate.Window {
    using ListFields;

    [Serializable]
    public class ScrollParams {
        public Vector2 scroll = Vector2.zero;
        public bool horizontalBar = false;
        public bool verticalBar = true;
        public float minHeight = 100.0f;
    }

    public class SelectTemplate : EditorWindow {
        private MetadataHolder holder = null;
        private Metadatas metadatas = null;
        private ScrollParams sparams = new ScrollParams();

        [MenuItem("A3Utility/Custom Template/Open Edit Window")]
        public static SelectTemplate Open() {
            var window = GetWindow<SelectTemplate>();
            window.Init();

            return window;
        }

        public void Save2File() {
            var path = Getters4Editor.GetFilePath(this.holder);
            this.holder.metadatas.UpdateValues(this.metadatas);

            DataFiler.Save2File(this.metadatas, Getters4Editor.GetFullFilePath(path));
        }

        private void Init() {
            if(this.holder == null) { this.holder = Getters4Editor.GetHolder(); }
            this.metadatas = new Metadatas(this.holder.metadatas);

            this.titleContent.text = "Select Template";
            this.titleContent.tooltip = "Select Template Window";
        }

        #region "GUI"
        void OnGUI() {
            if(this.holder == null || this.metadatas == null) { this.Init(); }

            EditorGUILayout.LabelField("CustomTemplate : Select template window");
            GUILayout.Space(20.0f);

            #region "Validation"
            EditorGUILayout.BeginHorizontal();
            EditorGUILayout.LabelField("Setting CustomTemplate's validation");
            this.metadatas.validity = (Validater)EditorGUILayout.EnumPopup(this.metadatas.validity);
            EditorGUILayout.EndHorizontal();
            #endregion

            #region "Select template"
            if(this.metadatas.templates.Count > 0) {
                EditorGUILayout.Space();
                EditorGUILayout.BeginVertical(GUILayout.MinHeight(this.sparams.minHeight));
                this.sparams.scroll = EditorGUILayout.BeginScrollView(this.sparams.scroll, this.sparams.horizontalBar, this.sparams.verticalBar);

                this.metadatas.templates.ForEach(template => this.GUI4SelectTempalte(template));

                EditorGUILayout.EndScrollView();
                EditorGUILayout.EndVertical();
            }
            #endregion

            EditorGUILayout.Space();
            if(GUILayout.Button("Add Template")) {
                this.metadatas.templates.Add(new TemplateSet());
            }
            EditorGUILayout.Space();
            if(GUILayout.Button("Save")) {
                this.Save2File();
            }
        }

        private void GUI4SelectTempalte(TemplateSet template) {
            EditorGUILayout.BeginHorizontal();

            template.Extension = EditorGUILayout.TextField("Extension: ", template.Extension);
            if(GUILayout.Button("Select")) {
                EditTemplate.Open(template);
            }

            EditorGUILayout.EndHorizontal();
        }
        #endregion
    }
}


text:
#ifndef SRC_KEYX_DIFFIEHELLMANPARAMETERS_H_
#define SRC_KEYX_DIFFIEHELLMANPARAMETERS_H_

#include <stdint.h>
#include <map>
#include <memory>
#include <string>
#include <vector>

namespace netflix {
namespace msl {
typedef std::vector<uint8_t> ByteArray;
namespace keyx {

class DHParameterSpec
{
public:
    DHParameterSpec() {}
    DHParameterSpec(std::shared_ptr<ByteArray> p, std::shared_ptr<ByteArray> g)
    : p(p), g(g) {}
    std::shared_ptr<ByteArray> getP() const { return p; }
    std::shared_ptr<ByteArray> getG() const { return g; }
private:
    std::shared_ptr<ByteArray> p;
    std::shared_ptr<ByteArray> g;

};

class DiffieHellmanParameters
{
public:
    /**
     * @return the map of Diffie-Hellman parameters by parameter ID.
     * @throws MslKeyExchangeException if there is an error accessing the
     *         parameters.
     */
    virtual std::map<std::string, DHParameterSpec> getParameterSpecs() const = 0;

    /**
     * Returns the Diffie-Hellman parameter specification identified by the
     * parameters ID.
     *
     * @param id the parameters ID.
     * @return the parameter specification or null if the parameters ID is
     *         not recognized.
     * @throws MslKeyExchangeException if there is an error accessing the
     *         parameter specification.
     */
    virtual DHParameterSpec getParameterSpec(const std::string& id) const = 0;

protected:
    virtual ~DiffieHellmanParameters() {}
};

}}} // namespace netflix::msl:keyx

#endif /* SRC_KEYX_DIFFIEHELLMANPARAMETERS_H_ */


text:
//
//  W A R N I N G
//  -------------
//
// This file is not part of the Qt API.  It exists purely as an
// implementation detail.  This header file may change from version to
// version without notice, or even be removed.
//
// We mean it.

#ifndef Patternist_StaticBaseURIContext_H
#define Patternist_StaticBaseURIContext_H

#include <private/qdelegatingstaticcontext_p.h>

QT_BEGIN_NAMESPACE

namespace QPatternist
{
    /**
     * @short A StaticContext that changes the static base URI.
     * of items.
     *
     * @since 4.5
     * @author Frans Englich <frans.englich@nokia.com>
     */
    class StaticBaseURIContext : public DelegatingStaticContext
    {
    public:
        /**
         * The @p bURI is the new static base URI, and it must be valid
         * and absolute.
         */
        StaticBaseURIContext(const QUrl &bURI,
                             const StaticContext::Ptr &prevContext);

        virtual QUrl baseURI() const;

    private:
        const QUrl m_baseURI;
    };
}

QT_END_NAMESPACE

#endif


text:
/**
 *
 */
package calabash.java;

/**
 * Provides callback while inspecting elements
 *
 */
public interface InspectCallback {

	/**
	 * This function gets called for each UIElement
	 *
	 * @param element
	 *            Current element
	 * @param nestingLevel
	 *            Nesting level. This indicates how deep the element in the tree
	 */
	void onEachElement(UIElement element, int nestingLevel);

}


text:
/*
 * Do not modify this file. This file is generated from the codepipeline-2015-07-09.normal.json service model.
 */
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;

using Amazon.CodePipeline.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;

namespace Amazon.CodePipeline.Model.Internal.MarshallTransformations
{
    /// <summary>
    /// Response Unmarshaller for ListActionTypes operation
    /// </summary>
    public class ListActionTypesResponseUnmarshaller : JsonResponseUnmarshaller
    {
        /// <summary>
        /// Unmarshaller the response from the service to the response class.
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context)
        {
            ListActionTypesResponse response = new ListActionTypesResponse();

            context.Read();
            int targetDepth = context.CurrentDepth;
            while (context.ReadAtDepth(targetDepth))
            {
                if (context.TestExpression("actionTypes", targetDepth))
                {
                    var unmarshaller = new ListUnmarshaller<ActionType, ActionTypeUnmarshaller>(ActionTypeUnmarshaller.Instance);
                    response.ActionTypes = unmarshaller.Unmarshall(context);
                    continue;
                }
                if (context.TestExpression("nextToken", targetDepth))
                {
                    var unmarshaller = StringUnmarshaller.Instance;
                    response.NextToken = unmarshaller.Unmarshall(context);
                    continue;
                }
            }

            return response;
        }

        /// <summary>
        /// Unmarshaller error response to exception.
        /// </summary>
        /// <param name="context"></param>
        /// <param name="innerException"></param>
        /// <param name="statusCode"></param>
        /// <returns></returns>
        public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode)
        {
            ErrorResponse errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context);
            if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidNextTokenException"))
            {
                return new InvalidNextTokenException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
            }
            if (errorResponse.Code != null && errorResponse.Code.Equals("ValidationException"))
            {
                return new ValidationException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
            }
            return new AmazonCodePipelineException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
        }

        private static ListActionTypesResponseUnmarshaller _instance = new ListActionTypesResponseUnmarshaller();

        internal static ListActionTypesResponseUnmarshaller GetInstance()
        {
            return _instance;
        }

        /// <summary>
        /// Gets the singleton.
        /// </summary>
        public static ListActionTypesResponseUnmarshaller Instance
        {
            get
            {
                return _instance;
            }
        }

    }
}


text:
With the video and unordered list elements, you may have noticed something interesting: these HTML elements had other HTML elements nested inside of them.

For example, in unordered lists, li elements are nested inside the ul.

First item

Second item

Web developers refer to the enclosing element as the parent element and the enclosed elements as children.

Referring to HTML elements as parents and children may sound funny, but it's a core web development concept. The web browser also knows about these parent/child relationships, which will be important as we explore CSS in the next lesson.

Instructions:

In the diagram to the right, notice the following:

The ul element is the parent of each li.

The li elements are children of the ul.

Code indentation signifies the relationship between parent and child elements.
After you have familiarized yourself with the diagram, click Next to continue the lesson.


text:
package kr.huny.controller;

import org.springframework.stereotype.Controller;

/**
 * Created by sousic on 2017-07-21.
 */
@Controller
//@RequestMapping(value="/oauth")
public class OAuthController {
}


text:
#ifndef __automaton1_hpp__
#define __automaton1_hpp__

#include <ioa/action.hpp>
#include <ioa/automaton.hpp>

template <class T>
struct bindable
{
  bool bound_;
  T bound_parameter;
  bool unbound_;
  T unbound_parameter;

  void bound () {
    bound_ = true;
  }

  void unbound () {
    unbound_ = true;
  }

  void bound (T param) {
    bound_ = true;
    bound_parameter = param;
  }

  void unbound (T param) {
    unbound_ = true;
    unbound_parameter = param;
  }

  bindable () :
    bound_ (false),
    unbound_ (false)
  { }

};

struct automaton1 :
  public ioa::automaton

{
  struct uv_up_input_action :
    public ioa::input,
    public ioa::no_value,
    public ioa::no_parameter,
    public bindable<int>
  {
    bool state;

    uv_up_input_action () :
      state (false)
    { }

    void effect (automaton1&) {
      state = true;
    }

    void schedule (const automaton1&) const { }
  };
  uv_up_input_action uv_up_input;

  struct uv_p_input_action :
    public ioa::input,
    public ioa::no_value,
    public ioa::parameter<int>,
    public bindable<int>
  {
    bool state;
    int last_parameter;

    uv_p_input_action () :
      state (false),
      last_parameter (0)
    { }

    void effect (automaton1&, int parameter) {
      state = true;
      last_parameter = parameter;
    }

    void schedule (const automaton1&, int parameter) const { }
  };
  uv_p_input_action uv_p_input;

  struct uv_ap_input_action :
    public ioa::input,
    public ioa::no_value,
    public ioa::auto_parameter,
    public bindable<ioa::aid_t>
  {
    bool state;
    ioa::aid_t last_parameter;

    uv_ap_input_action () :
      state (false),
      last_parameter (0)
    { }

    void effect (automaton1&, ioa::aid_t parameter) {
      state = true;
      last_parameter = parameter;
    }

    void schedule (const automaton1&, ioa::aid_t parameter) const { }
  };
  uv_ap_input_action uv_ap_input;

  struct v_up_input_action :
    public ioa::input,
    public ioa::value<int>,
    public ioa::no_parameter,
    public bindable<int>
  {
    int value;

    v_up_input_action () :
      value (0) { }

    void effect (automaton1&, const int t) {
      value = t;
    }

    void schedule (const automaton1&) const { }
  };
  v_up_input_action v_up_input;

  struct v_p_input_action :
    public ioa::input,
    public ioa::value<int>,
    public ioa::parameter<int>,
    public bindable<int>
  {
    int value;
    int last_parameter;

    v_p_input_action () :
      value (0),
      last_parameter (0)
    { }

    void effect (automaton1&, const int t, int parameter) {
      value = t;
      last_parameter = parameter;
    }

    void schedule (const automaton1&, int parameter) const { }
  };
  v_p_input_action v_p_input;

  struct v_ap_input_action :
    public ioa::input,
    public ioa::value<int>,
    public ioa::auto_parameter,
    public bindable<ioa::aid_t>
  {
    int value;
    ioa::aid_t last_parameter;

    v_ap_input_action () :
      value (0),
      last_parameter (0)
    { }

    void effect (automaton1&, const int t, ioa::aid_t parameter) {
      value = t;
      last_parameter = parameter;
    }

    void schedule (const automaton1&, ioa::aid_t parameter) const { }
  };
  v_ap_input_action v_ap_input;

  struct uv_up_output_action :
    public ioa::output,
    public ioa::no_value,
    public ioa::no_parameter,
    public bindable<int>
  {
    bool state;

    uv_up_output_action () :
      state (false) { }

    bool precondition (const automaton1&) const {
      return true;
    }

    void effect (automaton1&) {
      state = true;
    }

    void schedule (const automaton1&) const { }
  };
  uv_up_output_action uv_up_output;

  struct uv_p_output_action :
    public ioa::output,
    public ioa::no_value,
    public ioa::parameter<int>,
    public bindable<int>
  {
    bool state;
    int last_parameter;

    uv_p_output_action () :
      state (false),
      last_parameter (0)
    { }

    bool precondition (const automaton1&, int parameter) {
      return true;
    }

    void effect (automaton1&, int parameter) {
      state = true;
      last_parameter = parameter;
    }

    void schedule (const automaton1&, int parameter) const { }
  };
  uv_p_output_action uv_p_output;

  struct uv_ap_output_action :
    public ioa::output,
    public ioa::no_value,
    public ioa::auto_parameter,
    public bindable<ioa::aid_t>
  {
    bool state;
    ioa::aid_t last_parameter;

    uv_ap_output_action () :
      state (false),
      last_parameter (0)
    { }

    bool precondition (const automaton1&, ioa::aid_t parameter) {
      return true;
    }

    void effect (automaton1&, ioa::aid_t parameter) {
      state = true;
      last_parameter = parameter;
    }

    void schedule (const automaton1&, ioa::aid_t parameter) const { }
  };
  uv_ap_output_action uv_ap_output;

  struct v_up_output_action :
    public ioa::output,
    public ioa::value<int>,
    public ioa::no_parameter,
    public bindable<int>
  {
    bool state;

    v_up_output_action () :
      state (false)
    { }

    bool precondition (const automaton1&) const {
      return true;
    }

    int effect (automaton1&) {
      state = true;
      return 9845;
    }

    void schedule (const automaton1&) const { }
  };
  v_up_output_action v_up_output;

  struct v_p_output_action :
    public ioa::output,
    public ioa::value<int>,
    public ioa::parameter<int>,
    public bindable<int>
  {
    bool state;
    int last_parameter;

    v_p_output_action () :
      state (false),
      last_parameter (0)
    { }

    bool precondition (const automaton1&, int parameter) {
      return true;
    }

    int effect (automaton1&, int parameter) {
      state = true;
      last_parameter = parameter;
      return 9845;
    }

    void schedule (const automaton1&, int parameter) const { }
  };
  v_p_output_action v_p_output;

  struct v_ap_output_action :
    public ioa::output,
    public ioa::value<int>,
    public ioa::auto_parameter,
    public bindable<ioa::aid_t>
  {
    bool state;
    ioa::aid_t last_parameter;

    v_ap_output_action () :
      state (false),
      last_parameter (0)
    { }

    bool precondition (const automaton1&, ioa::aid_t parameter) {
      return true;
    }

    int effect (automaton1&, ioa::aid_t parameter) {
      state = true;
      last_parameter = parameter;
      return 9845;
    }

    void schedule (const automaton1&, ioa::aid_t parameter) const { }
  };
  v_ap_output_action v_ap_output;

  struct up_internal_action :
    public ioa::internal,
    public ioa::no_parameter
  {
    bool state;
    up_internal_action()
      : state(false) { }

    bool precondition (const automaton1&) const {
      return true;
    }

    void effect (automaton1&) {
      state = true;
    }

    void schedule (const automaton1&) const { }
  };
  up_internal_action up_internal;

  struct p_internal_action :
    public ioa::internal,
    public ioa::parameter<int>
  {
    bool state;
    int last_parameter;

    p_internal_action()
      : state(false) { }

    bool precondition (const automaton1&, int parameter) const {
      return true;
    }

    void effect (automaton1&, int parameter) {
      state = true;
      last_parameter = parameter;
    }

    void schedule (const automaton1&, int parameter) const { }
  };
  p_internal_action p_internal;

};

#endif


text:
import time
from typing import List

from bs4 import BeautifulSoup
from django.test import override_settings
from unittest.mock import Mock, patch
from zerver.lib.realm_icon import get_realm_icon_url
from zerver.lib.test_classes import ZulipTestCase
from zerver.middleware import is_slow_query, write_log_line
from zerver.models import get_realm

class SlowQueryTest(ZulipTestCase):
    SLOW_QUERY_TIME = 10
    log_data = {'extra': '[transport=websocket]',
                'time_started': 0,
                'bugdown_requests_start': 0,
                'bugdown_time_start': 0,
                'remote_cache_time_start': 0,
                'remote_cache_requests_start': 0}

    def test_is_slow_query(self) -> None:
        self.assertFalse(is_slow_query(1.1, '/some/random/url'))
        self.assertTrue(is_slow_query(2, '/some/random/url'))
        self.assertTrue(is_slow_query(5.1, '/activity'))
        self.assertFalse(is_slow_query(2, '/activity'))
        self.assertFalse(is_slow_query(2, '/json/report/error'))
        self.assertFalse(is_slow_query(2, '/api/v1/deployments/report_error'))
        self.assertFalse(is_slow_query(2, '/realm_activity/whatever'))
        self.assertFalse(is_slow_query(2, '/user_activity/whatever'))
        self.assertFalse(is_slow_query(9, '/accounts/webathena_kerberos_login/'))
        self.assertTrue(is_slow_query(11, '/accounts/webathena_kerberos_login/'))

    @override_settings(SLOW_QUERY_LOGS_STREAM="logs")
    @patch('logging.info')
    def test_slow_query_log(self, mock_logging_info: Mock) -> None:
        self.log_data['time_started'] = time.time() - self.SLOW_QUERY_TIME
        write_log_line(self.log_data, path='/socket/open', method='SOCKET',
                       remote_ip='123.456.789.012', email='unknown', client_name='?')
        last_message = self.get_last_message()
        self.assertEqual(last_message.sender.email, "error-bot@zulip.com")
        self.assertIn("logs", str(last_message.recipient))
        self.assertEqual(last_message.topic_name(), "testserver: slow queries")
        self.assertRegexpMatches(last_message.content,
                                 r"123\.456\.789\.012 SOCKET  200 10\.\ds .*")

    @override_settings(ERROR_BOT=None)
    @patch('logging.info')
    @patch('zerver.lib.actions.internal_send_message')
    def test_slow_query_log_without_error_bot(self, mock_internal_send_message: Mock,
                                              mock_logging_info: Mock) -> None:
        self.log_data['time_started'] = time.time() - self.SLOW_QUERY_TIME
        write_log_line(self.log_data, path='/socket/open', method='SOCKET',
                       remote_ip='123.456.789.012', email='unknown', client_name='?')
        mock_internal_send_message.assert_not_called()

class OpenGraphTest(ZulipTestCase):
    def check_title_and_description(self, path: str, title: str,
                                    in_description: List[str],
                                    not_in_description: List[str],
                                    status_code: int=200) -> None:
        response = self.client_get(path)
        self.assertEqual(response.status_code, status_code)
        decoded = response.content.decode('utf-8')
        bs = BeautifulSoup(decoded, features='lxml')
        open_graph_title = bs.select_one('meta[property="og:title"]').get('content')
        self.assertEqual(open_graph_title, title)

        open_graph_description = bs.select_one('meta[property="og:description"]').get('content')
        for substring in in_description:
            self.assertIn(substring, open_graph_description)
        for substring in not_in_description:
            self.assertNotIn(substring, open_graph_description)

    def test_admonition_and_link(self) -> None:
        # disable-message-edit-history starts with an {!admin-only.md!}, and has a link
        # in the first paragraph.
        self.check_title_and_description(
            '/help/disable-message-edit-history',
            "Disable message edit history (Zulip Help Center)",
            ["By default, Zulip displays messages",
             "users can view the edit history of a message. | To remove the",
             "best to delete the message entirely. "],
            ["Disable message edit history", "feature is only available", "Related articles",
             "Restrict message editing"]
        )

    def test_double_quotes(self) -> None:
        # night-mode has a quoted string "night mode"
        self.check_title_and_description(
            '/help/night-mode',
            "Night mode (Zulip Help Center)",
            ['By default, Zulip has a white background. ',
             'Zulip also provides a "night mode", which is great for working in a dark space.'],
            []
        )

    def test_settings_tab(self) -> None:
        # deactivate-your-account starts with {settings_tab|your-account}
        self.check_title_and_description(
            '/help/deactivate-your-account',
            "Deactivate your account (Zulip Help Center)",
            ["Any bots that you maintain will be disabled. | Deactivating "],
            ["Confirm by clicking", "  ", "\n"])

    def test_tabs(self) -> None:
        # logging-out starts with {start_tabs}
        self.check_title_and_description(
            '/help/logging-out',
            "Logging out (Zulip Help Center)",
            # Ideally we'd do something better here
            ["We're here to help! Email us at zulip-admin@example.com with questions, feedback, or " +
             "feature requests."],
            ["Click on the gear"])

    def test_index_pages(self) -> None:
        self.check_title_and_description(
            '/help/',
            "Zulip Help Center",
            [("Zulip is a group chat app. Its most distinctive characteristic is that "
              "conversation within an organization is divided into "streams" and further ")], [])

        self.check_title_and_description(
            '/api/',
            "Zulip API Documentation",
            [("Zulip's APIs allow you to integrate other services with Zulip. This "
              "guide should help you find the API you need:")], [])

    def test_nonexistent_page(self) -> None:
        self.check_title_and_description(
            '/help/not-a-real-page',
            # Probably we should make this "Zulip Help Center"
            "No such article. (Zulip Help Center)",
            ["No such article. | We're here to help!",
             "Email us at zulip-admin@example.com with questions, feedback, or feature requests."],
            [],
            # Test that our open graph logic doesn't throw a 500
            404)

    def test_login_page_simple_description(self) -> None:
        name = 'Zulip Dev'
        description = "The Zulip development environment default organization. It's great for testing!"

        self.check_title_and_description(
            '/login/',
            name,
            [description],
            [])

    def test_login_page_markdown_description(self) -> None:
        realm = get_realm('zulip')
        description = ("Welcome to **Clojurians Zulip** - the place where the Clojure community meets.\n\n"
                       "Before you signup/login:\n\n"
                       "* note-1\n"
                       "* note-2\n"
                       "* note-3\n\n"
                       "Enjoy!")
        realm.description = description
        realm.save(update_fields=['description'])

        self.check_title_and_description(
            '/login/',
            'Zulip Dev',
            ['Welcome to Clojurians Zulip - the place where the Clojure community meets',
             '* note-1 * note-2 * note-3 | Enjoy!'],
            [])

    def test_login_page_realm_icon(self) -> None:
        realm = get_realm('zulip')
        realm.icon_source = 'U'
        realm.save(update_fields=['icon_source'])
        realm_icon = get_realm_icon_url(realm)

        response = self.client_get('/login/')
        self.assertEqual(response.status_code, 200)

        decoded = response.content.decode('utf-8')
        bs = BeautifulSoup(decoded, features='lxml')
        open_graph_image = bs.select_one('meta[property="og:image"]').get('content')
        self.assertEqual(open_graph_image, '%s%s' % (realm.uri, realm_icon))

    def test_login_page_realm_icon_absolute_url(self) -> None:
        realm = get_realm('zulip')
        realm.icon_source = 'U'
        realm.save(update_fields=['icon_source'])
        icon_url = "https://foo.s3.amazonaws.com/%s/realm/icon.png?version=%s" % (realm.id, 1)
        with patch('zerver.lib.realm_icon.upload_backend.get_realm_icon_url', return_value=icon_url):
            response = self.client_get('/login/')
        self.assertEqual(response.status_code, 200)

        decoded = response.content.decode('utf-8')
        bs = BeautifulSoup(decoded, features='lxml')
        open_graph_image = bs.select_one('meta[property="og:image"]').get('content')
        self.assertEqual(open_graph_image, icon_url)

    def test_no_realm_api_page_og_url(self) -> None:
        response = self.client_get('/api/', subdomain='')
        self.assertEqual(response.status_code, 200)

        decoded = response.content.decode('utf-8')
        bs = BeautifulSoup(decoded, features='lxml')
        open_graph_url = bs.select_one('meta[property="og:url"]').get('content')

        self.assertTrue(open_graph_url.endswith('/api/'))


text: """Tests for the :mod:`campy.datastructures.pqueue` module."""


text:
class Category < ActiveRecord::Base
  has_many :movie_categories, :foreign_key => :category_id
end


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Aperll Investments Development Corporation(AIDC)</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">

    <link href="css/modern-business.css" rel="stylesheet">

    <link href="font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation

                </button>

                        Home

                        About

                        Services

                        Contact

                        Pricing Table

                        FAQ

FAQ

Home

FAQ

                                How long after my application is approved will funds be available in my bank account?

It depends on the type of loan you are applying for.
Approval is faster for bridging loans and revolving credit facility, no business plan is required just a valid contract.
Term facilities take longer than bridging loans and need to be accompanied with a detailed business plan.
It is recommended to submit all required documentation as listed in the application check list in order for your application to be approved as soon as possible.

                                Will my application for funding be approved if I am black-listed?

We consider all applications that we receive. If you are black-listed, you must however show willingness to recover from this state by making arrangements with the institutions or individuals you owe.

                                What type of businesses do you provide funding for?

We offer funding for varying types of businesses, be it an existing business you would like to own or one you would like to start.

Copyright © Aperll.co.za 2016


text:
/**
*============================================================================
*  The Ohio State University Research Foundation, The University of Chicago -
*  Argonne National Laboratory, Emory University, SemanticBits LLC,
*  and Ekagra Software Technologies Ltd.
*
*  Distributed under the OSI-approved BSD 3-Clause License.
*  See http://ncip.github.com/cagrid-portal/LICENSE.txt for details.
*============================================================================
**/
package gov.nih.nci.cagrid.portal.domain.catalog;

import gov.nih.nci.cagrid.portal.domain.AbstractDomainObject;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;

import javax.persistence.*;

@Entity
@Table(name = "cat_fav_role")
@GenericGenerator(name = "id-generator", strategy = "native",
 parameters = {
        @Parameter(name="sequence", value="seq_cat_fav_role")
    })
public class FavoriteRole extends AbstractDomainObject {

    public String description;

    public CatalogEntry favorite;
    public FavoriteOfRole inverseRole;

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    @ManyToOne
    @JoinColumn(name="catalog_id")
    public CatalogEntry getFavorite() {
        return favorite;
    }

    public void setFavorite(CatalogEntry favorite) {
        this.favorite = favorite;
    }

    @OneToOne
    @PrimaryKeyJoinColumn
    public FavoriteOfRole getInverseRole() {
        return inverseRole;
    }

    public void setInverseRole(FavoriteOfRole inverseRole) {
        this.inverseRole = inverseRole;
    }
}


text:
import * as assert from 'assert';
import * as os from 'os';
import * as path from 'path';

import { IWorkspaceIdentifier } from 'vs/platform/workspaces/common/workspaces';
import { URI } from 'vs/base/common/uri';
import { IRecentlyOpened } from 'vs/platform/history/common/history';
import { toStoreData, restoreRecentlyOpened } from 'vs/platform/history/electron-main/historyStorage';

function toWorkspace(uri: URI): IWorkspaceIdentifier {
	return {
		id: '1234',
		configPath: uri
	};
}
function assertEqualURI(u1: URI | undefined, u2: URI | undefined, message?: string): void {
	assert.equal(u1 && u1.toString(), u2 && u2.toString(), message);
}

function assertEqualWorkspace(w1: IWorkspaceIdentifier | undefined, w2: IWorkspaceIdentifier | undefined, message?: string): void {
	if (!w1 || !w2) {
		assert.equal(w1, w2, message);
		return;
	}
	assert.equal(w1.id, w2.id, message);
	assertEqualURI(w1.configPath, w2.configPath, message);
}

function assertEqualRecentlyOpened(expected: IRecentlyOpened, actual: IRecentlyOpened, message?: string) {
	assert.equal(expected.files.length, actual.files.length, message);
	for (let i = 0; i < expected.files.length; i++) {
		assertEqualURI(expected.files[i], actual.files[i], message);
	}
	assert.equal(expected.workspaces.length, actual.workspaces.length, message);
	for (let i = 0; i < expected.workspaces.length; i++) {
		if (expected.workspaces[i] instanceof URI) {
			assertEqualURI(<URI>expected.workspaces[i], <URI>actual.workspaces[i], message);
		} else {
			assertEqualWorkspace(<IWorkspaceIdentifier>expected.workspaces[i], <IWorkspaceIdentifier>actual.workspaces[i], message);
		}
	}
}

function assertRestoring(state: IRecentlyOpened, message?: string) {
	const stored = toStoreData(state);
	const restored = restoreRecentlyOpened(stored);
	assertEqualRecentlyOpened(state, restored, message);
}

const testWSPath = URI.file(path.join(os.tmpdir(), 'windowStateTest', 'test.code-workspace'));
const testFileURI = URI.file(path.join(os.tmpdir(), 'windowStateTest', 'testFile.txt'));
const testFolderURI = URI.file(path.join(os.tmpdir(), 'windowStateTest', 'testFolder'));

const testRemoteFolderURI = URI.parse('foo://bar/c/e');
const testRemoteFileURI = URI.parse('foo://bar/c/d.txt');
const testRemoteWSURI = URI.parse('foo://bar/c/test.code-workspace');

suite('History Storage', () => {
	test('storing and restoring', () => {
		let ro: IRecentlyOpened;
		ro = {
			files: [],
			workspaces: []
		};
		assertRestoring(ro, 'empty');
		ro = {
			files: [testFileURI],
			workspaces: []
		};
		assertRestoring(ro, 'file');
		ro = {
			files: [],
			workspaces: [testFolderURI]
		};
		assertRestoring(ro, 'folder');
		ro = {
			files: [],
			workspaces: [toWorkspace(testWSPath), testFolderURI]
		};
		assertRestoring(ro, 'workspaces and folders');

		ro = {
			files: [testRemoteFileURI],
			workspaces: [toWorkspace(testRemoteWSURI), testRemoteFolderURI]
		};
		assertRestoring(ro, 'remote workspaces and folders');
	});

	test('open 1_25', () => {
		const v1_25_win = `{
			"workspaces": [
				{
					"id": "2fa677dbdf5f771e775af84dea9feaea",
					"configPath": "C:\\\\workspaces\\\\testing\\\\test.code-workspace"
				},
				"C:\\\\workspaces\\\\testing\\\\test-ext",
				{
					"id": "d87a0241f8abc86b95c4e5481ebcbf56",
					"configPath": "C:\\\\workspaces\\\\test.code-workspace"
				}
			],
			"files": [
				"C:\\\\workspaces\\\\test.code-workspace",
				"C:\\\\workspaces\\\\testing\\\\test-ext\\\\.gitignore"
			]
		}`;

		let actual = restoreRecentlyOpened(JSON.parse(v1_25_win));
		let expected: IRecentlyOpened = {
			files: [URI.file('C:\\workspaces\\test.code-workspace'), URI.file('C:\\workspaces\\testing\\test-ext\\.gitignore')],
			workspaces: [
				{ id: '2fa677dbdf5f771e775af84dea9feaea', configPath: URI.file('C:\\workspaces\\testing\\test.code-workspace') },
				URI.file('C:\\workspaces\\testing\\test-ext'),
				{ id: 'd87a0241f8abc86b95c4e5481ebcbf56', configPath: URI.file('C:\\workspaces\\test.code-workspace') }
			]
		};

		assertEqualRecentlyOpened(expected, actual, 'v1_31_win');
	});

	test('open 1_31', () => {
		const v1_31_win = `{
			"workspaces2": [
				"file:///c%3A/workspaces/testing/test-ext",
				"file:///c%3A/WINDOWS/system32",
				{
					"id": "d87a0241f8abc86b95c4e5481ebcbf56",
					"configPath": "c:\\\\workspaces\\\\test.code-workspace"
				}
			],
			"files2": [
				"file:///c%3A/workspaces/vscode/.yarnrc"
			]
		}`;

		let actual = restoreRecentlyOpened(JSON.parse(v1_31_win));
		let expected: IRecentlyOpened = {
			files: [URI.parse('file:///c%3A/workspaces/vscode/.yarnrc')],
			workspaces: [
				URI.parse('file:///c%3A/workspaces/testing/test-ext'),
				URI.parse('file:///c%3A/WINDOWS/system32'),
				{ id: 'd87a0241f8abc86b95c4e5481ebcbf56', configPath: URI.file('c:\\workspaces\\test.code-workspace') }
			]
		};

		assertEqualRecentlyOpened(expected, actual, 'v1_31_win');
	});

	test('open 1_32', () => {
		const v1_32 = `{
			"workspaces3": [
				{
					"id": "53b714b46ef1a2d4346568b4f591028c",
					"configURIPath": "file:///home/user/workspaces/testing/custom.code-workspace"
				},
				"file:///home/user/workspaces/testing/folding"
			],
			"files2": [
				"file:///home/user/.config/code-oss-dev/storage.json"
			]
		}`;

		let windowsState = restoreRecentlyOpened(JSON.parse(v1_32));
		let expected: IRecentlyOpened = {
			files: [URI.parse('file:///home/user/.config/code-oss-dev/storage.json')],
			workspaces: [
				{ id: '53b714b46ef1a2d4346568b4f591028c', configPath: URI.parse('file:///home/user/workspaces/testing/custom.code-workspace') },
				URI.parse('file:///home/user/workspaces/testing/folding')
			]
		};

		assertEqualRecentlyOpened(expected, windowsState, 'v1_32');

	});

});


text:
/**
 * @author banpot srihawong
 */

//Info View Component Constructor
function InfoView() {
	//create object instance, parasitic subclass of Observable
	var self = Ti.UI.createView({
		//backgroundColor:'white'
		backgroundColor:'#f7d5cf',
		layout:'vertical',
	});

	self.add(Ti.UI.createLabel({
		top:15,
		color:'black',
		font:{fontSize:20},
		text:"แจ้งปัญหาการใช้งานหรือเสนอแนะปรับปรุงแอพพลิเคชั่น"
	}));
	self.add(txtArea = Ti.UI.createTextArea({
		width:'90%',
		height:'80%',
		returnKeyType: Ti.UI.RETURNKEY_SEND,
	}));
	self.add(btSend = Ti.UI.createButton({
		title:"ส่งข้อมูล"
	}));
	var client = Ti.Network.createHTTPClient({
		timeout:15000,
		onerror:function(e){
				Ti.API.debug(e.error);
				alert('เกิดความผิดพลาดกรุณาลองใหม่อีกครั้ง');
		},
		onload:function(e){
			alert('ขอบคุณสำหรับการแจ้งปัญหาและคำแนะนำ');
			self.fireEvent('closeInfo',{});
		}
	});
	txtArea.addEventListener('return',function(e){
		tracker.trackEvent({
			category: "category",
			action: "sendInfomation",
			label: "app",
			value: 1
		});
		client.open('POST','http://srihawong.info/app/thaimtb_submitInfo.php');
		client.send({message:txtArea.getValue()});
	});
	btSend.addEventListener('click',function(e){
		tracker.trackEvent({
			category: "category",
			action: "sendInfomation",
			label: "app",
			value: 1
		});
		client.open('POST','http://srihawong.info/app/thaimtb_submitInfo.php');
		client.send({message:txtArea.getValue()});
	});
	self.addEventListener('focus',function(e){
		tracker.trackScreen(Ti.Platform.osname+"/infomation");
	});
	return self;
}
module.exports = InfoView;


text:
// Initialize sum
sum = 0;

/*
Loop through process.argv, starting at position 2
NOTE: process.argv is by default a string,
must be converted to integer using +process.argv
*/
for (i=2; i<process.argv.length; ++i) {
	sum = +process.argv[i] + sum;
}

// Print answer to console out
console.log(sum);


text:
// This file is automatically generated.

package adila.db;

/*
 * Samsung Galaxy Tab S 10.5
 *
 * DEVICE: chagalllte
 * MODEL: SM-T805
 */
final class chagalllte_sm2dt805 {
    public static final String DATA = "Samsung|Galaxy Tab S 10.5|Galaxy Tab";
}


text:
using BrewLib.UserInterface;
using BrewLib.Util;
using OpenTK;
using StorybrewEditor.ScreenLayers;
using StorybrewEditor.Storyboarding;
using System.Diagnostics;

namespace StorybrewEditor.UserInterface.Components
{
    public class SettingsMenu : Widget
    {
        private readonly LinearLayout layout;
        private Project project;

        public override Vector2 MinSize => layout.MinSize;
        public override Vector2 MaxSize => layout.MaxSize;
        public override Vector2 PreferredSize => layout.PreferredSize;

        public SettingsMenu(WidgetManager manager, Project project) : base(manager)
        {
            this.project = project;

            Button referencedAssemblyButton, floatingPointTimeButton, helpButton;
            Label dimLabel;
            Slider dimSlider;

            Add(layout = new LinearLayout(manager)
            {
                StyleName = "panel",
                Padding = new FourSide(16),
                FitChildren = true,
                Fill = true,
                Children = new Widget[]
                    {
                    new Label(manager)
                    {
                        Text = "Settings",
                        CanGrow = false,
                    },
                    new LinearLayout(manager)
                    {
                        Fill = true,
                        FitChildren = true,
                        CanGrow = false,
                        Children = new Widget[]
                        {
                            helpButton = new Button(manager)
                            {
                                Text = "Help!",
                                AnchorFrom = BoxAlignment.Centre,
                                AnchorTo = BoxAlignment.Centre,
                            },
                            referencedAssemblyButton = new Button(manager)
                            {
                                Text = "Referenced Assemblies",
                                AnchorFrom = BoxAlignment.Centre,
                                AnchorTo = BoxAlignment.Centre,
                            },
                            new LinearLayout(manager)
                            {
                                StyleName = "condensed",
                                FitChildren = true,
                                Children = new Widget[]
                                {
                                    dimLabel = new Label(manager)
                                    {
                                        StyleName = "small",
                                        Text = "Dim",
                                    },
                                    dimSlider = new Slider(manager)
                                    {
                                        StyleName = "small",
                                        AnchorFrom = BoxAlignment.Centre,
                                        AnchorTo = BoxAlignment.Centre,
                                        Value = 0,
                                        Step = .05f,
                                    },
                                }
                            },
                            floatingPointTimeButton = new Button(manager)
                            {
                                Text = "Export Time as Floating Point",
                                AnchorFrom = BoxAlignment.Centre,
                                AnchorTo = BoxAlignment.Centre,
                                Checkable = true,
                                Checked = project.ExportSettings.UseFloatForTime,
                                Tooltip = "A storyboard exported with this option enabled\nwill only be compatible with lazer",
                            },
                        }
                    }
                },
            });

            helpButton.OnClick += (sender, e) => Process.Start($"https://github.com/{Program.Repository}/wiki");
            referencedAssemblyButton.OnClick += (sender, e) => Manager.ScreenLayerManager.Add(new ReferencedAssemblyConfig(project));
            dimSlider.OnValueChanged += (sender, e) =>
            {
                project.DimFactor = dimSlider.Value;
                dimLabel.Text = $"Dim ({project.DimFactor:p})";
            };
            floatingPointTimeButton.OnValueChanged += (sender, e) => project.ExportSettings.UseFloatForTime = floatingPointTimeButton.Checked;
        }

        protected override void Dispose(bool disposing)
        {
            project = null;
            base.Dispose(disposing);
        }

        protected override void Layout()
        {
            base.Layout();
            layout.Size = Size;
        }
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>mango.mtype.dtype — mango 0.9.8 documentation</title>

    <link rel="stylesheet" href="../../../_static/default.css" type="text/css" />
    <link rel="stylesheet" href="../../../_static/pygments.css" type="text/css" />

    <link rel="top" title="mango 0.9.8 documentation" href="../../../index.html" />
    <link rel="up" title="mango.mtype" href="../../mango.mtype.html" />
    <link rel="next" title="mango.DdsNonHaloSubDomain" href="../../mango.DdsNonHaloSubDomain.html" />
    <link rel="prev" title="mango.mtype.shortName" href="../methods/mango.mtype.shortName.html" />

Navigation

          index

          modules |

          next |

          previous |

mango 0.9.8 documentation »

Mango 3D Image Processing Package  (<tt class="docutils literal">mango</tt>) »

mango.mtype »

mango.mtype.dtype¶

<tt class="descclassname">mtype.</tt><tt class="descname">dtype</tt>¶

Returns <tt class="samp docutils literal">numpy.dtype</tt> object associated with the basic-type of this mtype.

<col class="field-name" />
<col class="field-body" />

Return type:	numpy.dtype

Returns:	<tt class="samp docutils literal">numpy.dtype</tt> object.

Previous topic

mango.mtype.shortName

Next topic

mango.DdsNonHaloSubDomain

This Page

Show Source

Quick search

    <form class="search" action="../../../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

    Enter search terms or a module, class or function name.

Navigation

          index

          modules |

          next |

          previous |

mango 0.9.8 documentation »

Mango 3D Image Processing Package  (<tt class="docutils literal">mango</tt>) »

mango.mtype »

        © Copyright 2014, Department of Applied Mathematics, The Australian National University.
      Created using Sphinx 1.2.3.


text: - Casey Dunham <casey.dunham@gmail.com>


text:
<?xml version="1.0" encoding="UTF-8" ?>
<rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wikidot="http://www.wikidot.com/rss-namespace">

	<channel>
		<title>Comments for page "Stalker Style: Freaking Laser Beams"</title>
		<link>http://bvs.wikidot.com/forum/t-109999/stalker-style:freaking-laser-beams</link>
		<description>Posts in the discussion thread "Stalker Style: Freaking Laser Beams"</description>
				<copyright></copyright>
		<lastBuildDate>Sun, 10 Jul 2022 04:00:26 +0000</lastBuildDate>

				</channel>
</rss>


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>Entrenamiento</title>
  <meta name="description" content="">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="app/bower_components/bootstrap/dist/css/bootstrap.css">
  <link rel="stylesheet" href="app/bower_components/html5-boilerplate/dist/css/normalize.css">
  <link rel="stylesheet" href="app/bower_components/html5-boilerplate/dist/css/main.css">
  <link rel="stylesheet" href="app/app.css">

        <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
          Toggle navigation

        </button>
        AngularJS Services

            Service Creation

Home

Provider Function

Factory Function

Service Function

Value Function

Constant Function

Dependency Annotations

            Built-in Services

$q: promises

Routing Services

Cookies

Log

            Networking Services

$http

Transformations and Interceptors

$resource

            Caching and Sharing

Caching

Sharing

            Service Decorators

Intro


text:
package models

// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command

import (
	"context"

	"github.com/go-openapi/errors"
	"github.com/go-openapi/strfmt"
	"github.com/go-openapi/swag"
	"github.com/go-openapi/validate"
)

// ControllerStatus Status of a controller
//
// +k8s:deepcopy-gen=true
//
// swagger:model ControllerStatus
type ControllerStatus struct {

	// configuration
	Configuration *ControllerStatusConfiguration `json:"configuration,omitempty"`

	// Name of controller
	Name string `json:"name,omitempty"`

	// status
	Status *ControllerStatusStatus `json:"status,omitempty"`

	// UUID of controller
	// Format: uuid
	UUID strfmt.UUID `json:"uuid,omitempty"`
}

// Validate validates this controller status
func (m *ControllerStatus) Validate(formats strfmt.Registry) error {
	var res []error

	if err := m.validateConfiguration(formats); err != nil {
		res = append(res, err)
	}

	if err := m.validateStatus(formats); err != nil {
		res = append(res, err)
	}

	if err := m.validateUUID(formats); err != nil {
		res = append(res, err)
	}

	if len(res) > 0 {
		return errors.CompositeValidationError(res...)
	}
	return nil
}

func (m *ControllerStatus) validateConfiguration(formats strfmt.Registry) error {
	if swag.IsZero(m.Configuration) { // not required
		return nil
	}

	if m.Configuration != nil {
		if err := m.Configuration.Validate(formats); err != nil {
			if ve, ok := err.(*errors.Validation); ok {
				return ve.ValidateName("configuration")
			} else if ce, ok := err.(*errors.CompositeError); ok {
				return ce.ValidateName("configuration")
			}
			return err
		}
	}

	return nil
}

func (m *ControllerStatus) validateStatus(formats strfmt.Registry) error {
	if swag.IsZero(m.Status) { // not required
		return nil
	}

	if m.Status != nil {
		if err := m.Status.Validate(formats); err != nil {
			if ve, ok := err.(*errors.Validation); ok {
				return ve.ValidateName("status")
			} else if ce, ok := err.(*errors.CompositeError); ok {
				return ce.ValidateName("status")
			}
			return err
		}
	}

	return nil
}

func (m *ControllerStatus) validateUUID(formats strfmt.Registry) error {
	if swag.IsZero(m.UUID) { // not required
		return nil
	}

	if err := validate.FormatOf("uuid", "body", "uuid", m.UUID.String(), formats); err != nil {
		return err
	}

	return nil
}

// ContextValidate validate this controller status based on the context it is used
func (m *ControllerStatus) ContextValidate(ctx context.Context, formats strfmt.Registry) error {
	var res []error

	if err := m.contextValidateConfiguration(ctx, formats); err != nil {
		res = append(res, err)
	}

	if err := m.contextValidateStatus(ctx, formats); err != nil {
		res = append(res, err)
	}

	if len(res) > 0 {
		return errors.CompositeValidationError(res...)
	}
	return nil
}

func (m *ControllerStatus) contextValidateConfiguration(ctx context.Context, formats strfmt.Registry) error {

	if m.Configuration != nil {
		if err := m.Configuration.ContextValidate(ctx, formats); err != nil {
			if ve, ok := err.(*errors.Validation); ok {
				return ve.ValidateName("configuration")
			} else if ce, ok := err.(*errors.CompositeError); ok {
				return ce.ValidateName("configuration")
			}
			return err
		}
	}

	return nil
}

func (m *ControllerStatus) contextValidateStatus(ctx context.Context, formats strfmt.Registry) error {

	if m.Status != nil {
		if err := m.Status.ContextValidate(ctx, formats); err != nil {
			if ve, ok := err.(*errors.Validation); ok {
				return ve.ValidateName("status")
			} else if ce, ok := err.(*errors.CompositeError); ok {
				return ce.ValidateName("status")
			}
			return err
		}
	}

	return nil
}

// MarshalBinary interface implementation
func (m *ControllerStatus) MarshalBinary() ([]byte, error) {
	if m == nil {
		return nil, nil
	}
	return swag.WriteJSON(m)
}

// UnmarshalBinary interface implementation
func (m *ControllerStatus) UnmarshalBinary(b []byte) error {
	var res ControllerStatus
	if err := swag.ReadJSON(b, &res); err != nil {
		return err
	}
	*m = res
	return nil
}

// ControllerStatusConfiguration Configuration of controller
//
// +deepequal-gen=true
// +k8s:deepcopy-gen=true
//
// swagger:model ControllerStatusConfiguration
type ControllerStatusConfiguration struct {

	// Retry on error
	ErrorRetry bool `json:"error-retry,omitempty"`

	// Base error retry back-off time
	// Format: duration
	ErrorRetryBase strfmt.Duration `json:"error-retry-base,omitempty"`

	// Regular synchronization interval
	// Format: duration
	Interval strfmt.Duration `json:"interval,omitempty"`
}

// Validate validates this controller status configuration
func (m *ControllerStatusConfiguration) Validate(formats strfmt.Registry) error {
	var res []error

	if err := m.validateErrorRetryBase(formats); err != nil {
		res = append(res, err)
	}

	if err := m.validateInterval(formats); err != nil {
		res = append(res, err)
	}

	if len(res) > 0 {
		return errors.CompositeValidationError(res...)
	}
	return nil
}

func (m *ControllerStatusConfiguration) validateErrorRetryBase(formats strfmt.Registry) error {
	if swag.IsZero(m.ErrorRetryBase) { // not required
		return nil
	}

	if err := validate.FormatOf("configuration"+"."+"error-retry-base", "body", "duration", m.ErrorRetryBase.String(), formats); err != nil {
		return err
	}

	return nil
}

func (m *ControllerStatusConfiguration) validateInterval(formats strfmt.Registry) error {
	if swag.IsZero(m.Interval) { // not required
		return nil
	}

	if err := validate.FormatOf("configuration"+"."+"interval", "body", "duration", m.Interval.String(), formats); err != nil {
		return err
	}

	return nil
}

// ContextValidate validates this controller status configuration based on context it is used
func (m *ControllerStatusConfiguration) ContextValidate(ctx context.Context, formats strfmt.Registry) error {
	return nil
}

// MarshalBinary interface implementation
func (m *ControllerStatusConfiguration) MarshalBinary() ([]byte, error) {
	if m == nil {
		return nil, nil
	}
	return swag.WriteJSON(m)
}

// UnmarshalBinary interface implementation
func (m *ControllerStatusConfiguration) UnmarshalBinary(b []byte) error {
	var res ControllerStatusConfiguration
	if err := swag.ReadJSON(b, &res); err != nil {
		return err
	}
	*m = res
	return nil
}

// ControllerStatusStatus Current status of controller
//
// +k8s:deepcopy-gen=true
//
// swagger:model ControllerStatusStatus
type ControllerStatusStatus struct {

	// Number of consecutive errors since last success
	ConsecutiveFailureCount int64 `json:"consecutive-failure-count,omitempty"`

	// Total number of failed runs
	FailureCount int64 `json:"failure-count,omitempty"`

	// Error message of last failed run
	LastFailureMsg string `json:"last-failure-msg,omitempty"`

	// Timestamp of last error
	// Format: date-time
	LastFailureTimestamp strfmt.DateTime `json:"last-failure-timestamp,omitempty"`

	// Timestamp of last success
	// Format: date-time
	LastSuccessTimestamp strfmt.DateTime `json:"last-success-timestamp,omitempty"`

	// Total number of successful runs
	SuccessCount int64 `json:"success-count,omitempty"`
}

// Validate validates this controller status status
func (m *ControllerStatusStatus) Validate(formats strfmt.Registry) error {
	var res []error

	if err := m.validateLastFailureTimestamp(formats); err != nil {
		res = append(res, err)
	}

	if err := m.validateLastSuccessTimestamp(formats); err != nil {
		res = append(res, err)
	}

	if len(res) > 0 {
		return errors.CompositeValidationError(res...)
	}
	return nil
}

func (m *ControllerStatusStatus) validateLastFailureTimestamp(formats strfmt.Registry) error {
	if swag.IsZero(m.LastFailureTimestamp) { // not required
		return nil
	}

	if err := validate.FormatOf("status"+"."+"last-failure-timestamp", "body", "date-time", m.LastFailureTimestamp.String(), formats); err != nil {
		return err
	}

	return nil
}

func (m *ControllerStatusStatus) validateLastSuccessTimestamp(formats strfmt.Registry) error {
	if swag.IsZero(m.LastSuccessTimestamp) { // not required
		return nil
	}

	if err := validate.FormatOf("status"+"."+"last-success-timestamp", "body", "date-time", m.LastSuccessTimestamp.String(), formats); err != nil {
		return err
	}

	return nil
}

// ContextValidate validates this controller status status based on context it is used
func (m *ControllerStatusStatus) ContextValidate(ctx context.Context, formats strfmt.Registry) error {
	return nil
}

// MarshalBinary interface implementation
func (m *ControllerStatusStatus) MarshalBinary() ([]byte, error) {
	if m == nil {
		return nil, nil
	}
	return swag.WriteJSON(m)
}

// UnmarshalBinary interface implementation
func (m *ControllerStatusStatus) UnmarshalBinary(b []byte) error {
	var res ControllerStatusStatus
	if err := swag.ReadJSON(b, &res); err != nil {
		return err
	}
	*m = res
	return nil
}


text:
Celery Tracker
=================

Receive/Sending event tracking data for the `Celery. <http://celeryproject.org/>`_

ZabbixPlugin
--------------

Send

.. image:: http://dl.dropbox.com/u/6574724/Screenshots/xna0.png
   :width: 900px
   :scale: 90%

Receive

.. image:: http://dl.dropbox.com/u/6574724/Screenshots/b~o_.png
   :width: 900px
   :scale: 90%

FluentPlugin
---------------

Send

.. image:: http://dl.dropbox.com/u/6574724/Screenshots/r~_z.png
   :width: 900px
   :scale: 90%

Receive

.. image:: http://dl.dropbox.com/u/6574724/Screenshots/cxws.png
   :width: 900px
   :scale: 90%

ReceivePlugin
---------------

JSON response, e.g. at http://127.0.0.1:27015

.. image:: http://dl.dropbox.com/u/6574724/Screenshots/4mb9.png
   :width: 900px
   :scale: 90%

Customize
--------------

`Customize Documentation - celery-tracker.rtfd.org <http://celery-tracker.rtfd.org>`_

Setup
=====

*PyPI*

::

    $ pip install celery-tracker

*GitHub*

`github.com/ikeikeikeike/celery-tracker <https://github.com/ikeikeikeike/celery-tracker>`_

Examples
-----------

For more information, please see the `Example <https://github.com/ikeikeikeike/celery-tracker/tree/master/examples>`_

License
=========

MIT License


text:
    <hs-panel-header name="language" [title]="'PANEL_HEADER.LANGUAGE' | translateHs : data" [app]="data.app">
    </hs-panel-header>

            <button *ngFor="let lang of available_languages" class="btn m-1"
                [ngClass]="isCurrentLang(lang.key) ? ' btn-primary' : ' btn-secondary'"
                (click)="setLanguage(lang.key)">{{lang.name}}</button>


text:
package abstractfactory;

import abstractfactory.creator.RedStarburstTeleFactory;
import abstractfactory.creator.SilverStratFactory;

/**
 * The 'Abstract Factory' pattern is used to create families of objects without
 * having to know the class type. It makes the instantiation of the objects
 * private to keep them decoupled from the code that uses them.
 *
 * 'Factory Method' (FM) pattern vs 'Abstract Factory' (AF) pattern:
 *
 * FM: Defines a method in the creator abstract base class for creating one
 * product AF: Defines many methods in creator abstract base class for creating
 * a family of products.
 *
 * FM: Concrete creator decide which concrete class to instantiate. AF: Concrete
 * creator subclasses create a family of products.
 */
public class AbstractFactoryPatternRunner {

	public static void main(String[] args) {
		GuitarOrder order1 = new GuitarOrder(new SilverStratFactory());
		order1.displayOrder();

		GuitarOrder order2 = new GuitarOrder(new RedStarburstTeleFactory());
		order2.displayOrder();
	}

}