text:
/*
 * Copyright (C) 2014 Cloudius Systems, Ltd.
 */

#pragma once

#include <memory>
#include <vector>
#include <cstring>
#include <seastar/core/future.hh>
#include <seastar/net/byteorder.hh>
#include <seastar/net/socket_defs.hh>
#include <seastar/net/packet.hh>
#include <seastar/core/temporary_buffer.hh>
#include <seastar/core/iostream.hh>
#include <seastar/util/std-compat.hh>
#include "../core/internal/api-level.hh"
#include <sys/types.h>

namespace seastar {

inline
bool is_ip_unspecified(const ipv4_addr& addr) noexcept {
    return addr.is_ip_unspecified();
}

inline
bool is_port_unspecified(const ipv4_addr& addr) noexcept {
    return addr.is_port_unspecified();
}

inline
socket_address make_ipv4_address(const ipv4_addr& addr) noexcept {
    return socket_address(addr);
}

inline
socket_address make_ipv4_address(uint32_t ip, uint16_t port) noexcept {
    return make_ipv4_address(ipv4_addr(ip, port));
}

namespace net {

// see linux tcp(7) for parameter explanation
struct tcp_keepalive_params {
    std::chrono::seconds idle; // TCP_KEEPIDLE
    std::chrono::seconds interval; // TCP_KEEPINTVL
    unsigned count; // TCP_KEEPCNT
};

// see linux sctp(7) for parameter explanation
struct sctp_keepalive_params {
    std::chrono::seconds interval; // spp_hbinterval
    unsigned count; // spp_pathmaxrt
};

using keepalive_params = std::variant<tcp_keepalive_params, sctp_keepalive_params>;

/// \cond internal
class connected_socket_impl;
class socket_impl;

class server_socket_impl;
class udp_channel_impl;
class get_impl;
/// \endcond

class udp_datagram_impl {
public:
    virtual ~udp_datagram_impl() {};
    virtual socket_address get_src() = 0;
    virtual socket_address get_dst() = 0;
    virtual uint16_t get_dst_port() = 0;
    virtual packet& get_data() = 0;
};

class udp_datagram final {
private:
    std::unique_ptr<udp_datagram_impl> _impl;
public:
    udp_datagram(std::unique_ptr<udp_datagram_impl>&& impl) noexcept : _impl(std::move(impl)) {};
    socket_address get_src() { return _impl->get_src(); }
    socket_address get_dst() { return _impl->get_dst(); }
    uint16_t get_dst_port() { return _impl->get_dst_port(); }
    packet& get_data() { return _impl->get_data(); }
};

class udp_channel {
private:
    std::unique_ptr<udp_channel_impl> _impl;
public:
    udp_channel() noexcept;
    udp_channel(std::unique_ptr<udp_channel_impl>) noexcept;
    ~udp_channel();

    udp_channel(udp_channel&&) noexcept;
    udp_channel& operator=(udp_channel&&) noexcept;

    socket_address local_address() const;

    future<udp_datagram> receive();
    future<> send(const socket_address& dst, const char* msg);
    future<> send(const socket_address& dst, packet p);
    bool is_closed() const;
    /// Causes a pending receive() to complete (possibly with an exception)
    void shutdown_input();
    /// Causes a pending send() to complete (possibly with an exception)
    void shutdown_output();
    /// Close the channel and releases all resources.
    ///
    /// Must be called only when there are no unfinished send() or receive() calls. You
    /// can force pending calls to complete soon by calling shutdown_input() and
    /// shutdown_output().
    void close();
};

class network_interface_impl;

} /* namespace net */

/// \addtogroup networking-module
/// @{

/// Configuration for buffered connected_socket input operations
///
/// This structure allows tuning of buffered input operations done via
/// connected_socket. It is a hint to the implementation and may be
/// ignored (e.g. the zero-copy native stack does not allocate buffers,
/// so it ignores buffer-size parameters).
struct connected_socket_input_stream_config final {
    /// Initial buffer size to use for input buffering
    unsigned buffer_size = 8192;
    /// Minimum buffer size to use for input buffering. The system will decrease
    /// buffer sizes if it sees a tendency towards small requests, but will not go
    /// below this buffer size.
    unsigned min_buffer_size = 512;
    /// Maximum buffer size to use for input buffering. The system will increase
    /// buffer sizes if it sees a tendency towards large requests, but will not go
    /// above this buffer size.
    unsigned max_buffer_size = 128 * 1024;
};

/// A TCP (or other stream-based protocol) connection.
///
/// A \c connected_socket represents a full-duplex stream between
/// two endpoints, a local endpoint and a remote endpoint.
class connected_socket {
    friend class net::get_impl;
    std::unique_ptr<net::connected_socket_impl> _csi;
public:
    /// Constructs a \c connected_socket not corresponding to a connection
    connected_socket() noexcept;
    ~connected_socket();

    /// \cond internal
    explicit connected_socket(std::unique_ptr<net::connected_socket_impl> csi) noexcept;
    /// \endcond
    /// Moves a \c connected_socket object.
    connected_socket(connected_socket&& cs) noexcept;
    /// Move-assigns a \c connected_socket object.
    connected_socket& operator=(connected_socket&& cs) noexcept;
    /// Gets the input stream.
    ///
    /// \param csisc Configuration for the input_stream returned
    ///
    /// Gets an object returning data sent from the remote endpoint.
    input_stream<char> input(connected_socket_input_stream_config csisc = {});
    /// Gets the output stream.
    ///
    /// Gets an object that sends data to the remote endpoint.
    /// \param buffer_size how much data to buffer
    output_stream<char> output(size_t buffer_size = 8192);
    /// Sets the TCP_NODELAY option (disabling Nagle's algorithm)
    void set_nodelay(bool nodelay);
    /// Gets the TCP_NODELAY option (Nagle's algorithm)
    ///
    /// \return whether the nodelay option is enabled or not
    bool get_nodelay() const;
    /// Sets SO_KEEPALIVE option (enable keepalive timer on a socket)
    void set_keepalive(bool keepalive);
    /// Gets O_KEEPALIVE option
    /// \return whether the keepalive option is enabled or not
    bool get_keepalive() const;
    /// Sets TCP keepalive parameters
    void set_keepalive_parameters(const net::keepalive_params& p);
    /// Get TCP keepalive parameters
    net::keepalive_params get_keepalive_parameters() const;
    /// Sets custom socket options. Based on setsockopt function.
    /// Linux users should refer to protocol-specific manuals
    /// to see available options, e.g. tcp(7), ip(7), etc.
    void set_sockopt(int level, int optname, const void* data, size_t len);
    /// Gets custom socket options. Based on getsockopt function.
    /// Linux users should refer to protocol-specific manuals
    /// to see available options, e.g. tcp(7), ip(7), etc.
    int get_sockopt(int level, int optname, void* data, size_t len) const;

    /// Disables output to the socket.
    ///
    /// Current or future writes that have not been successfully flushed
    /// will immediately fail with an error.  This is useful to abort
    /// operations on a socket that is not making progress due to a
    /// peer failure.
    void shutdown_output();
    /// Disables input from the socket.
    ///
    /// Current or future reads will immediately fail with an error.
    /// This is useful to abort operations on a socket that is not making
    /// progress due to a peer failure.
    void shutdown_input();
};
/// @}

/// \addtogroup networking-module
/// @{

/// The seastar socket.
///
/// A \c socket that allows a connection to be established between
/// two endpoints.
class socket {
    std::unique_ptr<net::socket_impl> _si;
public:
    socket() noexcept = default;
    ~socket();

    /// \cond internal
    explicit socket(std::unique_ptr<net::socket_impl> si) noexcept;
    /// \endcond
    /// Moves a \c seastar::socket object.
    socket(socket&&) noexcept;
    /// Move-assigns a \c seastar::socket object.
    socket& operator=(socket&&) noexcept;

    /// Attempts to establish the connection.
    ///
    /// \return a \ref connected_socket representing the connection.
    future<connected_socket> connect(socket_address sa, socket_address local = {}, transport proto = transport::TCP);

    /// Sets SO_REUSEADDR option (enable reuseaddr option on a socket)
    void set_reuseaddr(bool reuseaddr);
    /// Gets O_REUSEADDR option
    /// \return whether the reuseaddr option is enabled or not
    bool get_reuseaddr() const;
    /// Stops any in-flight connection attempt.
    ///
    /// Cancels the connection attempt if it's still in progress, and
    /// terminates the connection if it has already been established.
    void shutdown();
};

/// @}

/// \addtogroup networking-module
/// @{

/// The result of an server_socket::accept() call
struct accept_result {
    connected_socket connection;  ///< The newly-accepted connection
    socket_address remote_address;  ///< The address of the peer that connected to us
};

/// A listening socket, waiting to accept incoming network connections.
class server_socket {
    std::unique_ptr<net::server_socket_impl> _ssi;
    bool _aborted = false;
public:
    enum class load_balancing_algorithm {
        // This algorithm tries to distribute all connections equally between all shards.
        // It does this by sending new connections to a shard with smallest amount of connections.
        connection_distribution,
        // This algorithm distributes new connection based on peer's tcp port. Destination shard
        // is calculated as a port number modulo number of shards. This allows a client to connect
        // to a specific shard in a server given it knows how many shards server has by choosing
        // src port number accordingly.
        port,
        // This algorithm distributes all new connections to listen_options::fixed_cpu shard only.
        fixed,
        default_ = connection_distribution
    };
    /// Constructs a \c server_socket not corresponding to a connection
    server_socket() noexcept;
    /// \cond internal
    explicit server_socket(std::unique_ptr<net::server_socket_impl> ssi) noexcept;
    /// \endcond
    /// Moves a \c server_socket object.
    server_socket(server_socket&& ss) noexcept;
    ~server_socket();
    /// Move-assigns a \c server_socket object.
    server_socket& operator=(server_socket&& cs) noexcept;

    /// Accepts the next connection to successfully connect to this socket.
    ///
    /// \return an accept_result representing the connection and
    ///         the socket_address of the remote endpoint.
    ///
    /// \see listen(socket_address sa)
    /// \see listen(socket_address sa, listen_options opts)
    future<accept_result> accept();

    /// Stops any \ref accept() in progress.
    ///
    /// Current and future \ref accept() calls will terminate immediately
    /// with an error.
    void abort_accept();

    /// Local bound address
    socket_address local_address() const noexcept;
};

/// @}

struct listen_options {
    bool reuse_address = false;
    server_socket::load_balancing_algorithm lba = server_socket::load_balancing_algorithm::default_;
    transport proto = transport::TCP;
    int listen_backlog = 100;
    unsigned fixed_cpu = 0u;
    void set_fixed_cpu(unsigned cpu) {
        lba = server_socket::load_balancing_algorithm::fixed;
        fixed_cpu = cpu;
    }
};

class network_interface {
private:
    shared_ptr<net::network_interface_impl> _impl;
public:
    network_interface() = delete;
    network_interface(shared_ptr<net::network_interface_impl>) noexcept;
    network_interface(network_interface&&) noexcept;

    network_interface& operator=(network_interface&&) noexcept;

    uint32_t index() const;
    uint32_t mtu() const;

    const sstring& name() const;
    const sstring& display_name() const;
    const std::vector<net::inet_address>& addresses() const;
    const std::vector<uint8_t> hardware_address() const;

    bool is_loopback() const;
    bool is_virtual() const;
    bool is_up() const;
    bool supports_ipv6() const;
};

class network_stack {
public:
    virtual ~network_stack() {}
    virtual server_socket listen(socket_address sa, listen_options opts) = 0;
    // FIXME: local parameter assumes ipv4 for now, fix when adding other AF
    future<connected_socket> connect(socket_address sa, socket_address = {}, transport proto = transport::TCP);
    virtual ::seastar::socket socket() = 0;
    virtual net::udp_channel make_udp_channel(const socket_address& = {}) = 0;
    virtual future<> initialize() {
        return make_ready_future();
    }
    virtual bool has_per_core_namespace() = 0;
    // NOTE: this is not a correct query approach.
    // This question should be per NIC, but we have no such
    // abstraction, so for now this is "stack-wide"
    virtual bool supports_ipv6() const {
        return false;
    }

