text:
namespace gfx {
class ColorSpace;
}  // namespace gfx

namespace viz {

class ScopedAllowGpuAccessForDisplayResourceProvider;

// This class provides abstractions for receiving and using resources from other
// modules/threads/processes. It abstracts away GL textures vs GpuMemoryBuffers
// vs software bitmaps behind a single ResourceId so that code in common can
// hold onto ResourceIds, as long as the code using them knows the correct type.
// It accepts as input TransferableResources which it holds internally, tracks
// state on, and exposes as a ResourceId.
//
// The resource's underlying type is accessed through locks that help to
// scope and safeguard correct usage with DCHECKs.
//
// This class is not thread-safe and can only be called from the thread it was
// created on.
class VIZ_SERVICE_EXPORT DisplayResourceProvider
    : public base::trace_event::MemoryDumpProvider {
 public:
  enum Mode {
    kGpu,
    kSoftware,
  };
  ~DisplayResourceProvider() override;

  DisplayResourceProvider(const DisplayResourceProvider&) = delete;
  DisplayResourceProvider& operator=(const DisplayResourceProvider&) = delete;

  bool IsSoftware() const { return mode_ == kSoftware; }
  size_t num_resources() const { return resources_.size(); }

  // base::trace_event::MemoryDumpProvider implementation.
  bool OnMemoryDump(const base::trace_event::MemoryDumpArgs& args,
                    base::trace_event::ProcessMemoryDump* pmd) override;

  base::WeakPtr<DisplayResourceProvider> GetWeakPtr();

#if BUILDFLAG(IS_ANDROID)
  // Indicates if this resource is backed by an Android SurfaceTexture, and thus
  // can't really be promoted to an overlay.
  bool IsBackedBySurfaceTexture(ResourceId id);
#endif

#if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_WIN)
  // Indicates if this resource wants to receive promotion hints.
  bool DoesResourceWantPromotionHint(ResourceId id);
#endif

  // Returns the size in pixels of the underlying gpu mailbox/software bitmap.
  const gfx::Size GetResourceBackedSize(ResourceId id);

  bool IsResourceSoftwareBacked(ResourceId id);
  // Return the format of the underlying buffer that can be used for scanout.
  gfx::BufferFormat GetBufferFormat(ResourceId id);
  ResourceFormat GetResourceFormat(ResourceId id);
  // Returns the color space that the resource needs to be interpreted in by the
  // operating system.
  const gfx::ColorSpace& GetOverlayColorSpace(ResourceId id);
  // Returns the color space that samples of this resource in a shader will be
  // in.
  gfx::ColorSpace GetSamplerColorSpace(ResourceId id);
  const absl::optional<gfx::HDRMetadata>& GetHDRMetadata(ResourceId id);

  // Indicates if this resource may be used for a hardware overlay plane.
  bool IsOverlayCandidate(ResourceId id);
  SurfaceId GetSurfaceId(ResourceId id);
  int GetChildId(ResourceId id);

  // Checks whether a resource is in use.
  bool InUse(ResourceId id);

  // Try removing the resources that are pending the |resource_fence|.
  void OnResourceFencePassed(ResourceFence* resource_fence,
                             base::flat_set<ResourceId> resources);

  // The following lock classes are part of the DisplayResourceProvider API and
  // are needed to read the resource contents. The user must ensure that they
  // only use GL locks on GL resources, etc, and this is enforced by assertions.

 protected:
  // Forward declared for ScopedReadLockSharedImage below.
  struct ChildResource;

 public:
  // Lock the resource to make sure the shared image is alive when accessing
  // SharedImage Mailbox.
  class VIZ_SERVICE_EXPORT ScopedReadLockSharedImage {
   public:
    ScopedReadLockSharedImage(DisplayResourceProvider* resource_provider,
                              ResourceId resource_id);
    ~ScopedReadLockSharedImage();

    ScopedReadLockSharedImage(ScopedReadLockSharedImage&& other);
    ScopedReadLockSharedImage& operator=(ScopedReadLockSharedImage&& other);

    const gpu::Mailbox& mailbox() const {
      DCHECK(resource_);
      return resource_->transferable.mailbox_holder.mailbox;
    }
    const gpu::SyncToken& sync_token() const {
      DCHECK(resource_);
      return resource_->sync_token();
    }

    // Sets the given |release_fence| onto this resource.
    // This is propagated to ReturnedResource when the resource is freed.
    void SetReleaseFence(gfx::GpuFenceHandle release_fence);

    // Returns true iff this resource has a read lock fence set.
    bool HasReadLockFence() const;

   protected:
    ChildResource* resource() { return resource_; }

   private:
    void Reset();

    raw_ptr<DisplayResourceProvider> resource_provider_ = nullptr;
    ResourceId resource_id_ = kInvalidResourceId;
    raw_ptr<ChildResource> resource_ = nullptr;
  };

  // All resources that are returned to children while an instance of this
  // class exists will be stored and returned when the instance is destroyed.
  class VIZ_SERVICE_EXPORT ScopedBatchReturnResources {
   public:
    explicit ScopedBatchReturnResources(
        DisplayResourceProvider* resource_provider,
        bool allow_access_to_gpu_thread = false);
    ~ScopedBatchReturnResources();

   private:
    const raw_ptr<DisplayResourceProvider> resource_provider_;
    const bool was_access_to_gpu_thread_allowed_;
  };

  // Creates accounting for a child. Returns a child ID. surface_id is used to
  // associate resources to the surface they belong to. This is used for
  // overlays on webview where overlays are updated outside of normal draw (i.e
  // DrawAndSwap isn't called).
  int CreateChild(ReturnCallback return_callback, const SurfaceId& surface_id);

  // Destroys accounting for the child, deleting all accounted resources.
  void DestroyChild(int child);

  // Gets the child->parent resource ID map.
  const std::unordered_map<ResourceId, ResourceId, ResourceIdHasher>&
  GetChildToParentMap(int child) const;

  // Receives resources from a child, moving them from mailboxes. ResourceIds
  // passed are in the child namespace, and will be translated to the parent
  // namespace, added to the child->parent map.
  // This adds the resources to the working set in the ResourceProvider without
  // declaring which resources are in use. Use DeclareUsedResourcesFromChild
  // after calling this method to do that. All calls to ReceiveFromChild should
  // be followed by a DeclareUsedResourcesFromChild.
  // NOTE: if the sync_token is set on any TransferableResource, this will
  // wait on it.
  void ReceiveFromChild(
      int child,
      const std::vector<TransferableResource>& transferable_resources);

  // Once a set of resources have been received, they may or may not be used.
  // This declares what set of resources are currently in use from the child,
  // releasing any other resources back to the child.
  void DeclareUsedResourcesFromChild(int child,
                                     const ResourceIdSet& resources_from_child);

  // Returns the mailbox corresponding to a resource id.
  gpu::Mailbox GetMailbox(ResourceId resource_id);

  // Sets if the GPU thread is available (it always is for Chrome, but for
  // WebView it happens only when Android calls us on RenderThread.
  void SetAllowAccessToGPUThread(bool allow);

 protected:
  friend class ScopedAllowGpuAccessForDisplayResourceProvider;

  enum class CanDeleteNowResult { kYes, kYesButLoseResource, kNo };

  enum DeleteStyle {
    NORMAL,
    FOR_SHUTDOWN,
  };

  struct Child {
    Child();
    Child(Child&& other);
    Child& operator=(Child&& other);
    ~Child();

    int id;
    std::unordered_map<ResourceId, ResourceId, ResourceIdHasher>
        child_to_parent_map;
    ReturnCallback return_callback;
    SurfaceId surface_id;
    bool marked_for_deletion = false;
  };

  // The data structure used to track state of Gpu and Software-based
  // resources and the service, for resources transferred
  // between the two. This is an implementation detail of the resource tracking
  // for client and service libraries and should not be used directly from
  // external client code.
  struct ChildResource {
    ChildResource(int child_id, const TransferableResource& transferable);
    ChildResource(ChildResource&& other);
    ~ChildResource();

    bool is_gpu_resource_type() const { return !transferable.is_software; }
    const gpu::SyncToken& sync_token() const { return sync_token_; }

    bool InUse() const {
      return lock_for_read_count > 0 || locked_for_external_use ||
             lock_for_overlay_count > 0;
    }

    void UpdateSyncToken(const gpu::SyncToken& sync_token);

    // This is the id of the client the resource comes from.
    const int child_id;
    // Data received from the client that describes the resource fully.
    const TransferableResource transferable;

    // The number of times the resource has been received from a client. It must
    // have this many number of references returned back to the client in order
    // for it to know it is no longer in use in the service. This is used to
    // avoid races where a resource is in flight to the service while also being
    // returned to the client. It starts with an initial count of 1, for the
    // first time the resource is received.
    int imported_count = 1;

    // The number of active users of a resource in the display compositor. While
    // a resource is in use, it will not be returned back to the client even if
    // the ResourceId is deleted.
    int lock_for_read_count = 0;
    // When true, the resource is currently being used externally. This is a
    // parallel counter to |lock_for_read_count| which can only go to 1.
    bool locked_for_external_use = false;
    // The number of active users using this resource as overlay content.
    int lock_for_overlay_count = 0;

    // When the resource should be deleted until it is actually reaped.
    bool marked_for_deletion = false;

    // A pointer to the shared memory structure for software-backed resources,
    // when it is mapped into memory in this process.
    std::unique_ptr<SharedBitmap> shared_bitmap;
    // A GUID for reporting the |shared_bitmap| to memory tracing. The GUID is
    // known by other components in the system as well to give the same id for
    // this shared memory bitmap everywhere. This is empty until the resource is
    // mapped for use in the display compositor.
    base::UnguessableToken shared_bitmap_tracing_guid;

    // A fence used for returning resources after the display compositor has
    // completed accessing the resources it received from a client. This can
    // either be a read lock or a release fence. If the |transferable| has
    // synchronization type set as kGpuCommandsCompleted, the resource can be
    // returned after ResourceFence::HasPassed is true. If the |transferable|
    // has the synchronization type set as kReleaseFence, the resource can be
    // returned after the fence has a release fence set.
    scoped_refptr<ResourceFence> resource_fence;

    // SkiaRenderer specific details about this resource. Added to ChildResource
    // to avoid map lookups further down the pipeline.
    std::unique_ptr<ExternalUseClient::ImageContext> image_context;

    // A release fence to propagate to ReturnedResource so clients may
    // use it.
    gfx::GpuFenceHandle release_fence;

   private:
    // A SyncToken associated with a texture-backed or GpuMemoryBuffer-backed
    // resource. It is given from a child to the service, and waited on in order
    // to use the resource.
    gpu::SyncToken sync_token_;
  };

  using ChildMap = std::unordered_map<int, Child>;
  using ResourceMap =
      std::unordered_map<ResourceId, ChildResource, ResourceIdHasher>;

  explicit DisplayResourceProvider(Mode mode);

  ChildResource* GetResource(ResourceId id);

  // TODO(ericrk): TryGetResource is part of a temporary workaround for cases
  // where resources which should be available are missing. This version may
  // return nullptr if a resource is not found. https://crbug.com/811858
  ChildResource* TryGetResource(ResourceId id);

  void TryReleaseResource(ResourceId id, ChildResource* resource);
  bool ResourceFenceHasPassed(const ChildResource* resource);

  void DeleteAndReturnUnusedResourcesToChild(
      ChildMap::iterator child_it,
      DeleteStyle style,
      const std::vector<ResourceId>& unused);
  virtual std::vector<ReturnedResource>
  DeleteAndReturnUnusedResourcesToChildImpl(
      Child& child_info,
      DeleteStyle style,
      const std::vector<ResourceId>& unused) = 0;
  CanDeleteNowResult CanDeleteNow(const Child& child_info,
                                  const ChildResource& resource,
                                  DeleteStyle style);

  // Destroys DisplayResourceProvider, must be called before destructor because
  // it might call virtual functions from inside.
  void Destroy();
  void DestroyChildInternal(ChildMap::iterator it, DeleteStyle style);

  void SetBatchReturnResources(bool aggregate);
  void TryFlushBatchedResources();

  THREAD_CHECKER(thread_checker_);
  const Mode mode_;

  ResourceMap resources_;
  ChildMap children_;

  base::flat_map<int, std::vector<ResourceId>> batched_returning_resources_;
  // Keep track of whether deleted resources should be batched up or returned
  // immediately.
  int batch_return_resources_lock_count_ = 0;
  // The ResourceIds in DisplayResourceProvider start from 2 to avoid
  // conflicts with id from ClientResourceProvider.
  ResourceIdGenerator resource_id_generator_{2u};
  // Used as child id when creating a child.
  int next_child_ = 1;
  // A process-unique ID used for disambiguating memory dumps from different
  // resource providers.
  int tracing_id_;

  // Indicates that gpu thread is available and calls like
  // ReleaseImageContexts() are expected to finish in finite time. It's always
  // true for Chrome, but on WebView we need to have access to RenderThread.
  bool can_access_gpu_thread_ = true;

  // OnResourceFencePassed() may be called by resource_fence that lives past
  // destruction of this class.
  base::WeakPtrFactory<DisplayResourceProvider> weak_factory_{this};
};

}  // namespace viz

