text:
package org.apache.accumulo.core.util.cleaner;

import static java.util.Objects.requireNonNull;

import java.lang.ref.Cleaner;
import java.lang.ref.Cleaner.Cleanable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.atomic.AtomicBoolean;

import org.apache.accumulo.core.client.AccumuloClient;
import org.apache.accumulo.core.client.BatchWriter;
import org.apache.accumulo.core.client.MutationsRejectedException;
import org.apache.accumulo.fate.zookeeper.ZooCache;
import org.slf4j.Logger;

/**
 * This class collects all the cleaner actions executed in various parts of the code.
 *
 *

 * These actions replace the use of finalizers, which are deprecated in Java 9 and later, and should
 * be avoided. These actions are triggered by their respective objects when those objects become
 * phantom reachable.
 *
 *

 * In the "unclosed*" methods below, the object should have been closed (implements AutoCloseable).
 * We could possibly consolidate these into a single method which only warns, and doesn't try to
 * clean up. We could also delete them entirely, since it is the caller's responsibility to close
 * AutoCloseable resources, not the object's own responsibility to detect that it wasn't closed.
 */
public class CleanerUtil {

  public static final Cleaner CLEANER = Cleaner.create();

  /**
   * Register an action to warn about caller failing to close an {@link AutoCloseable} object.
   *
   *

   * This task will register a generic action to:
   *

   *
check that the monitored object wasn't closed,
   *
log a warning that the monitored object was not closed,
   *
attempt to close a resource within the object, and
   *
log an error if the resource cannot be closed for any reason
   *

   *
   * @param obj
   *          the object to monitor for becoming phantom-reachable without having been closed
   * @param objClass
   *          the class whose simple name will be used in the log message for o
   *          (usually an interface name, rather than the actual impl name of the object)
   * @param closed
   *          a flag to check whether o has already been closed
   * @param log
   *          the logger to use when emitting error/warn messages
   * @param closeable
   *          the resource within o to close when o is cleaned; must not
   *          contain a reference to the monitoredObject or it won't become
   *          phantom-reachable and will never be cleaned
   * @return the registered {@link Cleanable} from {@link Cleaner#register(Object, Runnable)}
   */
  public static Cleanable unclosed(AutoCloseable obj, Class<?> objClass, AtomicBoolean closed,
      Logger log, AutoCloseable closeable) {
    String className = requireNonNull(objClass).getSimpleName();
    requireNonNull(closed);
    requireNonNull(log);
    String closeableClassName = closeable == null ? null : closeable.getClass().getSimpleName();

    // capture the stack trace during setup for logging later, so user can find unclosed object
    var stackTrace = new Exception();

    // register the action to run when obj becomes phantom-reachable or clean is explicitly called
    return CLEANER.register(obj, () -> {
      if (closed.get()) {
        // already closed; nothing to do
        return;
      }
      log.warn("{} found unreferenced without calling close()", className, stackTrace);
      if (closeable != null) {
        try {
          closeable.close();
        } catch (Exception e1) {
          log.error("{} internal error; exception closing {}", objClass, closeableClassName, e1);
        }
      }
    });
  }

  public static Cleanable shutdownThreadPoolExecutor(ExecutorService pool, AtomicBoolean closed,
      Logger log) {
    requireNonNull(pool);
    requireNonNull(log);
    return CLEANER.register(pool, () -> {
      if (closed.get()) {
        return;
      }
      log.warn("{} found unreferenced without calling shutdown() or shutdownNow()",
          pool.getClass().getSimpleName());
      try {
        pool.shutdownNow();
      } catch (Exception e) {
        log.error("internal error; exception closing {}", pool.getClass().getSimpleName(), e);
      }
    });
  }

  // this done for the BatchWriterIterator test code; I don't trust that pattern, but
  // registering a cleaner is something any user is probably going to have to do to clean up
  // resources used in an iterator, until iterators properly implement their own close()
  public static Cleanable batchWriterAndClientCloser(Object o, Logger log, BatchWriter bw,
      AccumuloClient client) {
    requireNonNull(log);
    requireNonNull(bw);
    requireNonNull(client);
    return CLEANER.register(o, () -> {
      try (client) {
        bw.close();
      } catch (MutationsRejectedException e) {
        log.error("Failed to close BatchWriter; some mutations may not be applied", e);
      }
    });
  }

  // this is dubious; MetadataConstraints should probably use the ZooCache provided by context
  // can be done in a follow-on action; for now, this merely replaces the previous finalizer
  public static Cleanable zooCacheClearer(Object o, ZooCache zc) {
    requireNonNull(zc);
    return CLEANER.register(o, zc::clear);
  }

}


text:
#pragma once

#include <vili/node.hpp>

#include <Animation/Animator.hpp>
#include <Collision/PolygonalCollider.hpp>
#include <Debug/Logger.hpp>
#include <Graphics/Sprite.hpp>
#include <Scene/SceneNode.hpp>
#include <Triggers/TriggerGroup.hpp>
#include <Triggers/TriggerManager.hpp>
#include <Types/Serializable.hpp>

#include <sol/sol.hpp>

#include <vili/node.hpp>

namespace obe::Scene
{
    class Scene;
}

/**
 * \additionalinclude{Scene/Scene.hpp}
 */
namespace obe::Script
{
    class GameObject;

    /**
     * \brief Manages and caches GameObject definition files and Requirements
     */
    class GameObjectDatabase
    {
    private:
        static vili::node allRequires;
        static vili::node allDefinitions;

    public:
        /**
         * \brief Gets the Requires ComplexNode of the GameObject
         * \param type Type of the GameObject to get the Requirements
         * \return A pointer to the Requires ComplexNode of the GameObject
         */
        static vili::node GetRequirementsForGameObject(const std::string& type);
        /**
         * \brief Gets the ObjectDefinition ComplexNode of the GameObject
         * \param type Type of the GameObject to get the GameObject Definition File
         * \return A pointer to the ObjectDefinition ComplexNode
         */
        static vili::node GetDefinitionForGameObject(const std::string& type);
        /**
         * \brief Applies the Requirements to a GameObject using a Requires
         *        ComplexNode
         * \param obj GameObject to applies the requirements to
         * \param requires ComplexNode containing the Requirements
         */
        static void ApplyRequirements(sol::environment environment, vili::node& requires);
        /**
         * \brief Clears the GameObjectDatabase (cache reload)
         */
        static void Clear();
    };

    /**
     * \brief A GameObject is a set of Components used in the Scene
     */
    class GameObject final : public Types::Identifiable, public Types::Serializable
    {
    private:
        Triggers::TriggerManager& m_triggers;
        bool m_permanent = false;
        std::unique_ptr<Animation::Animator> m_animator;
        Graphics::Sprite* m_sprite = nullptr;
        Collision::PolygonalCollider* m_collider = nullptr;
        Triggers::TriggerGroupPtr t_local;
        Scene::SceneNode m_objectNode;
        sol::state_view m_lua;
        sol::environment m_environment;

        std::vector<std::pair<std::weak_ptr<Triggers::Trigger>, std::string>>
            m_registeredTriggers;
        std::vector<std::tuple<std::string, std::string, std::string>>
            m_registeredAliases;

        std::string m_type;
        std::string m_privateKey;

        bool m_hasScriptEngine = false;
        bool m_active = false;
        bool m_canUpdate = true;

        friend class Scene::Scene;

    public:
        /**
         * \brief Creates a new GameObject
         * \param type Type of the GameObject
         * \param id Id of the GameObject you want to create
         */
        explicit GameObject(Triggers::TriggerManager& triggers, sol::state_view lua,
            const std::string& type, const std::string& id);
        /**
         * \brief Destructor of the GameObject
         */
        ~GameObject();
        /**
         * \brief Get the Type of the GameObject
         * \return A std::string containing the type of the GameObject
         */
        [[nodiscard]] std::string getType() const;
        /**
         * \brief Checks if the GameObject has an Animator Component
         * \return true if the GameObject contains an Animator Component, false
         *         otherwise
         */
        [[nodiscard]] bool doesHaveAnimator() const;
        /**
         * \brief Checks if the GameObject has a Collider Component
         * \return true if the GameObject contains the Collider Component, false
         *         otherwise
         */
        [[nodiscard]] bool doesHaveCollider() const;
        /**
         * \brief Checks if the GameObject has a Sprite Component
         * \return true if the GameObject contains the Sprite Component,
         *         false otherwise
         */
        [[nodiscard]] bool doesHaveSprite() const;
        /**
         * \brief Checks if the GameObject has a Script Component
         * \return true if the GameObject contains the Script Component, false
         *         otherwise
         */
        [[nodiscard]] bool doesHaveScriptEngine() const;
        /**
         * \brief Is the GameObject updated
         * \return true if the GameObject is updated, false otherwise
         */
        [[nodiscard]] bool getUpdateState() const;
        /**
         * \brief Sets if the GameObject should be otherwise or not
         * \param state Should be equal to true if the GameObject must updates,
         *        false otherwise
         */
        void setUpdateState(bool state);
        /**
         * \bind{Animator}
         * \asproperty
         * \brief Gets the Animator Component of the GameObject (Raises
         *        ObEngine.Script.GameObject.NoAnimator if no Animator Component)
         * \return A pointer to the Animator Component of the GameObject
         */
        Animation::Animator& getAnimator() const;
        /**
         * \bind{Collider}
         * \asproperty
         * \brief Gets the Collider Component of the GameObject (Raises
         *        ObEngine.Script.GameObject.NoCollider if no Collider Component)
         * \return A pointer to the Collider Component of the GameObject
         */
        Collision::PolygonalCollider& getCollider() const;
        /**
         * \bind{Sprite}
         * \asproperty
         * \brief Gets the Sprite Component of the GameObject (Raises
         *        ObEngine.Script.GameObject.NoSprite if no Sprite Component)
         * \return A pointer to the Sprite Component of the GameObject
         */
        Graphics::Sprite& getSprite() const;
        /**
         * \bind{SceneNode}
         * \asproperty
         * \brief Gets the Scene Node of the GameObject (SceneNode that can
         *        manipulate the position of all Scene Components) \return A reference
         * to the GameObject's Scene Node
         */
        Scene::SceneNode& getSceneNode();
        /**
         * \brief Register a non-local Trigger for the GameObject
         * \param trNsp Namespace where the Trigger to register is
         * \param trGrp TriggerGroup where the Trigger to register is
         * \param trName Name of the Trigger to register
         * \param callAlias Alias (name of the callback) associated with the
         *        Trigger
         */
        void useTrigger(const std::string& trNsp, const std::string& trGrp,
            const std::string& trName, const std::string& callAlias = "");
        void removeTrigger(const std::string& trNsp, const std::string& trGrp,
            const std::string& trName) const;
        /**
         * \brief Execute a Lua String in the Lua State of the GameObject
         * \param query String to execute
         */
        void exec(const std::string& query);
        /**
         * \brief Send a parameter to the Local.Init trigger
         * \tparam U Template Type of the Parameter
         * \param argName Name of the Parameter to push
         * \param value Value of the Parameter
         */
        template <typename U> void sendInitArg(const std::string& argName, U value);
        /**
         * \bind{sendInitArg}
         * \brief Send a parameter to the Local.Init trigger from a Lua VM
         * \param argName Name of the Parameter to push
         * \param value Value of the Parameter
         */
        void sendInitArgFromLua(const std::string& argName, sol::object value) const;
        /**
         * \brief Register a Trigger in the GameObject
         * \param trg Pointer to the Trigger
         * \param callbackName Name of the callback to call when Trigger will be
         *        enabled
         */
        void registerTrigger(
            std::weak_ptr<Triggers::Trigger> trg, const std::string& callbackName);
        /**
         * \brief Loads the GameObject through the GameObject Definition File
         * \param scene Scene reference to create components
         * \param obj Vili Node containing the GameObject components
         * \param resources pointer to the ResourceManager
         */
        void loadGameObject(Scene::Scene& scene, vili::node& obj,
            Engine::ResourceManager* resources = nullptr);
        /**
         * \brief Updates the GameObject
         */
        void update();
        /**
         * \brief Deletes the GameObject
         */
        void deleteObject();
        /**
         * \brief Delete State of the GameObject (false = not deleted)
         */
        bool deletable = false;
        /**
         * \brief Access the exposition table of the GameObject
         * \return A reference to the exposition table of the GameObject
         */
        [[nodiscard]] sol::table access() const;
        /**
         * \brief Gets a reference to the Lua function used to build the
         *        GameObject (Local.Init proxy)
         * \return A reference to the Lua function used to build the GameObject
         */
        [[nodiscard]] sol::function getConstructor() const;
        /**
         * \brief Triggers the GameObject's Local.Init
         */
        void initialize();
        /**
         * \brief Configures the permanent parameter of the GameObject
         * \param permanent Should be true if the GameObject should be
         *        permanent, false otherwise
         */
        void setPermanent(bool permanent);
        /**
         * \brief Gets if the GameObject is permanent (Will stay after loading
         *        another map)
         * \return true if the GameObject is permanent, false otherwise
         */
        [[nodiscard]] bool isPermanent() const;