    /**
     * Returns available network interfaces. This represents a
     * snapshot of interfaces available at call time, hence the
     * return by value.
     */
    virtual std::vector<network_interface> network_interfaces();
};

}


text:
package ml.sparkling.graph.operators.measures.vertex.betweenness.edmonds.struct

import ml.sparkling.graph.operators.measures.vertex.betweenness.edmonds.struct.messages.EdmondsMessage
import org.apache.spark.graphx.VertexId

/**
  * Created by mth on 3/13/17.
  */
class EdmondsVertex(val preds: List[VertexId], val sigma: Int, val depth: Int, val delta: Double, val bc:Double) extends Serializable {
  val explored = preds.nonEmpty

  def applyMessage(msg: EdmondsMessage): EdmondsVertex = EdmondsVertex(msg.preds, msg.sigma, msg.depth)

  override def toString = s"EdmondsVertex($sigma, $depth, $delta, $bc)"
}

object EdmondsVertex {
  def apply(preds: List[VertexId] = List.empty, sigma: Int = -1, depth: Int = -1, delta: Double = 0.0, bc:Double = 0.0): EdmondsVertex =
    new EdmondsVertex(preds, sigma, depth, delta, bc)

  def unapply(arg: EdmondsVertex): Option[(List[VertexId], Int, Int, Double, Double)] = Some((arg.preds, arg.sigma, arg.depth, arg.delta, arg.bc))
}

redpajama_set_name: RedPajamaGithub


text:
// Copyright (c) 2012 Ecma International.  All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.

/*---
es5id: 15.2.3.13-2-7
description: Object.isExtensible returns true for all built-in objects (Number)
---*/

  var e = Object.isExtensible(Number);

assert.sameValue(e, true, 'e');


text:
% Response to reviewers
% Bivariate spatial point patterns . . . by S. J. Eglen

Dear Christophe,

I thank you and the reviewers for the positive comments on the
manuscript.

Please see below for my response to each reviewer.  Comments from
each reviewer are numbered and indented below.  Changes made to the
manuscript are highlighted in Olive Green and annotated in the manuscript
with the corresponding number.  e.g. R2.5 refers to point 5 of
referee\ 2.

Yours faithfully,

Stephen

2015-09-29

## Reviewer 1

> \defr{R1.1} eq. 2: correct equation is $\sqrt{K_{12}/\pi}$

Corrected \lastref.

> \defr{R1.2} Fig. 3: I wonder why there is no confidence interval. It
> will gives an estimate of d_\mbox{min}.

I have added confidence intervals to Figure 3, together with an
explanation of how they were generated in the legend \rpref{R1.2b}.
The confidence intervals are described further in the text
\rpref{R1.2a}.

> \defr{R1.3} Choice of d_\mbox{min} is questionnable. You mainly described an
> hard-core process (or Strauss process). You may find the set of
> d, the exclusion distance compatible with your data. Compatible
> means that the process does not go out the confidence interval
> (at 5% level for example).

The dmin algorithm has both a hard-core and soft-core acceptance
region, similar in spirit to alternatives like Strauss processes.  I
use it here simply as it is most familiar within the field of retinal
mosaics.  I do note however that changing models might improve the fit
slightly (page \arabic{lastr}).

> \defr{R1.4} Fig 4 since we mostly print inblack and white, I personnaly
> prefer different symbols than different colors.

I have used colour consistently throughout the paper to refer to
different cell types: the colours in figure 1 are used in figure 2, 4
and 7.  Also, the colours in figure 8 naturally reflect the colour
sensitivity of the cell types.  So, if possible, I'd like to keep the
colours.

> \defr{R1.5} Why do you present the results for functional
> independence ?

I have expanded on the reasons for the three examples and explain
functional independence is the "null hypothesis" for no interactions,
to be compared against cases when interactions must exist \lastref.

> \defr{R1.6} According to Fig. 6 you reject random for distances between 100
> and 150. Please discuss.

I have added a note to this point in the text \lastref.  However, the
departure from the envelope is very small and could also be driven
simply be small amounts of noise in the original data.  In my
experience, these deviations are relatively minor.

> \defr{R1.7} In order to avoid confusion among readers, please precise
> difference between independence and random labelling.

I have clarified this \lastref.

> \defr{R1.8} Fig. 7: By simulating CSR, you may construct confidence
> interval.

In Figure 7B, there is no model to simulate CSR, and hence to
confidence intervals to generate from repeated runs.  In the paper by
Diggle (1986), confidence intervals were generated by comparing the
observed $L_{12}$ function against 99 simulations, where one of the
mosaics was toroidally shifted by some random amount in the x and y
direction.  Toroidal shifting is a poor approximation to generate
synthetic data sets as neurons that were not neighbours in the real
data can become neighbours in the simulated data.

> \defr{R1.9} You may be interested to read paper like Illian, J., Benson,
> E., Crawford, J., & Staines, H. (2006). Principal component analysis
> for spatial point processes—assessing the appropriateness of the
> approach in an ecological context. In Case studies in spatial point
> process modeling (pp. 135-150). Springer New York.

Thank you.

## Reviewer 2

> \defr{R2.1} The introduction needs more background. As it is the text jumps
> from the fact that the retina does unique computations to (x,y,z)
> positions, and doesn't explain why we should care about the latter.

I have added text to the first paragraph of the introduction
to address this point \lastref.

> \defr{R2.2} The title is a bit too general considering the paper's
> contents. I'd replace "in the visual system" with "in the retina",
> since no other structure is mentioned.

Corrected \lastref.

> \defr{R2.3} Confidence bands are missing from fig 3 and fig 7B.

I have added them (see R1.3) for Figure 3.  See my response to R1.8
for Fig 7B.

> \defr{R2.4} I know very little about how the retina develops, but maybe the
> author could explain why complete spatial randomness would be a
> reasonable null model? Somas are to a good approximation 2D
> objects, but whole neurons aren't. Dendrites and axons need to
> be packed in there as well, doesn't that constrain where somas
> can be?

I have added a comment to this effect \lastref.

> \defr{R2.5} I'm not sure to what extent this belongs in a review paper, but
> second-order statistics such as Ripley's K function become much
> harder to use when you can't assume a uniform intensity function.
> Does uniform density really holds in the retinal mosaics the author
> examines?

This is a good question, but indeed I think too specific for such a
review.  Our experience is that when examining cells within a spatial
field of less than 1mm in each dimension, any gradients in cell
density tend to be quite modest.  We have occasionally examined kernel
density estimates to check that the field is approximately
homogeoneous.  There is a tradeoff -- increasing the field of view
increases the number of cells within the field of view, but then
increases the chances of hitting density-dependent variations (as are
expected: cells in the centre tend to be at higher density than the
periphery).

> \defr{R2.6} I appreciated that the author put an entire R package on github
> for easy distribution, and docker sounds extremely useful. My only
> worry is that we rely on private companies (github, docker) that
> might stop providing free services any time. Perhaps reproducibility
> would require public, durable infrastructure but that's not a
> problem for this review to solve.

Again I agree with this comment but feel it may be too specific for
this review.  I have however added a small comment to note this point
\lastref.

## Other additions

I have made one extra change to the manuscript:

> \defr{R3.1} I have included a mention of the ENCODE consortium (2012)
> project which was a prominent early example of using a virtual machine
> to package code and data for reuse \lastref.

\rule{\textwidth}{1pt}


text:
package com.xored.scalajs.react

import scala.scalajs.js

object TypedThisLike {
  val STATE_KEY = "__scalajs_react_state"
  val PROPS_KEY = "__scalajs_react_props"
  val COMPONENT_ID_KEY = "__scalajs_react_component_id"

  def reactPropsBridge[T] = new JSBridge[T] {
    def apply(props: T) = {
      js.Dictionary(
        (PROPS_KEY, props.asInstanceOf[js.Any]),
        (COMPONENT_ID_KEY, java.util.UUID.randomUUID().toString)
      )
    }

    def apply(value: js.Any) = {
      val dynamic = value.asInstanceOf[js.Dynamic]
      dynamic.selectDynamic(PROPS_KEY).asInstanceOf[T]
    }
  }

  def reactStateBridge[T] = new JSBridge[T] {
    def apply(state: T): js.Any = {
      js.Dictionary(
        (STATE_KEY, state.asInstanceOf[js.Any])
      )
    }

    def apply(value: js.Any) = {
      val dynamic = value.asInstanceOf[js.Dynamic]
      dynamic.selectDynamic(STATE_KEY).asInstanceOf[T]
    }
  }
}

class TypedThisLike(self: js.Any) extends ThisLike {

  import TypedThisLike._

  private val dynamic = self.asInstanceOf[js.Dynamic]

  def props = dynamic.props.selectDynamic(PROPS_KEY).asInstanceOf[Props]

  def state = dynamic.state.selectDynamic(STATE_KEY).asInstanceOf[State]

  def componentId = dynamic.props.selectDynamic(COMPONENT_ID_KEY).toString

  def refs(key: String) = dynamic.refs.selectDynamic(key).asInstanceOf[ReactDOMRef]

  def isMounted: Boolean = dynamic.isMounted().asInstanceOf[Boolean]

  def setState(newState: State) {
    setState(newState, () => {})
  }

  def setState(newState: State, callback: () => Unit) {
    val dict = js.Dictionary((STATE_KEY, newState))
    dynamic.setState(dict, js.Any.fromFunction0(callback))
  }

  def forceUpdate(): Unit = {
    dynamic.forceUpdate()
  }
}

trait TypedReactSpec extends ReactSpec {
  spec =>

  type State
  type Props

  implicit final val reactStateBridge = TypedThisLike.reactStateBridge[State]
  implicit final val reactPropsBridge = TypedThisLike.reactPropsBridge[Props]

  implicit final val thisReader = new JSBridgeFrom[This] {
    def apply(value: js.Any) = {
      val dynamic = value.asInstanceOf[js.Dynamic]
      new TypedThisLike(dynamic) {
        type State = spec.type#State
        type Props = spec.type#Props
      }
    }
  }

  final type This = TypedThisLike {
    type State = spec.type#State
    type Props = spec.type#Props
  }
}


text:
namespace aura {
class Window;
class WindowTreeHost;
}

namespace gfx {
class Point;
}

namespace ash {
class RootWindowTransformer;

namespace test {

class MirrorWindowTestApi {
 public:
  MirrorWindowTestApi() {}
  ~MirrorWindowTestApi() {}

  const aura::WindowTreeHost* GetHost() const;

  int GetCurrentCursorType() const;

  // Returns the position of the hot point within the cursor. This is
  // unaffected by the cursor location.
  const gfx::Point& GetCursorHotPoint() const;

  // Returns the position of the cursor hot point in root window coordinates.
  // This should be the same as the native cursor location.
  gfx::Point GetCursorHotPointLocationInRootWindow() const;

  const aura::Window* GetCursorWindow() const;
  gfx::Point GetCursorLocation() const;

 private:
  DISALLOW_COPY_AND_ASSIGN(MirrorWindowTestApi);
};

}  // namespace test
}  // namespace ash

#endif  // ASH_TEST_MIRROR_WINDOW_TEST_API_H_


text:
package com.amazonaws.services.clouddirectory.model.transform;

import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.services.clouddirectory.model.*;

import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;