#endif  // COMPONENTS_VIZ_SERVICE_DISPLAY_DISPLAY_RESOURCE_PROVIDER_H_


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.sonatype.oss</groupId>
        <artifactId>oss-parent</artifactId>
        <version>9</version>
    </parent>

    <groupId>org.meridor.stecker</groupId>
    <artifactId>stecker</artifactId>
    <version>1.0.3-SNAPSHOT</version>
    <packaging>pom</packaging>

    <name>Stecker</name>
    <description>Stecker is a lightweight plugin engine similar to OSGi but with no contracts and restrictions.</description>

    <properties>
        <compiler.version>1.8</compiler.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <modules>
        <module>stecker-plugin-loader</module>
        <module>stecker-plugin-generator</module>
    </modules>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.meridor.stecker</groupId>
                <artifactId>stecker-plugin-loader</artifactId>
                <version>${project.version}</version>
            </dependency>
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.11</version>
                <scope>test</scope>
            </dependency>
            <dependency>
                <groupId>org.hamcrest</groupId>
                <artifactId>hamcrest-library</artifactId>
                <version>1.3</version>
                <scope>test</scope>
            </dependency>
            <dependency>
                <groupId>org.mockito</groupId>
                <artifactId>mockito-all</artifactId>
                <version>1.9.5</version>
                <scope>test</scope>
            </dependency>
            <dependency>
                <groupId>org.apache.maven.plugin-testing</groupId>
                <artifactId>maven-plugin-testing-harness</artifactId>
                <version>3.2.0</version>
                <scope>test</scope>
            </dependency>
            <dependency>
                <groupId>com.marvinformatics</groupId>
                <artifactId>kiss-matchers</artifactId>
                <version>0.14</version>
                <scope>test</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-resources-plugin</artifactId>
                    <version>2.6</version>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.0</version>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-source-plugin</artifactId>
                    <version>2.2.1</version>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-jar-plugin</artifactId>
                    <version>2.4</version>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-deploy-plugin</artifactId>
                    <version>2.8.1</version>
                </plugin>
            </plugins>
        </pluginManagement>

        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>${compiler.version}</source>
                    <target>${compiler.version}</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-source-plugin</artifactId>
                <executions>
                    <execution>
                        <id>attach-sources</id>
                        <goals>
                            <goal>jar</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-enforcer-plugin</artifactId>
                <version>1.4</version>
                <executions>
                    <execution>
                        <id>enforce-versions</id>
                        <phase>initialize</phase>
                        <goals>
                            <goal>enforce</goal>
                        </goals>
                        <configuration>
                            <fail>true</fail>
                            <rules>
                                <requireMavenVersion>
                                    <message>Version of Maven required to build the project should be
                                        ${project.prerequisites.maven}, or higher!
                                    </message>
                                    <version>[${project.prerequisites.maven},)</version>
                                </requireMavenVersion>
                                <requireJavaVersion>
                                    <message>Current JDK version ${java.version} should be ${compiler.version}, or higher!
                                    </message>
                                    <version>${compiler.version}</version>
                                </requireJavaVersion>
                            </rules>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-javadoc-plugin</artifactId>
                <version>2.10.3</version>
                <configuration>
                    <additionalparam>-Xdoclint:none</additionalparam>
                    <author>false</author>
                    <aggregate>true</aggregate>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.jacoco</groupId>
                <artifactId>jacoco-maven-plugin</artifactId>
                <version>0.7.7.201606060606</version>
                <executions>
                    <execution>
                        <id>pre-unit-test</id>
                        <goals>
                            <goal>prepare-agent</goal>
                        </goals>
                        <configuration>
                            <propertyName>surefireArgLine</propertyName>
                        </configuration>
                    </execution>
                    <execution>
                        <id>post-unit-test</id>
                        <phase>test</phase>
                        <goals>
                            <goal>report</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.19.1</version>
                <configuration>
                    <argLine>${surefireArgLine}</argLine>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <organization>
        <name>Meridor</name>
        <url>http://meridor.ru/</url>
    </organization>

    <licenses>
        <license>
            <name>The Apache Software License, Version 2.0</name>
            <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
            <distribution>repo</distribution>
        </license>
    </licenses>

    <scm>
        <url>https://github.com/meridor/stecker</url>
        <connection>scm:git@github.com:meridor/stecker.git</connection>
        <developerConnection>scm:git:git@github.com:meridor/stecker.git</developerConnection>
    </scm>

    <issueManagement>
        <system>GitHub Issues</system>
        <url>https://github.com/meridor/stecker/issues</url>
    </issueManagement>

    <ciManagement>
        <system>Travis</system>
        <url>https://travis-ci.org/meridor/stecker</url>
    </ciManagement>

    <developers>
        <developer>
            <id>vania-pooh</id>
            <name>Ivan Krutov</name>
            <email>support@meridor.org</email>
            <organization>Meridor</organization>
        </developer>
    </developers>

</project>

redpajama_set_name: RedPajamaGithub


text:
using Gx.Common;
// <auto-generated>
//
//
// Generated by Enunciate.
// </auto-generated>
using System;

namespace Gx.Agent
{

    /// <remarks>
    ///  An online account for a web application.
    /// </remarks>
    ///
    ///  An online account for a web application.
    ///
    [System.SerializableAttribute()]
    [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://gedcomx.org/v1/", TypeName = "OnlineAccount")]
    public partial class OnlineAccount : Gx.Common.ExtensibleData
    {

        private string _accountName;
        private Gx.Common.ResourceReference _serviceHomepage;
        ///
        ///  The name associated the holder of this account with the account.
        ///
        [System.Xml.Serialization.XmlElementAttribute(ElementName = "accountName", Namespace = "http://gedcomx.org/v1/")]
        [Newtonsoft.Json.JsonProperty("accountName")]
        public string AccountName
        {
            get
            {
                return this._accountName;
            }
            set
            {
                this._accountName = value;
            }
        }
        ///
        ///  The homepage of the service that provides this account.
        ///
        [System.Xml.Serialization.XmlElementAttribute(ElementName = "serviceHomepage", Namespace = "http://gedcomx.org/v1/")]
        [Newtonsoft.Json.JsonProperty("serviceHomepage")]
        public Gx.Common.ResourceReference ServiceHomepage
        {
            get
            {
                return this._serviceHomepage;
            }
            set
            {
                this._serviceHomepage = value;
            }
        }

        /**
         * Build up this online account with a service homepage.
         *
         * @param serviceHomepage The service homepage.
         * @return this.
         */
        public OnlineAccount SetServiceHomepage(ResourceReference serviceHomepage)
        {
            this.ServiceHomepage = serviceHomepage;
            return this;
        }

        /**
         * Build up this online account with an account name.
         *
         * @param accountName The account name.
         */
        public OnlineAccount SetAccountName(String accountName)
        {
            this.AccountName = accountName;
            return this;
        }
    }
}


text:
<?php
/**
 * Created for deadDrop.
 * User: bill
 * Date: 2013-10-09
 * Time: 10:11 AM
 */

include_once("./class/storage.php");

//validate request

//TODO: should put something in to make sure that the page was generated within the last 5 minutes or somethign
//TODO: lets get a time generated key in the form post that we can check against

//must be post
if (! strtoupper($_SERVER['REQUEST_METHOD'])=="POST"){
    header('HTTP/1.1 500 Internal Server Error');
    print("invalid method");
    exit;
}

//only 1 form value
if (! (count(array_keys($_POST)) ==2)){
    header('HTTP/1.1 500 Internal Server Error');
    print("invalid number of values");
    exit;
}

if (! array_key_exists("data",$_POST) || ! array_key_exists("key",$_POST)){
    header('HTTP/1.1 500 Internal Server Error');
    print("data missing");
    exit;
}

//ok, looks alright
$data = $_POST["data"];
$id = $_POST["key"];

//data should look as expected, and parse as data
$jsonData = json_decode($data);

$keysToCheck = ["iv","v","iter","ks","ts","mode","adata","cipher","salt","ct"];

//verify our various keys
foreach($keysToCheck as $key=>$value){
    if (! property_exists($jsonData,$value)){
        header('HTTP/1.1 500 Internal Server Error');
        print("data missing:".$value);
        exit;
    }
}

$storage = new Storage();

if (!$storage->checkTimedKey($id)){
    header('HTTP/1.1 500 Internal Server Error');
    print("data missing");
    exit;
}

$id = $storage->StoreData($jsonData);

header('Content-Type: application/json');
print json_encode(Array("id"=>$id));


text:
 - Blinker rechts

 - Blinker links

 - zuschaltbare Frontbeleuchtung

 - zuschaltbare Rückbeleuchtung

 - Warnblinker aktivieren

 - Kommandos über Funk, Infrarot, oder?

 - einfache bis triviale Programmierung

 - möglichst auf offene und freie Software und Bibliotheken setzen

 - Stop/Halt eines Fahrzeugs auf Befehl

 - Anfahrverzögerung

 - Bremsverzögerung

 - Abstandhalten zum Vordermann/vorfahrenden Fahrzeug

 - ...

 ## How to programm a Arduino Pro Mini with Arduino MEGA 2560?

 1) Open the example "ArduinoISP" and put it onto an ATMEGA2560.

 2) 5. Use a breadboard, and make sure you connect the following pins:
```
  MEGA  =>  Pro Mini
   52   =>   13
   53   =>   RST
   50   =>   12
   51   =>   11
   GND  =>   GND
   +5V = >   VCC
```
Also connect  a 10uF capacitor over GND and RESET on the Arduino MEGA 2560. The "minus"-sign must be connected to the GND.

 3) Open the "Blink LED" example, and change the code to fit your setup:
```CPP
void setup() {
  pinMode(7, OUTPUT); pinMode(8, OUTPUT);
  pinMode(9, OUTPUT); pinMode(10, OUTPUT);
}

void loop() {
  digitalWrite(7, HIGH);   // turn the LED on (HIGH is the voltage level)
  digitalWrite(8, HIGH);   // turn the LED on (HIGH is the voltage level)
  digitalWrite(9, HIGH);   // turn the LED on (HIGH is the voltage level)
  digitalWrite(10, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);              // wait for a second
  digitalWrite(7, LOW);    // turn the LED off by making the voltage LOW
  digitalWrite(8, LOW);    // turn the LED off by making the voltage LOW
  digitalWrite(9, LOW);    // turn the LED off by making the voltage LOW
  digitalWrite(10, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);              // wait for a second
}
```

 4) Set your programmer to "Arduino as ISP", and do "Upload with Programmer" from the file-menu in the Arduino IDE.