        sol::environment getEnvironment() const;
        void setState(bool state);

        [[nodiscard]] vili::node dump() const override;
        void load(vili::node& data) override;
    };

    template <typename U>
    void GameObject::sendInitArg(const std::string& argName, U value)
    {
        Debug::Log->debug(
            "<GameObject> Sending Local.Init argument {0} to GameObject {1}", argName,
            m_id);
        t_local->pushParameter("Init", argName, value);
    }
} // namespace obe::Script

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Yusuke\HimatanBundle\Entity\Repository;

use Doctrine\ORM\EntityRepository;
use Yusuke\HimatanBundle\Entity\User;
use Symfony\Component\Validator\Validator;
use Yusuke\HimatanBundle\Exception\ClientErrorException;

/**
 * UserRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class UserRepository extends EntityRepository
{
    public function selectUser($id)
    {
        $user = $this->findOneBy(array(
            'id' => $id,
            'deleteFlag' => 0
        ));
        return $user;
    }

    public function setUser(User $user)
    {
        $em = $this->getEntityManager();
        $em->persist($user);
        $em->flush();
        return $user;
    }
}


text:
The following tutorials demonstrate how to configure the Google Cloud Platform
to run quantum simulations with qsim.

You can use Google Cloud to run high-performance CPU-based simulations or
GPU-based simulations, depending on your requirements. For more information
about making a choice between CPU- and GPU-based simulations, see
[Choosing hardware for your qsim simulation]().

This tutorial depends on resources provided by the Google Cloud Platform.

*   **Ensure that you have a Google Cloud Platform project.** You can reuse an
    existing project, or create a new one, from your
    [project dashboard](https://console.cloud.google.com/projectselector2/home/dashboard).
    *   For more information about Google Cloud projects, see
        [Creating and managing projects](https://cloud.google.com/resource-manager/docs/creating-managing-projects)
        in the Google Cloud documentation.
*   **Ensure that billing is enabled for your project.**
    *   For more information about billing, see
        [Enable, disable, or change billing for a project](https://cloud.google.com/billing/docs/how-to/modify-project#enable-billing)
        in the Google Cloud documentation.
*   **Estimate costs for your project** Use the
    [Google Cloud Pricing Calculator](https://cloud.google.com/products/calculator)
    to estimate the scale of the costs you might incur, based on your projected
    usage. The resources that you use to simulate a quantum circuit on the
    Google Cloud platform are billable.
*   **Enable the Compute Engine API for your project.** You can enable APIs from
    the [API Library Console](https://console.cloud.google.com/apis/library). On
    the console, in the search box, enter "compute engine api" to find the API
    and click through to Enable it.
    *   For more information about enabling the Compute Engine API, see
        [Getting Started](https://cloud.google.com/apis/docs/getting-started) in
        the Google Cloud documentation.


text:
// flow-typed signature: cba49e3d508faf2f2d6ffdfce73cf5b2
// flow-typed version: <<STUB>>/qs_v^6.3.0/flow_v0.36.0

/**
 * This is an autogenerated libdef stub for:
 *
 *   'qs'
 *
 * Fill this stub out by replacing all the `any` types.
 *
 * Once filled out, we encourage you to share your work with the
 * community by sending a pull request to:
 * https://github.com/flowtype/flow-typed
 */

declare module 'qs' {
  declare module.exports: any;
}

/**
 * We include stubs for each file inside this npm package in case you need to
 * require those files directly. Feel free to delete any files that aren't
 * needed.
 */
declare module 'qs/dist/qs' {
  declare module.exports: any;
}

declare module 'qs/lib/formats' {
  declare module.exports: any;
}

declare module 'qs/lib/index' {
  declare module.exports: any;
}

declare module 'qs/lib/parse' {
  declare module.exports: any;
}

declare module 'qs/lib/stringify' {
  declare module.exports: any;
}

declare module 'qs/lib/utils' {
  declare module.exports: any;
}

declare module 'qs/test/index' {
  declare module.exports: any;
}

declare module 'qs/test/parse' {
  declare module.exports: any;
}

declare module 'qs/test/stringify' {
  declare module.exports: any;
}

declare module 'qs/test/utils' {
  declare module.exports: any;
}

// Filename aliases
declare module 'qs/dist/qs.js' {
  declare module.exports: $Exports<'qs/dist/qs'>;
}
declare module 'qs/lib/formats.js' {
  declare module.exports: $Exports<'qs/lib/formats'>;
}
declare module 'qs/lib/index.js' {
  declare module.exports: $Exports<'qs/lib/index'>;
}
declare module 'qs/lib/parse.js' {
  declare module.exports: $Exports<'qs/lib/parse'>;
}
declare module 'qs/lib/stringify.js' {
  declare module.exports: $Exports<'qs/lib/stringify'>;
}
declare module 'qs/lib/utils.js' {
  declare module.exports: $Exports<'qs/lib/utils'>;
}
declare module 'qs/test/index.js' {
  declare module.exports: $Exports<'qs/test/index'>;
}
declare module 'qs/test/parse.js' {
  declare module.exports: $Exports<'qs/test/parse'>;
}
declare module 'qs/test/stringify.js' {
  declare module.exports: $Exports<'qs/test/stringify'>;
}
declare module 'qs/test/utils.js' {
  declare module.exports: $Exports<'qs/test/utils'>;
}


text:
package io.rsocket.plugins;

import io.rsocket.RSocket;
import java.util.function.Function;

/**
 * Contract to decorate an {@link RSocket}, providing a way to intercept interactions. This can be
 * applied to a {@link InterceptorRegistry#forRequester(RSocketInterceptor) requester} or {@link
 * InterceptorRegistry#forResponder(RSocketInterceptor) responder} {@code RSocket} of a client or
 * server.
 */
public @FunctionalInterface interface RSocketInterceptor extends Function<RSocket, RSocket> {}


text:
title: OSS to Cluster Migration
aliases:
    - /enterprise/v1.0/guides/migration/
menu:
  enterprise_influxdb_1_0:
    weight: 10
    parent: Guides
---

The following guide has step-by-step instructions for migrating an InfluxDB OSS
instance into and InfluxEnterprise cluster.

The process assumes that you already have a fully configured InfluxEnterprise cluster
of three or more meta nodes and zero or more data nodes.

Please note that this migration process:

* Deletes all data from any data nodes that are already part of the InfluxEnterprise Cluster
* Will transfer all users from the OSS instance to the InfluxEnterprise Cluster*
* Will **not** transfer any users from the OSS instance to the InfluxEnterprise Web Console
* Requires downtime for writes and reads for the OSS instance

{{% warn %}}
\* If you're using an InfluxEnterprise cluster version prior to 0.7.4, the
following steps will **not** transfer users from the OSS instance to the
InfluxEnterprise Cluster.
{{% /warn %}}

In addition, please refrain from creating a Global Admin user in the InfluxEnterprise Web Console before implementing these steps. If you've already created a Global Admin user, contact support.

## Modify the /etc/hosts file

Add the IP and hostname of the OSS instance to the
`/etc/hosts` file on all nodes in the InfluxEnterprise Cluster.
Ensure that all cluster IPs and hostnames are also in the OSS
instance's `/etc/hosts` file.

**Note:** All node hostnames must be completely resolvable by all
other nodes in the cluster. If you have DNS already setup in your
environment, then this step can be skipped.

## For all existing InfluxEnterprise data nodes:

### 1. Remove the node from the InfluxEnterprise Cluster

From a **meta** node in your InfluxEnterprise Cluster, enter:
```
influxd-ctl remove-data <data_node_hostname>:8088
```
### 2. Delete any existing data

On each **data** node that you dropped from the cluster, enter:
```
sudo rm -rf /var/lib/influxdb/{meta,data,hh}
```

### 3. Create new directories

On each data node that you dropped from the cluster, enter:
```
sudo mkdir /var/lib/influxdb/{data,hh,meta}
```
To ensure the file permissions are correct please run:
```
sudo chown -R influxdb:influxdb /var/lib/influxdb
```

## For the OSS Instance:

### 1. Stop all writes to the OSS Instance

### 2. Stop the influxdb service on the OSS Instance

On sysvinit systems, use the `service` command:
```
sudo service influxdb stop
```