/**
 * DirectoryMarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class DirectoryMarshaller {

    private static final MarshallingInfo<String> NAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("Name").build();
    private static final MarshallingInfo<String> DIRECTORYARN_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("DirectoryArn").build();
    private static final MarshallingInfo<String> STATE_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("State").build();
    private static final MarshallingInfo<java.util.Date> CREATIONDATETIME_BINDING = MarshallingInfo.builder(MarshallingType.DATE)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("CreationDateTime").build();

    private static final DirectoryMarshaller instance = new DirectoryMarshaller();

    public static DirectoryMarshaller getInstance() {
        return instance;
    }

    /**
     * Marshall the given parameter object.
     */
    public void marshall(Directory directory, ProtocolMarshaller protocolMarshaller) {

        if (directory == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(directory.getName(), NAME_BINDING);
            protocolMarshaller.marshall(directory.getDirectoryArn(), DIRECTORYARN_BINDING);
            protocolMarshaller.marshall(directory.getState(), STATE_BINDING);
            protocolMarshaller.marshall(directory.getCreationDateTime(), CREATIONDATETIME_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

}


text:
Overview

Traditions

Team

Purpose

Past

Request

Sponsors

Values

Process

Application

      menu

About

Projects

Companies

Contact

Web Lab

Blog

Apply

About

Projects

Companies

Contact

Web Lab

Blog

Apply


text:
//Generated by the Argon Build System

/*
   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions
   are met:

   - Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.

   - Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.

   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
   ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
   A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
   OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
   EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
   PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
   PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
   LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
   NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

/* Original code from libtheora modified to suit to Opus */

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#ifdef OPUS_HAVE_RTCD

#include "opus/celt/arm/armcpu.h"
#include "opus/celt/cpu_support.h"
#include "opus/celt/os_support.h"
#include "opus/opus_types.h"

#define OPUS_CPU_ARM_V4    (1)
#define OPUS_CPU_ARM_EDSP  (1<<1)
#define OPUS_CPU_ARM_MEDIA (1<<2)
#define OPUS_CPU_ARM_NEON  (1<<3)

#if defined(_MSC_VER)
/*For GetExceptionCode() and EXCEPTION_ILLEGAL_INSTRUCTION.*/
# define WIN32_LEAN_AND_MEAN
# define WIN32_EXTRA_LEAN
# include <windows.h>

static OPUS_INLINE opus_uint32 opus_cpu_capabilities(void){
  opus_uint32 flags;
  flags=0;
  /* MSVC has no OPUS_INLINE __asm support for ARM, but it does let you __emit
   * instructions via their assembled hex code.
   * All of these instructions should be essentially nops. */
# if defined(OPUS_ARM_MAY_HAVE_EDSP)
  __try{
    /*PLD [r13]*/
    __emit(0xF5DDF000);
    flags|=OPUS_CPU_ARM_EDSP;
  }
  __except(GetExceptionCode()==EXCEPTION_ILLEGAL_INSTRUCTION){
    /*Ignore exception.*/
  }
#  if defined(OPUS_ARM_MAY_HAVE_MEDIA)
  __try{
    /*SHADD8 r3,r3,r3*/
    __emit(0xE6333F93);
    flags|=OPUS_CPU_ARM_MEDIA;
  }
  __except(GetExceptionCode()==EXCEPTION_ILLEGAL_INSTRUCTION){
    /*Ignore exception.*/
  }
#   if defined(OPUS_ARM_MAY_HAVE_NEON)
  __try{
    /*VORR q0,q0,q0*/
    __emit(0xF2200150);
    flags|=OPUS_CPU_ARM_NEON;
  }
  __except(GetExceptionCode()==EXCEPTION_ILLEGAL_INSTRUCTION){
    /*Ignore exception.*/
  }
#   endif
#  endif
# endif
  return flags;
}

#elif defined(__linux__)
/* Linux based */
opus_uint32 opus_cpu_capabilities(void)
{
  opus_uint32 flags = 0;
  FILE *cpuinfo;

  /* Reading /proc/self/auxv would be easier, but that doesn't work reliably on
   * Android */
  cpuinfo = fopen("/proc/cpuinfo", "r");

  if(cpuinfo != NULL)
  {
    /* 512 should be enough for anybody (it's even enough for all the flags that
     * x86 has accumulated... so far). */
    char buf[512];

    while(fgets(buf, 512, cpuinfo) != NULL)
    {
# if defined(OPUS_ARM_MAY_HAVE_EDSP) || defined(OPUS_ARM_MAY_HAVE_NEON)
      /* Search for edsp and neon flag */
      if(memcmp(buf, "Features", 8) == 0)
      {
        char *p;
#  if defined(OPUS_ARM_MAY_HAVE_EDSP)
        p = strstr(buf, " edsp");
        if(p != NULL && (p[5] == ' ' || p[5] == '\n'))
          flags |= OPUS_CPU_ARM_EDSP;
#  endif

#  if defined(OPUS_ARM_MAY_HAVE_NEON)
        p = strstr(buf, " neon");
        if(p != NULL && (p[5] == ' ' || p[5] == '\n'))
          flags |= OPUS_CPU_ARM_NEON;
#  endif
      }
# endif

# if defined(OPUS_ARM_MAY_HAVE_MEDIA)
      /* Search for media capabilities (>= ARMv6) */
      if(memcmp(buf, "CPU architecture:", 17) == 0)
      {
        int version;
        version = atoi(buf+17);

        if(version >= 6)
          flags |= OPUS_CPU_ARM_MEDIA;
      }
# endif
    }

    fclose(cpuinfo);
  }
  return flags;
}
#else
/* The feature registers which can tell us what the processor supports are
 * accessible in priveleged modes only, so we can't have a general user-space
 * detection method like on x86.*/
# error "Configured to use ARM asm but no CPU detection method available for " \
   "your platform.  Reconfigure with --disable-rtcd (or send patches)."
#endif

int opus_select_arch(void)
{
  opus_uint32 flags = opus_cpu_capabilities();
  int arch = 0;

  if(!(flags & OPUS_CPU_ARM_EDSP))
    return arch;
  arch++;

  if(!(flags & OPUS_CPU_ARM_MEDIA))
    return arch;
  arch++;

  if(!(flags & OPUS_CPU_ARM_NEON))
    return arch;
  arch++;

  return arch;
}

#endif


text:
layout: page
title: "Documentation"
subheadline: "How to use Webcampak"
permalink: "/documentation/"
header:
   image_fullwidth: "header_roadmap_2.jpg"
redirect_from:
    - /en/doc/
---

We are constantly adding new features into Webcampak and do our best to maintain an up-to-date and detailed documentation.

### Current Version

* [Webcampak 3.x Documentation](http://doc.webcampak.com/webcampak3.x/web/en/)

### Previous Versions

* [Webcampak 1.x Documentation](http://doc.webcampak.com/webcampak1.x/en/)
* [Webcampak 2.x Documentation](http://doc.webcampak.com/webcampak2.x/en/)


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Aspose.DNN.ExchangeSync.Components
{
    public class ExchangeContact
    {
        public ExchangeContact() { }
        public ExchangeContact(string displayName, string email) { DisplayName = displayName; Email = email; }

        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string DisplayName { get; set; }
        public string Email { get; set; }
    }
}


text:
package org.jboss.weld.tests.inheritance.generic;

import javax.enterprise.context.ApplicationScoped;

@ApplicationScoped
public class Car implements Entity {

}


text:
var taskNumber = ("taskNumber" in localStorage) ? localStorage.taskNumber : 0;

function addTask() {
	var ul = document.getElementById("todo-tasks");
	var li = document.createElement("li");
	var input = document.createElement("input");
	var taskText = document.getElementById("task-to-add").value;

	document.getElementById("task-to-add").value = "";
	if(taskText == "") {
		alert("Warning: You left the Add Task empty");
		return true;
	}

	li.setAttribute("id", "task" + taskNumber++);

	//input.setAttribute("type", "checkbox");

	//li.appendChild(input);
	li.appendChild(document.createTextNode(taskText));

	ul.appendChild(li);
	localStorage[li.id] = JSON.stringify({checked: false, taskText: taskText});

	//Updating the task number
	localStorage.taskNumber = taskNumber;

	return false;
}

function uploadFromLocalStorage() {
	var ul = document.getElementById("todo-tasks");
	var li = null;
	var input = null;
	var storedTasks = Object.keys(localStorage);
	var task = null;

	for(var i = 0, length = storedTasks.length; i < length; ++i) {
		task = JSON.parse(localStorage[storedTasks[i]]);
		if(storedTasks[i] != "taskNumber" && !task.checked) {
			li = document.createElement("li");
			input = document.createElement("input");

			li.setAttribute("id", storedTasks[i]);
			//input.setAttribute("type", "checkbox");
			//li.appendChild(input);
			li.appendChild(document.createTextNode(task.taskText));
			ul.appendChild(li);
		}
	}
}


text:
using System.ComponentModel;
using PropertyChanged;

public class ClassWithBeforeAfterAndSimpleImplementation : INotifyPropertyChanged
{

    public string Property1 { get; set; }
    [DependsOn("Property1")]
    public string Property2 { get; set; }

    public event PropertyChangedEventHandler PropertyChanged;

    public void OnPropertyChanged(string propertyName)
    {

    }
    public void OnPropertyChanged(string propertyName, object before, object after)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

}


text:
module Ruboty
  module StockPriceJp
    VERSION = "0.2.3"
  end
end


text:
<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

if(!isset($bootstrapped))
{
?>

<?php

    require_once ($_SERVER['DOCUMENT_ROOT'] . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'config.php');
    require_once (ROOT . DS . 'library' . DS . 'functions.php');
    require_once (ROOT . DS . 'library' . DS . 'Autoloader.class.php');
    require_once (ROOT . DS . 'library' . DS . 'shared.php');

    //require_once (ROOT . DS . 'library' . DS . 'templatetags.php');

}

$bootstrapped = true;
?>


text:
import React from 'react';
import {Button, Input, Form, Icon, Select, Card, Tag} from 'antd';
import {toClass} from 'recompose';
import _ from 'lodash';
import {withFormik} from 'formik';
import * as util from '../utils';
import PoliciesEditor from './PolicyEditor';
import {filterPoliciesBasedOnTag} from '../utils';
import {getHelpText} from '../utils/helpText';
import HelpTooltip from './HelpTooltip';

// @TODO Move to config service
const REQUIRED_TAGS = ['dc', 'env', 'service', 'type'];

const FormItem = Form.Item;
const formItemLayout = {
  labelCol: {
    xs: {span: 24},
    sm: {span: 4},
  },
  wrapperCol: {
    xs: {span: 24},
    sm: {span: 18},
  },
};

function removeRequiredTags(tags, requiredTags) {
  return _.filter(tags, t => !_.includes(requiredTags, t));
}

function addRequiredTags(tags, requiredTags) {
  return _.concat(tags, requiredTags);
}

function RollupRuleEditor({values, handleChange, handleSubmit, setFieldValue}) {
  const typeTag = util.getTypeTag(values.filter);
  return (
    <Form onSubmit={handleSubmit}>

          <FormItem
            required
            colon={false}
            label="Rule Name"
            {...formItemLayout}>
            <Input
              name="name"
              autoComplete="off"
              value={values.name}
              onChange={handleChange}
            />
          </FormItem>

          <FormItem
            required
            colon={false}
            label="Metric Filter"
            help={getHelpText('metric-filter')}
            {...formItemLayout}>
            <Input
              name="filter"
              autoComplete="off"
              value={values.filter}
              onChange={e => {
                const newTypeTag = util.getTypeTag(e.target.value);
                const targets = _.map(values.targets, t => ({
                  ...t,
                  policies: filterPoliciesBasedOnTag(t.policies, newTypeTag),
                }));
                setFieldValue('target', targets);
                handleChange(e);
              }}
            />
          </FormItem>

          <FormItem
            required
            label={

                Targets <HelpTooltip helpTextKey="target" />

            }
            colon={false}
            {...formItemLayout}>
            <TargetsEditor
              typeTag={typeTag}
              value={values.targets}
              onChange={e => setFieldValue('targets', e)}
            />
          </FormItem>

          <Button type="primary" htmlType="submit" className="right">
            Add
          </Button>

    </Form>
  );
}

const TargetsEditorBase = props => {
  const {value: targets = [], onChange, typeTag} = props;
  const handleChange = (index, property, newValue) => {
    targets[index][property] = newValue;
    onChange(targets);
  };
  return (

      {_.isEmpty(targets) &&
No targets
}
      {_.map(targets, (t, i) => {
        return (
          <Card
            className="mb1"
            key={i}
            title={t.name}
            extra={
               {
                  onChange(_.filter(targets, (__, index) => index !== i));
                }}>
                <Icon type="delete" />

            }>
            Rollup Metric Name
            <Input
              className="mb2"
              value={t.name}
              onChange={e => handleChange(i, 'name', e.target.value)}
            />

              Rollup Tags <HelpTooltip helpTextKey="rollup-tag" />

              {_.map(REQUIRED_TAGS, requiredTag => <Tag>{requiredTag}</Tag>)}
              <Select
                className="inline-block"
                placeholder="Additional Tags"
                style={{minWidth: 200, width: 'inherit'}}
                onChange={e =>
                  handleChange(i, 'tags', addRequiredTags(e, REQUIRED_TAGS))}
                value={removeRequiredTags(t.tags, REQUIRED_TAGS)}
                autoComplete="off"
                mode="tags"
                tokenSeparators={[',']}
                notFoundContent={false}
              />

              Policies <HelpTooltip helpTextKey="policy" />

            <PoliciesEditor
              typeTag={typeTag}
              value={t.policies}
              onChange={e => handleChange(i, 'policies', e)}
            />
          </Card>
        );
      })}
      <Button
        type="dashed"
        onClick={() =>
          onChange(targets.concat({name: '', tags: [], policies: []}))}>
        Add Target
      </Button>

  );
};
const TargetsEditor = toClass(TargetsEditorBase);

export default withFormik({
  enableReinitialize: true,
  mapPropsToValues: ({rollupRule}) => {
    return rollupRule || {};
  },
  handleSubmit: (values, {props}) => {
    props.onSubmit({
      ...values,
      targets: _.map(values.targets, target => {
        return {
          ...target,
          tags: _.union(target.tags, REQUIRED_TAGS),
        };
      }),
    });
  },
})(RollupRuleEditor);


text:
package tp.boundaries.net.packets;

import tp.boundaries.net.GameClient;
import tp.boundaries.net.GameServer;

public abstract class Packet {

    public static enum PacketTypes {
        INVALID(-1), LOGIN(00), DISCONNECT(01), MOVE(02);

        private int packetId;

        private PacketTypes(int packetId) {
            this.packetId = packetId;
        }

        public int getId() {
            return packetId;
        }
    }

    public byte packetId;

    public Packet(int packetId) {
        this.packetId = (byte) packetId;
    }

    public abstract void writeData(GameClient client);

    public abstract void writeData(GameServer server);

    public String readData(byte[] data) {
        String message = new String(data).trim();
        return message.substring(2);
    }

    public abstract byte[] getData();

    public static PacketTypes lookupPacket(String packetId) {
        try {
            return lookupPacket(Integer.parseInt(packetId));
        } catch (NumberFormatException e) {
            return PacketTypes.INVALID;
        }
    }

    public static PacketTypes lookupPacket(int id) {
        for (PacketTypes p : PacketTypes.values()) {
            if (p.getId() == id) {
                return p;
            }
        }
        return PacketTypes.INVALID;
    }
}


text:
from sys import version_info
if version_info >= (2,6,0):
    def swig_import_helper():
        from os.path import dirname
        import imp
        fp = None
        try:
            fp, pathname, description = imp.find_module('_dia', [dirname(__file__)])
        except ImportError:
            import _dia
            return _dia
        if fp is not None:
            try:
                _mod = imp.load_module('_dia', fp, pathname, description)
            finally:
                fp.close()
            return _mod
    _dia = swig_import_helper()
    del swig_import_helper
else:
    import _dia
del version_info
try:
    _swig_property = property
except NameError:
    pass # Python < 2.2 doesn't have 'property'.
def _swig_setattr_nondynamic(self,class_type,name,value,static=1):
    if (name == "thisown"): return self.this.own(value)
    if (name == "this"):
        if type(value).__name__ == 'SwigPyObject':
            self.__dict__[name] = value
            return
    method = class_type.__swig_setmethods__.get(name,None)
    if method: return method(self,value)
    if (not static):
        self.__dict__[name] = value
    else:
        raise AttributeError("You cannot add attributes to %s" % self)

def _swig_setattr(self,class_type,name,value):
    return _swig_setattr_nondynamic(self,class_type,name,value,0)

def _swig_getattr(self,class_type,name):
    if (name == "thisown"): return self.this.own()
    method = class_type.__swig_getmethods__.get(name,None)
    if method: return method(self)
    raise AttributeError(name)

def _swig_repr(self):
    try: strthis = "proxy of " + self.this.__repr__()
    except: strthis = ""
    return "<%s.%s; %s >" % (self.__class__.__module__, self.__class__.__name__, strthis,)

try:
    _object = object
    _newclass = 1
except AttributeError:
    class _object : pass
    _newclass = 0

def dia_matvec(*args):
  """
    dia_matvec(int const n_row, int const n_col, int const n_diags, int const L, int const [] offsets,
        npy_bool_wrapper const [] diags, npy_bool_wrapper const [] Xx, npy_bool_wrapper [] Yx)
    dia_matvec(int const n_row, int const n_col, int const n_diags, int const L, int const [] offsets,
        signed char const [] diags, signed char const [] Xx, signed char [] Yx)
    dia_matvec(int const n_row, int const n_col, int const n_diags, int const L, int const [] offsets,
        unsigned char const [] diags, unsigned char const [] Xx, unsigned char [] Yx)
    dia_matvec(int const n_row, int const n_col, int const n_diags, int const L, int const [] offsets,
        short const [] diags, short const [] Xx, short [] Yx)
    dia_matvec(int const n_row, int const n_col, int const n_diags, int const L, int const [] offsets,
        unsigned short const [] diags, unsigned short const [] Xx, unsigned short [] Yx)
    dia_matvec(int const n_row, int const n_col, int const n_diags, int const L, int const [] offsets,
        int const [] diags, int const [] Xx, int [] Yx)
    dia_matvec(int const n_row, int const n_col, int const n_diags, int const L, int const [] offsets,
        unsigned int const [] diags, unsigned int const [] Xx, unsigned int [] Yx)
    dia_matvec(int const n_row, int const n_col, int const n_diags, int const L, int const [] offsets,
        long long const [] diags, long long const [] Xx, long long [] Yx)
    dia_matvec(int const n_row, int const n_col, int const n_diags, int const L, int const [] offsets,
        unsigned long long const [] diags, unsigned long long const [] Xx, unsigned long long [] Yx)
    dia_matvec(int const n_row, int const n_col, int const n_diags, int const L, int const [] offsets,
        float const [] diags, float const [] Xx, float [] Yx)
    dia_matvec(int const n_row, int const n_col, int const n_diags, int const L, int const [] offsets,
        double const [] diags, double const [] Xx, double [] Yx)
    dia_matvec(int const n_row, int const n_col, int const n_diags, int const L, int const [] offsets,
        long double const [] diags, long double const [] Xx, long double [] Yx)
    dia_matvec(int const n_row, int const n_col, int const n_diags, int const L, int const [] offsets,
        npy_cfloat_wrapper const [] diags, npy_cfloat_wrapper const [] Xx, npy_cfloat_wrapper [] Yx)
    dia_matvec(int const n_row, int const n_col, int const n_diags, int const L, int const [] offsets,
        npy_cdouble_wrapper const [] diags, npy_cdouble_wrapper const [] Xx,
        npy_cdouble_wrapper [] Yx)
    dia_matvec(int const n_row, int const n_col, int const n_diags, int const L, int const [] offsets,
        npy_clongdouble_wrapper const [] diags, npy_clongdouble_wrapper const [] Xx,
        npy_clongdouble_wrapper [] Yx)
    """
  return _dia.dia_matvec(*args)
# This file is compatible with both classic and new-style classes.


text:
[![PkgGoDev](https://pkg.go.dev/badge/gomodules.xyz/pointer)](https://pkg.go.dev/gomodules.xyz/pointer)
![CI](https://github.com/gomodules/pointer/workflows/CI/badge.svg)
[![Go Report Card](https://goreportcard.com/badge/gomodules.xyz/pointer)](https://goreportcard.com/report/gomodules.xyz/pointer)

# pointer

Fork of https://github.com/aws/aws-sdk-go/blob/v1.35.21/aws/convert_types.go


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <item name="id_weibo_header" type="id"></item>
    <item name="id_weibo_content" type="id"></item>
</resources>


text:
            <button class="btn btn-box-tool dropdown-toggle" data-toggle="dropdown"></button>

control tool

reset

Matrix Graph

Force Graph

refresh

        <button class="btn btn-box-tool" data-widget="collapse"></button>

            Charge

                <input id="range_1" type="text" name="range_1" value="">

            Friction

                <input id="range_2" type="text" name="range_2" value="">

            Gravity

                <input id="range_3" type="text" name="range_3" value="">

            LinkDistance

                <input id="range_4" type="text" name="range_4" value="">


text:
package delay

import (
	"bytes"
	"encoding/gob"
	"errors"
	"fmt"
	"net/http"
	"net/http/httptest"
	"reflect"
	"testing"

	"github.com/golang/protobuf/proto"
	"golang.org/x/net/context"

	"google.golang.org/appengine/internal"
	"google.golang.org/appengine/taskqueue"
)

type CustomType struct {
	N int
}

type CustomInterface interface {
	N() int
}

type CustomImpl int

func (c CustomImpl) N() int { return int(c) }

// CustomImpl needs to be registered with gob.
func init() {
	gob.Register(CustomImpl(0))
}

var (
	invalidFunc = Func("invalid", func() {})

	regFuncRuns = 0
	regFuncMsg  = ""
	regFunc     = Func("reg", func(c context.Context, arg string) {
		regFuncRuns++
		regFuncMsg = arg
	})

	custFuncTally = 0
	custFunc      = Func("cust", func(c context.Context, ct *CustomType, ci CustomInterface) {
		a, b := 2, 3
		if ct != nil {
			a = ct.N
		}
		if ci != nil {
			b = ci.N()
		}
		custFuncTally += a + b
	})

	anotherCustFunc = Func("cust2", func(c context.Context, n int, ct *CustomType, ci CustomInterface) {
	})

	varFuncMsg = ""
	varFunc    = Func("variadic", func(c context.Context, format string, args ...int) {
		// convert []int to []interface{} for fmt.Sprintf.
		as := make([]interface{}, len(args))
		for i, a := range args {
			as[i] = a
		}
		varFuncMsg = fmt.Sprintf(format, as...)
	})

	errFuncRuns = 0
	errFuncErr  = errors.New("error!")
	errFunc     = Func("err", func(c context.Context) error {
		errFuncRuns++
		if errFuncRuns == 1 {
			return nil
		}
		return errFuncErr
	})

	dupeWhich = 0
	dupe1Func = Func("dupe", func(c context.Context) {
		if dupeWhich == 0 {
			dupeWhich = 1
		}
	})
	dupe2Func = Func("dupe", func(c context.Context) {
		if dupeWhich == 0 {
			dupeWhich = 2
		}
	})
)

type fakeContext struct {
	ctx     context.Context
	logging [][]interface{}
}

func newFakeContext() *fakeContext {
	f := new(fakeContext)
	f.ctx = internal.WithCallOverride(context.Background(), f.call)
	f.ctx = internal.WithLogOverride(f.ctx, f.logf)
	return f
}

func (f *fakeContext) call(ctx context.Context, service, method string, in, out proto.Message) error {
	panic("should never be called")
}

var logLevels = map[int64]string{1: "INFO", 3: "ERROR"}

func (f *fakeContext) logf(level int64, format string, args ...interface{}) {
	f.logging = append(f.logging, append([]interface{}{logLevels[level], format}, args...))
}

func TestInvalidFunction(t *testing.T) {
	c := newFakeContext()

	if got, want := invalidFunc.Call(c.ctx), fmt.Errorf("delay: func is invalid: %s", errFirstArg); got.Error() != want.Error() {
		t.Errorf("Incorrect error: got %q, want %q", got, want)
	}
}

func TestVariadicFunctionArguments(t *testing.T) {
	// Check the argument type validation for variadic functions.

	c := newFakeContext()

	calls := 0
	taskqueueAdder = func(c context.Context, t *taskqueue.Task, _ string) (*taskqueue.Task, error) {
		calls++
		return t, nil
	}

	varFunc.Call(c.ctx, "hi")
	varFunc.Call(c.ctx, "%d", 12)
	varFunc.Call(c.ctx, "%d %d %d", 3, 1, 4)
	if calls != 3 {
		t.Errorf("Got %d calls to taskqueueAdder, want 3", calls)
	}

	if got, want := varFunc.Call(c.ctx, "%d %s", 12, "a string is bad"), errors.New("delay: argument 3 has wrong type: string is not assignable to int"); got.Error() != want.Error() {
		t.Errorf("Incorrect error: got %q, want %q", got, want)
	}
}

func TestBadArguments(t *testing.T) {
	// Try running regFunc with different sets of inappropriate arguments.

	c := newFakeContext()

	tests := []struct {
		args    []interface{} // all except context
		wantErr string
	}{
		{
			args:    nil,
			wantErr: "delay: too few arguments to func: 1 < 2",
		},
		{
			args:    []interface{}{"lala", 53},
			wantErr: "delay: too many arguments to func: 3 > 2",
		},
		{
			args:    []interface{}{53},
			wantErr: "delay: argument 1 has wrong type: int is not assignable to string",
		},
	}
	for i, tc := range tests {
		got := regFunc.Call(c.ctx, tc.args...)
		if got.Error() != tc.wantErr {
			t.Errorf("Call %v: got %q, want %q", i, got, tc.wantErr)
		}
	}
}

func TestRunningFunction(t *testing.T) {
	c := newFakeContext()

	// Fake out the adding of a task.
	var task *taskqueue.Task
	taskqueueAdder = func(_ context.Context, tk *taskqueue.Task, queue string) (*taskqueue.Task, error) {
		if queue != "" {
			t.Errorf(`Got queue %q, expected ""`, queue)
		}
		task = tk
		return tk, nil
	}

	regFuncRuns, regFuncMsg = 0, "" // reset state
	const msg = "Why, hello!"
	regFunc.Call(c.ctx, msg)

	// Simulate the Task Queue service.
	req, err := http.NewRequest("POST", path, bytes.NewBuffer(task.Payload))
	if err != nil {
		t.Fatalf("Failed making http.Request: %v", err)
	}
	rw := httptest.NewRecorder()
	runFunc(c.ctx, rw, req)

	if regFuncRuns != 1 {
		t.Errorf("regFuncRuns: got %d, want 1", regFuncRuns)
	}
	if regFuncMsg != msg {
		t.Errorf("regFuncMsg: got %q, want %q", regFuncMsg, msg)
	}
}

func TestCustomType(t *testing.T) {
	c := newFakeContext()

	// Fake out the adding of a task.
	var task *taskqueue.Task
	taskqueueAdder = func(_ context.Context, tk *taskqueue.Task, queue string) (*taskqueue.Task, error) {
		if queue != "" {
			t.Errorf(`Got queue %q, expected ""`, queue)
		}
		task = tk
		return tk, nil
	}

	custFuncTally = 0 // reset state
	custFunc.Call(c.ctx, &CustomType{N: 11}, CustomImpl(13))

	// Simulate the Task Queue service.
	req, err := http.NewRequest("POST", path, bytes.NewBuffer(task.Payload))
	if err != nil {
		t.Fatalf("Failed making http.Request: %v", err)
	}
	rw := httptest.NewRecorder()
	runFunc(c.ctx, rw, req)

	if custFuncTally != 24 {
		t.Errorf("custFuncTally = %d, want 24", custFuncTally)
	}

	// Try the same, but with nil values; one is a nil pointer (and thus a non-nil interface value),
	// and the other is a nil interface value.
	custFuncTally = 0 // reset state
	custFunc.Call(c.ctx, (*CustomType)(nil), nil)

	// Simulate the Task Queue service.
	req, err = http.NewRequest("POST", path, bytes.NewBuffer(task.Payload))
	if err != nil {
		t.Fatalf("Failed making http.Request: %v", err)
	}
	rw = httptest.NewRecorder()
	runFunc(c.ctx, rw, req)

	if custFuncTally != 5 {
		t.Errorf("custFuncTally = %d, want 5", custFuncTally)
	}
}

func TestRunningVariadic(t *testing.T) {
	c := newFakeContext()

	// Fake out the adding of a task.
	var task *taskqueue.Task
	taskqueueAdder = func(_ context.Context, tk *taskqueue.Task, queue string) (*taskqueue.Task, error) {
		if queue != "" {
			t.Errorf(`Got queue %q, expected ""`, queue)
		}
		task = tk
		return tk, nil
	}

	varFuncMsg = "" // reset state
	varFunc.Call(c.ctx, "Amiga %d has %d KB RAM", 500, 512)

	// Simulate the Task Queue service.
	req, err := http.NewRequest("POST", path, bytes.NewBuffer(task.Payload))
	if err != nil {
		t.Fatalf("Failed making http.Request: %v", err)
	}
	rw := httptest.NewRecorder()
	runFunc(c.ctx, rw, req)

	const expected = "Amiga 500 has 512 KB RAM"
	if varFuncMsg != expected {
		t.Errorf("varFuncMsg = %q, want %q", varFuncMsg, expected)
	}
}

func TestErrorFunction(t *testing.T) {
	c := newFakeContext()

	// Fake out the adding of a task.
	var task *taskqueue.Task
	taskqueueAdder = func(_ context.Context, tk *taskqueue.Task, queue string) (*taskqueue.Task, error) {
		if queue != "" {
			t.Errorf(`Got queue %q, expected ""`, queue)
		}
		task = tk
		return tk, nil
	}

	errFunc.Call(c.ctx)

	// Simulate the Task Queue service.
	// The first call should succeed; the second call should fail.
	{
		req, err := http.NewRequest("POST", path, bytes.NewBuffer(task.Payload))
		if err != nil {
			t.Fatalf("Failed making http.Request: %v", err)
		}
		rw := httptest.NewRecorder()
		runFunc(c.ctx, rw, req)
	}
	{
		req, err := http.NewRequest("POST", path, bytes.NewBuffer(task.Payload))
		if err != nil {
			t.Fatalf("Failed making http.Request: %v", err)
		}
		rw := httptest.NewRecorder()
		runFunc(c.ctx, rw, req)
		if rw.Code != http.StatusInternalServerError {
			t.Errorf("Got status code %d, want %d", rw.Code, http.StatusInternalServerError)
		}

		wantLogging := [][]interface{}{
			{"ERROR", "delay: func failed (will retry): %v", errFuncErr},
		}
		if !reflect.DeepEqual(c.logging, wantLogging) {
			t.Errorf("Incorrect logging: got %+v, want %+v", c.logging, wantLogging)
		}
	}
}

func TestDuplicateFunction(t *testing.T) {
	c := newFakeContext()

	// Fake out the adding of a task.
	var task *taskqueue.Task
	taskqueueAdder = func(_ context.Context, tk *taskqueue.Task, queue string) (*taskqueue.Task, error) {
		if queue != "" {
			t.Errorf(`Got queue %q, expected ""`, queue)
		}
		task = tk
		return tk, nil
	}

	if err := dupe1Func.Call(c.ctx); err == nil {
		t.Error("dupe1Func.Call did not return error")
	}
	if task != nil {
		t.Error("dupe1Func.Call posted a task")
	}
	if err := dupe2Func.Call(c.ctx); err != nil {
		t.Errorf("dupe2Func.Call error: %v", err)
	}
	if task == nil {
		t.Fatalf("dupe2Func.Call did not post a task")
	}

	// Simulate the Task Queue service.
	req, err := http.NewRequest("POST", path, bytes.NewBuffer(task.Payload))
	if err != nil {
		t.Fatalf("Failed making http.Request: %v", err)
	}
	rw := httptest.NewRecorder()
	runFunc(c.ctx, rw, req)

	if dupeWhich == 1 {
		t.Error("dupe2Func.Call used old registered function")
	} else if dupeWhich != 2 {
		t.Errorf("dupeWhich = %d; want 2", dupeWhich)
	}
}


text:
package org.testifyproject.trait;

import static java.util.Optional.ofNullable;

import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.Optional;

/**
 *

 * A contracts that specifies methods for reading property values. class.
 *

 *

 * Note that with respect to null keys and values the behavior the methods in contract are
 * dependent on the {@link Map} implementation returned by {@link #getProperties()
 * }
 *

 *
 * @author saden
 */
public interface PropertiesReader extends PropertiesTrait {

    /**
     *

     * Get a PropertiesReader instance for the given mapKey. Note that:
     *

     *

     *
If the key is empty then the this PropertiesReader instance will be returned

     *
If the key is not found then an empty map will be returned

     *

     * @param key the key associated with the map
     * @return an instance that wraps the found map
     */
    default PropertiesReader getPropertiesReader(String key) {
        if (key.isEmpty()) {
            return this;
        }

        return DefaultPropertiesReader.of(findMap(key));
    }

    /**
     * Get the value the value associated with the given key.
     *
     * @param <T> the value type
     * @param key the key
     * @return the value to which the specified key is mapped, null otherwise
     */
    default <T> T getProperty(String key) {
        return (T) getProperties().get(key);
    }

    /**
     * Find the value associated with the given key.
     *
     * @param <T> the value type
     * @param key the key associated with the property
     * @return an optional with the value, empty optional otherwise
     */
    default <T> Optional<T> findProperty(String key) {
        return ofNullable((T) getProperties().get(key));
    }

    /**
     * Find a collection value associated with the given key. If the queue is not found an
     * {@link Collections#emptyList()} will be returned.
     *
     * @param <E> the collection element type
     * @param key the key associated with the queue
     * @return the found collection, empty collection otherwise
     */
    default <E> Collection<E> findCollection(String key) {
        Map<String, Collection<E>> properties = getProperties();

        return properties.getOrDefault(key, Collections.emptyList());
    }

    /**
     * Find a map typed associated with the given key. If the map is not found an
     * {@link Collections#emptyMap()} is returned.
     *
     * @param <K> the map key type
     * @param <V> the map value type
     * @param key the key associated with the map
     * @return the found map, empty map otherwise
     */
    default <K, V> Map<K, V> findMap(String key) {
        Map<String, Map<K, V>> properties = getProperties();

        return properties.getOrDefault(key, Collections.emptyMap());
    }

}


text:
<ompts:test>
<ompts:testdescription>Test which checks the omp threadprivate directive by filling an array with random numbers in an parallelised region. Each thread generates one number of the array and saves this in a temporary threadprivate variable. In a second parallelised region the test controls, that the temporary variable contains still the former value by comparing it with the one in the array.</ompts:testdescription>
<ompts:ompversion>2.0</ompts:ompversion>
<ompts:directive>omp threadprivate</ompts:directive>
<ompts:dependences>omp critical,omp_set_dynamic,omp_get_num_threads,omp master</ompts:dependences>
<ompts:testcode>
!Yi Wen modified this function from his own understanding of the semantics
!of C version at 05042004
!The undeestanding is that sum0 and myvalue can be local static variables
!of the chk_omp_threadprivate function. There is no need to use common
!block
      INTEGER FUNCTION <ompts:testcode:functionname>omp_threadprivate</ompts:testcode:functionname>()
        IMPLICIT NONE
        INTEGER sum, known_sum, i , iter, rank,size, failed
        INTEGER omp_get_num_threads, omp_get_thread_num
        REAL my_random
        REAL, ALLOCATABLE:: data(:)
        INTEGER random_size
        INTRINSIC random_number
        INTRINSIC random_seed
        EXTERNAL omp_set_dynamic

!Yi Wen modified at 05042004 : add "save"
        INTEGER, SAVE:: sum0
        REAL, SAVE::myvalue
!Yi Wen commented two common blocks
!	common/csum0/ sum0
!	common/cmyvalue/ myvalue
!!!!!!!!!!$omp threadprivate(/csum0/,/cmyvalue/)
		<ompts:check>
!$omp threadprivate(sum0,myvalue)
		</ompts:check>
        INCLUDE "omp_testsuite.f"

        sum = 0
        failed = 0
        sum0=0
        myvalue=0
        random_size=45
        CALL omp_set_dynamic(.FALSE.)
!$omp parallel
        sum0 = 0
!$omp do
        DO i=1, LOOPCOUNT
          sum0 = sum0 + i
        END DO
!$omp end do
!$omp critical
        sum = sum + sum0
!$omp end critical
!$omp end parallel
        known_sum = (LOOPCOUNT*(LOOPCOUNT+1))/2
        IF ( known_sum .NE. sum ) THEN
          PRINT *, ' known_sum =', known_sum, ', sum =',sum
        END IF

        CALL omp_set_dynamic(.FALSE.)

!$omp parallel
!$omp master
        size = omp_get_num_threads()
        ALLOCATE ( data(size) )
!$omp end master
!$omp end parallel
        CALL RANDOM_SEED(SIZE=random_size)
        DO iter = 0, 99
          CALL RANDOM_NUMBER(HARVEST=my_random)
!$omp parallel private(rank)
          rank = omp_get_thread_num()+1
          myvalue = my_random + rank
          data(rank) = myvalue
!$omp end parallel
!$omp parallel private(rank)
          rank = omp_get_thread_num()+1
          IF ( myvalue .NE. data(rank) ) THEN
            failed = failed + 1
            PRINT *, ' myvalue =',myvalue,' data(rank)=', data(rank)
          END IF
!$omp end parallel
        END DO
        DEALLOCATE( data)
        IF ( (known_sum .EQ. sum) .AND. (failed .NE. 1) ) THEN
          <testfunctionname></testfunctionname> = 1
        else
          <testfunctionname></testfunctionname> = 0
        end if
      END
</ompts:testcode>
</ompts:test>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using Octopus.Client;
using Octopus.Client.Model;
using Octostache;

namespace GV.AspNet.Configuration.Contrib.Octopus
{
	public class OctopusClientVariableDictionaryProvider : IVariableDictionaryProvider
	{
		public VariableDictionary Get(OctopusConfigurationProviderOptions options)
		{
			var variableDictionary = new VariableDictionary();

			var endpoint = new OctopusServerEndpoint(options.ServerAddress.ToString(), options.ApiKey);
			var repository = new OctopusRepository(endpoint);

			var project = repository.Projects.FindByName(options.ProjectName);
			if (project == null)
			{
				return variableDictionary;
			}

			var scopes = new Dictionary<ScopeField, string>();
			if (!string.IsNullOrEmpty(options.EnvironmentName))
			{
				scopes[ScopeField.Environment] = options.EnvironmentName;
			}
			if (!string.IsNullOrEmpty(options.MachineName))
			{
				scopes[ScopeField.Machine] = options.MachineName;
			}

			var variableSetIds = new List<string> { project.VariableSetId };
			variableSetIds.AddRange(project.IncludedLibraryVariableSetIds.Select(id => repository.LibraryVariableSets.Get(id).VariableSetId));

			var variables = new Dictionary<string, SortedSet<VariableResource>>();
			foreach (var variableSetId in variableSetIds)
			{
				var variableSet = repository.VariableSets.Get(variableSetId);
				AddVariableSet(variables, variableSet, scopes);
			}

			foreach (var variableName in variables.Keys)
			{
				variableDictionary.Set(variableName, variables[variableName].First().Value);
			}

			return variableDictionary;
		}

		private void AddVariableSet(IDictionary<string, SortedSet<VariableResource>> variables, VariableSetResource variableSet, Dictionary<ScopeField, string> scopes)
		{
			var variableScopes = GetVariableScopes(variableSet, scopes);

			foreach (var variable in variableSet.Variables)
			{
				var variableName = variable.Name;

				if (variable.IsSensitive)
				{
					continue;
				}

				if (!variable.Scope.IsApplicableTo(variableScopes))
				{
					continue;
				}

				if (!variables.ContainsKey(variableName))
				{
					variables[variableName] = new SortedSet<VariableResource>(new VariableResourceScopeRankComparer());
				}
				variables[variableName].Add(variable);
			}
		}

		private Dictionary<ScopeField, ScopeValue> GetVariableScopes(VariableSetResource variableSet, Dictionary<ScopeField, string> scopes)
		{
			var variableScopes = new Dictionary<ScopeField, ScopeValue>();

			foreach (var scopeField in scopes.Keys)
			{
				var scopeValues = GetScopeValues(variableSet.ScopeValues, scopeField);
				var scopeValueName = scopes[scopeField];
				var scopeValue = scopeValues.FirstOrDefault(item => item.Name == scopeValueName);
				if (scopeValue == null)
				{
					continue;
				}

				variableScopes.Add(scopeField, new ScopeValue(scopeValue.Id));
			}

			return variableScopes;
		}

		private static IEnumerable<ReferenceDataItem> GetScopeValues(VariableScopeValues scopeValues, ScopeField scopeField)
		{
			switch (scopeField)
			{
				case ScopeField.Environment:
					return scopeValues.Environments;

				case ScopeField.Machine:
					return scopeValues.Machines;

				default:
					return new ReferenceDataItem[] { };
			}
		}
	}
}


text:
class Helpdesk < Sinatra::Base
  #List all users
  get '/users-list' do
    self.init_ctx
    #check if role is admin
    if !self.is_user_logged_in() || @rolename != 'admin'
      redirect '/'
      return #Does execution stop with a redirect, or do we need a return in this framework?
    end

    @skip = 0
    if @skip != nil && @skip != ''
      @skip = @params[:skip].to_i
    end

    @criteria = {}
    if (@params[:username] != nil && @params[:username] != '') then @criteria[:username] = {  '$regex' => '.*' + Regexp.escape(@params[:username]) + '.*', '$options' => 'i' } end
    if (@params[:rolename] != nil && @params[:rolename] != '') then @criteria[:rolename] = {  '$regex' => '.*' + Regexp.escape(@params[:rolename]) + '.*', '$options' => 'i' } end
    if (@params[:email] != nil && @params[:email] != '') then @criteria[:email] = {  '$regex' => '.*' + Regexp.escape(@params[:email]) + '.*', '$options' => 'i' } end
    if (@params[:display] != nil && @params[:display] != '') then @criteria[:display] = {  '$regex' => '.*' + Regexp.escape(@params[:display]) + '.*', '$options' => 'i' } end
    if (@params[:phone] != nil && @params[:phone] != '') then @criteria[:phone] = {  '$regex' => '.*' + Regexp.escape(@params[:phone]) + '.*', '$options' => 'i' } end

    @totalrowcount = 0
    @totalrowcount = @list = @db[:users].find(@criteria).count()
    @list = @db[:users].find(@criteria).skip(@skip).limit(@pagesize)

    @showpager = true

    erb :userslist
  end

  #Create a user account
  post '/user-save/:opmode' do
    self.init_ctx
    #check if role is admin before saving
    if !self.is_user_logged_in() || @rolename != 'admin'
      redirect '/'
      return #Does execution stop with a redirect, or do we need a return in this framework?
    end

    cnt = @db[:users].find('username' => @params[:id]).count()
    if cnt == 0 && @params[:opmode] == 'new'
      cntemail = @db[:users].find('email' => @params[:email]).count()
      if cntemail > 0 #!= nil
        redirect '/users-list?msg=Email+already+exists'
        return
      end

      recuser = {
          :username => @params[:id],
          :password => Digest::SHA1.hexdigest(@params[:pw]),
          :rolename => @params[:rolename],
          :email => @params[:email],
          :phone => @params[:phone],
          :display => @params[:display],
          :ticket_details => @params[:ticket_details] == 'on' ? true : false,
          :islocked => 'false'
      }

      @db[:users].insert_one recuser
    elsif cnt == 1 && @params[:opmode] == 'update'
      recuser = @db[:users].find('username' => @params[:id]).limit(1).first

      if recuser[:email] != @params[:email]
        cntemail = @db[:users].find('email' => @params[:email]).count()
        if cntemail > 0 #!= nil
          redirect "/user-detail/#{@params[:id]}?msg=Email+already+exists"
          return
        end
      end

      recuser[:rolename] = @params[:rolename]
      recuser[:email] = @params[:email]
      recuser[:phone] = @params[:phone]
      recuser[:display] = @params[:display]
      recuser[:ticket_details] = @params[:ticket_details] == 'on' ? true : false
      #recuser[:islocked] = 'false'

      recuser[:islocked] = @params[:islocked] == 'on' ? 'true' : 'false'

      if @params[:pw] != nil && @params[:pw] != ''
        recuser[:password] = Digest::SHA1.hexdigest(@params[:pw])
      end

      @db[:users].update_one(
          {'username' => @params[:id]},
          recuser,
          {:upsert => false}
      )
    else
      #TODO: Toss a warning
    end

    session[:ticket_details] = @params[:ticket_details] == 'on' ? true : false

    @db.close
    redirect '/users-list?msg=Saved'
  end

  #Get info about a single user
  get '/user-detail/:username' do
    self.init_ctx
    if !self.is_user_logged_in()
      redirect '/login'
      return
    end

    if @rolename != 'admin'
      redirect '/'
      return
    end

    @rec = @db[:users].find('username' => @params[:username]).limit(1).first

    erb :userdetail
  end

  #Get info about a single user
  get '/userprofile' do
    self.init_ctx
    if !self.is_user_logged_in()
      redirect '/login'
      return
    end

    @rec = @db[:users].find('username' => @username).limit(1).first

    erb :userprofile
  end

  post '/userprofile' do
    self.init_ctx
    if !self.is_user_logged_in()
      redirect '/login'
      return
    end

    @rec = @db[:users].find('username' => @username).limit(1).first

    reccnt = @db[:users].find('email' => @params[:email], 'username' => {'$ne' => @username}).count #limit(1).first issue post #36 Message displayed "Email+already+exists", but only current record has this email.
    if reccnt > 0 #!= nil
      redirect '/userprofile?msg=Email+already+exists'
      return
    end

    fields = ['display', 'phone', 'email']

    fields.each do |x|
      @rec[x] = @params[x]
    end

    @rec[:ticket_details] = @params[:ticket_details] == 'on' ? true : false

    @db[:users].update_one(
        {'username' => @username},
        @rec,
        {:upsert => false}
    )

    session[:ticket_details] = @rec[:ticket_details]

    redirect '/userprofile?msg=Saved'
  end

  get '/register-user' do
    self.init_ctx
    erb :registeruser
  end

  post '/register-user' do
    self.init_ctx

    if @params[:pw] != @params[:confirmpw]
      redirect '/register-user?msg=Password+and+confirmation+do+not+match'
      return
    end

    reccnt = @db[:users].find('username' => @username).count #limit(1).first
    if reccnt > 0 #!= nil
      redirect '/register-user?msg=Username+already+exists'
      return
    end

    reccnt = @db[:users].find('email' => @params[:email]).count #limit(1).first
    if reccnt > 0 #!= nil
      redirect '/register-user?msg=Email+already+exists'
      return
    end

    recuser = {
        :username => @params[:id],
        :password => Digest::SHA1.hexdigest(@params[:pw]),
        :rolename => 'requester',
        :email => @params[:email],
        :phone => @params[:phone],
        :display => @params[:display],
        :ticket_details => @params[:ticket_details] == 'on' ? true : false,
        :islocked => 'false'
    }

    @db[:users].insert_one recuser

    redirect '/login'
  end
end


text:
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using JetBrains.Application.Progress;
using JetBrains.ProjectModel;
using JetBrains.ReSharper.Feature.Services.Bulbs;
using JetBrains.ReSharper.Feature.Services.QuickFixes;
using JetBrains.ReSharper.Psi;
using JetBrains.ReSharper.Psi.CSharp.Impl;
using JetBrains.ReSharper.Refactorings.Util;
using JetBrains.TextControl;
using JetBrains.Util;
using ReSharper.ContractExtensions.Utilities;

namespace ReSharper.ContractExtensions.ProblemAnalyzers.PreconditionAnalyzers
{
    /// <summary>
    /// Fix inconsistent visibility of the referenced member in the precondition.
    /// </summary>
    [QuickFix]
    public sealed class RequiresInconsistentVisibiityQuickFix : QuickFixBase
    {
        private AccessRights? _destinationTypeAccess;
        private AccessRights? _destinationMemberAccess;

        private readonly RequiresInconsistentVisibiityHighlighting _highlighting;

        public RequiresInconsistentVisibiityQuickFix(RequiresInconsistentVisibiityHighlighting highlighting)
        {
            Contract.Requires(highlighting != null);

            _highlighting = highlighting;
        }

        protected override Action<ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator progress)
        {
            Contract.Assert(_destinationMemberAccess != null || _destinationTypeAccess != null);

            // TODO: R# documentation saying that GetDeclarations is VERY expensive!
            // Can I do the same but in some other way???

            if (_destinationMemberAccess != null)
                FixReferencedMemberAccess(_destinationMemberAccess.Value);

            if (_destinationTypeAccess != null)
                FixReferencedTypeAccess(_destinationTypeAccess.Value);

            return null;
        }

        private void FixReferencedTypeAccess(AccessRights newTypeAccess)
        {
            var declaration =
                _highlighting.LessVisibleReferencedMember.DeclaredElement
                .With(x => x.GetContainingType())
                .With(x => x.GetDeclarations().FirstOrDefault());

            Contract.Assert(declaration != null);

            ModifiersUtil.SetAccessRights(
                declaration,
                newTypeAccess);
        }

        private void FixReferencedMemberAccess(AccessRights memberAccessRights)
        {
            var declaration =
                _highlighting.LessVisibleReferencedMember.DeclaredElement
                    .GetDeclarations().FirstOrDefault();

            Contract.Assert(declaration != null);

            ModifiersUtil.SetAccessRights(
                declaration,
                memberAccessRights);
        }

        public override string Text
        {
            get
            {
                Contract.Assert(_destinationMemberAccess != null || _destinationTypeAccess != null);

                var referencedMember = _highlighting.LessVisibleReferencedMember;

                if (_destinationTypeAccess == null)
                {
                    return string.Format("Change visibility of the referenced {0} '{1}' to '{2}'",
                        referencedMember.MemberTypeString, referencedMember.MemberName,
                        _destinationMemberAccess.Value.ToCSharpString());
                }

                if (_destinationMemberAccess == null)
                {
                    return string.Format("Change visibility of the referenced type '{0}' to '{1}'",
                        referencedMember.MemberTypeName, _destinationTypeAccess.Value.ToCSharpString());
                }

                return string.Format(
                    "Change visibility of the referenced {0} '{1}' to '{2}' and type '{3}' to '{4}'",
                    referencedMember.MemberTypeString, referencedMember.MemberName,
                    _destinationMemberAccess.Value.ToCSharpString(), referencedMember.MemberTypeName,
                    _destinationTypeAccess.Value.ToCSharpString());
            }
        }

        public override bool IsAvailable(IUserDataHolder cache)
        {
            return ComputeDestinationTypeAndMemberAccessCore(out _destinationTypeAccess, out _destinationMemberAccess);
        }

        private bool ComputeDestinationTypeAndMemberAccessCore(out AccessRights? typeAccess, out AccessRights? memberAccess)
        {
            typeAccess = null;
            memberAccess = null;

            var preconditionContainer = _highlighting.PreconditionContainer;
            var referencedMember = _highlighting.LessVisibleReferencedMember;

            if (referencedMember.MemberType == MemberType.Event)
            {
                // We can't fix event visibility!
                return false;
            }

            if (preconditionContainer.BelongToTheSameType(referencedMember))
            {
                memberAccess = _highlighting.PreconditionContainer.MemberAccessRights;
                return true;
            }

            // We can't fix visibility for members from the different projects
            // (potentially, it's possible, but I don't care about this case for now)

            if (!preconditionContainer.BelongToTheSameProject(referencedMember))
            {
                return false;
            }

            // Referenced member is defined in another type.
            // Lets find out, is it possible to fix this issue!

            // If contract holder is protected we're really limited in our fixes!
            if (preconditionContainer.MemberAccessRights == AccessRights.PROTECTED)
            {
                // The only way we can fix visibility of the referenced member,
                // when the referenced member defined in the base class!

                var referencedType = (IClass)referencedMember.DeclaredElement.GetContainingType();
                var preconditionsClass = (IClass)preconditionContainer.DeclaredElement.GetContainingType();

                if (preconditionsClass.IsSuperType(referencedType))
                {
                    // Referenced member declared in one of the base types for member with contract!
                    memberAccess = preconditionContainer.MemberAccessRights;
                    return true;
                }

                return false;
            }

            // Simple case: members have the same access, the only one fix required: fix of the type access
            if (preconditionContainer.MemberAccessRights == referencedMember.MemberAccessRights)
            {
                typeAccess = preconditionContainer.TypeAccessRights;
                return true;
            }

            if (preconditionContainer.TypeAccessRights != referencedMember.TypeAccessRights)
            {
                typeAccess = preconditionContainer.TypeAccessRights;
            }

            memberAccess = preconditionContainer.MemberAccessRights;

            return true;
        }

    }

}


text:
> Easily bind functions, Event Emitters, and Streams to a session cache.

## Install
## Install with [npm](npmjs.org)

```bash
npm i sessionify --save
```

## Run tests

```bash
npm test
```

## Usage

```js
var sessionify = require('sessionify');
```

## API
### [sessionify](index.js#L23)

* `fn` **{Function|EventEmitter|Stream}**: Object to bind to.
* `session` **{Object}**: session-cache object to bind with.
* `context` **{Object}**: Optional context to bind to the sesssion.
* `returns` **{*}**: Bound object

Bind a function, EventEmitter, or Stream to the provided session object
with an optional context.

## Contributing
Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](https://github.com/doowb/sessionify/issues)

## Author

**Brian Woodward**

+ [github/doowb](https://github.com/doowb)
+ [twitter/doowb](http://twitter.com/doowb)

## License
Copyright (c) 2014 Brian Woodward
Released under the MIT license

***

_This file was generated by [verb](https://github.com/assemble/verb) on December 16, 2014._


text:
<?php

namespace Application\Infrastructure\HandlerFactory;
use Application\Model\User\RegisterUserHandler;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;

/**
 * Class RegisterUserHandlerFactory
 *
 * @package Application\Infrastructure\HandlerFactory
 * @author Alexander Miertsch <kontakt@codeliner.ws>
 */
final class RegisterUserHandlerFactory implements FactoryInterface
{
    /**
     * Create service
     *
     * @param ServiceLocatorInterface $serviceLocator
     * @return mixed
     */
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        return new RegisterUserHandler($serviceLocator->get('application.model.user_collection'));
    }
}


text:
$(document).ready(function() {

  $('.venue-create-game').on('click', function(event){
    clicked_div = event.target.closest('.venue-create-game')
    $(clicked_div).toggleClass('select-venue-game');
    $(clicked_div).find('input').prop('checked', !$(clicked_div).find('input').prop('checked'));
  })

  $('body').on('click', '.create-venue',function(event){
    event.preventDefault();
    var infoBox = $(this.parentElement.parentElement)
    var venueName = infoBox.find('.info-window-line-1').text()
    var venueAddress = infoBox.find('.info-window-line-2').text() + ", " + infoBox.find('.info-window-line-3').text()
    $('#venue_name').val(venueName)
    $('#venue_name').prop('readonly', true);
    $('#venue_address').val(venueAddress)
    $('#venue_address').prop('readonly', true);
    $("#venue-create-form-container").dialog('open');
  })

  $('#venue-create-form-container').on('click', '#add-new-game', function(event){
    event.preventDefault();
    $target = $('#other-text-field')
    $.ajax({
      url: "/games/add_game",
      type: "post",
      data: $target.serialize()
    }).done(function(response){
      $('#venue-create-games .no-games-p').remove()
      $('#venue-create-games').append(response)
      $('#other-text-field').val("")
    })
  })

  var removeGames = function() {
    $('#venue-create-games').html("
No Games Added
")
  }
  var resetVenueForm = function() {
    document.getElementById('venue-create-form').reset()
    $('#venue-create-form').find("input[type=hidden][id^='venue']")
    removeGames()
  }

  $('#venue-create-games').on('click', '.remove-game-button', function(event){
    event.preventDefault()
    $(this).closest('.update-game').remove()
    if ( $('#venue-create-games .update-game').length < 1 ) {
      removeGames()
    }
  })

  $("#venue-create-form-container").dialog(dialogOptions, {
    close: resetVenueForm
  })

});


text:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.tobrun.vision.qr">

    <application
        android:allowBackup="true"
        android:supportsRtl="true" />

</manifest>


text:
redis-lua-debugger
==================
rld is a non-interactive debugger for Lua scripts running in Redis. See [this post](https://redislabs.com/blog/pop-the-red-boxs-lid-redis-lua-debugger) for a runtime example.

rld's features include:
- Easy & native installation, only ~6KB payload.
- Prints output to local and remote consoles.
- Traces the execution of code lines.
- State-of-the-art automatic watch mechanism reports new variables and value changes.
- Reports function calls, returns and arguments and does on-the-fly profiling.

Basic usage
-----------
 1. Load rld.lua to Redis once (e.g. `redis-cli --eval rld.lua`).
 2. Add this line at the beginning of your Lua script: `rld.start()`.
 3. Run your code as usual (e.g. `redis-cli --eval prog.lua`).
 4. View rld's output in Redis' log file or by subscribing to the `rld` channel.

API
---
- `rld.start()` - starts the debugger
- `rld.stop()` - stops the debugger
- `rld.troff()` / `rld.tron()` - toggles tracing off/on
- `rld.options` - debugger options, see source for details

TODO
----
- Instead of auto-watch, watch explicit variables by regex (i.e. default is `.*`)
- Publish to different channels according to topic (trace, variables,...)
- Add options arguments to start()

Known Issues
------------
- This script is not compatible with Redis v3 and above (https://github.com/antirez/redis/commit/30278061cc834b4073b004cb1a2bfb0f195734f7)
- Last line of user script doesn't trigger auto-watch change printouts
- Function names are shown without global context (e.g. `redis.call` becomes `call`)
- rld functions are also traced (e.g. calling rld.stop/troff/tron from @user_script)
- Replication breaker: while the rld script is replicated, it is never run on the slave explicitly and therefore doesn't register in _G. This causes user scripts to break in the slave when trying to invoke rld.

Contributing
------------
 1. Fork it.
 2. Change it.
 3. Make a pull request.

License
-------
See the `LICENSE` file.

DISCLAIMER
----------
This script is highly experimental - use at your own risk! (and never in production ;))


text:
package com.app.hexuegang.wsnmonitor.view.fragment;

import android.view.View;
import android.widget.TextView;

import com.app.hexuegang.wsnmonitor.R;
import com.app.hexuegang.wsnmonitor.publish.MyConstants;
import com.app.hexuegang.wsnmonitor.util.NumberUtils;
import com.app.hexuegang.wsnmonitor.util.SPHelper;

/**
 * Created by HEXG on 2017/4/8.
 */

public class ComprehensiveFragment extends BaseFragment {

    private TextView tv_water_result;
    private TextView tv_water_describe;
    private TextView tv_air_result;
    private TextView tv_air_describe;
    private TextView tv_soil_result;
    private TextView tv_soil_describe;
    private TextView tv_noise_result;
    private TextView tv_noise_describe;
    private TextView tv_overall_result;
    private TextView tv_overall_describe;

    private double qualityWater;
    private double qualityAir;
    private double qualitySoil;
    private double qualityNoise;
    private double qualityOverall;

    @Override
    public int getFragmentLayout() {
        return R.layout.fragment_5;
    }

    @Override
    public void init(View view) {
        tv_water_result = (TextView) view.findViewById(R.id.tv_water_result);
        tv_water_describe = (TextView) view.findViewById(R.id.tv_water_describe);
        tv_air_result = (TextView) view.findViewById(R.id.tv_air_result);
        tv_air_describe = (TextView) view.findViewById(R.id.tv_air_describe);
        tv_soil_result = (TextView) view.findViewById(R.id.tv_soil_result);
        tv_soil_describe = (TextView) view.findViewById(R.id.tv_soil_describe);
        tv_noise_result = (TextView) view.findViewById(R.id.tv_noise_result);
        tv_noise_describe = (TextView) view.findViewById(R.id.tv_noise_describe);
        tv_overall_result = (TextView) view.findViewById(R.id.tv_overall_result);
        tv_overall_describe = (TextView) view.findViewById(R.id.tv_overall_describe);

        getData();
    }

    private void getData() {

        String qualityWaterStr = SPHelper.getString(SPHelper.sp_quality_evaluate_water, MyConstants.SP_KEY_QUALITY_WATER);
        String qualityAirStr = SPHelper.getString(SPHelper.sp_quality_evaluate_air, MyConstants.SP_KEY_QUALITY_AIR);
        String qualitySoilStr = SPHelper.getString(SPHelper.sp_quality_evaluate_soil, MyConstants.SP_KEY_QUALITY_SOIL);
        String qualityNoiseStr = SPHelper.getString(SPHelper.sp_quality_evaluate_noise, MyConstants.SP_KEY_QUALITY_NOISE);
        String qualityOverallStr = SPHelper.getString(SPHelper.sp_quality_evaluate_total, MyConstants.SP_KEY_QUALITY_OVERALL);

        try {
            qualityWater = Float.parseFloat(qualityWaterStr);
            qualityAir = Float.parseFloat(qualityAirStr);
            qualitySoil = Float.parseFloat(qualitySoilStr);
            qualityNoise = Float.parseFloat(qualityNoiseStr);
            qualityOverall = qualityWater*MyConstants.WEIGHT_WATER
                    + qualityAir*MyConstants.WEIGHT_AIR
                    + qualitySoil*MyConstants.WEIGHT_SOIL
                    + qualityNoise*MyConstants.WEIGHT_NOISE;
        } catch (NumberFormatException e) {
            e.printStackTrace();
        } finally {
        }

        tv_water_result.setText(qualityWaterStr);
        tv_air_result.setText(qualityAirStr);
        tv_soil_result.setText(qualitySoilStr);
        tv_noise_result.setText(qualityNoiseStr);
        tv_overall_result.setText(qualityOverallStr);
        setDescribe(qualityWater,qualityAir,qualitySoil,qualityNoise, qualityOverall);
    }

    private void refreshUI() {
        tv_water_result.setText(NumberUtils.formatDouble(qualityWater));
        tv_air_result.setText(NumberUtils.formatDouble(qualityAir));
        tv_soil_result.setText(NumberUtils.formatDouble(qualitySoil));
        tv_noise_result.setText(NumberUtils.formatDouble(qualityNoise));
        tv_overall_result.setText(NumberUtils.formatDouble(qualityOverall));

        setDescribe(qualityWater, qualityAir, qualitySoil, qualityNoise, qualityOverall);
    }

    private void setDescribe(double valueWater, double valueAir, double valueSoil, double valueNoise, double valueOverall){
        tv_water_describe.setText(getDescribe(valueWater));
        tv_air_describe.setText(getDescribe(valueAir));
        tv_soil_describe.setText(getDescribe(valueSoil));
        tv_noise_describe.setText(getDescribe(valueNoise));
        tv_overall_describe.setText(getDescribe(valueOverall));
    }

    private String getDescribe(double qualityValue){
        String describe = "";
        if (qualityValue <= 0){
            describe = "数据异常";
        }else if (qualityValue <= 0.1){
            describe = "质量非常好";
        }else if (qualityValue < 0.5){
            describe = "质量较好";
        }else if (qualityValue < 1){
            describe = "质量一般";
        }else if (qualityValue <= 1.5){
            describe = "质量较差";
        }else if (qualityValue <= 2.5){
            describe = "质量非常差";
        }else{
            describe = "质量极差";
        }
        return describe;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        SPHelper.putString(SPHelper.sp_quality_evaluate_water, MyConstants.SP_KEY_QUALITY_WATER, qualityWater+"");
        SPHelper.putString(SPHelper.sp_quality_evaluate_air, MyConstants.SP_KEY_QUALITY_AIR, qualityAir+"");
        SPHelper.putString(SPHelper.sp_quality_evaluate_soil, MyConstants.SP_KEY_QUALITY_SOIL, qualitySoil+"");
        SPHelper.putString(SPHelper.sp_quality_evaluate_noise, MyConstants.SP_KEY_QUALITY_NOISE, qualityNoise+"");
        SPHelper.putString(SPHelper.sp_quality_evaluate_total, MyConstants.SP_KEY_QUALITY_OVERALL, NumberUtils.formatDouble(qualityOverall));
    }
}


text:
namespace network_time {

namespace {

// Clock resolution is platform dependent.
#if defined(OS_WIN)
const int64_t kTicksResolutionMs = base::Time::kMinLowResolutionThresholdMs;
#else
const int64_t kTicksResolutionMs = 1;  // Assume 1ms for non-windows platforms.
#endif

// Number of time measurements performed in a given network time calculation.
const int kNumTimeMeasurements = 5;

}  // namespace

// static
void NetworkTimeTracker::RegisterPrefs(PrefRegistrySimple* registry) {
  registry->RegisterDictionaryPref(prefs::kNetworkTimeMapping,
                                   new base::DictionaryValue());
}

NetworkTimeTracker::NetworkTimeTracker(scoped_ptr<base::TickClock> tick_clock,
                                       PrefService* pref_service)
    : tick_clock_(std::move(tick_clock)),
      pref_service_(pref_service),
      received_network_time_(false) {
  const base::DictionaryValue* time_mapping =
      pref_service_->GetDictionary(prefs::kNetworkTimeMapping);
  double local_time_js = 0;
  double network_time_js = 0;
  if (time_mapping->GetDouble("local", &local_time_js) &&
      time_mapping->GetDouble("network", &network_time_js)) {
    base::Time local_time_saved = base::Time::FromJsTime(local_time_js);
    base::Time local_time_now = base::Time::Now();
    if (local_time_saved > local_time_now ||
        local_time_now - local_time_saved > base::TimeDelta::FromDays(7)) {
      // Drop saved mapping if clock skew has changed or the data is too old.
      pref_service_->ClearPref(prefs::kNetworkTimeMapping);
    } else {
      network_time_ = base::Time::FromJsTime(network_time_js) +
          (local_time_now - local_time_saved);
      network_time_ticks_ = base::TimeTicks::Now();
    }
  }
}

NetworkTimeTracker::~NetworkTimeTracker() {
  DCHECK(thread_checker_.CalledOnValidThread());
}

void NetworkTimeTracker::UpdateNetworkTime(base::Time network_time,
                                           base::TimeDelta resolution,
                                           base::TimeDelta latency,
                                           base::TimeTicks post_time) {
  DCHECK(thread_checker_.CalledOnValidThread());
  DVLOG(1) << "Network time updating to "
           << base::UTF16ToUTF8(
                  base::TimeFormatFriendlyDateAndTime(network_time));
  // Update network time on every request to limit dependency on ticks lag.
  // TODO(mad): Find a heuristic to avoid augmenting the
  // network_time_uncertainty_ too much by a particularly long latency.
  // Maybe only update when the the new time either improves in accuracy or
  // drifts too far from |network_time_|.
  network_time_ = network_time;

  // Calculate the delay since the network time was received.
  base::TimeTicks now = tick_clock_->NowTicks();
  base::TimeDelta task_delay = now - post_time;
  // Estimate that the time was set midway through the latency time.
  network_time_ticks_ = now - task_delay - latency / 2;

  // Can't assume a better time than the resolution of the given time
  // and 5 ticks measurements are involved, each with their own uncertainty.
  // 1 & 2 are the ones used to compute the latency, 3 is the Now() from when
  // this task was posted, 4 is the Now() above and 5 will be the Now() used in
  // GetNetworkTime().
  network_time_uncertainty_ =
      resolution + latency + kNumTimeMeasurements *
      base::TimeDelta::FromMilliseconds(kTicksResolutionMs);

  received_network_time_ = true;

  base::Time network_time_now;
  if (GetNetworkTime(base::TimeTicks::Now(), &network_time_now, NULL)) {
    // Update time mapping if tracker received time update from server, i.e.
    // mapping is accurate.
    base::Time local_now = base::Time::Now();
    base::DictionaryValue time_mapping;
    time_mapping.SetDouble("local", local_now.ToJsTime());
    time_mapping.SetDouble("network", network_time_now.ToJsTime());
    pref_service_->Set(prefs::kNetworkTimeMapping, time_mapping);
  }
}

bool NetworkTimeTracker::GetNetworkTime(base::TimeTicks time_ticks,
                                        base::Time* network_time,
                                        base::TimeDelta* uncertainty) const {
  DCHECK(thread_checker_.CalledOnValidThread());
  DCHECK(network_time);
  if (network_time_.is_null())
    return false;
  DCHECK(!network_time_ticks_.is_null());
  *network_time = network_time_ + (time_ticks - network_time_ticks_);
  if (uncertainty)
    *uncertainty = network_time_uncertainty_;
  return true;
}

}  // namespace network_time


text:
<template name="AcceptInvite">

Accept invitation?

            <button type="button" class="btn btn-success btn-lg accept-invite">Accept</button>
            <button type="button" class="btn btn-danger btn-lg decline-invite">Decline</button>

</template>


text:
package com.google.gerrit.lucene;

import com.google.gerrit.lifecycle.LifecycleModule;
import com.google.gerrit.server.index.ChangeIndex;
import com.google.gerrit.server.index.IndexModule;

public class LuceneIndexModule extends LifecycleModule {
  private final boolean checkVersion;
  private final int threads;

  public LuceneIndexModule() {
    this(true, 0);
  }

  public LuceneIndexModule(boolean checkVersion, int threads) {
    this.checkVersion = checkVersion;
    this.threads = threads;
  }

  @Override
  protected void configure() {
    install(new IndexModule(threads));
    bind(ChangeIndex.class).to(LuceneChangeIndex.class);
    listener().to(LuceneChangeIndex.class);
    if (checkVersion) {
      listener().to(IndexVersionCheck.class);
    }
  }
}


text:
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Threading.Tasks;

namespace RestClient.Tests.Client
{
    [TestClass]
    public class QueryStrings
    {
        [TestMethod]
        public async Task PrimitiveMayBeIncludedInQueryStringWithDefaultNameOfParameterName()
        {
            var value = TestData.RandomInt();
            var client = TestData.ClientOf<IQueryStrings>(x => x.RequireQueryStringOf($"number={value}"));
            await client.CallAsync(x => x.PrimitiveWithDefaultName(value));
        }

        [TestMethod]
        public async Task PrimitiveMayBeIncludedInQueryStringWithSpecifiedName()
        {
            var value = TestData.RandomInt();
            var client = TestData.ClientOf<IQueryStrings>(x => x.RequireQueryStringOf($"SpecifiedName={value}"));
            await client.CallAsync(x => x.PrimitiveWithSpecifiedName(value));
        }
    }
}