text: * Colors are Happy!


text:
#include "bistree.h"

/* void bistree_init(BisTree *tree,
		  int (*compare)(const void *key1, const void *key2),
		  void (*destroy)(void *data)) {

		  }*/

void bistree_init(BisTree *tree,
		  int (*compare)(const void *key1, const void *key2),
		  void (*destroy)(void *data)) {

}


text:
{% if page.comments != false %}
  {% case site.comments_provider %}
    {% when 'disqus' %}
      {% if site.disqus_username %}
        {% assign load_disqus = true %}

        {% if site.disqus_username == 'zwjlogin' %}
          {% assign load_disqus = false %}
          {% if site.url contains 'wilkins007.github.io' %}
            {% assign load_disqus = true %}
          {% endif %}
        {% endif %}
        {% if load_disqus %}

          Please enable JavaScript to view the comments powered by Disqus.
        {% endif %}
        {% if site.lazy_load_duoshuo and site.duoshuo_username %}
        想留言却没看到评论框?点这里。

        {% endif %}
      {% endif %}
    {% when 'duoshuo' %}
      {% if site.duoshuo_username %}

      {% endif %}
  {% endcase %}
{% endif %}


text:
/* ###
 * IP: GHIDRA
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package help.screenshot;

import static org.junit.Assert.*;

import java.io.IOException;

import javax.swing.JFrame;

import org.junit.*;

import docking.ActionContext;
import docking.action.DockingActionIf;
import docking.widgets.tree.GTreeNode;
import ghidra.framework.main.FrontEndTool;
import ghidra.framework.main.datatree.FindCheckoutsDialog;
import ghidra.framework.model.DomainFolder;
import ghidra.program.model.listing.Program;
import ghidra.program.model.symbol.SourceType;
import ghidra.program.model.symbol.SymbolTable;
import ghidra.test.FrontEndTestEnv;
import ghidra.util.exception.CancelledException;
import ghidra.util.exception.InvalidInputException;
import ghidra.util.task.TaskMonitor;

/**
 * This screen shot generator houses code that needs to connect to a running server
 */
public class VersionControlSlowScreenShots extends GhidraScreenShotGenerator {

	private FrontEndTestEnv frontEnd;

	@Override
	@Before
	public void setUp() throws Exception {

		// super.setUp();   don't do this; use our tool instead

		frontEnd = new FrontEndTestEnv(true);
	}

	@Override
	@After
	public void tearDown() throws Exception {

		// super.tearDown();  don't do this; use our tool instead
		if (frontEnd != null) {
			frontEnd.dispose();
		}
		showResults();
	}

	@Override
	public void loadProgram() {
		// don't need to load a program
	}

	@Override
	protected String getHelpTopicName() {
		// this is needed, since our filename does not match the help topic
		return "VersionControl";
	}

	@Test
	public void testCheckedOut() throws Exception {

		frontEnd.createMultipleCheckins();

		Program p1 = frontEnd.buildProgram(this);
		DomainFolder rootFolder = frontEnd.getRootFolder();

		// Program A created by the FrontEndTestEnv
		rootFolder.createFile("Program_B", p1, TaskMonitor.DUMMY);

		FrontEndTool t = frontEnd.getFrontEndTool();
		JFrame frame = t.getToolFrame();

		captureWindow(frame, 400, 550);
	}

	@Test
	public void testFindMyCheckouts() throws Exception {

		frontEnd.createMultipleCheckins();

		DomainFolder rootFolder = frontEnd.getRootFolder();
		DomainFolder folder = rootFolder.createFolder("myFolder_1");
		folder = folder.createFolder("myFolder_2");
		Program p = frontEnd.buildProgram(this);
		folder.createFile("My_Program", p, TaskMonitor.DUMMY);
		p.release(this);

		GTreeNode node = frontEnd.waitForFolderNode("myFolder_1");
		assertNotNull(node);
		node = node.getChild("myFolder_2");
		assertNotNull(node);
		node = node.getChild("My_Program");
		assertNotNull(node);
		frontEnd.addToVersionControl(node, true);

		GTreeNode rootNode = frontEnd.getRootNode();
		frontEnd.selectNodes(rootNode);
		DockingActionIf action = frontEnd.getAction("Find Checkouts");
		frontEnd.performFrontEndAction(action);

		FindCheckoutsDialog dialog = waitForDialogComponent(FindCheckoutsDialog.class);
		assertNotNull(dialog);

		captureDialog(dialog);
	}

//==================================================================================================
// Private Methods
//==================================================================================================

	private ActionContext createContext(GTreeNode... nodes) {
		return frontEnd.getDomainFileActionContext(nodes);
	}

	protected void createHistoryEntry(Program p, String symbolName)
			throws InvalidInputException, IOException, CancelledException {
		int transactionID = p.startTransaction("test");
		try {
			SymbolTable symTable = p.getSymbolTable();
			symTable.createLabel(p.getMinAddress().getNewAddress(0x010001000), symbolName,
				SourceType.USER_DEFINED);
		}
		finally {
			p.endTransaction(transactionID, true);
			p.save(null, TaskMonitor.DUMMY);
		}
	}

	protected void showHistory(final GTreeNode node) {
		final DockingActionIf historyAction = frontEnd.getAction("Show History");
		runSwing(() -> historyAction.actionPerformed(createContext(node)));
	}
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>X-Index</title>
<meta name="date" content="2014-02-28">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

X

x - Variable in class craj.CircleFinding

X - Static variable in class ij.gui.Plot

Display points using an X-shaped mark.

X - Static variable in class ij.gui.PlotWindow

Display points using an X-shaped mark.

x1 - Variable in class ij.gui.Line

X1 - Static variable in class ij.io.RoiDecoder

x1d - Variable in class ij.gui.Line

x2 - Variable in class ij.gui.Line

X2 - Static variable in class ij.io.RoiDecoder

x2d - Variable in class ij.gui.Line

X_CENTER_OF_MASS - Static variable in class ij.measure.ResultsTable

X_CENTROID - Static variable in class ij.measure.ResultsTable

X_FORCE2GRID - Static variable in class ij.gui.Plot

flag for forcing frame to coincide with the grid/ticks in x direction (results in unused space)

X_GRID - Static variable in class ij.gui.Plot

flag for drawing vertical grid lines for x-axis ticks

X_LOG_NUMBERS - Static variable in class ij.gui.Plot

flag for logarithmic labels of x-axis ticks

X_MINOR_TICKS - Static variable in class ij.gui.Plot

flag for drawing x-axis minor ticks

X_NUMBERS - Static variable in class ij.gui.Plot

flag for numeric labels of x-axis ticks

X_RESOLUTION - Static variable in class ij.io.TiffDecoder

X_TICKS - Static variable in class ij.gui.Plot

flag for drawing x-axis ticks

xCenter - Variable in class ij.process.EllipseFitter

X centroid

xCenterOfMass - Variable in class ij.process.ImageStatistics

xCentroid - Variable in class ij.process.ImageStatistics

xCoordinates - Variable in class ij.process.EllipseFitter

Initialized by makeRoi()

XD - Static variable in class ij.io.RoiDecoder

XINC - Static variable in class ij.plugin.frame.Editor

XINC - Static variable in class ij.plugin.MacroInstaller

xor(ShapeRoi) - Method in class ij.gui.ShapeRoi

Unary exclusive or operator.

XOR - Static variable in interface ij.process.Blitter

dst=dst XOR src

xor(int) - Method in class ij.process.FloatProcessor

xor(int) - Method in class ij.process.ImageProcessor

Binary exclusive OR of each pixel in the image or ROI with 'value'.

xor(int) - Method in class ij.process.ShortProcessor

xOrigin - Variable in class ij.measure.Calibration

X origin in pixels.

xpoints - Variable in class ij.gui.Wand

The x-coordinates of the points in the outline.

xpoints - Variable in class ij.process.FloatPolygon

xstart - Variable in class ij.process.ImageStatistics

Used internally by AnalyzeParticles

XY_Reader - Class in ij.plugin

This plugin implements the File/Import/XY Coordinates command.

XY_Reader() - Constructor for class ij.plugin.XY_Reader

XYCoordinates - Class in ij.plugin

Writes the XY coordinates and pixel values of all non-background pixels
        to a tab-delimited text file.

XYCoordinates() - Constructor for class ij.plugin.XYCoordinates

XYWriter - Class in ij.plugin.filter

Saves the XY coordinates of the current ROI boundary.

XYWriter() - Constructor for class ij.plugin.filter.XYWriter

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes


text:
package main

import (
	"fmt"
	"net"
	"os"
	"time"
)

const (
	MAX_CONN_NUM = 5
)

//echo server Goroutine
func EchoFunc(conn net.Conn, conn_close_flag chan int) {
	defer conn.Close()
	defer func() {
		conn_close_flag <- -1
	}()
	buf := make([]byte, 1024)
	for {
		_, err := conn.Read(buf)
		if err != nil {
			//println("Error reading:", err.Error())
			return
		}
		//send reply
		_, err = conn.Write(buf)
		if err != nil {
			//println("Error send reply:", err.Error())

			return

		}

	}

}

//initial listener and run
func main() {
	listener, err := net.Listen("tcp", "0.0.0.0:8088")
	if err != nil {
		println("error listening:", err.Error())
		os.Exit(1)
	}
	defer listener.Close()
	fmt.Printf("running on port 8088 ...\n")
	var cur_conn_num float64 = 0
	ch_conn_change := make(chan int, MAX_CONN_NUM)
	tick := time.Tick(1e8)
	for {
		//read all close flags berfor accept new connection
		//TODO: better code to handle batch close?
		readmore := 1
		for readmore > 0 {
			select {
			case conn_change := <-ch_conn_change:
				cur_conn_num = cur_conn_num + float64(conn_change)
			default:
				readmore = 0
			}
		}
		//FIXME: tick block by listener.Accept()
		select {
		case <-tick:
			fmt.Printf("cur conn num: %f\n", cur_conn_num)

		default:
		}
		if cur_conn_num >= MAX_CONN_NUM {
			//reach MAX_CONN_NUM, waiting for exist connection close
			time.Sleep(time.Second)
		} else {
			//accept new connetion
			conn, err := listener.Accept()
			if err != nil {
				println("Error accept:", err.Error())
				return
			}
			cur_conn_num++
			go EchoFunc(conn, ch_conn_change)
		}
	}
}


text:
Caesar Cipher

Input your key, select your algorithm, type your message, and click Go.

<FORM onSubmit="" NAME="caesar">

Key (0-25)
<INPUT TYPE="text" NAME="key" SIZE="2" MAXLENGTH="2" VALUE="3">
Algorithm:
<INPUT type="radio" name="encrypt" value="encrypt" checked="true">Encrypt
<INPUT type="radio" name="encrypt" value="decrypt">Decrypt

Message (40 chars)
<INPUT TYPE="text" NAME="message" SIZE="40" VALUE="hello">

<INPUT TYPE="button" VALUE="Go" onClick='doCipher()'>

Result

</FORM>


text:
					Vault

					B&E Bank

		Simple  Fast  Secure

					<input type="text" class="login-input" id="name" placeholder="USERNAME" onblur="checkInput(this)" />