On systemd systems, use the `systemctl` command:
```
sudo systemctl stop influxdb
```

Double check that the service is stopped (the following should return nothing):
```
ps ax | grep influxd
```

### 3. Remove the OSS package

On Debian/Ubuntu systems:
```
sudo apt-get remove influxdb
```

On RHEL/CentOS systems:
```
sudo yum remove influxdb
```

### 4. Update the binary

> **Note:** This step will overwrite your current configuration file.
If you have settings that you'd like to keep, please make a copy of your config file before running the following command.

#### Ubuntu & Debian (64-bit)
```
wget https://dl.influxdata.com/enterprise/releases/influxdb-data_1.0.2-c1.0.4_amd64.deb
sudo dpkg -i influxdb-data_1.0.2-c1.0.4_amd64.deb
```

#### RedHat & CentOS (64-bit)
```
wget https://dl.influxdata.com/enterprise/releases/influxdb-data-1.0.2_c1.0.4.x86_64.rpm
sudo yum localinstall influxdb-data-1.0.2_c1.0.4.x86_64.rpm
```

### 5. Update the configuration file

For the following settings in `/etc/influxdb/influxdb.conf`, set:

* `hostname` to the server's hostname (you must manually add this setting)
* `license-key` in the `[enterprise]` section to your license key
* `auth-enabled` in the `[http]` section to true
* `shared-secret` in the `[http]` section to your shared secret (you must manually add this setting for the Enterprise Web console to function)

```toml
# Change this option to true to disable reporting.
reporting-disabled = false
hostname="your-hostname" # enter your server's hostname
meta-tls-enabled = false

[enterprise]

registration-enabled = false
registration-server-url = ""
license-key = "<your_license_key>" # Enter your InfluxDB Enterprise license key
license-path = ""

[meta]
enabled = false
dir = "/var/lib/influxdb/meta"

[data]
enabled = true
dir = "/var/lib/influxdb/data"

[...]

[http]
 enabled = true
 bind-address = ":8086"
 auth-enabled = true # Set to 'true' to enable authentication
 log-enabled = true
 write-tracing = false
 pprof-enabled = false
 https-enabled = false
 https-certificate = "/etc/ssl/influxdb.pem"
 shared-secret = "long pass phrase used for signing tokens" # Enter your shared secret

[...]

retry-max-interval = "1m0s"
purge-interval = "1h0m0s"
```

### 6. Start the data node

On sysvinit systems, use the `service` command:
```
sudo service influxdb start
```

On systemd systems, use the `systemctl` command:
```
sudo systemctl start influxdb
```

### 7. Add the node to the cluster

From a **meta** node in the cluster, run:
```
influxd-ctl add-data <data-node-hostname>:8088
```
You should see:
```
Added data node y at data-node-hostname:8088
```

Note: it may take a few minutes before the existing data become available in the cluster.

## Final steps

### 1. Add any data nodes that you removed from cluster back into the cluster

From a **meta** node in the InfluxEnterprise Cluster, run:
```
influxd-ctl add-data <the-hostname>:8088
```
Output:
```
Added data node y at the-hostname:8088
```

Finally verify that all nodes are now members of the cluster as expected:

```
influxd-ctl show
```

### 2. Rebalance the cluster