					<input type="password" class="login-input" id="password" placeholder="PASSWORD" onblur="checkInput(this)" />

LOGIN

B&E Technology


text:
package kodkod.engine.fol2sat;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import kodkod.ast.BinaryExpression;
import kodkod.ast.BinaryFormula;
import kodkod.ast.BinaryIntExpression;
import kodkod.ast.BinaryTempFormula;
import kodkod.ast.ComparisonFormula;
import kodkod.ast.Comprehension;
import kodkod.ast.ConstantExpression;
import kodkod.ast.ConstantFormula;
import kodkod.ast.Decl;
import kodkod.ast.Decls;
import kodkod.ast.ExprToIntCast;
import kodkod.ast.Expression;
import kodkod.ast.Formula;
import kodkod.ast.IfExpression;
import kodkod.ast.IfIntExpression;
import kodkod.ast.IntComparisonFormula;
import kodkod.ast.IntConstant;
import kodkod.ast.IntExpression;
import kodkod.ast.IntToExprCast;
import kodkod.ast.LeafExpression;
import kodkod.ast.MultiplicityFormula;
import kodkod.ast.NaryExpression;
import kodkod.ast.NaryFormula;
import kodkod.ast.NaryIntExpression;
import kodkod.ast.Node;
import kodkod.ast.NotFormula;
import kodkod.ast.ProjectExpression;
import kodkod.ast.QuantifiedFormula;
import kodkod.ast.Relation;
import kodkod.ast.RelationPredicate;
import kodkod.ast.SumExpression;
import kodkod.ast.TempExpression;
import kodkod.ast.UnaryExpression;
import kodkod.ast.UnaryIntExpression;
import kodkod.ast.UnaryTempFormula;
import kodkod.ast.Variable;
import kodkod.ast.operator.ExprCompOperator;
import kodkod.ast.operator.ExprOperator;
import kodkod.ast.operator.FormulaOperator;
import kodkod.ast.operator.Multiplicity;
import kodkod.ast.operator.Quantifier;
import kodkod.ast.operator.TemporalOperator;
import kodkod.ast.visitor.ReturnVisitor;
import kodkod.engine.bool.BooleanAccumulator;
import kodkod.engine.bool.BooleanConstant;
import kodkod.engine.bool.BooleanFactory;
import kodkod.engine.bool.BooleanMatrix;
import kodkod.engine.bool.BooleanValue;
import kodkod.engine.bool.Dimensions;
import kodkod.engine.bool.Int;
import kodkod.engine.bool.Operator;
import kodkod.util.ints.IndexedEntry;
import kodkod.util.ints.IntIterator;
import kodkod.util.ints.IntSet;
import kodkod.util.nodes.AnnotatedNode;
import kodkod.util.nodes.Nodes;

/**
 * Translates an annotated node to boolean representation.
 * @specfield node: AnnotatedNode<? extends Node> // node to translate
 * @specfield interpreter: LeafInterpreter // the interpreter used for translation
 * @specfield env: Environment<BooleanMatrix> // current environment
 * @author Emina Torlak
 * @modified Nuno Macedo // [HASLab] temporal model finding
 */
abstract class FOL2BoolTranslator implements ReturnVisitor<BooleanMatrix, BooleanValue, Object, Int> {

	/**
	 * Translates the given annotated formula or expression into a boolean
	 * formula or matrix, using the provided interpreter.
	 * @requires interpreter.relations = AnnotatedNode.relations(annotated)
	 * @return {transl: T |
	 *           annotated.node in Formula => transl in BooleanValue,
	 *           annotated.node in Expression => transl in BooleanMatrix,
	 *           annotated.node in IntExpression => transl in Int}
	 * @throws HigherOrderDeclException  annotated.node contains a higher order declaration
	 * @throws UnboundLeafException  annotated.node refers to an undeclared variable
	 **/
	@SuppressWarnings("unchecked")
	static final <T> T translate(AnnotatedNode<? extends Node> annotated, LeafInterpreter interpreter) {
		final FOL2BoolCache cache = new FOL2BoolCache(annotated);
		final FOL2BoolTranslator translator = new FOL2BoolTranslator(cache, interpreter) {};
		return (T) annotated.node().accept(translator);
	}

	/**
	 * Translates the given annotated formula into a boolean
	 * accumulator with respect to the given interpreter and logs the translation events to the given logger.
	 * @requires interpreter.relations = AnnotatedNode.relations(annotated)
	 * @requires annotated.source[annotated.sourceSensitiveRoots()] = Nodes.roots(annotated.source[annotated.node])
	 * @return BooleanAccumulator that is the meaning of the given annotated formula with respect to the given interpreter
	 * @ensures log.records' contains the translation events that occurred while generating the returned value
	 * @throws HigherOrderDeclException  annotated.node contains a higher order declaration
	 * @throws UnboundLeafException  annotated.node refers to an undeclared variable
	 **/
	static final BooleanAccumulator translate(final AnnotatedNode<Formula> annotated, LeafInterpreter interpreter, final TranslationLogger logger) {
		final FOL2BoolCache cache = new FOL2BoolCache(annotated);
		final FOL2BoolTranslator translator = new FOL2BoolTranslator(cache, interpreter) {
			BooleanValue cache(Formula formula, BooleanValue translation) {
				logger.log(formula, translation, super.env);
				return super.cache(formula, translation);
			}
		};
		final BooleanAccumulator acc = BooleanAccumulator.treeGate(Operator.AND);

		for(Formula root : Nodes.conjuncts(annotated.node())) {
			acc.add(root.accept(translator));
		}
		logger.close();
		return acc;
	}

	/**
	 * Translates the given annotated expression into a boolean
	 * matrix that is a least sound upper bound on the expression's
	 * value, given the leaf and variable bindings in the
	 * the provided interpreter and environment.
	 * @requires interpreter.relations = AnnotatedNode.relations(annotated)
	 * @return a boolean matrix that is a least sound upper bound on the expression's value
	 * @throws HigherOrderDeclException  annotated.node contains a higher order declaration
	 * @throws UnboundLeafException  annotated.node refers to a variable that neither declared nor bound in env
	 **/
	static final BooleanMatrix approximate(AnnotatedNode<Expression> annotated, LeafInterpreter interpreter, Environment<BooleanMatrix, Expression> env) {
		final FOL2BoolTranslator approximator = new FOL2BoolTranslator(new FOL2BoolCache(annotated), interpreter, env) {
			public final BooleanMatrix visit(BinaryExpression binExpr) {
				final BooleanMatrix ret = lookup(binExpr);
				if (ret!=null) return ret;
				switch(binExpr.op()){
				case DIFFERENCE	: return cache(binExpr, binExpr.left().accept(this));
				case OVERRIDE  	: return cache(binExpr, binExpr.left().accept(this).or(binExpr.right().accept(this)));
				default			: return super.visit(binExpr);
				}
			}
			public final BooleanMatrix visit(Comprehension cexpr) {
				final BooleanMatrix ret = lookup(cexpr);
				return ret!=null ? ret : cache(cexpr, super.visit((Comprehension)Formula.TRUE.comprehension(cexpr.decls())));
			}
			public BooleanMatrix visit(IfExpression ifExpr) {
				final BooleanMatrix ret = lookup(ifExpr);
				return ret!=null ? ret : cache(ifExpr, ifExpr.thenExpr().accept(this).or(ifExpr.elseExpr().accept(this)));
			}
			public BooleanMatrix visit(IntToExprCast castExpr) {
				BooleanMatrix ret = lookup(castExpr);
				if (ret!=null) return ret;
				switch(castExpr.op()) {
				case INTCAST	: return cache(castExpr, Expression.INTS.accept(this));
				case BITSETCAST	:
					final BooleanFactory factory = super.interpreter.factory();
					ret = factory.matrix(Dimensions.square(super.interpreter.universe().size(), 1));
					final IntSet ints = super.interpreter.ints();
					final int msb = factory.bitwidth()-1;
					// handle all bits but the sign bit
					for(int i = 0; i < msb; i++) {
						int pow2 = 1<<i;
						if (ints.contains(pow2)) {
							ret.set(super.interpreter.interpret(pow2), BooleanConstant.TRUE);
						}
					}
					// handle the sign bit
					if (ints.contains(-1<<msb)) {
						ret.set(super.interpreter.interpret(-1<<msb), BooleanConstant.TRUE);
					}
					return cache(castExpr, ret);
				default : throw new IllegalArgumentException("Unknown operator: " + castExpr.op());
				}

			}
		};
		return annotated.node().accept(approximator);
	}

	/*---------------------------------------------------------*/

	private final LeafInterpreter interpreter;
	/* When visiting the body of a quantified formula or a comprehension, this
	 * environment contains the current values of the enclosing quantified variable(s),
	 * as well as overflow circuits accumulated during execution */
	private Environment<BooleanMatrix, Expression> env; // [AM] everywhere

	private final FOL2BoolCache cache;

	/* Holds variables discovered while visiting an expression to be cast to Int.
     * (because, for the new "overflow" semantics of quantifiers, we want to know the
     * variables that contribute to every Int */
    //[AM]
    private NestedSet<Variable> vars = NestedSet.empty();

	private final Map<LeafExpression, BooleanMatrix> leafCache;

	/**
	 * Constructs a new translator that will use the given translation cache
	 * and interpreter to perform the translation.
	 * @ensures this.node' = manager.node
	 */
	private FOL2BoolTranslator(FOL2BoolCache cache,  LeafInterpreter interpreter) {
	    this.cache = cache;
		this.interpreter = interpreter;
		this.env = Environment.empty();
		this.leafCache = new HashMap<LeafExpression, BooleanMatrix>(64);
	}

	/**
	 * Constructs a new translator that will use the given translation cache,
	 * interpreter and environment to perform the translation.
	 * @ensures this.node' = manager.node
	 */
	private FOL2BoolTranslator(FOL2BoolCache cache,  LeafInterpreter interpreter, Environment<BooleanMatrix, Expression> env) {
		this.interpreter = interpreter;
		this.env = env;
		this.cache = cache;
		this.leafCache = new HashMap<LeafExpression, BooleanMatrix>(64);
	}

	/**
	 * Retrieves the cached translation for the given node, if any.
	 * Otherwise returns null.
	 * @return the cached translation for the given node, if any.
	 * Otherwise returns null.
	 */
	@SuppressWarnings("unchecked")
	final <T> T lookup(Node node) {
		return (T) cache.lookup(node, env);
	}

	/**
	 * The translation is cached, if necessary, and returned.
	 * @return translation
	 * @ensures the translation may be cached
	 */
	final <T> T cache(Node node, T translation) {
		return cache.cache(node, translation, env);
	}

	/**
	 * The translation is cached, if necessary, and returned.
	 * @return translation
	 * @ensures the translation may be cached
	 */
	BooleanValue cache(Formula formula, BooleanValue translation) {
		return cache.cache(formula, translation, env);
	}

	/**
	 * Calls lookup(decls) and returns the cached value, if any.
	 * If a translation has not been cached, translates decls into a list
	 * of translations of its children,
	 * calls cache(...) on it and returns it.
	 * @return let t = lookup(decls) |
	 *   some t => t, cache(decl, decls.declarations.expression.accept(this))
	 */
	public final List<BooleanMatrix> visit(Decls decls) {
		List<BooleanMatrix> ret = lookup(decls);
		if (ret!=null) return ret;
		ret = new ArrayList<BooleanMatrix>(decls.size());
		for(Decl decl : decls) {
			ret.add(visit(decl));
		}
		return cache(decls, ret);
	}

	/**
	 * Calls lookup(decl) and returns the cached value, if any.
	 * If a translation has not been cached, translates decl.expression,
	 * calls cache(...) on it and returns it.
	 * @return let t = lookup(decl) |
	 *   some t => t, cache(decl, decl.expression.accept(this))
	 */
	public final BooleanMatrix visit(Decl decl) {
		BooleanMatrix matrix = lookup(decl);
		if (matrix!=null) return matrix;
		if (decl.multiplicity()!=Multiplicity.ONE)
			throw new HigherOrderDeclException(decl);
		return cache(decl, decl.expression().accept(this));
	}

	/**
	 * Calls this.env.lookup(variable) and returns the current binding for the
	 * given variable and adds it to the current level of nested variables (cars).
	 * If no binding is found, an UnboundLeafException is thrown.
	 * @return this.env.lookup(variable)
	 * @throws UnboundLeafException  no this.env.lookup(variable)
	 */
	// [AM]
	public final BooleanMatrix visit(Variable variable) {
		final BooleanMatrix ret = env.lookup(variable);
		if (ret == null)
		    throw new UnboundLeafException("Unbound variable", variable);
		vars.add(variable);
		return ret;
	}

	/**
	 * Returns this.interpreter.interpret(relation).
	 * @return this.interpreter.interpret(relation)
	 */
	public final BooleanMatrix visit(Relation relation) {
		BooleanMatrix ret = leafCache.get(relation);
		if (ret==null) {
			ret = interpreter.interpret(relation);
			leafCache.put(relation, ret);
		}
		return ret;
	}

	/**
	 * Returns this.interpreter.interpret(constExpr).
	 * @return this.interpreter.interpret(constExpr).
	 */
	public final BooleanMatrix visit(ConstantExpression constExpr) {
		BooleanMatrix ret = leafCache.get(constExpr);
		if (ret==null) {
			ret = interpreter.interpret(constExpr);
			leafCache.put(constExpr, ret);
		}
		return ret;
	}

	/**
	 * Calls lookup(binExpr) and returns the cached value, if any.
	 * If a translation has not been cached, translates the expression,
	 * calls cache(...) on it and returns it.
	 * @return let t = lookup(binExpr) | some t => t,
	 *      let op = (binExpr.op).(UNION->or + INTERSECTION->and + DIFFERENCE->difference + OVERRIDE->override + JOIN->dot + PRODUCT->cross) |
	 *       cache(binExpr, op(binExpr.left.accept(this), binExpr.right.accept(this)))
	 */
	public BooleanMatrix visit(BinaryExpression binExpr) {
		BooleanMatrix ret = lookup(binExpr);
		if (ret!=null) return ret;

		final BooleanMatrix left = binExpr.left().accept(this);
		final BooleanMatrix right = binExpr.right().accept(this);
		final ExprOperator op = binExpr.op();

		switch(op) {
		case UNION        	: ret = left.or(right); break;
		case INTERSECTION	: ret = left.and(right); break;
		case DIFFERENCE 	: ret = left.difference(right); break;
		case OVERRIDE 		: ret = left.override(right); break;
		case JOIN 			: ret = left.dot(right); break;
		case PRODUCT		: ret = left.cross(right); break;
		default :
			throw new IllegalArgumentException("Unknown operator: " + op);
		}

		return cache(binExpr, ret);
	}

	/**
	 * Calls lookup(expr) and returns the cached value, if any.
	 * If a translation has not been cached, translates the expression,
	 * calls cache(...) on it and returns it.
	 * @return let t = lookup(expr) | some t => t,
	 *      let op = (expr.op).(UNION->or + INTERSECTION->and + DIFFERENCE->difference + OVERRIDE->override + JOIN->dot + PRODUCT->cross) |
	 *       cache(expr, op(expr.left.accept(this), expr.right.accept(this)))
	 */
	public BooleanMatrix visit(NaryExpression expr) {
		BooleanMatrix ret = lookup(expr);
		if (ret!=null) return ret;

		final ExprOperator op = expr.op();
		final BooleanMatrix first = expr.child(0).accept(this);
		final BooleanMatrix[] rest = new BooleanMatrix[expr.size()-1];
		for(int i = 0; i < rest.length; i++) { 	rest[i] = expr.child(i+1).accept(this); }

		switch(op) {
		case UNION        	: ret = first.or(rest); break;
		case INTERSECTION	: ret = first.and(rest); break;
		case OVERRIDE 		: ret = first.override(rest); break;
		case PRODUCT		: ret = first.cross(rest); break;
		default :
			throw new IllegalArgumentException("Unknown associative operator: " + op);
		}

		return cache(expr, ret);
	}

	/**
	 * Calls lookup(unaryExpr) and returns the cached value, if any.
	 * If a translation has not been cached, translates the expression,
	 * calls cache(...) on it and returns it.
	 * @return let t = lookup(unaryExpr) | some t => t,
	 *      let op = (unaryExpr.op).(TRANSPOSE->transpose + CLOSURE->closure + REFLEXIVE_CLOSURE->(lambda(m)(m.closure().or(iden))) |
	 *       cache(unaryExpr, op(unaryExpr.child))
	 */
	public final BooleanMatrix visit(UnaryExpression unaryExpr) {
		BooleanMatrix ret = lookup(unaryExpr);
		if (ret!=null) return ret;

		final BooleanMatrix child = unaryExpr.expression().accept(this);
		final ExprOperator op = unaryExpr.op();

		switch(op) {
		case TRANSPOSE         	: ret = child.transpose(); break;
		case CLOSURE           	: ret = child.closure(); break;
		case REFLEXIVE_CLOSURE	: ret = child.closure().or(visit((ConstantExpression)Expression.IDEN)); break;
		default :
			throw new IllegalArgumentException("Unknown operator: " + op);
		}
		return cache(unaryExpr,ret);
	}

	/**
	 * Translates the given comprehension as follows
	 * (where A_0...A_|A| stand for boolean variables that represent the
	 * tuples of the expression A, etc.):
	 * let comprehension = "{ a: A, b: B, ..., x: X | F(a, b, ..., x) }" |
	 *     { a: A, b: B, ..., x: X | a in A && b in B && ... && x in X && F(a, b, ..., x) }.
	 * @param decls the declarations comprehension
	 * @param param formula the body of the comprehension
	 * @param currentDecl currently processed declaration; should be 0 initially
	 * @param declConstraints the constraints implied by the declarations; should be Boolean.TRUE intially
	 * @param partialIndex partial index into the provided matrix; should be 0 initially
	 * @param matrix boolean matrix that will retain the final results; should be an empty matrix of dimensions universe.size^decls.length initially
	 * @ensures the given matrix contains the translation of the comprehension "{ decls | formula }"
	 */
	private final void comprehension(Decls decls, Formula formula, int currentDecl,
			BooleanValue declConstraints, int partialIndex, BooleanMatrix matrix) {
		final BooleanFactory factory = interpreter.factory();

		if (currentDecl==decls.size()) {
		    //TODO: what about this and overflow???
			matrix.set(partialIndex, factory.and(declConstraints, formula.accept(this)));
			return;
		}

		final Decl decl = decls.get(currentDecl);
		final BooleanMatrix declTransl = visit(decl);
		final int position = (int)StrictMath.pow(interpreter.universe().size(), decls.size()-currentDecl-1);
		final BooleanMatrix groundValue = factory.matrix(declTransl.dimensions());
		env = env.extend(decl.variable(), decl.expression(), groundValue);
		for(IndexedEntry<BooleanValue> entry : declTransl) {
			groundValue.set(entry.index(), BooleanConstant.TRUE);
			comprehension(decls, formula, currentDecl+1, factory.and(entry.value(), declConstraints),
					partialIndex + entry.index()*position, matrix);
			groundValue.set(entry.index(), BooleanConstant.FALSE);
		}
		env = env.parent();
	}

	/**
	 * Calls lookup(cexpr) and returns the cached value, if any.
	 * If a translation has not been cached, translates the expression,
	 * calls cache(...) on it and returns it.
	 * @return let t = lookup(cexpr) | some t => t,
	 *      cache(cexpr, translate(cexpr))
	 */
	public BooleanMatrix visit(Comprehension cexpr) {
		BooleanMatrix ret = lookup(cexpr);
		if (ret!=null) return ret;

		ret = interpreter.factory().matrix(Dimensions.square(interpreter.universe().size(), cexpr.decls().size()));
		comprehension(cexpr.decls(), cexpr.formula(), 0, BooleanConstant.TRUE, 0, ret);

		return cache(cexpr,ret);
	}

	/**
	 * Calls lookup(ifExpr) and returns the cached value, if any.
	 * If a translation has not been cached, translates the expression,
	 * calls cache(...) on it and returns it.
	 * @return let t = lookup(ifExpr) | some t => t,
	 * 			cache(ifExpr, ifExpr.condition.accept(this).choice(ifExpr.then.accept(this), ifExpr.else.accept(this)))
	 */
	public BooleanMatrix visit(IfExpression ifExpr) {
		BooleanMatrix ret = lookup(ifExpr);
		if (ret!=null) return ret;

		final BooleanValue condition = ifExpr.condition().accept(this);
		final BooleanMatrix thenExpr = ifExpr.thenExpr().accept(this);
		final BooleanMatrix elseExpr = ifExpr.elseExpr().accept(this);
		ret = thenExpr.choice(condition, elseExpr);

		return cache(ifExpr,ret);
	}

	/**
	 * Calls lookup(project) and returns the cached value, if any.
	 * If a translation has not been cached, translates the expression,
	 * calls cache(...) on it and returns it.
	 * @return let t = lookup(project) | some t => t,
	 * 			cache(project, project.expression.accept(this).project(translate(project.columns))
	 */
	public final BooleanMatrix visit(ProjectExpression project) {
		BooleanMatrix ret = lookup(project);
		if (ret!=null) return ret;

		final Int[] cols = new Int[project.arity()];
		for(int i = 0, arity = project.arity(); i < arity; i++) {
			cols[i] = project.column(i).accept(this);
		}

		return cache(project, project.expression().accept(this).project(cols));
	}

	/**
	 * @return constant = ConstantFormula.TRUE => BooleanConstant.TRUE, BooleanConstant.FALSE
	 */
	public final BooleanValue visit(ConstantFormula constant) {
		return cache(constant, BooleanConstant.constant(constant.booleanValue()));
	}

	/**
	 * Translates the given universally quantified formula as follows
	 * (where A_0...A_|A| stand for boolean variables that represent the
	 * tuples of the expression A, etc.):
	 *
	 * let quantFormula = "all a: A, b: B, ..., x: X | F(a, b, ..., x)" |
	 *     (A_0 && B_0 && ... && X_0 => translate(F(A_0, B_0, ..., X_0))) && ... &&
	 *     (A_|A| && B_|B| && ... && X_|X| => translate(F(A_|A|, B_|B|, ..., X_|X|)))
	 *
	 * If the noOverflow option is specified, then the translation looks like:
	 *
	 * let quantFormula = "all a: A, b: B, ..., x: X | F(a, b, ..., x)" |
     *     (A_0 && B_0 && ... && X_0 => (!of(F(A_0, B_0, ..., X_0)) => translate(F(A_0, B_0, ..., X_0)))) && ... &&
     *     (A_|A| && B_|B| && ... && X_|X| => (!of(F(A_|A|, B_|B|, ..., X_|X|)) => translate(F(A_|A|, B_|B|, ..., X_|X|))))
	 *
	 * where of(F(A_|a|, B_|b|, ..., X_|x|)) is the portion of the overflow circuit generated by the translation of
	 * F(A_|a|, B_|b|, ..., X_|x|) contributed by arithmetic operations over only the integer variables of this quantifier
	 *
	 * @param decls formula declarations
	 * @param formula the formula body
	 * @param currentDecl currently processed declaration; should be 0 initially
	 * @param declConstraints the constraints implied by the declarations; should be Boolean.FALSE initially
	 * @param acc the accumulator that contains the top level conjunction; should be an empty AND accumulator initially
	 * @ensures the given accumulator contains the translation of the formula "all decls | formula"
	 */
	private void all(Decls decls, Formula formula, int currentDecl, BooleanValue declConstraints, BooleanAccumulator acc) {
		if (acc.isShortCircuited()) return;
		final BooleanFactory factory = interpreter.factory();

		if (decls.size()==currentDecl) {
		    BooleanValue formulaCircuit = formula.accept(this);
            BooleanValue finalCircuit = factory.or(declConstraints, formulaCircuit);
            acc.add(finalCircuit);
			return;
		}

		final Decl decl = decls.get(currentDecl);
		final BooleanMatrix declTransl = visit(decl);
		final BooleanMatrix groundValue = factory.matrix(declTransl.dimensions());
		env = env.extend(decl.variable(), decl.expression(), groundValue, Quantifier.ALL);
		for(IndexedEntry<BooleanValue> entry : declTransl) {
		    groundValue.set(entry.index(), BooleanConstant.TRUE);
			all(decls, formula, currentDecl+1, factory.or(factory.not(entry.value()), declConstraints), acc);
			groundValue.set(entry.index(), BooleanConstant.FALSE);
		}
		env = env.parent();
	}