Increase the [replication factor](/enterprise_influxdb/v1.0/concepts/glossary/#replication-factor) on all existing retention polices to the number of data nodes in your cluster.
You can do this with [ALTER RETENTION POLICY](/influxdb/v1.0/query_language/database_management/#modify-retention-policies-with-alter-retention-policy).

Next, [rebalance](/enterprise_influxdb/v1.0/features/web-console-features/#cluster-rebalancing) your cluster using the `Rebalance` button on the `Tasks` page.


text:
package org.lamport.tla.toolbox.editor.basic;

import java.util.Dictionary;
import java.util.Hashtable;

import org.eclipse.e4.ui.css.swt.theme.ITheme;
import org.eclipse.e4.ui.css.swt.theme.IThemeEngine;
import org.eclipse.e4.ui.css.swt.theme.IThemeManager;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.text.rules.IPartitionTokenScanner;
import org.eclipse.jface.text.rules.ITokenScanner;
import org.eclipse.swt.widgets.Display;
import org.lamport.tla.toolbox.AbstractTLCActivator;
import org.lamport.tla.toolbox.Activator;
import org.lamport.tla.toolbox.editor.basic.tla.PCALCodeScanner;
import org.lamport.tla.toolbox.editor.basic.tla.TLACodeScanner;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.event.Event;
import org.osgi.service.event.EventConstants;
import org.osgi.service.event.EventHandler;

/**
 * The activator class controls the plug-in life cycle
 */
@SuppressWarnings("restriction")
public class TLAEditorActivator extends AbstractTLCActivator {
    // The plug-in ID
    public static final String PLUGIN_ID = "org.lamport.tla.toolbox.editor.basic";

    // The shared instance
    private static TLAEditorActivator plugin;

    private static final String DARK_THEME_ID_PREFIX = "org.eclipse.e4.ui.css.theme.e4_dark";

    /**
     * Returns the shared instance
     *
     * @return the shared instance
     */
	public static TLAEditorActivator getDefault() {
        return plugin;
    }

    private TLAPartitionScanner partitionTokenScanner;
    private TLAColorProvider colorProvider;
    private TLACodeScanner tlaCodeScanner;
    private PCALCodeScanner pcalCodeScanner;

    private ServiceRegistration<?> themeChangeEventRegistration;

    private Boolean currentThemeIsDark;

    /**
     * The constructor
     */
	public TLAEditorActivator() {
    	super(PLUGIN_ID);
    }

    /*
     * (non-Javadoc)
     * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
     */
	public void start(final BundleContext context) throws Exception {
    	plugin = this;

        super.start(context);

    	final Dictionary<String, Object> serviceRegistrationProperties = new Hashtable<>();
    	serviceRegistrationProperties.put(EventConstants.EVENT_TOPIC, IThemeEngine.Events.THEME_CHANGED);

    	themeChangeEventRegistration = context.registerService(EventHandler.class.getName(), new EventHandler() {
    		@Override
    		public void handleEvent(final Event event) {
    			tlaCodeScanner = null;
    			pcalCodeScanner = null;
    			setDarkThemeStatus();
    		}
    	}, serviceRegistrationProperties);
    }

    /*
     * (non-Javadoc)
     * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
     */
	public void stop(final BundleContext context) throws Exception {
		themeChangeEventRegistration.unregister();
		plugin = null;
		super.stop(context);
	}

    private void setDarkThemeStatus () {
    	final BundleContext context = Activator.getDefault().getBundle().getBundleContext();
    	final ServiceReference<IThemeManager> serviceReference = context.getServiceReference(IThemeManager.class);

    	if (serviceReference != null) {
            final IThemeManager manager = context.getService(serviceReference);

            if (manager != null) {
            	final Display d = Display.getDefault();
            	final IThemeEngine engine = manager.getEngineForDisplay(d);
            	final ITheme it = engine.getActiveTheme();

            	if (it != null) {
            		boolean newThemeStatus = it.getId().startsWith(DARK_THEME_ID_PREFIX);

            		if ((currentThemeIsDark == null) || (currentThemeIsDark.booleanValue() != newThemeStatus)) {
						if (currentThemeIsDark != null) {
							d.asyncExec(() -> {
								MessageDialog.openInformation(d.getActiveShell(), "Theme Change",
										"You will need to close any open views and editors, then re-open them, to have "
												+ "your theme change fully reflected (or restart the Toolbox.)");
							});
            			}

            			currentThemeIsDark = Boolean.valueOf(newThemeStatus);
            		}
            	}
            }
    	}
    }

	/**
	 * @return true if the current UI theme is dark
	 */
	public boolean isCurrentThemeDark() {
		return (currentThemeIsDark == null) ? false : currentThemeIsDark.booleanValue();
	}

    /**
     * @return
     */
    public IPartitionTokenScanner getTLAPartitionScanner()
    {
        if (partitionTokenScanner == null)
        {
            partitionTokenScanner = new TLAPartitionScanner();
        }
        return partitionTokenScanner;
    }

    /**
     * @return
     */
    public TLAColorProvider getTLAColorProvider()
    {
        if (colorProvider == null)
        {
            colorProvider = new TLAColorProvider();
        }
        return colorProvider;
    }

    /**
     * @return
     */
    public ITokenScanner getTLACodeScanner()
    {
        if (tlaCodeScanner== null)
        {
            tlaCodeScanner = new TLACodeScanner();
        }
        return tlaCodeScanner;
    }

    // Added for PlusCal
    public ITokenScanner getPCALCodeScanner()
    {
        if (pcalCodeScanner== null)
        {
            pcalCodeScanner = new PCALCodeScanner();
        }
        return pcalCodeScanner;
    }
}


text:
describe('Directive msl-file-input', function() {
	var $compile, $rootScope;

	beforeEach(module('msl.uploads'));
	beforeEach(inject(function(_$compile_, _$rootScope_) {
		$compile = _$compile_;
		$rootScope = _$rootScope_;
	}));

	it('removes the \'multiple\' attribute if present', function() {
		var handler = 'handler';
		$rootScope[handler] = function () {};
		var element = $compile('<button msl-file-input="' + handler + '" multiple></button>')($rootScope);
		$rootScope.$digest();
		expect(element.attr('multiple')).toBeUndefined();
	});

	it('passes the \'multiple\' attribute (if present) to the appended input', function() {
		var handler = 'handler';
		$rootScope[handler] = function () {};
		var element = $compile('<button msl-file-input="' + handler + '" multiple></button>')($rootScope);
		$rootScope.$digest();
		expect(element.attr('multiple')).toBeFalsy();
		var input = element.children().eq(-1);
		expect(input.attr('multiple')).toBeTruthy();

		var element = $compile('<button msl-file-input="' + handler + '"></button>')($rootScope);
		$rootScope.$digest();
		expect(element.attr('multiple')).toBeFalsy();
		input = element.children().eq(-1);
		expect(input.attr('multiple')).toBeFalsy();
	});

	it('appends a hidden file input', function() {
		var handler = 'handler';
		$rootScope[handler] = function () {};
		var element = $compile('<button msl-file-input="' + handler + '"></button>')($rootScope);
		$rootScope.$digest();
		var input = element.children().eq(-1);
		expect(input.attr('type')).toEqual('file');
		expect(input.css('display')).toEqual('none');
	});

	it('allows to bind a handler for the \'change\' event of the appended input', function() {
		var handler = 'handler';
		$rootScope[handler] = function () {};
		var element = $compile('<button msl-file-input="' + handler + '"></button>')($rootScope);
		$rootScope.$digest();

		spyOn($rootScope, handler);
		var input = element.children().eq(-1);
		input.triggerHandler('change');
		expect($rootScope[handler]).toHaveBeenCalledWith(jasmine.any(FileList));

		input.triggerHandler($.Event('change', {
			target: {
				files: ['foo', 'bar', 'baz']
			}
		}));
		expect($rootScope[handler]).toHaveBeenCalledWith(['foo', 'bar', 'baz']);
	});

	it('throws if you forget to provide a handler', function() {
		function compileWithoutHandler() {
			$compile('<button msl-file-input></button>')($rootScope);
		}
		expect(compileWithoutHandler).toThrow();
	});

	it('throws if you provide a missing handler', function() {
		function compileWithMissingHandler() {
			var handler = 'handler';
			$rootScope[handler] = undefined;
			$compile('<button msl-file-input="' + handler + '"></button>')($rootScope);
		}
		expect(compileWithMissingHandler).toThrow();
	});

	it('when the container is clicked, triggers a click on the appended input', function() {
		var handler = 'handler';
		$rootScope[handler] = function () {};
		var element = $compile('<button msl-file-input="' + handler + '"></button>')($rootScope);
		$rootScope.$digest();

		var input = element.children().eq(-1);
		var click_on_input = spyOnEvent(input, 'click');
		element.triggerHandler('click');
		expect(click_on_input).toHaveBeenTriggered();
	});
});


text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: google/monitoring/v3/metric_service.proto

package com.google.monitoring.v3;

public interface ListMetricDescriptorsResponseOrBuilder
    extends
    // @@protoc_insertion_point(interface_extends:google.monitoring.v3.ListMetricDescriptorsResponse)
    com.google.protobuf.MessageOrBuilder {

  /**
   *
   *
   *

   * The metric descriptors that are available to the project
   * and that match the value of `filter`, if present.
   *

   *
   * repeated .google.api.MetricDescriptor metric_descriptors = 1;
   */
  java.util.List<com.google.api.MetricDescriptor> getMetricDescriptorsList();
  /**
   *
   *
   *

   * The metric descriptors that are available to the project
   * and that match the value of `filter`, if present.
   *

   *
   * repeated .google.api.MetricDescriptor metric_descriptors = 1;
   */
  com.google.api.MetricDescriptor getMetricDescriptors(int index);
  /**
   *
   *
   *

   * The metric descriptors that are available to the project
   * and that match the value of `filter`, if present.
   *

   *
   * repeated .google.api.MetricDescriptor metric_descriptors = 1;
   */
  int getMetricDescriptorsCount();
  /**
   *
   *
   *

   * The metric descriptors that are available to the project
   * and that match the value of `filter`, if present.
   *

   *
   * repeated .google.api.MetricDescriptor metric_descriptors = 1;
   */
  java.util.List<? extends com.google.api.MetricDescriptorOrBuilder>
      getMetricDescriptorsOrBuilderList();
  /**
   *
   *
   *

   * The metric descriptors that are available to the project
   * and that match the value of `filter`, if present.
   *

   *
   * repeated .google.api.MetricDescriptor metric_descriptors = 1;
   */
  com.google.api.MetricDescriptorOrBuilder getMetricDescriptorsOrBuilder(int index);

  /**
   *
   *
   *

   * If there are more results than have been returned, then this field is set
   * to a non-empty value.  To see the additional results,
   * use that value as `page_token` in the next call to this method.
   *

   *
   * string next_page_token = 2;
   *
   * @return The nextPageToken.
   */
  java.lang.String getNextPageToken();
  /**
   *
   *
   *

   * If there are more results than have been returned, then this field is set
   * to a non-empty value.  To see the additional results,
   * use that value as `page_token` in the next call to this method.
   *

   *
   * string next_page_token = 2;
   *
   * @return The bytes for nextPageToken.
   */
  com.google.protobuf.ByteString getNextPageTokenBytes();
}


text:
"""arachne tests."""

from unittest import TestCase

class arachneTest(TestCase):
    def setUp(self):
        pass

    def tearDown(self):
        pass


text:
import { AfterViewChecked,
  Component,
  ElementRef,
  EventEmitter,
  HostListener,
  Input,
  OnDestroy,
  OnInit,
  Output,
  ViewChild } from '@angular/core';
import { TreeNodeModel } from 'app/models/tree-node';

import { ITreeOptions, KEYS, TreeComponent, TreeNode } from 'angular-tree-component';
import { ClassificationCategoriesService } from 'app/shared/services/classifications/classification-categories.service';
import { Pair } from 'app/models/pair';
import { Subscription } from 'rxjs';
import { TreeService } from '../../services/tree/tree.service';
import { Classification } from '../../models/classification';
import { ClassificationDefinition } from '../../models/classification-definition';
import { ClassificationsService } from '../services/classifications/classifications.service';

@Component({
  selector: 'taskana-tree',
  templateUrl: './tree.component.html',
  styleUrls: ['./tree.component.scss'],
})
export class TaskanaTreeComponent implements OnInit, AfterViewChecked, OnDestroy {
  @ViewChild('tree', { static: true })
  private tree: TreeComponent;

  @Input() treeNodes: Array<TreeNodeModel>;
  @Output() treeNodesChange = new EventEmitter<Array<TreeNodeModel>>();
  @Input() selectNodeId: string;
  @Output() selectNodeIdChanged = new EventEmitter<string>();
  @Input() filterText: string;
  @Input() filterIcon = '';
  @Output() refreshClassification = new EventEmitter<string>();
  @Output() switchTaskanaSpinnerEmit = new EventEmitter<boolean>();

  private filterTextOld: string;
  private filterIconOld = '';
  private removedNodeIdSubscription: Subscription;

  options: ITreeOptions = {
    displayField: 'name',
    idField: 'classificationId',
    actionMapping: {
      keys: {
        [KEYS.ENTER]: (tree, node, $event) => {
          node.toggleExpanded();
        }
      }
    },
    useVirtualScroll: true,
    animateExpand: true,
    animateSpeed: 20,
    levelPadding: 20,
    allowDrag: true,
    allowDrop: true
  };

  @HostListener('document:click', ['$event'])
  onDocumentClick(event) {
    if (this.checkValidElements(event) && this.tree.treeModel.getActiveNode()) {
      this.unSelectActiveNode();
    }
  }

  constructor(
    private treeService: TreeService,
    private categoryService: ClassificationCategoriesService,
    private elementRef: ElementRef,
    private classificationsService: ClassificationsService
  ) {
  }

  ngOnInit() {
    this.removedNodeIdSubscription = this.treeService.getRemovedNodeId().subscribe(value => {
      const removedNode = this.getNode(value);
      if (removedNode.parent) {
        removedNode.parent.collapse();
      }
    });
  }

  ngAfterViewChecked(): void {
    if (this.selectNodeId && !this.tree.treeModel.getActiveNode()) {
      this.selectNode(this.selectNodeId);
    } else if (!this.selectNodeId && this.tree.treeModel.getActiveNode()) {
      this.unSelectActiveNode();
    }

    if (this.filterTextOld !== this.filterText
      || this.filterIconOld !== this.filterIcon) {
      this.filterIconOld = this.filterIcon;
      this.filterTextOld = this.filterText;
      this.filterNodes(this.filterText ? this.filterText : '', this.filterIcon);
      this.manageTreeState();
    }
  }

  onActivate(treeNode: any) {
    this.selectNodeIdChanged.emit(`${treeNode.node.data.classificationId}`);
  }

  onDeactivate(treeNode: any) {
    this.selectNodeIdChanged.emit();
  }

  async onMoveNode($event) {
    this.switchTaskanaSpinner(true);
    const classification = await this.getClassification($event.node.classificationId);
    classification.parentId = $event.to.parent.classificationId;
    classification.parentKey = $event.to.parent.key;
    this.collapseParentNodeIfItIsTheLastChild($event.node);
    await this.updateClassification(classification);
  }

  async onDrop($event) {
    if ($event.event.target.tagName === 'TREE-VIEWPORT') {
      this.switchTaskanaSpinner(true);
      const classification = await this.getClassification($event.element.data.classificationId);
      this.collapseParentNodeIfItIsTheLastChild($event.element.data);
      classification.parentId = '';
      classification.parentKey = '';
      await this.updateClassification(classification);
    }
  }

  getCategoryIcon(category: string): Pair {
    return this.categoryService.getCategoryIcon(category);
  }

  private selectNode(nodeId: string) {
    if (nodeId) {
      const selectedNode = this.getNode(nodeId);
      if (selectedNode) {
        selectedNode.setIsActive(true);
        this.expandParent(selectedNode);
      }
    }
  }

  private unSelectActiveNode() {
    const activeNode = this.tree.treeModel.getActiveNode();
    delete this.selectNodeId;
    activeNode.setIsActive(false);
    activeNode.blur();
  }

  private getNode(nodeId: string) {
    return this.tree.treeModel.getNodeById(nodeId);
  }

  private expandParent(node: TreeNode) {
    if (!node.parent || node.isRoot) {
      return;
    }
    node.parent.expand();
    this.expandParent(node.parent);
  }

  private filterNodes(text, iconText) {
    this.tree.treeModel.filterNodes(node => this.checkNameAndKey(node, text)
        && this.checkIcon(node, iconText));
  }

  private checkNameAndKey(node: any, text: string): boolean {
    return (node.data.name.toUpperCase().includes(text.toUpperCase())
      || node.data.key.toUpperCase().includes(text.toUpperCase()));
  }

  private checkIcon(node: any, iconText: string): boolean {
    return (node.data.category.toUpperCase() === iconText.toUpperCase()
      || iconText === '');
  }

  private manageTreeState() {
    if (this.filterText === '') {
      this.tree.treeModel.collapseAll();
    }
  }

  private checkValidElements(event): boolean {
    return (this.elementRef.nativeElement.contains(event.target)
      || this.elementRef.nativeElement === event.target)
      && (event.target.localName === 'tree-viewport'
        || event.target.localName === 'taskana-tree');
  }

  private getClassification(classificationId: string): Promise<ClassificationDefinition> {
    return this.classificationsService.getClassification(classificationId);
  }

  private async updateClassification(classification: Classification) {
    await this.classificationsService.putClassification(classification._links.self.href, classification);
    this.refreshClassification.emit(classification.key);
    this.switchTaskanaSpinner(false);
  }

  private collapseParentNodeIfItIsTheLastChild(node: any) {
    if (node.parentId.length > 0 && this.getNode(node.parentId) && this.getNode(node.parentId).children.length < 2) {
      this.tree.treeModel.update();
      this.getNode(node.parentId).collapse();
    }
  }

  switchTaskanaSpinner(active: boolean) {
    this.switchTaskanaSpinnerEmit.emit(active);
  }

  ngOnDestroy(): void {
    if (this.removedNodeIdSubscription) {
      this.removedNodeIdSubscription.unsubscribe();
    }
  }
}


text:
<!doctype html>

    <title>Code coverage report for ol/source/imagestaticsource.js</title>
    <meta charset="utf-8" />
    <link rel="stylesheet" href="../../prettify.css" />
    <link rel="stylesheet" href="../../base.css" />
    <meta name="viewport" content="width=device-width, initial-scale=1">

      all files / ol/source/ imagestaticsource.js

        96.3%
        Statements
        26/27

        60%
        Branches
        6/10

        100%
        Functions
        2/2

        96.3%
        Lines
        26/27

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74	1×

1×
1×
1×
1×
1×
1×
1×

1×

4×

4×

4×
4×
1×
1×
1×
1×

4×

4×

4×

4×

4×

1×

1×

1×
1×

goog.provide('ol.source.ImageStatic');

goog.require('goog.events');
goog.require('goog.events.EventType');
goog.require('ol.Image');
goog.require('ol.ImageLoadFunctionType');
goog.require('ol.extent');
goog.require('ol.proj');
goog.require('ol.source.Image');

/**
 * @classdesc
 * A layer source for displaying a single, static image.
 *
 * @constructor
 * @extends {ol.source.Image}
 * @param {olx.source.ImageStaticOptions} options Options.
 * @api stable
 */
ol.source.ImageStatic = function(options) {

  var attributions = options.attributions !== undefined ?
      options.attributions : null;

  var imageExtent = options.imageExtent;

  var xResolution, yResolution, resolutions, imgResolution;
  if (options.imageSize !== undefined) {
    xResolution = ol.extent.getWidth(imageExtent) / options.imageSize[0];
    yResolution = ol.extent.getHeight(imageExtent) / options.imageSize[1];
    imgResolution = [xResolution, yResolution];
    resolutions = [yResolution];
  }

  var crossOrigin = options.crossOrigin !== undefined ?
      options.crossOrigin : null;

  var /** @type {ol.ImageLoadFunctionType} */ imageLoadFunction =
      options.imageLoadFunction !== undefined ?
      options.imageLoadFunction : ol.source.Image.defaultImageLoadFunction;

  goog.base(this, {
    attributions: attributions,
    logo: options.logo,
    projection: ol.proj.get(options.projection),
    resolutions: resolutions
  });

  /**
   * @private
   * @type {ol.Image}
   */
  this.image_ = new ol.Image(imageExtent, imgResolution, 1,
      attributions, options.url, crossOrigin, imageLoadFunction);
  goog.events.listen(this.image_, goog.events.EventType.CHANGE,
      this.handleImageChange, false, this);

};
goog.inherits(ol.source.ImageStatic, ol.source.Image);

/**
 * @inheritDoc
 */
ol.source.ImageStatic.prototype.getImageInternal =
    function(extent, resolution, pixelRatio, projection) {
  Eif (ol.extent.intersects(extent, this.image_.getExtent())) {
    return this.image_;
  }
  return null;
};

  Code coverage
  generated by istanbul at Fri Nov 06 2015 19:36:11 GMT+0100 (CET)


text:
<link rel="import" href="product.html">
<link rel="import" href="settings.html">
<link rel="import" href="loghandler.html">
<link rel="import" href="admin-dialogs.html">

<dom-module id="admin-api">
  <template>
    <style>
      :host {
        display: block;
      }
    </style>
    <admin-dialogs></admin-dialogs>
  </template>
</dom-module>

<script>
Polymer({
  is: 'admin-api',
  behaviors: [
    Trendystore.API.Admin.Loghandler,
    Trendystore.API.Admin.Product,
    Trendystore.API.Admin.Settings
  ],

  properties: {

    appName: String,

    toastTarget: {
      type: HTMLElement
    },

    notificationsTarget: {
      type: Object,
      value: undefined
    },

    showToast: {
      type: Boolean,
      value: false
    },

    loaded: {
      type: Boolean,
      value: false
    }
  },

  observers: [
    '_setupToast(toastTarget, showToast)'
  ],

  _setupToast: function(target, show) {
    if (show && target) {
      // Only use a toast when asked for
      this.toast = target;
      if (Trendystore.API.Admin.Product.length && Trendystore.API.Admin.Settings.length) {
        Trendystore.API.Admin.Product[1].toast = this.toast;
        Trendystore.API.Admin.Settings[0].toast = this.toast;
      }
    }
  },

  openDialog: function(dialog) {
    Polymer.dom(this.root).querySelector('admin-dialogs').open(dialog);
    return new Promise(function(resolve, reject) {
      this._promiseReason().then(function(succes) {
        if (succes) {
          resolve(succes);
        }
      }).catch(function(error) {
        resolve(error);
      });
    }.bind(this));
  },

  _addEventListener: function(target, name, func) {
    target.addEventListener(name, func);
  },

  _promiseReason: function() {
    return new Promise(function(resolve, reject) {
      var dialogs = Polymer.dom(this.root).querySelector('admin-dialogs');
      this._addEventListener(dialogs, 'iron-overlay-closed', function(e) {
        if (e.detail.confirmed) {
          resolve('confirmed');
        } else if (e.detail.canceled) {
          resolve('canceled');
        } else {
          reject('error getting closing reason for: ' + e.detail);
        }
      }.bind(this));

    }.bind(this));

  }
});
</script>


text:
/**
 *
 */
package raw.blockChain.services.thickNode.messages.types;

import raw.blockChain.api.Block;
import raw.blockChain.api.HashValue;
import raw.blockChain.services.thickNode.ThickNode;
import raw.blockChain.services.thickNode.messages.ThickNodeMessages;
import raw.blockChain.services.thinNode.ThinNode;

/**
 * This message is meant to be used by {@link ThinNode}s to request informations about a given block
 * and by {@link ThickNode}s to reply to such requests.
 *
 * @author vic
 *
 */
public class BlockRequestMessage implements ThickNodeMessages {

	/**
	 * random generated UID
	 */
	private static final long serialVersionUID = 3569850394190538560L;

	private boolean isRequest;
	private boolean isReject;
	private RequestType typeOfRequest;

	private long blockNumber;
	private HashValue hash;
	private Block block;

	/**
	 * Create a request for a copy
	 * of the last {@link Block}
	 * in the block chain.
	 */
	public BlockRequestMessage() {
		isRequest = true;
		isReject = false;
		typeOfRequest = RequestType.LAST_IN_CHAIN;
	}

	/**
	 * Create a request for a {@link Block} by means of
	 * its number
	 *
	 * @param blockNumber the {@link Block} number
	 */
	public BlockRequestMessage(long blockNumber) {
		isRequest = true;
		isReject = false;
		this.blockNumber = blockNumber;
		typeOfRequest = RequestType.BY_BLOCK_NUMBER;
	}

	/**
	 * Create a request for a {@link Block} by means of
	 * its {@link HashValue} header hash.
	 *
	 * @param hash
	 */
	public BlockRequestMessage(HashValue hash) {
		isRequest = true;
		isReject = false;
		this.hash = hash;
		typeOfRequest = RequestType.BY_HASH;
	}

	/**
	 * Create a reply to a {@link Block} request.
	 *
	 * @param block the {@link Block} requested
	 */
	public BlockRequestMessage(Block block) {
		isRequest = false;
		isReject = false;
		this.block = block;
	}

	/**
	 * Change a message from a request one to
	 * a rejection.
	 */
	public void rejectMessage(){
		isRequest = false;
		isReject = true;
	}

	public boolean isRequestMessage(){
		return isRequest;
	}

	public boolean isPositiveReply(){
		return (!isRequest)&&(!isReject);
	}

	public boolean isNegativeReply(){
		return (!isRequest)&&isReject;
	}

	/**
	 * @return the typeOfRequest
	 */
	public RequestType getTypeOfRequest() {
		return typeOfRequest;
	}

	/**
	 * @return the blockNumber
	 */
	public long getBlockNumber() {
		return blockNumber;
	}

	/**
	 * @return the hash
	 */
	public HashValue getHash() {
		return hash;
	}

	/**
	 * @return the block
	 */
	public Block getBlock() {
		return block;
	}

	public enum RequestType{
		BY_BLOCK_NUMBER,
		BY_HASH,
		LAST_IN_CHAIN;
	}

}


text:
title: Telegram Messenger
description: The best messenger app in the market today
keywords: messenger, telegram, im, instant messaging
---

I love Telegram Messenger. It is the best instant messaging application today, IMO.

Reasons:
* Open source client. That too GPL!
* Promotes development by third party
* Has desktop clients, web clients, and even command line clients
* Cloud sync
* Encryption
* Usernames
* Groups that does not give away phone number
* Chat without giving away phone number
* Secret chat


text:
/**
 * @class Ext.BoxComponent
 * @extends Ext.Component
 *
Base class for any visual {@link Ext.Component} that uses a box container.  BoxComponent provides automatic box
 * model adjustments for sizing and positioning and will work correctly withnin the Component rendering model.  All
 * container classes should subclass BoxComponent so that they will work consistently when nested within other Ext
 * layout containers.

 *
A BoxComponent may be created as a custom Component which encapsulates any HTML element, either a pre-existing
 * element, or one that is created to your specifications at render time. Usually, to participate in layouts,
 * a Component will need to be a BoxComponent in order to have its width and height managed.

 *
To use a pre-existing element as a BoxComponent, configure it so that you preset the el property to the
 * element to reference:

var pageHeader = new Ext.BoxComponent({
    el: 'my-header-div'
});

 * This may then be {@link Ext.Container#add added} to a {@link Ext.Container Container} as a child item.

 *
To create a BoxComponent based around a HTML element to be created at render time, use the
 * {@link Ext.Component#autoEl autoEl} config option which takes the form of a
 * {@link Ext.DomHelper DomHelper} specification:

var myImage = new Ext.BoxComponent({
    autoEl: {
        tag: 'img',
        src: '/images/my-image.jpg'
    }
});

 * @constructor
 * @param {Ext.Element/String/Object} config The configuration options.
 */
Ext.BoxComponent = Ext.extend(Ext.Component, {
    /**
     * @cfg {Number} x
     * The local x (left) coordinate for this component if contained within a positioning container.
     */
    /**
     * @cfg {Number} y
     * The local y (top) coordinate for this component if contained within a positioning container.
     */
    /**
     * @cfg {Number} pageX
     * The page level x coordinate for this component if contained within a positioning container.
     */
    /**
     * @cfg {Number} pageY
     * The page level y coordinate for this component if contained within a positioning container.
     */
    /**
     * @cfg {Number} height
     * The height of this component in pixels (defaults to auto).
     */
    /**
     * @cfg {Number} width
     * The width of this component in pixels (defaults to auto).
     */
    /**
     * @cfg {Boolean} autoHeight
     * True to use height:'auto', false to use fixed height (defaults to false). Note: Although many components
     * inherit this config option, not all will function as expected with a height of 'auto'. Setting autoHeight:true
     * means that the browser will manage height based on the element's contents, and that Ext will not manage it at all.
     */
    /**
     * @cfg {Boolean} autoWidth
     * True to use width:'auto', false to use fixed width (defaults to false). Note: Although many components
     * inherit this config option, not all will function as expected with a width of 'auto'. Setting autoWidth:true
     * means that the browser will manage width based on the element's contents, and that Ext will not manage it at all.
     */

    /* // private internal config
     * {Boolean} deferHeight
     * True to defer height calculations to an external component, false to allow this component to set its own
     * height (defaults to false).
     */

	// private
    initComponent : function(){
        Ext.BoxComponent.superclass.initComponent.call(this);
        this.addEvents(
            /**
             * @event resize
             * Fires after the component is resized.
             * @param {Ext.Component} this
             * @param {Number} adjWidth The box-adjusted width that was set
             * @param {Number} adjHeight The box-adjusted height that was set
             * @param {Number} rawWidth The width that was originally specified
             * @param {Number} rawHeight The height that was originally specified
             */
            'resize',
            /**
             * @event move
             * Fires after the component is moved.
             * @param {Ext.Component} this
             * @param {Number} x The new x position
             * @param {Number} y The new y position
             */
            'move'
        );
    },

    // private, set in afterRender to signify that the component has been rendered
    boxReady : false,
    // private, used to defer height settings to subclasses
    deferHeight: false,

    /**
     * Sets the width and height of the component.  This method fires the {@link #resize} event.  This method can accept
     * either width and height as separate numeric arguments, or you can pass a size object like {width:10, height:20}.
     * @param {Number/Object} width The new width to set, or a size object in the format {width, height}
     * @param {Number} height The new height to set (not required if a size object is passed as the first arg)
     * @return {Ext.BoxComponent} this
     */
    setSize : function(w, h){
        // support for standard size objects
        if(typeof w == 'object'){
            h = w.height;
            w = w.width;
        }
        // not rendered
        if(!this.boxReady){
            this.width = w;
            this.height = h;
            return this;
        }

        // prevent recalcs when not needed
        if(this.lastSize && this.lastSize.width == w && this.lastSize.height == h){
            return this;
        }
        this.lastSize = {width: w, height: h};
        var adj = this.adjustSize(w, h);
        var aw = adj.width, ah = adj.height;
        if(aw !== undefined || ah !== undefined){ // this code is nasty but performs better with floaters
            var rz = this.getResizeEl();
            if(!this.deferHeight && aw !== undefined && ah !== undefined){
                rz.setSize(aw, ah);
            }else if(!this.deferHeight && ah !== undefined){
                rz.setHeight(ah);
            }else if(aw !== undefined){
                rz.setWidth(aw);
            }
            this.onResize(aw, ah, w, h);
            this.fireEvent('resize', this, aw, ah, w, h);
        }
        return this;
    },

    /**
     * Sets the width of the component.  This method fires the {@link #resize} event.
     * @param {Number} width The new width to set
     * @return {Ext.BoxComponent} this
     */
    setWidth : function(width){
        return this.setSize(width);
    },

    /**
     * Sets the height of the component.  This method fires the {@link #resize} event.
     * @param {Number} height The new height to set
     * @return {Ext.BoxComponent} this
     */
    setHeight : function(height){
        return this.setSize(undefined, height);
    },

    /**
     * Gets the current size of the component's underlying element.
     * @return {Object} An object containing the element's size {width: (element width), height: (element height)}
     */
    getSize : function(){
        return this.el.getSize();
    },

    /**
     * Gets the current XY position of the component's underlying element.
     * @param {Boolean} local (optional) If true the element's left and top are returned instead of page XY (defaults to false)
     * @return {Array} The XY position of the element (e.g., [100, 200])
     */
    getPosition : function(local){
        if(local === true){
            return [this.el.getLeft(true), this.el.getTop(true)];
        }
        return this.xy || this.el.getXY();
    },

    /**
     * Gets the current box measurements of the component's underlying element.
     * @param {Boolean} local (optional) If true the element's left and top are returned instead of page XY (defaults to false)
     * @return {Object} box An object in the format {x, y, width, height}
     */
    getBox : function(local){
        var s = this.el.getSize();
        if(local === true){
            s.x = this.el.getLeft(true);
            s.y = this.el.getTop(true);
        }else{
            var xy = this.xy || this.el.getXY();
            s.x = xy[0];
            s.y = xy[1];
        }
        return s;
    },

    /**
     * Sets the current box measurements of the component's underlying element.
     * @param {Object} box An object in the format {x, y, width, height}
     * @return {Ext.BoxComponent} this
     */
    updateBox : function(box){
        this.setSize(box.width, box.height);
        this.setPagePosition(box.x, box.y);
        return this;
    },

    // protected
    getResizeEl : function(){
        return this.resizeEl || this.el;
    },

    // protected
    getPositionEl : function(){
        return this.positionEl || this.el;
    },

    /**
     * Sets the left and top of the component.  To set the page XY position instead, use {@link #setPagePosition}.
     * This method fires the {@link #move} event.
     * @param {Number} left The new left
     * @param {Number} top The new top
     * @return {Ext.BoxComponent} this
     */
    setPosition : function(x, y){
        if(x && typeof x[1] == 'number'){
            y = x[1];
            x = x[0];
        }
        this.x = x;
        this.y = y;
        if(!this.boxReady){
            return this;
        }
        var adj = this.adjustPosition(x, y);
        var ax = adj.x, ay = adj.y;

        var el = this.getPositionEl();
        if(ax !== undefined || ay !== undefined){
            if(ax !== undefined && ay !== undefined){
                el.setLeftTop(ax, ay);
            }else if(ax !== undefined){
                el.setLeft(ax);
            }else if(ay !== undefined){
                el.setTop(ay);
            }
            this.onPosition(ax, ay);
            this.fireEvent('move', this, ax, ay);
        }
        return this;
    },

    /**
     * Sets the page XY position of the component.  To set the left and top instead, use {@link #setPosition}.
     * This method fires the {@link #move} event.
     * @param {Number} x The new x position
     * @param {Number} y The new y position
     * @return {Ext.BoxComponent} this
     */
    setPagePosition : function(x, y){
        if(x && typeof x[1] == 'number'){
            y = x[1];
            x = x[0];
        }
        this.pageX = x;
        this.pageY = y;
        if(!this.boxReady){
            return;
        }
        if(x === undefined || y === undefined){ // cannot translate undefined points
            return;
        }
        var p = this.el.translatePoints(x, y);
        this.setPosition(p.left, p.top);
        return this;
    },

    // private
    onRender : function(ct, position){
        Ext.BoxComponent.superclass.onRender.call(this, ct, position);
        if(this.resizeEl){
            this.resizeEl = Ext.get(this.resizeEl);
        }
        if(this.positionEl){
            this.positionEl = Ext.get(this.positionEl);
        }
    },

    // private
    afterRender : function(){
        Ext.BoxComponent.superclass.afterRender.call(this);
        this.boxReady = true;
        this.setSize(this.width, this.height);
        if(this.x || this.y){
            this.setPosition(this.x, this.y);
        }else if(this.pageX || this.pageY){
            this.setPagePosition(this.pageX, this.pageY);
        }
    },

    /**
     * Force the component's size to recalculate based on the underlying element's current height and width.
     * @return {Ext.BoxComponent} this
     */
    syncSize : function(){
        delete this.lastSize;
        this.setSize(this.autoWidth ? undefined : this.el.getWidth(), this.autoHeight ? undefined : this.el.getHeight());
        return this;
    },

    /* // protected
     * Called after the component is resized, this method is empty by default but can be implemented by any
     * subclass that needs to perform custom logic after a resize occurs.
     * @param {Number} adjWidth The box-adjusted width that was set
     * @param {Number} adjHeight The box-adjusted height that was set
     * @param {Number} rawWidth The width that was originally specified
     * @param {Number} rawHeight The height that was originally specified
     */
    onResize : function(adjWidth, adjHeight, rawWidth, rawHeight){

    },

    /* // protected
     * Called after the component is moved, this method is empty by default but can be implemented by any
     * subclass that needs to perform custom logic after a move occurs.
     * @param {Number} x The new x position
     * @param {Number} y The new y position
     */
    onPosition : function(x, y){

    },

    // private
    adjustSize : function(w, h){
        if(this.autoWidth){
            w = 'auto';
        }
        if(this.autoHeight){
            h = 'auto';
        }
        return {width : w, height: h};
    },

    // private
    adjustPosition : function(x, y){
        return {x : x, y: y};
    }
});
Ext.reg('box', Ext.BoxComponent);


text:
<?php namespace Fisharebest\Localization\Locale;

use Fisharebest\Localization\Territory\TerritoryGy;

class LocaleEnGy extends LocaleEn {
	public function territory() {
		return new TerritoryGy;
	}
}


text:
namespace System.ServiceModel.Discovery
{
    using System;
    using System.ServiceModel;
    using System.ServiceModel.Channels;

    class DiscoveryClientOutputChannel<TChannel> : DiscoveryClientChannelBase<TChannel>, IOutputChannel
        where TChannel : class, IOutputChannel
    {
        public DiscoveryClientOutputChannel(
            ChannelManagerBase channelManagerBase,
            IChannelFactory<TChannel> innerChannelFactory,
            FindCriteria findCriteria,
            DiscoveryEndpointProvider discoveryEndpointProvider)
            : base(channelManagerBase, innerChannelFactory, findCriteria, discoveryEndpointProvider)
        {
        }

        public EndpointAddress RemoteAddress
        {
            get
            {
                if (this.InnerChannel == null)
                {
                    return DiscoveryClientBindingElement.DiscoveryEndpointAddress;
                }

                return this.InnerChannel.RemoteAddress;
            }
        }

        public Uri Via
        {
            get
            {
                if (this.InnerChannel == null)
                {
                    return DiscoveryClientBindingElement.DiscoveryEndpointAddress.Uri;
                }

                return this.InnerChannel.Via;
            }
        }

        public virtual IAsyncResult BeginSend(Message message, TimeSpan timeout, AsyncCallback callback, object state)
        {
            return this.InnerChannel.BeginSend(message, timeout, callback, state);
        }

        public IAsyncResult BeginSend(Message message, AsyncCallback callback, object state)
        {
            return this.BeginSend(message, this.DefaultSendTimeout, callback, state);
        }

        public void EndSend(IAsyncResult result)
        {
            this.InnerChannel.EndSend(result);
        }

        public virtual void Send(Message message, TimeSpan timeout)
        {
            this.InnerChannel.Send(message, timeout);
        }

        public void Send(Message message)
        {
            this.Send(message, this.DefaultSendTimeout);
        }
    }
}


text:
This is a short tutorial demonstrating how to add search functionality to a SilverStripe site. It is recommended that
you have completed the earlier tutorials, especially the tutorial on forms, before attempting this tutorial. While this
tutorial will add search functionality to the site built in the previous tutorials, it should be straight forward to
follow this tutorial on any site of your own. If you are adding the search form to the tutorial site, please get
![this updated css file](_images/layout.css) and place it in *themes/tutorial/css* (as layout.css) and this
![search file tree icon](_images/search-file.gif) search file tree icon and place it in *themes/tutorial/images/treeicons* (as
search-file.gif).

## What are we working towards?

We are going to add a search box on the top of the page. When a user types something in the box, they are taken to a
results page.

![](_images/searchresults-small.png)

## Creating the search form

The Search Form functionality has been altered over time. Please use the section which applies to your SilverStripe
version.

### 2.4 and newer

SilverStripe 2.4 does not come bundled with the search engine enabled. To enable the search engine you need to include
the following code in your mysite/_config.php file

	:::php
	FulltextSearchable::enable();

After including that in your _config.php you will need to rebuild the database by visiting http://yoursite.com/dev/build
in your web browser. This will add the fulltext search columns.

The actual search form code is already provided in FulltextSearchable so when you add the enable line above to your
_config you can add your form as $SearchForm.

### 2.3

SilverStripe 2.3 came bundled with the code as well as a MySQL Search engine. If you are using the blackcandy theme you
should have everything you need already to have a search. If you are using the tutorial theme then you can simply skip
down to 'Adding the search form' as the PHP code is already provided in Page.php. If it is not then you can follow the
instructions below as well.
### 2.2

If you are using SilverStripe 2.2 or earlier then you need to define your own code. The first step in implementing
search on your site is to create a form for the user to type their query. Create a function named *SearchForm* on the
*Page_Controller* class (//mysite/code/Page.php//).

	:::php
	class Page_Controller extends ContentController {
	   function SearchForm() {
	      $searchText = isset($this->Query) ? $this->Query : 'Search';

	      $fields = new FieldSet(
	         new TextField("Search", "", $searchText)
	      );

	      $actions = new FieldSet(
	         new FormAction('results', 'Go')
	      );

	      return new SearchForm($this, "SearchForm", $fields, $actions);
	   }
	}

## Adding the search form

We then just need to add the search form to the template. Add *$SearchForm* to the 'Header' div in
*themes/tutorial/templates/Page.ss*.

*themes/tutorial/templates/Page.ss*

	:::ss

	  $SearchForm

$Title

![](_images/searchform.png)

## Showing the results

Next we need to create the *results* function.

*mysite/code/Page.php*

	:::php
	class Page_Controller extends ContentController {
	   ...

	   function results($data, $form){
	      $data = array(
	         'Results' => $form->getResults(),
	         'Query' => $form->getSearchQuery(),
	         'Title' => 'Search Results'
	      );
	      $this->Query = $form->getSearchQuery();

	      return $this->customise($data)->renderWith(array('Page_results', 'Page'));
	   }
	}

First we populate an array with the data we wish to pass to the template - the search results, query and title of the
page. The final line is a little more complicated.

When we call a function by its url (eg http://localhost/home/results), SilverStripe will look for a template with the
name `PageType_function.ss`. As we are implementing the *results* function on the *Page* page type, we create our
results page template as *Page_results.ss*. Unfortunately this doesn't work when we are using page types that are
children of the *Page* page type. For example, if someone used the search on the homepage, it would be rendered with
*Homepage.ss* rather than *Page_results.ss*. SilverStripe always looks for the template from the most specific page type
first, so in this case it would use the first template it finds in this list:

*  HomePage_results.ss
*  HomePage.ss
*  Page_results.ss
*  Page.ss

We can override this list by using the *renderWith* function. The *renderWith* function takes an array of the names of
the templates you wish to render the page with. Here we first add the data to the page by using the 'customise'
function, and then attempt to render it with *Page_results.ss*, falling back to *Page.ss* if there is no
*Page_results.ss*.

## Creating the template

Lastly we need to create the template for the search page. This template uses all the same techniques used in previous
tutorials. It also uses a number of pagination variables, which are provided by the `[api:DataObjectSet]`
class.

*themes/tutorial/templates/Layout/Page_results.ss*

	:::ss

$Title

	  <% if Query %>

You searched for "{$Query}"

	  <% end_if %>

	  <% if Results %>

	      <% control Results %>

	            <% if MenuTitle %>
	              $MenuTitle
	            <% else %>
	              $Title
	            <% end_if %>

$Content.LimitWordCountXML

	          Read more about "{$Title}"...

	      <% end_control %>

	  <% else %>

Sorry, your search query did not return any results.

	  <% end_if %>

	  <% if Results.MoreThanOnePage %>

	      <% if Results.NotLastPage %>
	        Next
	      <% end_if %>
	      <% if Results.NotFirstPage %>
	        Prev
	      <% end_if %>

	        <% control Results.Pages %>
	          <% if CurrentBool %>
	            $PageNum
	          <% else %>
	            $PageNum
	          <% end_if %>
	        <% end_control %>

Page $Results.CurrentPage of $Results.TotalPages

	  <% end_if %>

![](_images/searchresults.png)

## Summary

This tutorial has demonstrated how easy it is to have full text searching on your site. To add search to a SilverStripe
site, only a search form and a results page need to be created.

[Next Tutorial >>](5-dataobject-relationship-management)


text:
package cabf_br

import (
	"testing"

	"github.com/zmap/zlint/v3/lint"
	"github.com/zmap/zlint/v3/test"
)

func TestCaCountryNameInvalid(t *testing.T) {
	inputPath := "caInvalCountryCode.pem"
	expected := lint.Error
	out := test.TestLint("e_ca_country_name_invalid", inputPath)
	if out.Status != expected {
		t.Errorf("%s: expected %s, got %s", inputPath, expected, out.Status)
	}
}

func TestCaCountryNameValid(t *testing.T) {
	inputPath := "caValCountry.pem"
	expected := lint.Pass
	out := test.TestLint("e_ca_country_name_invalid", inputPath)
	if out.Status != expected {
		t.Errorf("%s: expected %s, got %s", inputPath, expected, out.Status)
	}
}


text:
import * as gulp from 'gulp';
import * as gulpLoadPlugins from 'gulp-load-plugins';
import * as merge from 'merge-stream';
import * as util from 'gulp-util';
import { join/*, sep, relative*/ } from 'path';

import Config from '../../config';
import { makeTsProject, TemplateLocalsBuilder } from '../../utils';
import { TypeScriptTask } from '../typescript_task';

const plugins = <any>gulpLoadPlugins();

let typedBuildCounter = Config.TYPED_COMPILE_INTERVAL; // Always start with the typed build.

/**
 * Executes the build process, transpiling the TypeScript files (except the spec and e2e-spec files) for the development
 * environment.
 */
export =
  class BuildJsDev extends TypeScriptTask {
    run() {
      let tsProject: any;
      let typings = gulp.src([
        Config.TOOLS_DIR + '/manual_typings/**/*.d.ts'
      ]);
      let src = [
        join(Config.APP_SRC, '**/*.ts'),
        '!' + join(Config.APP_SRC, '**/*.spec.ts'),
        '!' + join(Config.APP_SRC, '**/*.e2e-spec.ts'),
        '!' + join(Config.APP_SRC, `**/${Config.NG_FACTORY_FILE}.ts`)
      ];

      let projectFiles = gulp.src(src);
      let result: any;
      let isFullCompile = true;

      // Only do a typed build every X builds, otherwise do a typeless build to speed things up
      if (typedBuildCounter < Config.TYPED_COMPILE_INTERVAL) {
        isFullCompile = false;
        tsProject = makeTsProject({isolatedModules: true});
        projectFiles = projectFiles.pipe(plugins.cached());
        util.log('Performing typeless TypeScript compile.');
      } else {
        tsProject = makeTsProject();
        projectFiles = merge(typings, projectFiles);
      }

      result = projectFiles
        .pipe(plugins.plumber())
        .pipe(plugins.sourcemaps.init())
        .pipe(tsProject())
        .on('error', () => {
          typedBuildCounter = Config.TYPED_COMPILE_INTERVAL;
        });

      if (isFullCompile) {
        typedBuildCounter = 0;
      } else {
        typedBuildCounter++;
      }

      return result.js
        .pipe(plugins.sourcemaps.write())
        // Use for debugging with Webstorm/IntelliJ
        // https://github.com/mgechev/angular-seed/issues/1220
        //    .pipe(plugins.sourcemaps.write('.', {
        //      includeContent: false,
        //      sourceRoot: (file: any) =>
        //        relative(file.path, Config.PROJECT_ROOT + '/' + Config.APP_SRC).replace(sep, '/') + '/' + Config.APP_SRC
        //    }))
        .pipe(plugins.template(new TemplateLocalsBuilder().withStringifiedSystemConfigDev().build()))
        .pipe(gulp.dest(Config.APP_DEST));
    }
  };


text:
package com.dtodorov.zerobeat.teacher;

import com.dtodorov.zerobeat.Configuration;

/**
 * Created by diman on 7/19/2017.
 */

public interface ISchoolConfiguration
{
    Configuration.CourseLevel getCourseLevel();
    float getNoiseLevel();
}


text:
import random
import requests
from lxml import html

# accepts no parameter
# scrapes a list of most popular male and female first names from 'http://names.mongabay.com'
# returns an array of strings
def gen_first_name():
    page = requests.get('http://names.mongabay.com/male_names.htm')
    tree = html.fromstring(page.content)
    names = tree.xpath('//td[1]/text()')

    page = requests.get('http://names.mongabay.com/male_names3.htm')
    tree = html.fromstring(page.content)
    names += tree.xpath('//td[1]/text()')

    page = requests.get('http://names.mongabay.com/male_names6.htm')
    tree = html.fromstring(page.content)
    names += tree.xpath('//td[1]/text()')

    page = requests.get('http://names.mongabay.com/male_names9.htm')
    tree = html.fromstring(page.content)
    names += tree.xpath('//td[1]/text()')

    page = requests.get('http://names.mongabay.com/female_names.htm')
    tree = html.fromstring(page.content)
    names += tree.xpath('//td[1]/text()')
    return names

# accepts no parameter
# scrapes a list of most popular last names from 'http://names.mongabay.com/data/1000.html'
# returns an array of strings
def gen_last_name():
    page = requests.get('http://names.mongabay.com/data/1000.html')
    tree = html.fromstring(page.content)
    names = tree.xpath('//td[not(@class="c1")][not(@class="c2")][not(@class="c3")][not(@class="c4")]/text()')
    names = names[1:]
    return names

# accepts 3 parameters: key_limit, age_min, age_max
# selects a random first name, last name, age and formats it into an sql statement
# the sql statement in appended to an array
# returns an array of strings of sql statements
def gen_sql_array(key_limit, age_min, age_max):
    first_name_array = gen_first_name()
    last_name_array = gen_last_name()
    sql_array = []
    for i in range(1, key_limit + 1):
        first_name = random.choice(first_name_array).capitalize()
        last_name = random.choice(last_name_array).capitalize()
        age = random.randint(age_min, age_max)
        statement = "INSERT INTO person Values (" + str(i) + ", " + first_name + ", " + last_name + ", " + str(age) + ");"
        sql_array.append(statement)
    return sql_array

# accepts a parameter array
# creates a file named mysql.sql
# writes the contents of the array (sql statements) to the file named mysql.sql
# closes the array
def write_array_to_file(array):
    f = open('mysql.sql', 'w')
    for statement in array:
        f.write(statement+'\n')
    f.close()

# a function that calls write_array_to_file with preset parameters 100, 18, 80
def write_array_to_file_help():
    array = gen_sql_array(100, 18, 80)
    write_array_to_file(array)

# accepts no parameter
# scrapes a list of most popular last names from 'https://en.wikipedia.org/wiki/List_of_United_States_cities_by_population'
# returns an array of strings
def gen_city_names():
    page = requests.get('https://en.wikipedia.org/wiki/List_of_United_States_cities_by_population')
    tree = html.fromstring(page.content)
    names = tree.xpath('//td[@align="left"]/i/a/text()')
    names += tree.xpath('//td[@align="left"]/i/b/a/text()')
    names += tree.xpath('//td[@align="left"]/b/a/text()')

write_array_to_file_help()


text:
export SDL_FBDEV=/dev/fb1
cat /dev/stdin | ./raspipe.py $@


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

    <title>{{MainTitle}}</title>
    <link href="{{ContentUrl}}bootstrap.css" rel="stylesheet">

    <link href="{{ContentUrl}}prettify.css" type="text/css" rel="stylesheet" />

                    {{MainTitle}}

App Root

Metadata

NServiceMVC

        {{Content}}

Back to top

Metadata generated by NServiceMVC.


text:
using System.Collections.Generic;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Testura.Android.Device.Ui.Nodes.Data;
using Testura.Android.PageObjectCreator.Models;
using Testura.Android.PageObjectCreator.ViewModels;

namespace Testura.Android.PageObjectCreator.Views
{
    /// <summary>
    /// Interaction logic for ScreenView.xaml
    /// </summary>
    public partial class ScreenView : UserControl
    {
        private readonly ScreenViewModel _viewModel;
        private readonly IDictionary<Node, UIElement> _savedNodes;
        private AndroidDumpInfo _dumpInfo;
        private BitmapImage _lastImage;
        private Rectangle _lastSelectedNodeRectangle;
        private Rectangle _lastTemporaryHierarchyNode;

        public ScreenView()
        {
            _savedNodes = new Dictionary<Node, UIElement>();
            InitializeComponent();
            _viewModel = DataContext as ScreenViewModel;
            _viewModel.LoadImage += OnLoadImage;
            _viewModel.NewTemporaryHierarchyNode += OnNewTemporaryHierarchyNode;
            _viewModel.HierarchyNodeAdded += OnHierarchyNodeAdded;
            _viewModel.NodeRemoved += OnNodeRemoved;
        }

        private void OnNodeRemoved(object sender, Node node)
        {
            if (_savedNodes.ContainsKey(node))
            {
                DeviceCanvas.Children.Remove(_savedNodes[node]);
                _savedNodes.Remove(node);
            }
        }

        private void OnHierarchyNodeAdded(object sender, Node node)
        {
            _lastTemporaryHierarchyNode.Stroke = new SolidColorBrush(Colors.Red);
            _savedNodes.Add(node, _lastTemporaryHierarchyNode);
            _lastTemporaryHierarchyNode = null;
        }

        private void OnNewTemporaryHierarchyNode(object sender, Node node)
        {
            if (_lastTemporaryHierarchyNode != null)
            {
                DeviceCanvas.Children.Remove(_lastTemporaryHierarchyNode);
            }

            CreateTemporaryRectangle(node);
            _lastTemporaryHierarchyNode = DeviceCanvas.Children[DeviceCanvas.Children.Count - 1] as Rectangle;
        }

        private void OnLoadImage(object sender, AndroidDumpInfo dumpInfo)
        {
            _savedNodes.Clear();
            _dumpInfo = dumpInfo;
            _lastImage = null;
            var image = new BitmapImage();
            using (var stream = File.OpenRead(dumpInfo.ScreenshotPath))
            {
                image.BeginInit();
                image.CacheOption = BitmapCacheOption.OnLoad;
                image.StreamSource = stream;
                image.EndInit();
            }

            _lastImage = image;
            var fixedImage = new Image
            {
                Width = 350,
                Source = _lastImage,
            };
            DeviceCanvas.Children.Add(fixedImage);
        }

        private void DeviceCanvas_OnMouseMove(object sender, MouseEventArgs e)
        {
            if (DeviceCanvas.Children.Count == 0)
            {
                return;
            }

            if (_lastSelectedNodeRectangle != null && _lastSelectedNodeRectangle != _lastTemporaryHierarchyNode)
            {
                DeviceCanvas.Children.Remove(_lastSelectedNodeRectangle);
            }

            var node = MarkNode();

            if (e.LeftButton == MouseButtonState.Pressed && Keyboard.IsKeyDown(Key.LeftCtrl) && node != null)
            {
                var rec = _lastSelectedNodeRectangle;
                _lastSelectedNodeRectangle = null;
                rec.Stroke = new SolidColorBrush(Colors.Red);
                if (_viewModel.AddNode(node))
                {
                    _savedNodes.Add(node, rec);
                }
                else
                {
                    DeviceCanvas.Children.Remove(rec);
                }

                return;
            }

            if ((e.LeftButton == MouseButtonState.Pressed || e.RightButton == MouseButtonState.Pressed) && node != null)
            {
                DeviceCanvas.Children.Remove(_lastSelectedNodeRectangle);
                _lastSelectedNodeRectangle = null;
                _viewModel.ShowNodeDetails(node);
                return;
            }
        }

        private Node MarkNode()
        {
            var imageScale = GetImageScale();
            var mousePosition = Mouse.GetPosition(DeviceCanvas);
            var node = _viewModel.GetNodes(new Point((int)(mousePosition.X * imageScale.XScale), (int)(mousePosition.Y * imageScale.YScale)), _dumpInfo.DumpPath);

            if (node == null)
            {
                return null;
            }

            CreateTemporaryRectangle(node);
            return node;
        }

        private ImageScale GetImageScale()
        {
            var image = DeviceCanvas.Children[0] as Image;

            var ah = image.ActualHeight;
            var aw = image.ActualWidth;

            var imageHeight = _lastImage.Height;
            var imageWidth = _lastImage.Width;

            return new ImageScale { XScale = imageWidth / aw, YScale = imageHeight / ah };
        }

        private void CreateTemporaryRectangle(Node node)
        {
            var imageScale = GetImageScale();
            var bounds = node.GetNodeBounds();

            _lastSelectedNodeRectangle = new Rectangle();
            _lastSelectedNodeRectangle.Stroke = new SolidColorBrush(Colors.Blue);
            _lastSelectedNodeRectangle.Fill = new SolidColorBrush(Colors.Transparent);
            _lastSelectedNodeRectangle.Width = (bounds[1].X - bounds[0].X) / imageScale.XScale;
            _lastSelectedNodeRectangle.Height = (bounds[1].Y - bounds[0].Y) / imageScale.YScale;
            Canvas.SetLeft(_lastSelectedNodeRectangle, bounds[0].X / imageScale.XScale);
            Canvas.SetTop(_lastSelectedNodeRectangle, bounds[0].Y / imageScale.YScale);
            DeviceCanvas.Children.Add(_lastSelectedNodeRectangle);
        }

        private void DeviceCanvas_OnMouseLeave(object sender, MouseEventArgs e)
        {
            if (_lastSelectedNodeRectangle != null)
            {
                DeviceCanvas.Children.Remove(_lastSelectedNodeRectangle);
            }
        }
    }
}


text:
<?php

namespace Vuba\AuthN\AuthStack;

class AttributeMapper
{

}


text:
<?xml version="1.0" ?>
<!--
   Licensed to Cloudera, Inc. under one or more
   contributor license agreements.  See the NOTICE file distributed with
   this work for additional information regarding copyright ownership.
   Cloudera, Inc. licenses this file to You 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.
-->
<ivy-module version="1.0">
  <info organisation="com.cloudera.sqoop" module="${name}-shim-apache">
    <license name="Apache 2.0"/>
    <ivyauthor name="Sqoop Team" url="http://github.com/cloudera/sqoop" />
    <description>
        Sqoop shim for Apache Hadoop
    </description>
  </info>
  <configurations defaultconfmapping="default">
    <!--these match the Maven configurations-->
    <conf name="default" extends="master,runtime"/>
    <conf name="master" description="contains the artifact but no dependencies"/>
    <conf name="runtime" description="runtime but not the artifact" />
    <conf name="common" visibility="private"
      extends="runtime"
      description="artifacts needed to compile/test the application"/>
  </configurations>

  <publications>
    <!--get the artifact from our module name-->
    <artifact conf="master"/>
  </publications>
  <dependencies>
    <!-- Dependencies for Apache Hadoop (trunk) -->
    <dependency org="org.apache.hadoop" name="hadoop-common"
      rev="${hadoop-common.apache.version}" conf="common->default"/>
    <dependency org="org.apache.hadoop" name="hadoop-hdfs"
      rev="${hadoop-hdfs.apache.version}" conf="common->default"/>
    <dependency org="org.apache.hadoop" name="hadoop-mapred"
      rev="${hadoop-mapred.apache.version}" conf="common->default"/>
  </dependencies>
</ivy-module>