    /**
	 * Translates the given existentially quantified formula as follows
	 * (where A_0...A_|A| stand for boolean variables that represent the
	 * tuples of the expression A, etc.):
	 *
	 * let quantFormula = "some a: A, b: B, ..., x: X | F(a, b, ..., x)" |
	 *     (A_0 && B_0 && ... && X_0 && translate(F(A_0, B_0, ..., X_0))) || ... ||
	 *     (A_|A| && B_|B| && ... && X_|X| && translate(F(A_|A|, B_|B|, ..., X_|X|))
	 *
	 * If the noOverflow option is specified, then the translation looks like:
     *
     * let quantFormula = "some a: A, b: B, ..., x: X | F(a, b, ..., x)" |
     *     (A_0 && B_0 && ... && X_0 && !of(F(A_0, B_0, ..., X_0)) && translate(F(A_0, B_0, ..., X_0))) || ... ||
     *     (A_|A| && B_|B| && ... && X_|X| && !of(F(A_|A|, B_|B|, ..., X_|X|)) && translate(F(A_|A|, B_|B|, ..., X_|X|))
     *
	 * where of(F(A_|a|, B_|b|, ..., X_|x|)) is the portion of the overflow circuit generated by the translation of
     * F(A_|a|, B_|b|, ..., X_|x|) contributed by arithmetic operations over only the integer variables of this quantifier
     *
	 * @param decls formula declarations
	 * @param formula the formula body
	 * @param currentDecl currently processed declaration; should be 0 initially
	 * @param declConstraints the constraints implied by the declarations; should be Boolean.TRUE intially
	 * @param acc the accumulator that contains the top level conjunction; should be an empty OR accumulator initially
	 * @ensures the given accumulator contains the translation of the formula "some decls | formula"
	 */
	private void some(Decls decls, Formula formula, int currentDecl, BooleanValue declConstraints, BooleanAccumulator acc) {
		if (acc.isShortCircuited()) return;
		final BooleanFactory factory = interpreter.factory();

		if (decls.size()==currentDecl) {
			BooleanValue formulaCircuit = formula.accept(this);
            BooleanValue finalCircuit = factory.and(declConstraints, formulaCircuit);
            acc.add(finalCircuit);
            return;
		}

		final Decl decl = decls.get(currentDecl);
		final BooleanMatrix declTransl = visit(decl);
		final BooleanMatrix groundValue = factory.matrix(declTransl.dimensions());
		env = env.extend(decl.variable(), decl.expression(), groundValue, Quantifier.SOME);
		for(IndexedEntry<BooleanValue> entry : declTransl) {
			groundValue.set(entry.index(), BooleanConstant.TRUE);
			some(decls, formula, currentDecl+1, factory.and(entry.value(), declConstraints), acc);
			groundValue.set(entry.index(), BooleanConstant.FALSE);
		}
		env = env.parent();
	}

	/**
	 * Calls lookup(quantFormula) and returns the cached value, if any.
	 * If a translation has not been cached, translates the formula,
	 * calls cache(...) on it and returns it.
	 * @return let t = lookup(quantFormula) | some t => t,
	 *   cache(quantFormula, translate(quantFormula))
	 */
	public final BooleanValue visit(QuantifiedFormula quantFormula) {
		BooleanValue ret = lookup(quantFormula);
		if (ret!=null) return ret;

		final Quantifier quantifier = quantFormula.quantifier();
		switch(quantifier) {
		case ALL		:
			final BooleanAccumulator and = BooleanAccumulator.treeGate(Operator.AND);
			all(quantFormula.decls(), quantFormula.formula(), 0, BooleanConstant.FALSE, and);
			ret = interpreter.factory().accumulate(and);
			break;
		case SOME	:
			final BooleanAccumulator or = BooleanAccumulator.treeGate(Operator.OR);
			some(quantFormula.decls(), quantFormula.formula(), 0, BooleanConstant.TRUE, or);
			ret = interpreter.factory().accumulate(or);
			break;
		default :
			throw new IllegalArgumentException("Unknown quantifier: " + quantifier);
		}
		return cache(quantFormula,ret);
	}

	/**
	 * Calls lookup(formula) and returns the cached value, if any.
	 * If a translation has not been cached, translates the formula,
	 * calls cache(...) on it and returns it.
	 * @return let t = lookup(formula) | some t => t,
	 * 	cache(formula, formula.op(formula.left.accept(this), formula.right.accept(this))
	 */
	public final BooleanValue visit(NaryFormula formula) {
		final BooleanValue ret = lookup(formula);
		if (ret!=null) return ret;

		final FormulaOperator op = formula.op();
		final Operator.Nary boolOp;

		switch(op) {
		case AND : boolOp = Operator.AND; break;
		case OR  : boolOp = Operator.OR;  break;
		default	 : throw new IllegalArgumentException("Unknown nary operator: " + op);
		}

		final BooleanAccumulator acc = BooleanAccumulator.treeGate(boolOp);
		final BooleanValue shortCircuit = boolOp.shortCircuit();
		for(Formula child : formula) {
			if (acc.add(child.accept(this))==shortCircuit)
				break;
		}

		return cache(formula, interpreter.factory().accumulate(acc));
	}

	/**
	 * Calls lookup(binFormula) and returns the cached value, if any.
	 * If a translation has not been cached, translates the formula,
	 * calls cache(...) on it and returns it.
	 * @return let t = lookup(binFormula) | some t => t,
	 * 	cache(binFormula, binFormula.op(binFormula.left.accept(this), binFormula.right.accept(this))
	 */
	public final BooleanValue visit(BinaryFormula binFormula) {
		BooleanValue ret = lookup(binFormula);
		if (ret!=null) return ret;

		final BooleanValue left = binFormula.left().accept(this);
		final BooleanValue right = binFormula.right().accept(this);
		final FormulaOperator op = binFormula.op();
		final BooleanFactory f = interpreter.factory();

		switch(op) {
		case AND		: ret = f.and(left, right); break;
		case OR			: ret = f.or(left, right); break;
		case IMPLIES	: ret = f.implies(left, right); break;
		case IFF		: ret = f.iff(left, right); break;
		default :
			throw new IllegalArgumentException("Unknown operator: " + op);
		}
		return cache(binFormula, ret);
	}

	/**
	 * Calls lookup(not) and returns the cached value, if any.
	 * If a translation has not been cached, translates the formula,
	 * calls cache(...) on it and returns it.
	 * @return let t = lookup(not) | some t => t,
	 * 	cache(not, !not.formula.accept(this))
	 */
	public final BooleanValue visit(NotFormula not) {
		BooleanValue ret = lookup(not);
		if (ret != null)
		    return ret;
		env.negate();
		ret = cache(not, interpreter.factory().not(not.formula().accept(this)));
		env.negate();
		return ret;
	}

	/**
	 * Calls lookup(compFormula) and returns the cached value, if any.
	 * If a translation has not been cached, translates the formula,
	 * calls cache(...) on it and returns it.
	 * @return let t = lookup(compFormula) | some t => t,
	 *      let op = (binExpr.op).(SUBSET->subset + EQUALS->eq) |
	 *       cache(compFormula, op(compFormula.left.accept(this), compFormula.right.accept(this)))
	 */
	public final BooleanValue visit(ComparisonFormula compFormula) {
		BooleanValue ret = lookup(compFormula);
		if (ret!=null) return ret;

		final BooleanMatrix left = compFormula.left().accept(this);
		final BooleanMatrix right = compFormula.right().accept(this);
		final ExprCompOperator op = compFormula.op();

		switch(op) {
		case SUBSET	: ret = left.subset(right, env); break;
		case EQUALS	: ret = left.eq(right, env); break;
		default :
			throw new IllegalArgumentException("Unknown operator: " + compFormula.op());
		}
		return cache(compFormula,ret);
	}

	/**
	 * Calls lookup(multFormula) and returns the cached value, if any.
	 * If a translation has not been cached, translates the formula,
	 * calls cache(...) on it and returns it.
	 * @return let t = lookup(multFormula) | some t => t,
	 *      let op = (multFormula.mult).(NO->none + SOME->some + ONE->one + LONE->lone) |
	 *       cache(multFormula, op(multFormula.expression.accept(this)))
	 */
	public final BooleanValue visit(MultiplicityFormula multFormula) {
		BooleanValue ret = lookup(multFormula);
		if (ret!=null) return ret;

		final BooleanMatrix child = multFormula.expression().accept(this);
		final Multiplicity mult = multFormula.multiplicity();

		switch(mult) {
		case NO 	: ret = child.none(env); break;
		case SOME	: ret = child.some(env); break;
		case ONE 	: ret = child.one(env);  break;
		case LONE 	: ret = child.lone(env); break;
		default :
			throw new IllegalArgumentException("Unknown multiplicity: " + mult);
		}

		return cache(multFormula, ret);
	}

	/**
	 * Calls lookup(pred) and returns the cached value, if any.
	 * If a translation has not been cached, translates the expression,
	 * calls cache(...) on it and returns it.
	 * @return let t = lookup(pred) | some t => t,
	 * 	cache(pred, pred.toConstraints().accept(this))
	 */
	public final BooleanValue visit(RelationPredicate pred) {
		BooleanValue ret = lookup(pred);
		return ret != null ? ret : cache(pred, pred.toConstraints().accept(this));
	}

	/**
	 * Calls lookup(castExpr) and returns the cached value, if any.
	 * If a translation has not been cached, translates the expression,
	 * calls cache(...) on it and returns it.
	 * @return let t = lookup(castExpr) | some t => t,
	 * 	cache(castExpr, translate(castExpr))
	 */
	public BooleanMatrix visit(IntToExprCast castExpr) {
		BooleanMatrix ret = lookup(castExpr);
		if (ret!=null) return ret;

		final Int child = castExpr.intExpr().accept(this);
		final BooleanFactory factory =  interpreter.factory();
		final IntSet ints = interpreter.ints();

		ret = factory.matrix(Dimensions.square(interpreter.universe().size(), 1));

		switch(castExpr.op()) {
		case INTCAST :
			for(IntIterator iter = ints.iterator(); iter.hasNext(); ) {
				int i = iter.next();
				int atomIndex = interpreter.interpret(i);
				ret.set(atomIndex, factory.or(ret.get(atomIndex), child.eq(factory.integer(i))));
			}
			ret.setDefCond(child.defCond());
			break;
		case BITSETCAST :
			final List<BooleanValue> twosComplement = child.twosComplementBits();
			final int msb = twosComplement.size()-1;
			// handle all bits but the sign bit
			for(int i = 0; i < msb; i++) {
				int pow2 = 1<<i;
				if (ints.contains(pow2)) {
					ret.set(interpreter.interpret(pow2), twosComplement.get(i));
				}
			}
			// handle the sign bit
			if (ints.contains(-1<<msb)) {
				ret.set(interpreter.interpret(-1<<msb), twosComplement.get(msb));
			}
			break;
		default :
			throw new IllegalArgumentException("Unknown cast operator: " + castExpr.op());
		}

		return cache(castExpr, ret);
	}

	/**
	 * @return this.interpreter.factory.integer(intConst.value)
	 */
	public final Int visit(IntConstant intConst) {
		Int ret = interpreter.factory().integer(intConst.value());
		return ret;
	}

	/**
	 * Calls lookup(intExpr) and returns the cached value, if any.
	 * If a translation has not been cached, translates the expression,
	 * calls cache(...) on it and returns it.
	 * @return let t = lookup(intExpr) | some t => t,
	 * 			cache(intExpr, intExpr.condition.accept(this).choice(intExpr.then.accept(this), intExpr.else.accept(this)))
	 */
	public final Int visit(IfIntExpression intExpr) {
		Int ret = lookup(intExpr);
		if (ret!=null) return ret;

		final BooleanValue condition = intExpr.condition().accept(this);
		final Int thenExpr = intExpr.thenExpr().accept(this);
		final Int elseExpr = intExpr.elseExpr().accept(this);
		ret = thenExpr.choice(condition, elseExpr);
		return cache(intExpr, ret);
	}

	/**
	 * Returns an Int that represents the sum of all the integers that
	 * correspond to non-FALSE entries in the given matrix.
	 * @param iter an iterator over all the bound integers.  Initial should be this.manager.ints().iterator().
	 * @param lo the first element of the current partial sum. Initial should be 0.
	 * @param hi the last element of the current partial sum.  Initial should be size-1, where size is the total
	 * number of elements returned by the iterator.
	 * @return  an Int that represents the sum of all the integers that
	 * correspond to non-FALSE entries in the given matrix.
	 */
	private final Int sum(BooleanMatrix m, IntIterator iter, int low, int high) {
		if (low > high)
			return interpreter.factory().integer(0);
		else if (low==high) {
			int i = iter.next();
			return interpreter.factory().integer(i, m.get(interpreter.interpret(i)));
		} else {
			final int mid = (low + high) / 2;
			final Int lsum = sum(m, iter, low, mid);
			final Int hsum = sum(m, iter, mid+1, high);
			return lsum.plus(hsum);
		}
	}

	/**
	 * Calls lookup(intExpr) and returns the cached value, if any.
	 * If a translation has not been cached, translates the expression,
	 * calls cache(...) on it and returns it.
	 * @return let t = lookup(intExpr) | some t => t,
	 * 	cache(intExpr, translate(intExpr))
	 */
	// [AM]
	public final Int visit(ExprToIntCast intExpr) {
		Int ret = lookup(intExpr);
		if (ret!=null) return ret;
		vars = vars.createNested();
		BooleanMatrix expr = intExpr.expression().accept(this);
        switch(intExpr.op()) {
		case CARDINALITY :
			ret = expr.cardinality(); break;
		case SUM         :
			final IntSet ints = interpreter.ints();
			ret = sum(expr, ints.iterator(), 0, ints.size()-1); break;
		default:
			throw new IllegalArgumentException("unknown operator: " + intExpr.op());
		}
        for (Variable v : vars) ret.defCond().addVar(v);
        vars = vars.parent();
		return cache(intExpr, ret);
	}

	/**
	 * Calls lookup(intExpr) and returns the cached value, if any.
	 * If a translation has not been cached, translates the expression,
	 * calls cache(...) on it and returns it.
	 * @return let t = lookup(intExpr) | some t => t,
	 * 	cache(intExpr, intExpr.left.accept(this) intExpr.op intExpr.right.accept(this))
	 */
	public final Int visit(BinaryIntExpression intExpr) {
		Int ret = lookup(intExpr);
		if (ret!=null) return ret;
		final Int left = intExpr.left().accept(this);
		final Int right = intExpr.right().accept(this);
		switch(intExpr.op()) {
		case PLUS  		: ret = left.plus(right); break;
		case MINUS 		: ret = left.minus(right); break;
		case MULTIPLY 	: ret = left.multiply(right); break;
		case DIVIDE 	: ret = left.divide(right); break;
		case MODULO		: ret = left.modulo(right); break;
		case AND		: ret = left.and(right); break;
		case OR			: ret = left.or(right); break;
		case XOR		: ret = left.xor(right); break;
		case SHL		: ret = left.shl(right); break;
		case SHR		: ret = left.shr(right); break;
		case SHA		: ret = left.sha(right); break;
		default    :
			throw new IllegalArgumentException("Unknown operator: " + intExpr.op());
		}
		return cache(intExpr, ret);
	}

	/**
	 * Calls lookup(intExpr) and returns the cached value, if any.
	 * If a translation has not been cached, translates the expression,
	 * calls cache(...) on it and returns it.
	 * @return let t = lookup(intExpr) | some t => t,
	 * 	cache(intExpr, intExpr.left.accept(this) intExpr.op intExpr.right.accept(this))
	 */
	public final Int visit(NaryIntExpression intExpr) {
		Int ret = lookup(intExpr);
		if (ret!=null) return ret;
		final Int first = intExpr.child(0).accept(this);
		final Int[] rest = new Int[intExpr.size()-1];
		for(int i = 0; i < rest.length; i++) { 	rest[i] = intExpr.child(i+1).accept(this); }
		switch(intExpr.op()) {
		case PLUS  		: ret = first.plus(rest); break;
		case MULTIPLY 	: ret = first.multiply(rest); break;
		case AND		: ret = first.and(rest); break;
		case OR			: ret = first.or(rest); break;
		default    :
			throw new IllegalArgumentException("Unknown nary operator: " + intExpr.op());
		}
		return cache(intExpr, ret);
	}

	/**
	 * Calls lookup(intExpr) and returns the cached value, if any.
	 * If a translation has not been cached, translates the expression,
	 * calls cache(...) on it and returns it.
	 * @return let t = lookup(intExpr) | some t => t,
	 * 	cache(intExpr, intExpr.op(intExpr.expression.accept(this)))
	 */
	public final Int visit(UnaryIntExpression intExpr) {
		Int ret = lookup(intExpr);
		if (ret!=null) return ret;
		final Int child = intExpr.intExpr().accept(this);
		switch(intExpr.op()) {
		case NEG 	: ret = child.negate(); break;
		case NOT 	: ret = child.not(); break;
		case ABS 	: ret = child.abs(); break;
		case SGN 	: ret = child.sgn(); break;
		default :
			throw new IllegalArgumentException("Unknown operator: " + intExpr.op());
		}
		return cache(intExpr, ret);
	}

	/**
	 * Translates the given sum expression as follows
	 * (where A_0...A_|A| stand for boolean variables that represent the
	 * tuples of the expression A, etc.):
	 * let sum = "sum a: A, b: B, ..., x: X | IE(a, b, ..., x) " |
	 *     sum a: A, b: B, ..., x: X | if (a in A && b in B && ... && x in X) then IE(a, b, ..., x) else 0 }.
	 * @param decls intexpr declarations
	 * @param formula the formula body
	 * @param currentDecl currently processed declaration; should be 0 initially
	 * @param declConstraints the constraints implied by the declarations; should be Boolean.TRUE intially
	 * @param values integer values computed so far
	 */
	private final void sum(Decls decls, IntExpression expr, int currentDecl, BooleanValue declConstraints,
			List<Int> values) {
		final BooleanFactory factory = interpreter.factory();
		if (decls.size()==currentDecl) {
			Int intExpr = expr.accept(this);
            Int newInt = intExpr.choice(declConstraints, factory.integer(0));
            values.add(newInt);
			return;
		}

		final Decl decl = decls.get(currentDecl);
		final BooleanMatrix declTransl = visit(decl);
		final BooleanMatrix groundValue = factory.matrix(declTransl.dimensions());
		env = env.extend(decl.variable(), decl.expression(), groundValue);
		for(IndexedEntry<BooleanValue> entry : declTransl) {
			groundValue.set(entry.index(), BooleanConstant.TRUE);
			sum(decls, expr, currentDecl+1, factory.and(entry.value(), declConstraints), values);
			groundValue.set(entry.index(), BooleanConstant.FALSE);
		}
		env = env.parent();
	}

	/**
	 * Calls lookup(intExpr) and returns the cached value, if any.
	 * If a translation has not been cached, translates the expression,
	 * calls cache(...) on it and returns it.
	 * @return let t = lookup(intExpr) | some t => t,
	 * 	cache(intExpr, translate(intExpr))
	 */
	public final Int visit(SumExpression intExpr) {
		final Int ret = lookup(intExpr);
		if (ret!=null) return ret;
		final List<Int> values = new ArrayList<Int>();
		sum(intExpr.decls(), intExpr.intExpr(), 0, BooleanConstant.TRUE, values);
		for(int sums = values.size(); sums > 1; sums -= sums/2) {
			final int max = sums-1;
			for(int i = 0; i < max; i += 2) {
				values.set(i/2, values.get(i).plus(values.get(i+1)));
			}
			if (max%2==0) { // even max => odd number of entries
				values.set(max/2, values.get(max));
			}
		}
		if (values.isEmpty()) {
		    return cache(intExpr, interpreter.factory().integer(0));
		} else {
		    Int sumValue = values.get(0);
	        return cache(intExpr, sumValue);
		}
	}

	/**
	 * Calls lookup(intComp) and returns the cached value, if any.
	 * If a translation has not been cached, translates the formula,
	 * calls cache(...) on it and returns it.
	 *
	 * This is the only place where Ints are turned into
	 * formulas, so that's where the overflow circuits of individual
	 * Ints are built into the translated formula.
	 *
	 * @return let t = lookup(intComp) | some t => t,
	 * 	cache(intComp, intComp.left.accept(this) intComp.op intComp.right.accept(this))
	 */
	public final BooleanValue visit(IntComparisonFormula intComp) {
		BooleanValue ret = lookup(intComp);
		if (ret!=null) return ret;
		final Int left = intComp.left().accept(this);
		final Int right = intComp.right().accept(this);
		switch(intComp.op()) {
		case EQ  : ret = left.eq(right, env); break;
		case NEQ : ret = left.neq(right, env); break;
		case LT  : ret = left.lt(right, env); break;
		case LTE : ret = left.lte(right, env); break;
		case GT  : ret = left.gt(right, env); break;
		case GTE : ret = left.gte(right, env); break;
		default:
			throw new IllegalArgumentException("Unknown operator: " + intComp.op());
		}
		return cache(intComp, ret);
	}

	// [HASLab] will ignore the temporal operator and assume static version
	// Guarantees that the process terminates and is sound for static relations
	public final BooleanValue visit(UnaryTempFormula temporalFormula) {
		BooleanValue ret = temporalFormula.formula().accept(this);
		return cache(temporalFormula,ret);
	}

	// [HASLab] will ignore the temporal operator and assume static version
	// Guarantees that the process terminates and is sound for static relations
	public final BooleanValue visit(BinaryTempFormula temporalFormula) {
		Formula f;
		if (temporalFormula.op() == TemporalOperator.UNTIL)
			f = temporalFormula.right();
		else if (temporalFormula.op() == TemporalOperator.RELEASES)
			f = temporalFormula.left().or(temporalFormula.right());
		else
			f = temporalFormula.left();
		BooleanValue ret = f.accept(this);
		return cache(temporalFormula,ret);
	}

	// [HASLab] will ignore the temporal operator and assume static version
	// Guarantees that the process terminates and is sound for static relations
	public final BooleanMatrix visit(TempExpression temporalExpr) {
		BooleanMatrix ret = temporalExpr.expression().accept(this);
		return cache(temporalExpr,ret);
	}

}


text:
require "spec_helper"

describe StandardSkillRoutinePolicy do
  subject { described_class }

  let(:my_user) { FactoryBot.create(:user) }
  let(:my_registrant) { FactoryBot.create(:registrant, user: my_user) }
  let(:other_registrant) { FactoryBot.create(:registrant) }
  let(:my_routine) { FactoryBot.create(:standard_skill_routine, registrant: my_registrant) }
  let(:other_routine) { FactoryBot.create(:standard_skill_routine, registrant: other_registant) }
  let(:event_planner) { FactoryBot.create(:event_planner) }
  let(:std_director) { FactoryBot.create(:user) }
  let(:other_director) { FactoryBot.create(:user) }
  let(:standard_skill_event) { FactoryBot.create(:event, :standard_skill) }

  before do
    std_director.add_role :director, standard_skill_event
    other_director.add_role :director, FactoryBot.create(:event)
  end

  permissions :show? do
    it { expect(subject).to permit(my_user, my_routine) }
    it { expect(subject).not_to permit(other_registrant.user, my_routine) }
  end

  permissions :writing_judge?, :difficulty_judge?, :execution_judge? do
    it { expect(subject).to permit(event_planner, my_routine) }
    it { expect(subject).to permit(std_director, my_routine) }
    it { expect(subject).not_to permit(other_director, my_routine) }
  end

  describe "with a user context" do
    let(:reg_closed?) { false }
    let(:authorized_laptop?) { false }
    let(:user) { my_user }
    let(:standard_skill_closed?) { false }
    let(:config) { double(standard_skill_closed?: standard_skill_closed?) }
    let(:user_context) { UserContext.new(user, config, reg_closed?, reg_closed?, authorized_laptop?) }

    permissions :create? do
      it { expect(subject).to permit(user_context, my_routine) }
    end
  end
end


text:
pub struct MaskedStruct;

pub trait MaskedTrait {
    fn masked_method();
}

impl MaskedTrait for String {
    fn masked_method() {}
}


text:
<!DOCTYPE html>

		<title>three.js webgl - gpgpu - flocking</title>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">

			three.js -  webgl gpgpu birds

			Select  birds

			Move mouse to disturb birds.


text:
package au.com.scds.chats.dom.general.names;

import org.junit.Before;
import org.junit.Test;

import au.com.scds.chats.dom.general.names.ClassificationValue;

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

public class NameTest {

	private class ConcreteName extends ClassificationValue {

	}

	ConcreteName cname;

	@Before
	public void setUp() throws Exception {
		cname = new ConcreteName();
	}

	public static class Name extends NameTest {

		@Test
		public void happyCase() throws Exception {
			// given
			String name = "Foobar";
			assertThat(cname.getName()).isNull();

			// when
			cname.setName(name);

			// then
			assertThat(cname.getName()).isEqualTo(name);
		}
	}

}


text:
import unittest
from unittest import mock

from airflow.providers.google.cloud.transfers.adls_to_gcs import ADLSToGCSOperator

TASK_ID = 'test-adls-gcs-operator'
ADLS_PATH_1 = '*'
GCS_PATH = 'gs://test/'
MOCK_FILES = [
    "test/TEST1.csv",
    "test/TEST2.csv",
    "test/path/TEST3.csv",
    "test/path/PARQUET.parquet",
    "test/path/PIC.png",
]
AZURE_CONN_ID = 'azure_data_lake_default'
GCS_CONN_ID = 'google_cloud_default'
IMPERSONATION_CHAIN = ["ACCOUNT_1", "ACCOUNT_2", "ACCOUNT_3"]

class TestAdlsToGoogleCloudStorageOperator(unittest.TestCase):
    def test_init(self):
        """Test AdlsToGoogleCloudStorageOperator instance is properly initialized."""

        operator = ADLSToGCSOperator(
            task_id=TASK_ID,
            src_adls=ADLS_PATH_1,
            dest_gcs=GCS_PATH,
            replace=False,
            azure_data_lake_conn_id=AZURE_CONN_ID,
            gcp_conn_id=GCS_CONN_ID,
        )

        assert operator.task_id == TASK_ID
        assert operator.src_adls == ADLS_PATH_1
        assert operator.dest_gcs == GCS_PATH
        assert operator.replace is False
        assert operator.gcp_conn_id == GCS_CONN_ID
        assert operator.azure_data_lake_conn_id == AZURE_CONN_ID

    @mock.patch('airflow.providers.google.cloud.transfers.adls_to_gcs.AzureDataLakeHook')
    @mock.patch('airflow.providers.microsoft.azure.operators.adls.AzureDataLakeHook')
    @mock.patch('airflow.providers.google.cloud.transfers.adls_to_gcs.GCSHook')
    def test_execute(self, gcs_mock_hook, adls_one_mock_hook, adls_two_mock_hook):
        """Test the execute function when the run is successful."""

        operator = ADLSToGCSOperator(
            task_id=TASK_ID,
            src_adls=ADLS_PATH_1,
            dest_gcs=GCS_PATH,
            replace=False,
            azure_data_lake_conn_id=AZURE_CONN_ID,
            gcp_conn_id=GCS_CONN_ID,
            google_impersonation_chain=IMPERSONATION_CHAIN,
        )

        adls_one_mock_hook.return_value.list.return_value = MOCK_FILES
        adls_two_mock_hook.return_value.list.return_value = MOCK_FILES

        # gcs_mock_hook.return_value.upload.side_effect = _assert_upload
        uploaded_files = operator.execute(None)
        gcs_mock_hook.return_value.upload.assert_has_calls(
            [
                mock.call(
                    bucket_name='test', filename=mock.ANY, object_name='test/path/PARQUET.parquet', gzip=False
                ),
                mock.call(
                    bucket_name='test', filename=mock.ANY, object_name='test/path/TEST3.csv', gzip=False
                ),
                mock.call(bucket_name='test', filename=mock.ANY, object_name='test/path/PIC.png', gzip=False),
                mock.call(bucket_name='test', filename=mock.ANY, object_name='test/TEST1.csv', gzip=False),
                mock.call(bucket_name='test', filename=mock.ANY, object_name='test/TEST2.csv', gzip=False),
            ],
            any_order=True,
        )

        adls_one_mock_hook.assert_called_once_with(azure_data_lake_conn_id=AZURE_CONN_ID)
        adls_two_mock_hook.assert_called_once_with(azure_data_lake_conn_id=AZURE_CONN_ID)
        gcs_mock_hook.assert_called_once_with(
            gcp_conn_id=GCS_CONN_ID,
            delegate_to=None,
            impersonation_chain=IMPERSONATION_CHAIN,
        )

        # we expect MOCK_FILES to be uploaded
        assert sorted(MOCK_FILES) == sorted(uploaded_files)

    @mock.patch('airflow.providers.google.cloud.transfers.adls_to_gcs.AzureDataLakeHook')
    @mock.patch('airflow.providers.microsoft.azure.operators.adls.AzureDataLakeHook')
    @mock.patch('airflow.providers.google.cloud.transfers.adls_to_gcs.GCSHook')
    def test_execute_with_gzip(self, gcs_mock_hook, adls_one_mock_hook, adls_two_mock_hook):
        """Test the execute function when the run is successful."""

        operator = ADLSToGCSOperator(
            task_id=TASK_ID,
            src_adls=ADLS_PATH_1,
            dest_gcs=GCS_PATH,
            replace=False,
            azure_data_lake_conn_id=AZURE_CONN_ID,
            gcp_conn_id=GCS_CONN_ID,
            gzip=True,
        )

        adls_one_mock_hook.return_value.list.return_value = MOCK_FILES
        adls_two_mock_hook.return_value.list.return_value = MOCK_FILES

        # gcs_mock_hook.return_value.upload.side_effect = _assert_upload
        uploaded_files = operator.execute(None)
        gcs_mock_hook.return_value.upload.assert_has_calls(
            [
                mock.call(
                    bucket_name='test', filename=mock.ANY, object_name='test/path/PARQUET.parquet', gzip=True
                ),
                mock.call(
                    bucket_name='test', filename=mock.ANY, object_name='test/path/TEST3.csv', gzip=True
                ),
                mock.call(bucket_name='test', filename=mock.ANY, object_name='test/path/PIC.png', gzip=True),
                mock.call(bucket_name='test', filename=mock.ANY, object_name='test/TEST1.csv', gzip=True),
                mock.call(bucket_name='test', filename=mock.ANY, object_name='test/TEST2.csv', gzip=True),
            ],
            any_order=True,
        )

        # we expect MOCK_FILES to be uploaded
        assert sorted(MOCK_FILES) == sorted(uploaded_files)


text:
layout: page
title: "JavaScript str_split function"
comments: true
sharing: true
footer: true
alias:
- /functions/view/str_split:530
- /functions/view/str_split
- /functions/view/530
- /functions/str_split:530
- /functions/530
---
<!-- Generated by Rakefile:build -->
A JavaScript equivalent of PHP's str_split

{% codeblock strings/str_split.js lang:js https://raw.github.com/kvz/phpjs/master/functions/strings/str_split.js raw on github %}
function str_split (string, split_length) {
  // From: http://phpjs.org/functions
  // +     original by: Martijn Wieringa
  // +     improved by: Brett Zamir (http://brett-zamir.me)
  // +     bugfixed by: Onno Marsman
  // +      revised by: Theriault
  // +        input by: Bjorn Roesbeke (http://www.bjornroesbeke.be/)
  // +      revised by: Rafał Kukawski (http://blog.kukawski.pl/)
  // *       example 1: str_split('Hello Friend', 3);
  // *       returns 1: ['Hel', 'lo ', 'Fri', 'end']
  if (split_length === null) {
    split_length = 1;
  }
  if (string === null || split_length < 1) {
    return false;
  }
  string += '';
  var chunks = [],
    pos = 0,
    len = string.length;
  while (pos < len) {
    chunks.push(string.slice(pos, pos += split_length));
  }

  return chunks;
}
{% endcodeblock %}

 - [Raw function on GitHub](https://github.com/kvz/phpjs/blob/master/functions/strings/str_split.js)

Please note that php.js uses JavaScript objects as substitutes for PHP arrays, they are
the closest match to this hashtable-like data structure.

Please also note that php.js offers community built functions and goes by the
[McDonald's Theory](https://medium.com/what-i-learned-building/9216e1c9da7d). We'll put online
functions that are far from perfect, in the hopes to spark better contributions.
Do you have one? Then please just:

 - [Edit on GitHub](https://github.com/kvz/phpjs/edit/master/functions/strings/str_split.js)

### Example 1
This code
{% codeblock lang:js example %}
str_split('Hello Friend', 3);
{% endcodeblock %}

Should return
{% codeblock lang:js returns %}
['Hel', 'lo ', 'Fri', 'end']
{% endcodeblock %}

### Other PHP functions in the strings extension
{% render_partial _includes/custom/strings.html %}


text:
/* global d3 */
(function () {
  let Controller = function () {
    this.state = {
      graph: {},
      selection: {
        id: null,
        snippet: null
      }
    }

    this.initialize = function (graphEl, snippetEl) {
      this.graph = new this.GraphView(graphEl, this.onMessage)
      this.snippet = new this.SnippetView(snippetEl)

      // Todo: move from d3 to something more neutral for state-loading?
      d3.json('graph/default', this.onLoad)
    }

    this.onLoad = function (err, json) {
      if (err) {
        console.error(err)
        return
      }
      this.setState({
        graph: json,
        selection: []
      })
    }.bind(this)

    this.onSnippetLoad = function (selectionDetails, err, json) {
      if (err) {
        console.error(err)
        return
      }
      selectionDetails.snippet = json
      this.setState({
        graph: this.state.graph,
        selection: selectionDetails
      })
    }

    this.onMessage = function (message, data) {
      var parts = message.split(':')
      var entity = parts[0]
      var command = parts[1]

      if (entity === 'graph') {
        let newSelection = {
          id: null,
          snippet: null
        }
        if (command === 'select') {
          newSelection.id = data.node_id
          d3.json(
            'graph/default/snippet/' + newSelection.id,
            this.onSnippetLoad.bind(this, newSelection))
        } else if (command === 'deselect') {
          // this.setState({
          //   graph: this.state.graph,
          //   selection: newSelection
          // })
        }
      } else if (entity === 'snippet') {
        console.log('snippet says ' + command)
      }
    }.bind(this)

    this.setState = function (newState) {
      var oldState = this.state
      this.state = newState
      this.graph.onStateChanged(this.state, oldState)
      this.snippet.onStateChanged(this.state, oldState)
    }
  }

  window.p2 = new Controller()
}())


text:
@interface ShowTimeViewController : UIViewController

@end