text:
package influent.internal.nio;

import influent.exception.InfluentIOException;
import influent.internal.util.ThreadSafeQueue;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.EnumSet;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import javax.net.ssl.SSLEngineResult;
import javax.net.ssl.SSLEngineResult.HandshakeStatus;
import javax.net.ssl.SSLEngineResult.Status;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * A non-blocking secure {@code SocketChannel}.
 *
 * <p>This implementation is naive and its performance is poor yet.
 */
public final class NioTcpTlsChannel implements NioTcpChannel {
  private static final Logger logger = LoggerFactory.getLogger(NioTcpTlsChannel.class);

  private final NioTcpPlaintextChannel channel;
  private final NioTlsEngine engine;

  private ByteBuffer inboundNetworkBuffer = newInboundNetworkBuffer();
  private final ThreadSafeQueue<ByteBuffer> outboundNetworkBuffers = new ThreadSafeQueue<>();
  private final Set<Op> applicationInterests = new CopyOnWriteArraySet<>();

  private static ByteBuffer newInboundNetworkBuffer() {
    // Prepare a ByteBuffer with sufficient size
    final ByteBuffer buffer = ByteBuffer.allocate(1024 * 1024);
    buffer.position(buffer.limit());
    return buffer;
  }

  private NioTcpTlsChannel(final NioTcpPlaintextChannel channel, final NioTlsEngine engine) {
    this.channel = channel;
    this.engine = engine;
  }

  /**
   * Creates a new {@code NioTcpTlsChannel}.
   *
   * @param channel the accepted {@code SocketChannel}
   * @param eventLoop the {@code NioEventLoop}
   * @param tcpConfig the {@code NioTcpConfig}
   * @param engine the {@code SSLEngine}
   * @throws InfluentIOException if some IO error occurs
   */
  public static NioTcpTlsChannel open(
      final SocketChannel channel,
      final NioEventLoop eventLoop,
      final NioTcpConfig tcpConfig,
      final NioTlsEngine engine) {
    final NioTcpPlaintextChannel plaintextChannel =
        NioTcpPlaintextChannel.open(channel, eventLoop, tcpConfig);
    return new NioTcpTlsChannel(plaintextChannel, engine);
  }

  /** {@inheritDoc} */
  @Override
  public boolean write(final ByteBuffer src) {
    if (!handshake()) {
      return false;
    }
    final int current = src.position();
    flush(); // must flush at least once
    while (src.hasRemaining() && wrapAndSend(src).getStatus() == Status.OK) ;
    return src.position() != current;
  }

  /** {@inheritDoc} */
  @Override
  public boolean read(final ByteBuffer dst) {
    if (!handshake()) {
      return false;
    }
    final int current = dst.position();
    while (receiveAndUnwrap(dst).getStatus() == Status.OK) ;
    return dst.position() != current;
  }

  private boolean handshake() {
    final HandshakeStatus current = engine.getHandshakeStatus();
    logger.debug("Handshake with {}, status = {}", getRemoteAddress(), current);
    if (current == HandshakeStatus.NOT_HANDSHAKING) {
      return true;
    }
    final HandshakeStatus status = doHandshake(current);
    switch (status) {
        // FINISHED is returned by wrapping or unwrapping once the handshake is just finished
      case FINISHED:
        channel.disable(Op.READ);
        if (outboundNetworkBuffers.isEmpty()) {
          channel.disable(Op.WRITE);
        }
        applicationInterests.forEach(channel::enable);
        applicationInterests.clear();
        return true;
        // NOT_HANDSHAKE means that the handshake was already finished
        // This status appears when the TLS communication finishes
        // At the end of a TLS communication, the status may change as follows
        // 1. NOT_HANDSHAKING into NEED_WRAP to send a closure message
        // 2. NEED_WRAP to NOT_HANDSHAKING when the closure message is sent
      case NOT_HANDSHAKING: // already finished
        return true;
      case NEED_WRAP:
        channel.disable(Op.READ);
        channel.enable(Op.WRITE);
        return false;
      case NEED_UNWRAP:
        if (outboundNetworkBuffers.isEmpty()) {
          channel.disable(Op.WRITE);
        }
        channel.enable(Op.WRITE);
        return false;
        // case NEED_UNWRAP_AGAIN: JDK 9 has this new status for DTLS, but normal TLS does not use
      default:
        throw new AssertionError();
    }
  }

  private HandshakeStatus doHandshake(final HandshakeStatus status) {
    logger.debug("The current HandshakeStatus for {}: {}", getRemoteAddress(), status);
    // previous buffers may remain
    flush();

    switch (status) {
      case FINISHED:
      case NOT_HANDSHAKING:
        return status;
      case NEED_WRAP:
        final SSLEngineResult wrapResult = wrapAndSend(ByteBuffer.allocate(0));
        if (wrapResult.getStatus() != Status.OK) {
          return wrapResult.getHandshakeStatus();
        }
        return doHandshake(wrapResult.getHandshakeStatus());
      case NEED_UNWRAP:
        final SSLEngineResult unwrapResult = receiveAndUnwrap(ByteBuffer.allocate(1024));
        if (unwrapResult.getStatus() != Status.OK) {
          return unwrapResult.getHandshakeStatus();
        }
        return doHandshake(unwrapResult.getHandshakeStatus());
      case NEED_TASK:
        engine.completeDelegatedTasks();
        return doHandshake(engine.getHandshakeStatus());
        // case NEED_UNWRAP_AGAIN: JDK 9 has this new status for DTLS, but this is not used
      default:
        throw new AssertionError();
    }
  }

  private SSLEngineResult wrapAndSend(final ByteBuffer src) {
    final ByteBuffer buffer = ByteBuffer.allocate(1024 * 1024);
    final SSLEngineResult result = engine.wrap(src, buffer);
    logger.debug("The wrapping result for {}: {}", getRemoteAddress(), result);
    switch (result.getStatus()) {
      case OK:
      case CLOSED:
        break;
      case BUFFER_OVERFLOW: // allocating large size currently
      case BUFFER_UNDERFLOW: // happens only when unwrapping
      default:
        throw new AssertionError();
    }

    buffer.flip();
    if (buffer.hasRemaining()) {
      outboundNetworkBuffers.enqueue(buffer);
    }

    flush();
    return result;
  }

  private void flush() {
    while (channel.isOpen() && outboundNetworkBuffers.nonEmpty()) {
      final ByteBuffer head = outboundNetworkBuffers.peek();
      if (!channel.write(head)) {
        break;
      }
      if (!head.hasRemaining()) {
        outboundNetworkBuffers.dequeue();
      }
    }
  }

  private SSLEngineResult receiveAndUnwrap(final ByteBuffer dst) {
    // the phase to receive new network data
    // mark = the index which has data received from network, but not consumed by application(dst)
    // position = the index in order to receive new network data
    // limit = the capacity
    if (inboundNetworkBuffer.hasRemaining()) {
      inboundNetworkBuffer.mark();
      inboundNetworkBuffer.position(inboundNetworkBuffer.limit());
      inboundNetworkBuffer.limit(inboundNetworkBuffer.capacity());
    } else {
      inboundNetworkBuffer.clear();
      inboundNetworkBuffer.mark();
    }
    while (channel.isOpen() && channel.read(inboundNetworkBuffer)) ;

    // the phase that the application consumes the non-consumed network data
    // position = the index to consume
    // limit = the index which has no new network data
    inboundNetworkBuffer.limit(inboundNetworkBuffer.position());
    inboundNetworkBuffer.reset();
    final SSLEngineResult result = engine.unwrap(inboundNetworkBuffer, dst);
    logger.debug("The unwrapping result for {}: {}", getRemoteAddress(), result);
    switch (result.getStatus()) {
      case OK:
      case BUFFER_UNDERFLOW: // inbound data is not enough
      case CLOSED:
        break;
      case BUFFER_OVERFLOW: // application buffer(dst) is not enough
        inboundNetworkBuffer.limit(inboundNetworkBuffer.position());
        return receiveAndUnwrap(dst);
      default:
        throw new AssertionError();
    }
    return result;
  }

  /** {@inheritDoc} */
  @Override
  public void register(final Set<Op> ops, final NioAttachment attachment) {
    applicationInterests.addAll(ops);
    channel.register(EnumSet.of(Op.READ), attachment);
  }

  /** {@inheritDoc} */
  @Override
  public void enable(final Op op) {
    if (!handshake()) {
      applicationInterests.add(op);
      return;
    }
    channel.enable(op);
  }

  /** {@inheritDoc} */
  @Override
  public void disable(final Op op) {
    if (!handshake()) {
      applicationInterests.remove(op);
      return;
    }
    if (op == Op.WRITE && outboundNetworkBuffers.nonEmpty()) {
      // application has no more data to send, but TLS layer has remaining data to send
      return;
    }
    channel.disable(op);
  }

  /** {@inheritDoc} */
  @Override
  public void close() {
    channel.close();
  }

  /** {@inheritDoc} */
  @Override
  public boolean isOpen() {
    return channel.isOpen();
  }

  /** {@inheritDoc} */
  @Override
  public SocketAddress getRemoteAddress() {
    return channel.getRemoteAddress();
  }

  /** {@inheritDoc} */
  @Override
  public String toString() {
    return "NioTcpTlsChannel(" + getRemoteAddress() + ")";
  }
}


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <title>Relay: State of the State | React</title>
  <meta name="viewport" content="width=device-width">
  <meta property="og:title" content="Relay: State of the State | React">
  <meta property="og:type" content="website">
  <meta property="og:url" content="https://facebook.github.io/react/blog/2016/08/05/relay-state-of-the-state.html">
  <meta property="og:image" content="https://facebook.github.io/react/img/logo_og.png">
  <meta property="og:description" content="A JavaScript library for building user interfaces">
  <meta property="fb:app_id" content="623268441017527">

  <link rel="shortcut icon" href="/react/favicon.ico">
  <link rel="alternate" type="application/rss+xml" title="React" href="https://127.0.0.1/react/feed.xml">

  <link rel="stylesheet" href="https://cdn.jsdelivr.net/docsearch.js/1/docsearch.min.css" />
  <link rel="stylesheet" href="/react/css/syntax.css">
  <link rel="stylesheet" href="/react/css/codemirror.css">
  <link rel="stylesheet" href="/react/css/react.css">

  <link href="//netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.css" rel="stylesheet">

          React

Docs/文档

Support/支持

Download/下载

Blog/博客

            <input id="algolia-doc-search" type="text" placeholder="Search docs..." />

GitHub

React Native

Recent posts

Relay: State of the State

Create Apps with No Configuration

Mixins Considered Harmful

Introducing React's Error Code System

React v15.0.1

React v15.0

React v0.14.8

React v15.0 Release Candidate 2

React v15.0 Release Candidate

New Versioning Scheme

All posts ...

  Relay: State of the State

  August  5, 2016
  by

      Joseph Savona

This month marks a year since we released Relay and we'd like to share an update on the project and what's next.

A Year In Review #

A year after launch, we're incredibly excited to see an active community forming around Relay and that companies such as Twitter are using Relay in production:

For a project like mission control, GraphQL and Relay were a near-perfect solution, and the cost of building it any other way justified the investment.

-- Fin Hopkins

This kind of positive feedback is really encouraging (I'll admit to re-reading that post far too many times), and great motivation for us to keep going and make Relay even better.

With the community's help we've already come a long way since the technical preview. Here are some highlights:

In March we added support for server-side rendering and for creating multiple instances of Relay on a single page. This was a coordinated effort over the course of several months by community members Denis Nedelyaev and Gerald Monaco (now at Facebook).

Also in March we added support for React Native. While we use Relay and React Native together internally, they didn't quite work together in open-source out of the box. We owe a big thanks to Adam Miskiewicz, Tom Burns, Gaëtan Renaudeau, David Aurelio, Martín Bigio, Paul O'Shannessy, Ben Alpert, and many others who helped track down and resolve issues. Finally, thanks to Steven Luscher for coordinating this effort and building the first Relay/ReactNative example app.

We've also seen some great open-source projects spring up around Relay:

Denis Nedelyaev created isomorphic-relay, a package that helps developers build server-rendered Relay apps where data is prepared on the server and then used to bootstrap the app on the client.

Jimmy Jia created react-router-relay to integrate Relay data-fetching into React Router.

Pavel Chertorogov released relay-network-layer, which adds features such as batching query requests, middleware, authentication, logging, and more.

This is just a small sampling of the community's contributions. So far we've merged over 300 PRs - about 25% of our commits - from over 80 of you. These PRs have improved everything from the website and docs down the very core of the framework. We're humbled by these outstanding contributions and excited to keep working with each of you!

Retrospective & Roadmap #

Earlier this year we paused to reflect on the state of the project. What was working well? What could be improved? What features should we add, and what could we remove? A few themes emerged: performance on mobile, developer experience, and empowering the community.

Mobile Perf #

First, Relay was built to serve the needs of product developers at Facebook. In 2016, that means helping developers to build apps that work well on mobile devices connecting on slower networks. For example, people in developing markets commonly use 2011 year-class phones and connect via 2G class networks. These scenarios present their own challenges.

Therefore, one of our primary goals this year is to optimize Relay for performance on low-end mobile devices first, knowing that this can translate to improved performance on high-end devices as well. In addition to standard approaches such as benchmarking, profiling, and optimizations, we're also working on big-picture changes.

For example, in today's Relay, here's what happens when an app is opened. First, React Native starts initializing the JavaScript context (loading and parsing your code and then running it). When this finishes, the app executes and Relay sees that you need data. It constructs and prints the query, uploads the query text to the server, processes the response, and renders your app. (Note that this process applies on the web, except that the code has to be downloaded instead of loaded from the device.)

Ideally, though, we could begin fetching data as soon as the native code had loaded - in parallel with the JS context initialization. By the time your JS code was ready to run, the data-fetching would already be under way. To do this we would need a way to determine statically - at build time - what query an application would send.

The key is that GraphQL is already static - we just need to fully embrace this fact. More on this later.

Developer Experience #

Next, we've paid attention to the community's feedback and know that, to put it simply, Relay could be "easier" to use (and "simpler" too). This isn't entirely surprising to us - Relay was originally designed as a routing library and gradually morphed into a data-fetching library. Concepts like Relay "routes", for example, no longer serve as critical a role and are just one more concept that developers have to learn about. Another example is mutations: while writes are inherently more complex than reads, our API doesn't make the simple things simple enough.

Alongside our focus on mobile performance, we've also kept the developer experience in mind as we evolve Relay core.

Empowering the Community #

Finally, we want to make it easier for people in the community to develop useful libraries that work with Relay. By comparison, React's small surface area - components - allows developers to build cool things like routing, higher-order components, or reusable text editors. For Relay, this would mean having the framework provide core primitives that users can build upon. We want it to be possible for the community to integrate Relay with view libraries other than React, or to build real-time subscriptions as a complementary library.

What's Next #

These were big goals, and also a bit scary; we knew that incremental improvements would only allow us to move so fast. So in April we started a project to build a new implementation of Relay core targeting low-end mobile devices from the start.

As you can guess since we're writing this, the experiment was a success. The result is a new core that retains the best parts of Relay today - colocated components & data-dependencies, automatic data/view consistency, declarative data-fetching - while improving performance on mobile devices and addressing several common areas of confusion.

We're currently focused on shipping the first applications using the new core: ironing out bugs, refining the API changes and developer experience, and adding any missing features. We're excited to bring these changes to open source, and will do so once we've proven them in production. We'll go into more detail in some upcoming talks - links below - but for now here's an overview:

Static Queries: By adding a couple of Relay-specific directives, we've been able to retain the expressivity of current Relay queries using static syntax (concretely: you know what query an app will execute just by looking at the source text, without having to run that code). For starters this will allow Relay apps to start fetching data in parallel with JavaScript initialization. But it also unlocks other possibilities: knowing the query ahead of time means that we can generate optimized code for handling query responses, for example, or for reading query data from an offline cache.

Expressive Mutations: We'll continue to support a higher-level mutation API for common cases, but will also provide a lower-level API that allows "raw" data access where necessary. If you need to order a list of cached elements, for example, there will be a way to sort() it.

Route-less Relay: Routes will be gone in open source. Instead of a route with multiple query definitions, you'll just provide a single query with as many root fields as you want.

Cache Eviction/Garbage Collection: The API and architecture is designed from the start to allow removing cached data that is no longer referenced by a mounted view.

Stepping back, we recognize that any API changes will require an investment on your part. To make the transition easier, though, we will continue to support the current API for the foreseeable future (we're still using it too). And as much as possible we will open-source the tools that we use to migrate our own code. Ideas that we're exploring include codemods, an interoperability layer for the old/new APIs, and tutorials & guides to ease migration.

Ultimately, we're making these changes because we believe they make Relay better all around: simpler for developers building apps and faster for the people using them.

Conclusion #

If you made it this far, congrats and thanks for reading! We'll be sharing more information about these changes in some upcoming talks:

Greg Hurrell will presenting a Relay "Deep Dive" at the Silicon Valley ReactJS Meetup on August 17th.

I (@josephsavona) will be speaking about Relay at React Rally on August 25th.

We can't wait to share the new code with you and are working as fast as we can to do so!

        A Facebook & Instagram collaboration.

        Acknowledgements

        © 2013–2016 Facebook Inc.

        Documentation licensed under CC BY 4.0.

redpajama_set_name: RedPajamaGithub


text:
package transgenic.lauterbrunnen.lateral.example.simplehazelcast.libdomain;

/**
 * Created by stumeikle on 28/05/16.
 */
public class DeputyHead extends MemberOfStaff {
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
  <persistence-unit name="SOSCalendarPU" transaction-type="JTA">
    <jta-data-source>SOSCalendar</jta-data-source>
    <exclude-unlisted-classes>false</exclude-unlisted-classes>
    <properties/>
  </persistence-unit>
</persistence>


text:
import com.sendgrid.Method;
import com.sendgrid.Request;
import com.sendgrid.Response;
import com.sendgrid.SendGrid;

import java.io.IOException;

//////////////////////////////////////////////////////////////////
// Retrieve bounce purge mail settings
// GET /mail_settings/bounce_purge

public class GetBouncePurgeMailSettings {
  public static void main(String[] args) throws IOException {
    try {
      SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY"));
      Request request = new Request();
      request.setMethod(Method.GET);
      request.setEndpoint("mail_settings/bounce_purge");
      Response response = sg.api(request);
      System.out.println(response.getStatusCode());
      System.out.println(response.getBody());
      System.out.println(response.getHeaders());
    } catch (IOException ex) {
      throw ex;
    }
  }
}


text:
package com.fcduarte.showmetweets.utils;

import twitter4j.Twitter;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
import twitter4j.conf.Configuration;
import twitter4j.conf.ConfigurationBuilder;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;

import com.fcduarte.showmetweets.model.User;

public class TwitterUtils {

	protected static final String TWITTER_CONSUMER_KEY = "QZhiS4PAxHk1gfM94K2iSkxpr";
	protected static final String TWITTER_CONSUMER_SECRET = "aNQg7QPrzNKtZc9RU8Fu85Gj4VFOgGu5qHSYMIK3fWeXSCffFd";
	private static final String ACCESS_TOKEN_SECRET_KEY = "access_token_secret";
	private static final String ACCESS_TOKEN_KEY = "access_token";
	private static final String REQUEST_TOKEN_SECRET_KEY = "request_token_secret";
	private static final String REQUEST_TOKEN_KEY = "request_token";
	private static final String LOGGED_USER_KEY = "logged-user";

	private SharedPreferences prefs;

	public TwitterUtils(Context context) {
		this.prefs = PreferenceManager.getDefaultSharedPreferences(context);
	}

	public void saveRequestToken(String requestToken, String requestTokenSecret) {
		SharedPreferences.Editor editor = prefs.edit();

		editor.putString(REQUEST_TOKEN_KEY, requestToken);
		editor.putString(REQUEST_TOKEN_SECRET_KEY, requestTokenSecret);

		editor.commit();
	}

	public RequestToken loadRequestToken() {
		String reqToken = prefs.getString(REQUEST_TOKEN_KEY, null);
		String reqTokenSecret = prefs.getString(REQUEST_TOKEN_SECRET_KEY, null);

		return new RequestToken(reqToken, reqTokenSecret);
	}

	public void saveAccessToken(String accessToken, String accessTokenSecret) {
		SharedPreferences.Editor editor = prefs.edit();

		editor.putString(ACCESS_TOKEN_KEY, accessToken);
		editor.putString(ACCESS_TOKEN_SECRET_KEY, accessTokenSecret);

		editor.commit();
	}

	public AccessToken loadAccessToken() {
		String accessToken = prefs.getString(ACCESS_TOKEN_KEY, null);
		String accessTokenSecret = prefs.getString(ACCESS_TOKEN_SECRET_KEY, null);

		if (accessToken == null || accessTokenSecret == null) {
			return null;
		}

		return new AccessToken(accessToken, accessTokenSecret);
	}

	public void clear() {
		prefs.edit().clear().commit();
	}

	public void saveLoggedUser(User loggedUser) {
		SharedPreferences.Editor editor = prefs.edit();

		editor.putString(LOGGED_USER_KEY, loggedUser.getUsername());

		editor.commit();

	}

	public String loadLoggedUser() {
		return prefs.getString(LOGGED_USER_KEY, null);
	}

	public boolean userChanged(User user) {
		String loggedUser = loadLoggedUser();
		return loggedUser == null || !user.getUsername().equals(loggedUser);
	}

	public Twitter getTwitterClient() {
		ConfigurationBuilder builder = new ConfigurationBuilder();
		builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
		builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
		Configuration configuration = builder.build();

		TwitterFactory factory = new TwitterFactory(configuration);
		Twitter twitter = factory.getInstance();

		AccessToken accessToken = loadAccessToken();

		if (accessToken != null) {
			twitter.setOAuthAccessToken(accessToken);
		}
		return twitter;
	}

}


text:
// * This makes emacs happy -*-Mode: C++;-*-

/****************************************************************************
 *   Author: Juergen Pfeifer, 1997                                          *
 ****************************************************************************/

#ifndef NCURSES_CURSESP_H_incl
#define NCURSES_CURSESP_H_incl 1

// $Id: cursesp.h,v 1.29 2008/08/16 17:20:23 tom Exp $

#include <ncurses/cursesw.h>

extern "C" {
#  include <ncurses/panel.h>
}

class NCURSES_IMPEXP NCursesPanel
  : public NCursesWindow
{
protected:
  PANEL *p;
  static NCursesPanel *dummy;

private:
  // This structure is used for the panel's user data field to link the
  // PANEL* to the C++ object and to provide extra space for a user pointer.
  typedef struct {
    void*               m_user;      // the pointer for the user's data
    const NCursesPanel* m_back;      // backward pointer to C++ object
    const PANEL*        m_owner;     // the panel itself
  } UserHook;

  inline UserHook *UserPointer()
  {
    UserHook* uptr = reinterpret_cast<UserHook*>(
                           const_cast<void *>(::panel_userptr (p)));
    return uptr;
  }

  void init();                       // Initialize the panel object

protected:
  void set_user(void *user)
  {
    UserHook* uptr = UserPointer();
    if (uptr != 0 && uptr->m_back==this && uptr->m_owner==p) {
      uptr->m_user = user;
    }
  }
  // Set the user pointer of the panel.

  void *get_user()
  {
    UserHook* uptr = UserPointer();
    void *result = 0;
    if (uptr != 0 && uptr->m_back==this && uptr->m_owner==p)
      result = uptr->m_user;
    return result;
  }

  void OnError (int err) const THROWS(NCursesPanelException)
  {
    if (err==ERR)
      THROW(new NCursesPanelException (this, err));
  }
  // If err is equal to the curses error indicator ERR, an error handler
  // is called.

  // Get a keystroke. Default implementation calls getch()
  virtual int getKey(void);

public:
  NCursesPanel(int nlines,
	       int ncols,
	       int begin_y = 0,
	       int begin_x = 0)
    : NCursesWindow(nlines,ncols,begin_y,begin_x), p(0)
  {
    init();
  }
  // Create a panel with this size starting at the requested position.

  NCursesPanel()
    : NCursesWindow(::stdscr), p(0)
  {
    init();
  }
  // This constructor creates the default Panel associated with the
  // ::stdscr window

  NCursesPanel& operator=(const NCursesPanel& rhs)
  {
    if (this != &rhs) {
      *this = rhs;
      NCursesWindow::operator=(rhs);
    }
    return *this;
  }

  NCursesPanel(const NCursesPanel& rhs)
    : NCursesWindow(rhs),
      p(rhs.p)
  {
  }

  virtual ~NCursesPanel();

  // basic manipulation
  inline void hide()
  {
    OnError (::hide_panel(p));
  }
  // Hide the panel. It stays in the stack but becomes invisible.

  inline void show()
  {
    OnError (::show_panel(p));
  }
  // Show the panel, i.e. make it visible.

  inline void top()
  {
    OnError (::top_panel(p));
  }
  // Make this panel the top panel in the stack.

  inline void bottom()
  {
    OnError (::bottom_panel(p));
  }
  // Make this panel the bottom panel in the stack.
  // N.B.: The panel associated with ::stdscr is always on the bottom. So
  // actually bottom() makes the panel the first above ::stdscr.

  virtual int mvwin(int y, int x)
  {
    OnError(::move_panel(p, y, x));
    return OK;
  }

  inline bool hidden() const
  {
    return (::panel_hidden (p) ? TRUE : FALSE);
  }
  // Return TRUE if the panel is hidden, FALSE otherwise.

/* The functions panel_above() and panel_below() are not reflected in
   the NCursesPanel class. The reason for this is, that we cannot
   assume that a panel retrieved by those operations is one wrapped
   by a C++ class. Although this situation might be handled, we also
   need a reverse mapping from PANEL to NCursesPanel which needs some
   redesign of the low level stuff. At the moment, we define them in the
   interface but they will always produce an error. */
  inline NCursesPanel& above() const
  {
    OnError(ERR);
    return *dummy;
  }

  inline NCursesPanel& below() const
  {
    OnError(ERR);
    return *dummy;
  }

  // Those two are rewrites of the corresponding virtual members of
  // NCursesWindow
  virtual int refresh();
  // Propagate all panel changes to the virtual screen and update the
  // physical screen.

  virtual int noutrefresh();
  // Propagate all panel changes to the virtual screen.

  static void redraw();
  // Redraw all panels.

  // decorations
  virtual void frame(const char* title=NULL,
		     const char* btitle=NULL);
  // Put a frame around the panel and put the title centered in the top line
  // and btitle in the bottom line.

  virtual void boldframe(const char* title=NULL,
			 const char* btitle=NULL);
  // Same as frame(), but use highlighted attributes.

  virtual void label(const char* topLabel,
		     const char* bottomLabel);
  // Put the title centered in the top line and btitle in the bottom line.

  virtual void centertext(int row,const char* label);
  // Put the label text centered in the specified row.
};

/* We use templates to provide a typesafe mechanism to associate
 * user data with a panel. A NCursesUserPanel<T> is a panel
 * associated with some user data of type T.
 */
template<class T> class NCursesUserPanel : public NCursesPanel
{
public:
  NCursesUserPanel (int nlines,
		    int ncols,
		    int begin_y = 0,
		    int begin_x = 0,
		    const T* p_UserData = STATIC_CAST(T*)(0))
    : NCursesPanel (nlines, ncols, begin_y, begin_x)
  {
      if (p)
	set_user (const_cast<void *>(p_UserData));
  };
  // This creates an user panel of the requested size with associated
  // user data pointed to by p_UserData.

  NCursesUserPanel(const T* p_UserData = STATIC_CAST(T*)(0)) : NCursesPanel()
  {
    if (p)
      set_user(const_cast<void *>(p_UserData));
  };
  // This creates an user panel associated with the ::stdscr and user data
  // pointed to by p_UserData.

  virtual ~NCursesUserPanel() {};

  T* UserData (void) const
  {
    return reinterpret_cast<T*>(get_user ());
  };
  // Retrieve the user data associated with the panel.

  virtual void setUserData (const T* p_UserData)
  {
    if (p)
      set_user (const_cast<void *>(p_UserData));
  }
  // Associate the user panel with the user data pointed to by p_UserData.
};

#endif /* NCURSES_CURSESP_H_incl */


text:
Swift 2.0 required. Working with Xcode 7.1.

Disclaimer: It is a work in progress, it may break. Use it at your own risk.

Taylor is a library which allows you to create web server applications in [Swift](https://developer.apple.com/swift/)

## Status
At this moment, Taylor only supports GET, POST and PUT HTTP requests. Better documentation is on the way.

## Hello World

```swift

import Taylor

let server = Taylor.Server()

server.get("/") { req, res in
    res.bodyString = "Hello, world!"
    return .Send
}

let port = 3002
do {
   print("Starting server on port: \(port)")
   try server.serveHTTP(port: port, forever: true)
} catch {
   print("Server start failed \(error)")
}
```

More advanced usage instructions coming soon!

## Playground
The easiest way to try out Taylor is using a playground.

For this, you need to have Carthage installed in your computer, is what it is used for fetching the dependencies.

```sh
$ git clone https://github.com/izqui/Taylor.git -b playground
$ cd taylor
$ sh setup.sh
```

And that's it, you should be good to go. Have fun!

## Usage
You can use Taylor from the command line using [CocoaPods Rome](https://github.com/neonichu/Rome) or [Carthage](https://github.com/Carthage/Carthage) as dependency managers.

### Carthage
Create a `Cartfile`:

```
github "izqui/taylor"
```

And then run:

```sh
$ carthage update
$ xcrun swift -F Carthage/Build/Mac yourfile.swift
```

### CocoaPods Rome
Create a `Podfile`:

```
platform :osx, '10.10'

plugin 'cocoapods-rome'

pod 'Taylor'
```

And then run:

```sh
$ pod install
$ xcrun swift -F Rome yourfile.swift
```

Credits to [Ayaka Nonaka](https://twitter.com/ayanonagon)'s [Swift Summit](http://swiftsummit.com) talk for sharing this method for doing Scripting in Swift

## Dependencies
Right now Taylor relies on an Swift library called [SwiftSockets](https://github.com/AlwaysRightInstitute/SwiftSockets/).

## Development
Join our Slack [![Slack Status](https://taylor-framework.herokuapp.com/badge.svg)](https://taylor-framework.herokuapp.com)

For the development of the Taylor framework we use Carthage for managing dependencies.

To contribute to Taylor, clone the project on your local machine and run:

```sh
$ carthage bootstrap
```

Then you can open `Taylor.xcodeproj` and start developing.

The reason there is a Mac app inside the project is for testing purposes given that you cannot have frameworks linked with a Command Line application in Xcode using Carthage. See [here](https://github.com/Carthage/Carthage/issues/287).

## Inspiration
- [Go's Martini](https://github.com/go-martini/martini)
- [Barista](https://github.com/SteveStreza/barista)


text:
import * as m from 'mithril';

import { Comp, Component } from 'mithril';

///////////////////////////////////////////////////////////
// 0.
// Simplest component example - no attrs or state.
//
const comp0 = {
	view() {
		return m('span', "Test");
	}
};

// Mount the component
m.mount(document.getElementById('comp0')!, comp0);

// Unmount the component
m.mount(document.getElementById('comp0')!, null);

///////////////////////////////////////////////////////////
// 1.
// Simple example. Vnode type for component methods is inferred.
//
const comp1: Component<{}, {}> = {
	oncreate({dom}) {
		// vnode.dom type inferred
	},
	view(vnode) {
		return m('span', "Test");
	}
};

///////////////////////////////////////////////////////////
// 2.
// Component with attrs
//
interface Comp2Attrs {
	title: string;
	description: string;
}

const comp2: Component<Comp2Attrs, {}> = {
	view({attrs: {title, description}}) { // Comp2Attrs type is inferred
		return [m('h2', title), m('p', description)];
	}
};

// Correct use
m(comp2, {title: '', description: ''});

// Correct use with lifecycle method
m(comp2, {title: '', description: '', oncreate: (v) => v.attrs.title + '\n' + v.attrs.description});

// Properties missing
// $ExpectError
m(comp2, {});

// Property 'description' is missing in type '{ title: string; }'.
// $ExpectError
m(comp2, {title: ''});

// Property 'title' is missing in type '{ description: string; }'.
// $ExpectError
m(comp2, {description: ''});

// Type 'boolean' is not assignable to type 'string'.
// $ExpectError
m(comp2, {title: '', description: true});

// Object literal may only specify known properties, and 'foo' does not exist in type 'Comp2Attrs & Lifecycle<Comp2Attrs, {}> & { key?: string | number | undefined; }'.
// $ExpectError
m(comp2, {title: '', description: '', foo: ''});

///////////////////////////////////////////////////////////
// 3.
// Declares attrs type inline.
// Uses comp2 with typed attrs and makes use of `onremove`
// lifecycle method.
//
const comp3: Component<{pageHead: string}, {}> = {
	oncreate({dom}) {
		// Can do stuff with dom
	},
	view({attrs}) {
		return m('.page',
			m('h1', attrs.pageHead),
			m(comp2,
				{
					// attrs is type checked - nice!
					title: "A Title",
					description: "Some descriptive text.",
					onremove(vnode) {
						console.log("comp2 was removed");
					},
				}
			),
			// Test other hyperscript parameter variations
			m(comp1, m(comp1)),
			m('br')
		);
	}
};

///////////////////////////////////////////////////////////
// 4.
// Typed attrs and state, and `this` type is inferred.
//
interface Comp4Attrs {
	name: string;
}

interface Comp4State {
	count: number;
	add(this: Comp4State, num: number): void;
}

// Either of these two Comp4 defs will work:
type Comp4 = Component<Comp4Attrs, Comp4State> & Comp4State;
// interface Comp4 extends Component<Comp4Attrs,Comp4State>, Comp4State {}

const comp4: Comp4 = {
	count: 0, // <- Must be declared to satisfy Comp4 type which includes Comp4State type
	add(num) {
		// num and this types inferred
		this.count += num;
	},
	oninit() {
		this.count = 0;
	},
	view({attrs}) {
		return [
			m('h1', `This ${attrs.name} has been clicked ${this.count} times`),
			m('button',
				{
					// 'this' is typed!
					onclick: () => this.add(1)
				},
			"Click me")
		];
	}
};

///////////////////////////////////////////////////////////
// 5.
// Stateful component (Equivalent to Comp4 example.)
// Avoids the use of `this` completely; state manipulated
// through vnode.state.
//
const comp5: Component<Comp4Attrs, Comp4State> = {
	oninit({state}) {
		state.count = 0;
		state.add = num => { state.count += num; };
	},
	view({attrs, state}) {
		return [
			m('h1', `This ${attrs.name} has been clicked ${state.count} times`),
			m('button',
				{
					onclick() { state.add(1); }
				},
				"Click me"
			)
		];
	}
};

///////////////////////////////////////////////////////////
//
// Concise module example with default export
//
interface Attrs {
	name: string;
}

interface State {
	count: number;
}

// Using the Comp type will apply the State intersection type for us.
const comp: Comp<Attrs, State> = {
	count: 0,
	view({attrs}) {
		return m('span', `name: ${attrs.name}, count: ${this.count}`);
	}
};
export default comp;


text:
The easy to understand coding guides help you check the features without any need to write your own code. Barcode reader API in cURL can be applied with ByteScout Cloud API Server. ByteScout Cloud API Server is API server that is ready to use and can be installed and deployed in less than 30 minutes on your own Windows server or server in a cloud. It can save data and files on your local server-based file storage or in Amazon AWS S3 storage. Data is processed solely on the API server and is powered by ByteScout engine, no cloud services or Internet connection is required for data processing..

CURL code snippet like this for ByteScout Cloud API Server works best when you need to quickly implement barcode reader API in your cURL application.  This sample code in cURL is all you need. Just copy-paste it to the code editor, then add a reference to ByteScout Cloud API Server and you are ready to try it! Writing cURL application mostly includes various stages of the software development so even if the functionality works please check it with your data and the production environment.

Trial version of ByteScout is available for free download from our website. This and other source code samples for cURL and other programming languages are available.

## REQUEST FREE TECH SUPPORT

[Click here to get in touch](https://bytescout.zendesk.com/hc/en-us/requests/new?subject=ByteScout%20Cloud%20API%20Server%20Question)

or just send email to [support@bytescout.com](mailto:support@bytescout.com?subject=ByteScout%20Cloud%20API%20Server%20Question)

## ON-PREMISE OFFLINE SDK

[Get Your 60 Day Free Trial](https://bytescout.com/download/web-installer?utm_source=github-readme)
[Explore SDK Docs](https://bytescout.com/documentation/index.html?utm_source=github-readme)
[Sign Up For Online Training](https://academy.bytescout.com/)

## ON-DEMAND REST WEB API

[Get your API key](https://pdf.co/documentation/api?utm_source=github-readme)
[Explore Web API Documentation](https://pdf.co/documentation/api?utm_source=github-readme)
[Explore Web API Samples](https://github.com/bytescout/ByteScout-SDK-SourceCode/tree/master/PDF.co%20Web%20API)

## VIDEO REVIEW

[https://www.youtube.com/watch?v=NEwNs2b9YN8](https://www.youtube.com/watch?v=NEwNs2b9YN8)

<!-- code block begin -->

##### ****ReadBarcodeFromURL.cmd:**

```
@echo off

:: Path of the cURL executable
set CURL="curl.exe"

:: Direct URL of source file to search barcodes in.
set SOURCE_FILE_URL=https://bytescout-com.s3.amazonaws.com/files/demo-files/cloud-api/barcode-reader/sample.pdf
:: Comma-separated list of barcode types to search.
:: barcode types
set BARCODE_TYPES=Code128,Code39,Interleaved2of5,EAN13
:: Comma-separated list of page indices (or ranges) to process. Leave empty for all pages. Example: '0,2-5,7-'.
set PAGES=

:: Please NOTE: In this sample we're assuming Cloud Api Server is hosted at "https://localhost".
:: If it's not then please replace this with with your hosting url.

:: Prepare URL for `Barcode Reader` API endpoint
set QUERY="https://localhost/barcode/read/from/url?types=%BARCODE_TYPES%&pages=%PAGES%&url=%SOURCE_FILE_URL%"

:: Perform request and save response to a file
%CURL% -# -X GET %QUERY% >response.json

:: Display the response
type response.json

:: Use any convenient way to parse JSON response and get information about decoded barcodes.

echo.
pause
```

<!-- code block end -->


text:
* Systèmes de gestion de contenus
* Langages et technologies : JavaScript


text:
Reports for Administrators
==========

CiviHR allows the creation of a huge variety of reports using a powerful built-in visual tool.

**Access CiviHR reports**
---------------

The Reports module is only accessible to Administrators. Login as a CiviHR admin and go to your Self Service Portal. Click on the Reports menu as shown below:

![image](../img/report-1.png)

There are two broad categories of reports in CiviHR 1.6:

-   People reports: Reports on headcount, demographics, job contract and job roles
-   Leave and Absence reports: Reports on absence duration, occurrence, request status, and more.

From this screen, you can also adjust the age groupings used in reports by clicking Age groups under Reports settings towards the bottom of the screen. From there, you can Edit or Delete age ranges, or Create new Age Group by clicking the appropriate links.

**Use built-in reports**
---------------

CiviHR offers a range of built-in reports such as on headcount, demographics and absence duration. To access built-in reports, click on either People or Leave and Absences reports to see the related report options.

![image](../img/report-2.png)

-   Click Show Filters and input the date or date range for which you would like to generate your report
-   Click Filter
-   Click on the Pivot Table tab.
-   Select the report you would like to use from the Configuration dropdown.

**Customise a built-in report**
-------------

You may want to tweak and save a built-in report so that it meets your reporting requirement perfectly.

![image](../img/report-3.png)

You can change and save:
-   Columns: Drag and drop any parameter on the vertical bar. To remove a parameter, drag and drop the box from the vertical bar into the Parameter area.
-   Rows: Drag and drop any parameter on the horizontal bar. To remove a parameter, drag and drop the box from the horizontal bar into the Parameter area.
-   Filter values: You can further filter the values you would like to include in your report by clicking the chevron icon on the parameter box and making a selection.
-   Dimensions: You can add more than one parameter on the horizontal and vertical bars to drill further into your data.
-   Chart or table type: You can change the type of chart or table by clicking the dropdown box showing Table by default and selecting any of the options there.
-   Mathematical operation: You can change the mathematical operation being performed on your data, for instance from a Count of the number of part-time staff to Average part-time hours.
Once you have configured the report as you like, you can save it for future use by clicking Save Report or Save as New. Save Report permanently replaces the built-in report. Save as New will bring up a dialogue box where you can name your new report. Your new report will be available from the Configuration dropdown.

**Create a new report**
-------------

Building a new report is very similar to customising an existing report. Let us go through the process of creating and saving a new report using an example:

Building an absence report: Let's say you want to see the total number of days staff were absent in each office location.

Go to Self Service Portal -> Reports -> Leave and Absences reports. Click on the pivot table tab here.

-   Add column: Drag Absence Type into the vertical bar. This gives you a table of the total number of days of leave of each type taken by your staff.

![image](../img/report-4.png)

-   Add row: To see the days of the week that these absences fell on, drag Absence Day of the Week onto the horizontal bar.

![image](../img/report-5.png)

-   Filter values: Click on the chevron icon next to the parameters you have added into the horizontal and vertical bars. Select the values that you would like to include in your report, uncheck the rest and click OK.

![image](../img/report-6.png)

-   Add dimensions: You can drill further into your data by adding more than one parameter to the horizontal or vertical bars. For example, you can drag and drop location into the vertical bar to break down the above absence data by location.

![image](../img/report-7.png)

-   Select appropriate chart or table type: The report instantly offers more insight when it is viewed as a Heatmap instead of a simple table.

![image](../img/report-8.png)

Save this report for future by clicking Save as New and giving it a suitable name. Your new report will now be available from the Configuration dropdown.

**Exporting your data**
-------------

When you click on People or Leave and Absences reports, you first see your staff data in table form. You can export this data by clicking on the Export button. If you have specified a filtered view, only the filtered data is exported.

![image](../img/report-9.png)

You can also export data specific to a particular report. Select TSV (tab-separated values) from the Chart type dropdown. Copy and paste this data into a spreadsheet.

![image](../img/report-10.png)


text:
package com.opengamma.core.link;

import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;

import org.joda.beans.Bean;
import org.joda.beans.BeanDefinition;
import org.joda.beans.ImmutableBean;
import org.joda.beans.ImmutableConstructor;
import org.joda.beans.JodaBeanUtils;
import org.joda.beans.MetaProperty;
import org.joda.beans.Property;
import org.joda.beans.PropertyDefinition;
import org.joda.beans.impl.direct.DirectFieldsBeanBuilder;
import org.joda.beans.impl.direct.DirectMetaBean;
import org.joda.beans.impl.direct.DirectMetaProperty;
import org.joda.beans.impl.direct.DirectMetaPropertyMap;

import com.opengamma.util.ArgumentChecker;

/**
 * Represents a link to a Config object using an actual instance. When the resolve
 * method is called, the embedded object is then returned.
 *
 * @param <C> type of the config
 */
@BeanDefinition
public final class ResolvedConfigLink<C>
    extends ConfigLink<C>
    implements ImmutableBean {

  /**
   * The config instance.
   */
  @PropertyDefinition(validate = "notNull")
  private final C _value;

  /**
   * Create the link, embedding the provided object.
   *
   * @param value the config object to be embedded
   */
  @ImmutableConstructor
  /* package */ ResolvedConfigLink(C value) {
    _value = ArgumentChecker.notNull(value, "config");
  }

  @Override
  public C resolve() {
    return _value;
  }

  @Override
  @SuppressWarnings("unchecked")
  public Class<C> getTargetType() {
    return (Class<C>) _value.getClass();
  }

  //------------------------- AUTOGENERATED START -------------------------
  ///CLOVER:OFF
  /**
   * The meta-bean for {@code ResolvedConfigLink}.
   * @return the meta-bean, not null
   */
  @SuppressWarnings("rawtypes")
  public static ResolvedConfigLink.Meta meta() {
    return ResolvedConfigLink.Meta.INSTANCE;
  }

  /**
   * The meta-bean for {@code ResolvedConfigLink}.
   * @param <R>  the bean's generic type
   * @param cls  the bean's generic type
   * @return the meta-bean, not null
   */
  @SuppressWarnings("unchecked")
  public static <R> ResolvedConfigLink.Meta<R> metaResolvedConfigLink(Class<R> cls) {
    return ResolvedConfigLink.Meta.INSTANCE;
  }

  static {
    JodaBeanUtils.registerMetaBean(ResolvedConfigLink.Meta.INSTANCE);
  }

  /**
   * Returns a builder used to create an instance of the bean.
   * @param <C>  the type
   * @return the builder, not null
   */
  public static <C> ResolvedConfigLink.Builder<C> builder() {
    return new ResolvedConfigLink.Builder<C>();
  }

  @SuppressWarnings("unchecked")
  @Override
  public ResolvedConfigLink.Meta<C> metaBean() {
    return ResolvedConfigLink.Meta.INSTANCE;
  }

  @Override
  public <R> Property<R> property(String propertyName) {
    return metaBean().<R>metaProperty(propertyName).createProperty(this);
  }

  @Override
  public Set<String> propertyNames() {
    return metaBean().metaPropertyMap().keySet();
  }

  //-----------------------------------------------------------------------
  /**
   * Gets the config instance.
   * @return the value of the property, not null
   */
  public C getValue() {
    return _value;
  }

  //-----------------------------------------------------------------------
  /**
   * Returns a builder that allows this bean to be mutated.
   * @return the mutable builder, not null
   */
  public Builder<C> toBuilder() {
    return new Builder<C>(this);
  }

  @Override
  public boolean equals(Object obj) {
    if (obj == this) {
      return true;
    }
    if (obj != null && obj.getClass() == this.getClass()) {
      ResolvedConfigLink<?> other = (ResolvedConfigLink<?>) obj;
      return JodaBeanUtils.equal(getValue(), other.getValue());
    }
    return false;
  }

  @Override
  public int hashCode() {
    int hash = getClass().hashCode();
    hash = hash * 31 + JodaBeanUtils.hashCode(getValue());
    return hash;
  }

  @Override
  public String toString() {
    StringBuilder buf = new StringBuilder(64);
    buf.append("ResolvedConfigLink{");
    buf.append("value").append('=').append(JodaBeanUtils.toString(getValue()));
    buf.append('}');
    return buf.toString();
  }

  //-----------------------------------------------------------------------
  /**
   * The meta-bean for {@code ResolvedConfigLink}.
   * @param <C>  the type
   */
  public static final class Meta<C> extends DirectMetaBean {
    /**
     * The singleton instance of the meta-bean.
     */
    @SuppressWarnings("rawtypes")
    static final Meta INSTANCE = new Meta();

    /**
     * The meta-property for the {@code value} property.
     */
    @SuppressWarnings({"unchecked", "rawtypes" })
    private final MetaProperty<C> _value = (DirectMetaProperty) DirectMetaProperty.ofImmutable(
        this, "value", ResolvedConfigLink.class, Object.class);
    /**
     * The meta-properties.
     */
    private final Map<String, MetaProperty<?>> _metaPropertyMap$ = new DirectMetaPropertyMap(
        this, null,
        "value");

    /**
     * Restricted constructor.
     */
    private Meta() {
    }

    @Override
    protected MetaProperty<?> metaPropertyGet(String propertyName) {
      switch (propertyName.hashCode()) {
        case 111972721:  // value
          return _value;
      }
      return super.metaPropertyGet(propertyName);
    }

    @Override
    public ResolvedConfigLink.Builder<C> builder() {
      return new ResolvedConfigLink.Builder<C>();
    }

    @SuppressWarnings({"unchecked", "rawtypes" })
    @Override
    public Class<? extends ResolvedConfigLink<C>> beanType() {
      return (Class) ResolvedConfigLink.class;
    }

    @Override
    public Map<String, MetaProperty<?>> metaPropertyMap() {
      return _metaPropertyMap$;
    }

    //-----------------------------------------------------------------------
    /**
     * The meta-property for the {@code value} property.
     * @return the meta-property, not null
     */
    public MetaProperty<C> value() {
      return _value;
    }

    //-----------------------------------------------------------------------
    @Override
    protected Object propertyGet(Bean bean, String propertyName, boolean quiet) {
      switch (propertyName.hashCode()) {
        case 111972721:  // value
          return ((ResolvedConfigLink<?>) bean).getValue();
      }
      return super.propertyGet(bean, propertyName, quiet);
    }

    @Override
    protected void propertySet(Bean bean, String propertyName, Object newValue, boolean quiet) {
      metaProperty(propertyName);
      if (quiet) {
        return;
      }
      throw new UnsupportedOperationException("Property cannot be written: " + propertyName);
    }

  }

  //-----------------------------------------------------------------------
  /**
   * The bean-builder for {@code ResolvedConfigLink}.
   * @param <C>  the type
   */
  public static final class Builder<C> extends DirectFieldsBeanBuilder<ResolvedConfigLink<C>> {

    private C _value;

    /**
     * Restricted constructor.
     */
    private Builder() {
    }

    /**
     * Restricted copy constructor.
     * @param beanToCopy  the bean to copy from, not null
     */
    private Builder(ResolvedConfigLink<C> beanToCopy) {
      this._value = beanToCopy.getValue();
    }

    //-----------------------------------------------------------------------
    @Override
    public Object get(String propertyName) {
      switch (propertyName.hashCode()) {
        case 111972721:  // value
          return _value;
        default:
          throw new NoSuchElementException("Unknown property: " + propertyName);
      }
    }

    @SuppressWarnings("unchecked")
    @Override
    public Builder<C> set(String propertyName, Object newValue) {
      switch (propertyName.hashCode()) {
        case 111972721:  // value
          this._value = (C) newValue;
          break;
        default:
          throw new NoSuchElementException("Unknown property: " + propertyName);
      }
      return this;
    }

    @Override
    public Builder<C> set(MetaProperty<?> property, Object value) {
      super.set(property, value);
      return this;
    }

    @Override
    public Builder<C> setString(String propertyName, String value) {
      setString(meta().metaProperty(propertyName), value);
      return this;
    }

    @Override
    public Builder<C> setString(MetaProperty<?> property, String value) {
      super.setString(property, value);
      return this;
    }

    @Override
    public Builder<C> setAll(Map<String, ? extends Object> propertyValueMap) {
      super.setAll(propertyValueMap);
      return this;
    }

    @Override
    public ResolvedConfigLink<C> build() {
      return new ResolvedConfigLink<C>(
          _value);
    }

    //-----------------------------------------------------------------------
    /**
     * Sets the {@code value} property in the builder.
     * @param value  the new value, not null
     * @return this, for chaining, not null
     */
    public Builder<C> value(C value) {
      JodaBeanUtils.notNull(value, "value");
      this._value = value;
      return this;
    }

    //-----------------------------------------------------------------------
    @Override
    public String toString() {
      StringBuilder buf = new StringBuilder(64);
      buf.append("ResolvedConfigLink.Builder{");
      buf.append("value").append('=').append(JodaBeanUtils.toString(_value));
      buf.append('}');
      return buf.toString();
    }

  }

  ///CLOVER:ON
  //-------------------------- AUTOGENERATED END --------------------------
}


text:
package org.apache.helix.messaging.handling;

import java.util.HashSet;
import java.util.concurrent.ThreadPoolExecutor;

import org.apache.helix.ConfigAccessor;
import org.apache.helix.HelixDataAccessor;
import org.apache.helix.HelixManager;
import org.apache.helix.NotificationContext;
import org.apache.helix.integration.ZkStandAloneCMTestBase;
import org.apache.helix.integration.manager.MockParticipantManager;
import org.apache.helix.messaging.DefaultMessagingService;
import org.apache.helix.model.ClusterConfig;
import org.apache.helix.model.ConfigScope;
import org.apache.helix.model.Message;
import org.apache.helix.model.builder.ConfigScopeBuilder;
import org.testng.Assert;
import org.testng.annotations.Test;

public class TestConfigThreadpoolSize extends ZkStandAloneCMTestBase {
  public static class TestMessagingHandlerFactory implements MessageHandlerFactory {
    public static HashSet<String> _processedMsgIds = new HashSet<String>();

    @Override
    public MessageHandler createHandler(Message message, NotificationContext context) {
      return null;
    }

    @Override
    public String getMessageType() {
      return "TestMsg";
    }

    @Override
    public void reset() {
      // TODO Auto-generated method stub
    }

  }

  public static class TestMessagingHandlerFactory2 implements MessageHandlerFactory {
    public static HashSet<String> _processedMsgIds = new HashSet<String>();

    @Override
    public MessageHandler createHandler(Message message, NotificationContext context) {
      return null;
    }

    @Override
    public String getMessageType() {
      return "TestMsg2";
    }

    @Override
    public void reset() {
      // TODO Auto-generated method stub
    }

  }

  @Test
  public void TestThreadPoolSizeConfig() {
    String instanceName = PARTICIPANT_PREFIX + "_" + (START_PORT + 0);
    HelixManager manager = _participants[0];

    ConfigAccessor accessor = manager.getConfigAccessor();
    ConfigScope scope =
        new ConfigScopeBuilder().forCluster(manager.getClusterName()).forParticipant(instanceName)
            .build();
    accessor.set(scope, "TestMsg." + HelixTaskExecutor.MAX_THREADS, "" + 12);

    scope = new ConfigScopeBuilder().forCluster(manager.getClusterName()).build();
    accessor.set(scope, "TestMsg." + HelixTaskExecutor.MAX_THREADS, "" + 8);

    for (int i = 0; i < NODE_NR; i++) {
      instanceName = PARTICIPANT_PREFIX + "_" + (START_PORT + i);

      _participants[i].getMessagingService().registerMessageHandlerFactory("TestMsg",
          new TestMessagingHandlerFactory());
      _participants[i].getMessagingService()
          .registerMessageHandlerFactory("TestMsg2", new TestMessagingHandlerFactory2());

    }

    for (int i = 0; i < NODE_NR; i++) {
      instanceName = PARTICIPANT_PREFIX + "_" + (START_PORT + i);

      DefaultMessagingService svc =
          (DefaultMessagingService) (_participants[i]
              .getMessagingService());
      HelixTaskExecutor helixExecutor = svc.getExecutor();
      ThreadPoolExecutor executor =
          (ThreadPoolExecutor) (helixExecutor._executorMap.get("TestMsg"));

      ThreadPoolExecutor executor2 =
          (ThreadPoolExecutor) (helixExecutor._executorMap.get("TestMsg2"));
      if (i != 0) {

        Assert.assertEquals(8, executor.getMaximumPoolSize());
      } else {
        Assert.assertEquals(12, executor.getMaximumPoolSize());
      }
      Assert.assertEquals(HelixTaskExecutor.DEFAULT_PARALLEL_TASKS, executor2.getMaximumPoolSize());
    }
  }

  @Test
  public void testBatchMessageStateTransitionThreadPoolSize() throws InterruptedException {
    int customizedThreads = 123;
    for (MockParticipantManager participantManager : _participants) {
      participantManager.syncStop();
    }

    HelixDataAccessor accessor = _manager.getHelixDataAccessor();
    ClusterConfig clusterConfig = accessor.getProperty(accessor.keyBuilder().clusterConfig());
    clusterConfig.setBatchStateTransitionMaxThreads(customizedThreads);
    accessor.setProperty(accessor.keyBuilder().clusterConfig(), clusterConfig);

    // Since old participants already checked the threadpool, shutdown all of others
    _setupTool.addInstanceToCluster(CLUSTER_NAME, "TestParticipant");
    MockParticipantManager newParticipant =
        new MockParticipantManager(ZK_ADDR, CLUSTER_NAME, "TestParticipant");
    newParticipant.syncStart();

    // Let messsage trigger update thread pool
    String dbName = "TestDBSubMessageThreadPool";
    _setupTool.addResourceToCluster(CLUSTER_NAME, dbName, 5, "OnlineOffline");
    _setupTool.rebalanceStorageCluster(CLUSTER_NAME, dbName, 1);

    Thread.sleep(1000);

    DefaultMessagingService svc = (DefaultMessagingService) (newParticipant.getMessagingService());
    HelixTaskExecutor helixExecutor = svc.getExecutor();
    Assert.assertEquals(
        ((ThreadPoolExecutor) helixExecutor._batchMessageExecutorService).getMaximumPoolSize(),
        customizedThreads);

  }
}


text:
module CommunicationsHelper
end


text:
jest.mock('../../../../internal/esi-agent');

import { API, makeAPI } from '../../../../index';
import { ESIAgent } from '../../../../internal/esi-agent';

let api: API = makeAPI();
// Cast to any to get the private agent property
let agent: ESIAgent = (api as any).agent;

afterEach(() => {
  agent.__reset();
});

test('Window.info', () => {
  agent.__expectRoute('post_ui_openwindow_information', {
    'target_id': 2
  }, { 'token': 'my_token' });
  return api.characters(1, 'my_token').window.info(2).then(result => {
    expect(result).not.toBeDefined();
  });
});

test('Window.market', () => {
  agent.__expectRoute('post_ui_openwindow_marketdetails', {
    'type_id': 2
  }, { 'token': 'my_token' });
  return api.characters(1, 'my_token').window.market(2).then(result => {
    expect(result).not.toBeDefined();
  });
});

test('Window.contract', () => {
  agent.__expectRoute('post_ui_openwindow_contract', {
    'contract_id': 2
  }, { 'token': 'my_token' });
  return api.characters(1, 'my_token').window.contract(2).then(result => {
    expect(result).not.toBeDefined();
  });
});

test('Window.newMail', () => {
  agent.__expectRoute('post_ui_openwindow_newmail', {
    'new_mail': {
      'subject': 'SUBJECT',
      'recipients': [1, 2],
      'body': 'this is the body text.',
      'to_corp_or_alliance_id': 0,
      'to_mailing_list_id': 0
    }
  }, { 'token': 'my_token' });
  return api.characters(1, 'my_token').window.newMail({
    'subject': 'SUBJECT',
    'recipients': [1, 2],
    'body': 'this is the body text.',
    'to_corp_or_alliance_id': 0,
    'to_mailing_list_id': 0
  }).then(result => {
    expect(result).not.toBeDefined();
  });
});


text:
package com.douwe.notes.service.impl;

import com.douwe.generic.dao.DataAccessException;
import com.douwe.notes.dao.IAnneeAcademiqueDao;
import com.douwe.notes.dao.IEnseignementDao;
import com.douwe.notes.dao.INiveauDao;
import com.douwe.notes.dao.IOptionDao;
import com.douwe.notes.entities.AnneeAcademique;
import com.douwe.notes.entities.Enseignement;
import com.douwe.notes.entities.Niveau;
import com.douwe.notes.entities.Option;
import com.douwe.notes.service.IEnseignementService;
import com.douwe.notes.service.ServiceException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.Stateless;
import javax.inject.Inject;

/**
 *
 * @author Kenfack Valmy-Roi <roykenvalmy@gmail.com>
 */
@Stateless
public class EnseignementServiceImpl implements IEnseignementService {

    @Inject
    private IEnseignementDao enseignementDao;

    @Inject
    private IAnneeAcademiqueDao  anneeDao;

    @Inject
    private INiveauDao niveauDao;

    @Inject
    private IOptionDao optionDao;

    public IEnseignementDao getEnseignementDao() {
        return enseignementDao;
    }

    public void setEnseignementDao(IEnseignementDao enseignementDao) {
        this.enseignementDao = enseignementDao;
    }

    public IAnneeAcademiqueDao getAnneeDao() {
        return anneeDao;
    }

    public void setAnneeDao(IAnneeAcademiqueDao anneeDao) {
        this.anneeDao = anneeDao;
    }

    public INiveauDao getNiveauDao() {
        return niveauDao;
    }

    public void setNiveauDao(INiveauDao niveauDao) {
        this.niveauDao = niveauDao;
    }

    public IOptionDao getOptionDao() {
        return optionDao;
    }

    public void setOptionDao(IOptionDao optionDao) {
        this.optionDao = optionDao;
    }

    @Override
    public Enseignement saveOrUpdateEnseignement(Enseignement enseignement) throws ServiceException {
        try {
            if (enseignement.getId() == null) {
                enseignement.setActive(1);
                return enseignementDao.create(enseignement);
            } else {
                return enseignementDao.update(enseignement);
            }
        } catch (DataAccessException ex) {
            Logger.getLogger(EnseignementServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
            throw new ServiceException("La ressource demandée est introuvable");
        }
    }

    @Override
    public void deleteEnseignement(Long id) throws ServiceException {
        try {
            Enseignement enseignement = enseignementDao.findById(id);
            if (enseignement != null) {
                enseignement.setActive(0);
                enseignementDao.update(enseignement);
            }

        } catch (DataAccessException ex) {
            Logger.getLogger(EnseignementServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
            throw new ServiceException("La ressource demandée est introuvable");
        }
    }

    @Override
    public Enseignement findEnseignementById(long id) throws ServiceException {
        try {
            return enseignementDao.findById(id);
        } catch (DataAccessException ex) {
            Logger.getLogger(EnseignementServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
            throw new ServiceException("La ressource demandée est introuvable");
        }
    }

    @Override
    public List<Enseignement> getAllEnseignements() throws ServiceException {
        try {
            return enseignementDao.findAllActive();
        } catch (DataAccessException ex) {
            Logger.getLogger(EnseignementServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
            throw new ServiceException("La ressource demandée est introuvable");
        }
    }

    @Override
    public List<Enseignement> getEnseignementByOption(Long anneeId, Long niveauId, Long optionId) throws ServiceException {
        try {
            AnneeAcademique annee = anneeDao.findById(anneeId);
            Niveau niveau = niveauDao.findById(niveauId);
            Option option = optionDao.findById(optionId);
            return enseignementDao.findByOption(annee, niveau, option);
        } catch (DataAccessException ex) {
            Logger.getLogger(EnseignementServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
            throw new ServiceException("La ressource demandée est introuvable");
        }
    }

}


text:
import { useState } from 'react'
import {
  CloudUploadIcon,
  CheckCircleIcon,
  ExclamationCircleIcon,
} from '@heroicons/react/outline'
import { classNames } from '@/utils/dom'
import Loading from '@/navigation/Loading'

const defaultAccept = 'image/*,.pdf'

const DocumentUpload = ({
  type,
  label,
  handleFiles,
  accept,
  multiple,
}: {
  type: string,
  label: string,
  handleFiles: Function,
  accept?: string,
  multiple?: boolean
}) => {
  const [uploading, setUploading] = useState(false)
  const [uploaded, setUploaded] = useState(false)
  const [failed, setFailed] = useState(false)
  const [filesLabel, setFilesLabel] = useState<string | null>(null)
  multiple = multiple ?? false

  const onChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const files = e.target.files
    if (!files) return
    setFailed(false)
    setUploaded(false)
    setUploading(true)

    try {
      await handleFiles({ files, type, label })
      setUploaded(true)
      console.log(files);

      setFilesLabel(
        files.length > 1
          ? `${files.length} files added`
          : files[0]?.name ?? 'File added'
      )
    } catch (error) {
      setFailed(true)
    } finally {
      setUploading(false)
    }
  }

  return (

          {
            failed
              ? <ExclamationCircleIcon className="h-10 text-error transition" />
              : uploaded
                ? <CheckCircleIcon className="h-10 text-success transition" />
                : uploading
                  ? <Loading />
                  : <CloudUploadIcon className="h-10 text-neutral"/>
          }

            {filesLabel || label}

        <input id={type} type="file" name={type}
          className="opacity-0 cursor-pointer w-full"
          accept={accept || defaultAccept}
          onChange={onChange}
          multiple={multiple}
          disabled={uploading}
        />

  )
}

export default DocumentUpload


text:
"""
:author: Damian Eads, 2009
:license: modified BSD
"""

import numpy as np
from scipy import ndimage
from .. import draw

def square(width, dtype=np.uint8):
    """Generates a flat, square-shaped structuring element.

    Every pixel along the perimeter has a chessboard distance
    no greater than radius (radius=floor(width/2)) pixels.

    Parameters
    ----------
    width : int
        The width and height of the square.

    Other Parameters
    ----------------
    dtype : data-type
        The data type of the structuring element.

    Returns
    -------
    selem : ndarray
        A structuring element consisting only of ones, i.e. every
        pixel belongs to the neighborhood.

    """
    return np.ones((width, width), dtype=dtype)

def rectangle(width, height, dtype=np.uint8):
    """Generates a flat, rectangular-shaped structuring element.

    Every pixel in the rectangle generated for a given width and given height
    belongs to the neighboorhood.

    Parameters
    ----------
    width : int
        The width of the rectangle.
    height : int
        The height of the rectangle.

    Other Parameters
    ----------------
    dtype : data-type
        The data type of the structuring element.

    Returns
    -------
    selem : ndarray
        A structuring element consisting only of ones, i.e. every
        pixel belongs to the neighborhood.

    """
    return np.ones((width, height), dtype=dtype)

def diamond(radius, dtype=np.uint8):
    """Generates a flat, diamond-shaped structuring element.

    A pixel is part of the neighborhood (i.e. labeled 1) if
    the city block/manhattan distance between it and the center of
    the neighborhood is no greater than radius.

    Parameters
    ----------
    radius : int
        The radius of the diamond-shaped structuring element.

    Other Parameters
    ----------------
    dtype : data-type
        The data type of the structuring element.

    Returns
    -------

    selem : ndarray
        The structuring element where elements of the neighborhood
        are 1 and 0 otherwise.
    """
    L = np.arange(0, radius * 2 + 1)
    I, J = np.meshgrid(L, L)
    return np.array(np.abs(I - radius) + np.abs(J - radius) <= radius,
                    dtype=dtype)

def disk(radius, dtype=np.uint8):
    """Generates a flat, disk-shaped structuring element.

    A pixel is within the neighborhood if the euclidean distance between
    it and the origin is no greater than radius.

    Parameters
    ----------
    radius : int
        The radius of the disk-shaped structuring element.

    Other Parameters
    ----------------
    dtype : data-type
        The data type of the structuring element.

    Returns
    -------
    selem : ndarray
        The structuring element where elements of the neighborhood
        are 1 and 0 otherwise.
    """
    L = np.arange(-radius, radius + 1)
    X, Y = np.meshgrid(L, L)
    return np.array((X ** 2 + Y ** 2) <= radius ** 2, dtype=dtype)

def ellipse(width, height, dtype=np.uint8):
    """Generates a flat, ellipse-shaped structuring element.

    Every pixel along the perimeter of ellipse satisfies
    the equation ``(x/width+1)**2 + (y/height+1)**2 = 1``.

    Parameters
    ----------
    width : int
        The width of the ellipse-shaped structuring element.
    height : int
        The height of the ellipse-shaped structuring element.

    Other Parameters
    ----------------
    dtype : data-type
        The data type of the structuring element.

    Returns
    -------
    selem : ndarray
        The structuring element where elements of the neighborhood
        are 1 and 0 otherwise.

    Examples
    --------
    >>> from skimage.morphology import selem
    >>> selem.ellipse(5, 3)
    array([[0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0],
           [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
           [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
           [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
           [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
           [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
           [0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0]], dtype=uint8)

    """
    selem = np.zeros((2 * height + 1, 2 * width + 1), dtype=dtype)
    rows, cols = draw.ellipse(height, width, height + 1, width + 1)
    selem[rows, cols] = 1
    return selem

def cube(width, dtype=np.uint8):
    """ Generates a cube-shaped structuring element.

    This is the 3D equivalent of a square.
    Every pixel along the perimeter has a chessboard distance
    no greater than radius (radius=floor(width/2)) pixels.

    Parameters
    ----------
    width : int
        The width, height and depth of the cube.

    Other Parameters
    ----------------
    dtype : data-type
        The data type of the structuring element.

    Returns
    -------
    selem : ndarray
        A structuring element consisting only of ones, i.e. every
        pixel belongs to the neighborhood.

    """
    return np.ones((width, width, width), dtype=dtype)

def octahedron(radius, dtype=np.uint8):
    """Generates a octahedron-shaped structuring element.

    This is the 3D equivalent of a diamond.
    A pixel is part of the neighborhood (i.e. labeled 1) if
    the city block/manhattan distance between it and the center of
    the neighborhood is no greater than radius.

    Parameters
    ----------
    radius : int
        The radius of the octahedron-shaped structuring element.

    Other Parameters
    ----------------
    dtype : data-type
        The data type of the structuring element.

    Returns
    -------

    selem : ndarray
        The structuring element where elements of the neighborhood
        are 1 and 0 otherwise.
    """
    # note that in contrast to diamond(), this method allows non-integer radii
    n = 2 * radius + 1
    Z, Y, X = np.mgrid[-radius:radius:n * 1j,
                       -radius:radius:n * 1j,
                       -radius:radius:n * 1j]
    s = np.abs(X) + np.abs(Y) + np.abs(Z)
    return np.array(s <= radius, dtype=dtype)

def ball(radius, dtype=np.uint8):
    """Generates a ball-shaped structuring element.

    This is the 3D equivalent of a disk.
    A pixel is within the neighborhood if the euclidean distance between
    it and the origin is no greater than radius.

    Parameters
    ----------
    radius : int
        The radius of the ball-shaped structuring element.

    Other Parameters
    ----------------
    dtype : data-type
        The data type of the structuring element.

    Returns
    -------
    selem : ndarray
        The structuring element where elements of the neighborhood
        are 1 and 0 otherwise.
    """
    n = 2 * radius + 1
    Z, Y, X = np.mgrid[-radius:radius:n * 1j,
                       -radius:radius:n * 1j,
                       -radius:radius:n * 1j]
    s = X ** 2 + Y ** 2 + Z ** 2
    return np.array(s <= radius * radius, dtype=dtype)

def octagon(m, n, dtype=np.uint8):
    """Generates an octagon shaped structuring element.

    For a given size of (m) horizontal and vertical sides
    and a given (n) height or width of slanted sides octagon is generated.
    The slanted sides are 45 or 135 degrees to the horizontal axis
    and hence the widths and heights are equal.

    Parameters
    ----------
    m : int
        The size of the horizontal and vertical sides.
    n : int
        The height or width of the slanted sides.

    Other Parameters
    ----------------
    dtype : data-type
        The data type of the structuring element.

    Returns
    -------
    selem : ndarray
        The structuring element where elements of the neighborhood
        are 1 and 0 otherwise.

    """
    from . import convex_hull_image
    selem = np.zeros((m + 2 * n, m + 2 * n))
    selem[0, n] = 1
    selem[n, 0] = 1
    selem[0, m + n - 1] = 1
    selem[m + n - 1, 0] = 1
    selem[-1, n] = 1
    selem[n, -1] = 1
    selem[-1, m + n - 1] = 1
    selem[m + n - 1, -1] = 1
    selem = convex_hull_image(selem).astype(dtype)
    return selem

def star(a, dtype=np.uint8):
    """Generates a star shaped structuring element.

    Start has 8 vertices and is an overlap of square of size `2*a + 1`
    with its 45 degree rotated version.
    The slanted sides are 45 or 135 degrees to the horizontal axis.

    Parameters
    ----------
    a : int
        Parameter deciding the size of the star structural element. The side
        of the square array returned is `2*a + 1 + 2*floor(a / 2)`.

    Other Parameters
    ----------------
    dtype : data-type
        The data type of the structuring element.

    Returns
    -------
    selem : ndarray
        The structuring element where elements of the neighborhood
        are 1 and 0 otherwise.

    """
    from . import convex_hull_image

    if a == 1:
        bfilter = np.zeros((3, 3), dtype)
        bfilter[:] = 1
        return bfilter

    m = 2 * a + 1
    n = a // 2
    selem_square = np.zeros((m + 2 * n, m + 2 * n))
    selem_square[n: m + n, n: m + n] = 1

    c = (m + 2 * n - 1) // 2
    selem_rotated = np.zeros((m + 2 * n, m + 2 * n))
    selem_rotated[0, c] = selem_rotated[-1, c] = 1
    selem_rotated[c, 0] = selem_rotated[c, -1] = 1
    selem_rotated = convex_hull_image(selem_rotated).astype(int)

    selem = selem_square + selem_rotated
    selem[selem > 0] = 1

    return selem.astype(dtype)

def _default_selem(ndim):
    """Generates a cross-shaped structuring element (connectivity=1).

    This is the default structuring element (selem) if no selem was specified.

    Parameters
    ----------
    ndim : int
        Number of dimensions of the image.

    Returns
    -------
    selem : ndarray
        The structuring element where elements of the neighborhood
        are 1 and 0 otherwise.

    """
    return ndimage.morphology.generate_binary_structure(ndim, 1)


text:
package org.xander.creational.factory.factory.pizzastore;

import org.xander.creational.factory.factory.pizza.Pizza;

public abstract class PizzaStore {
    public Pizza orderPizza(String type) {
        Pizza pizza;

        pizza = createPizza(type);

        pizza.prepare();
        pizza.bake();
        pizza.cut();
        pizza.box();

        return pizza;
    }

    protected abstract Pizza createPizza(String type);
}


text:
package nl.ulso.magisto.action;

import java.util.Comparator;

/**
 * Comparator for {@link Action}s. It puts actions in order of type. If actions are of the same type, they are ordered
 * lexicographically on path, except for {@link DeleteTargetAction}s. These are ordered in reverse.
 */
class ActionComparator implements Comparator<Action> {

    private final Class[] actionClasses = new Class[]{
            SkipSourceAction.class,
            DeleteTargetAction.class,
            CopySourceAction.class,
            ConvertSourceAction.class,
            SkipStaticAction.class,
            CopyStaticAction.class
    };

    @Override
    public int compare(Action action1, Action action2) {
        for (Class actionClass : actionClasses) {
            if (actionClass.isInstance(action1) && !actionClass.isInstance(action2)) {
                return -1;
            }
            if (actionClass.isInstance(action2) && !actionClass.isInstance(action1)) {
                return 1;
            }
        }
        if (action1 instanceof DeleteTargetAction) {
            return action2.getPath().compareTo(action1.getPath());
        }
        return action1.getPath().compareTo(action2.getPath());
    }
}


text:
package me.cyning.gifle.app.ui;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.orangegangsters.github.swipyrefreshlayout.library.SwipyRefreshLayout;
import com.orangegangsters.github.swipyrefreshlayout.library.SwipyRefreshLayoutDirection;

import java.util.ArrayList;
import java.util.List;

import me.cyning.gifle.app.R;
import me.cyning.gifle.app.api.ApiInterface;
import me.cyning.gifle.app.base.BaseFragment;
import me.cyning.gifle.app.common.LayzLog;
import me.cyning.gifle.app.handler.FunApiHandler;
import me.cyning.gifle.app.http.BaseApiHandler;
import me.cyning.gifle.app.http.RestHttpClient;
import me.cyning.gifle.app.pojo.GifInfo;

/**
 * Author Cyning
 * Date   2015.09.04
 * Time   下午3:30
 * Desc
类/接口描述

 */

public class FunListFragment extends BaseFragment implements SwipyRefreshLayout.OnRefreshListener, FunListAdapter.OnRecyclerViewListener {

    public static final String TAG_CHANNELID = "TAG_CHANNELID";
    private  int currPage = 1;

    private  int channelId = 1;

    private RecyclerView   mRView;

    private SwipyRefreshLayout mSwipyRefreshLayout;

    private List<GifInfo>  mDataList;

    private FunListAdapter mListAdapter;

    BaseApiHandler mApiHandler;

    public static FunListFragment newInstance(int mChannelId) {
         Bundle args = new Bundle();
         args.putInt(TAG_CHANNELID,mChannelId);
         FunListFragment fragment = new FunListFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        channelId = getArguments().getInt(TAG_CHANNELID,1);
        requestPage(channelId, 1);

    }

    public FunListFragment() {
    }

    private void init() {
        mApiHandler = new FunApiHandler() {
            @Override
            public void OnGifSuccess(List<GifInfo> mGifInfos) {
                mDataList.addAll(mGifInfos);
                mListAdapter.notifyDataSetChanged();
                mSwipyRefreshLayout.setRefreshing(false);
                currPage++;
            }
        };
    }

    @Override
    protected int getRootViewId() {
        return R.layout.fun_list_fragment;
    }

    @Override
    protected void setupViews(View view) {
        mRView = v(view, R.id.rvList);

        mSwipyRefreshLayout = v(view,R.id.srLayout);
        mSwipyRefreshLayout.setOnRefreshListener(this);
        mRView.setHasFixedSize(true);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
        mRView.setLayoutManager(layoutManager);
        mDataList = new ArrayList<>();
        mListAdapter = new FunListAdapter(getActivity(), mDataList);
        mListAdapter.setOnRecyclerViewListener(this);
        mRView.setAdapter(mListAdapter);
        init();
    }

    public  void requestPage(int channel,int page){
        String URL = ApiInterface.URL_WITH_PAGE;
        String url2 = "";
        if (channel == 1){
            URL = ApiInterface.URL_First_PAGE;
            url2 = String.format(URL,page);
        }else{
            String tag = getTag(channel);
            url2 = String.format(URL,tag,channel,page);
        }

        mSwipyRefreshLayout.setRefreshing(true);
        RestHttpClient.getInstance().doGet(null, url2, mApiHandler);
    }

    private  String getTag(int type){
        switch (type){
            case 1:
                return "index";
            case 2:
                return "meinv";
            case 3:
                return "fun";
            case 4:
                return "diaobao";

            default:
                return "index";
        }
    }

    @Override
    public void onRefresh(SwipyRefreshLayoutDirection mSwipyRefreshLayoutDirection) {
        if (mSwipyRefreshLayoutDirection == SwipyRefreshLayoutDirection.TOP){
            mDataList.clear();
            mListAdapter.notifyDataSetChanged();
            requestPage(channelId,1);

        }else  if (mSwipyRefreshLayoutDirection == SwipyRefreshLayoutDirection.BOTTOM){
            requestPage(channelId,currPage);
        }

    }

    @Override
    public void onItemClick(int position, View mView) {
        GifInfo mGifInfo = mDataList.get(position);
        GifDetailActivity.launch(getActivity(),mGifInfo);
    }

    @Override
    public boolean onItemLongClick(int position, View mView) {
        return false;
    }
}


text:
from __future__ import unicode_literals

import logging

from six import iteritems, itervalues

from ... import DEFAULT_COREIMAGE, DEFAULT_BASEIMAGE, DEFAULT_HOSTNAME_REPLACEMENT, DEFAULT_PRESET_NETWORKS
from ..input import UsedVolume
from .cache import ContainerCache, ImageCache, NetworkCache, VolumeCache
from .dep import ContainerDependencyResolver, ContainerDependentsResolver

log = logging.getLogger(__name__)

class BasePolicy(object):
    """
    Abstract base class providing the basic infrastructure for generating actions based on container state.

    :param container_maps: Container maps.
    :type container_maps: dict[unicode | str, dockermap.map.config.main.ContainerMap]
    :param clients: Dictionary of clients.
    :type clients: dict[unicode | str, dockermap.map.config.client.ClientConfiguration]
    """
    core_image = DEFAULT_COREIMAGE
    base_image = DEFAULT_BASEIMAGE
    default_client_name = '__default__'
    hostname_replace = DEFAULT_HOSTNAME_REPLACEMENT
    default_network_names = ['bridge']

    def __init__(self, container_maps, clients, map_defaults=None, option_defaults=None):
        self._maps = maps = {
            map_name: map_contents.get_extended_map(map_defaults)
            for map_name, map_contents in iteritems(container_maps)
        }
        self._clients = clients
        self._option_defaults = default_opts = {}
        if option_defaults:
            default_opts.update(option_defaults)
            for p_opt in ['core_image', 'base_image', 'default_client_name',
                          'hostname_replace', 'default_network_names']:
                if p_opt in default_opts:
                    setattr(self, p_opt, default_opts.pop(p_opt))
        self._container_names = ContainerCache(clients)
        self._network_names = NetworkCache(clients)
        self._volume_names = VolumeCache(clients)
        self._images = ImageCache(clients)
        self._f_resolver = f_resolver = ContainerDependencyResolver()
        self._r_resolver = r_resolver = ContainerDependentsResolver()
        self._default_volume_paths = volume_paths = {}
        self._volume_users = volume_users = {}
        self._volume_permissions = volume_permissions = {}
        for m in itervalues(maps):
            depdendency_items = list(m.dependency_items())
            f_resolver.update(depdendency_items)
            r_resolver.update(depdendency_items)
            volume_paths[m.name] = map_paths = {}
            volume_users[m.name] = map_users = {}
            volume_permissions[m.name] = map_permissions = {}
            default_paths = m.volumes.get_default_paths()
            v_users = m.volumes.get_users()
            v_permissions = m.volumes.get_permissions()
            map_paths.update(default_paths)
            if m.use_attached_parent_name:
                map_paths.update(('{0}.{1}'.format(c_name, a.name),
                                  a.path if isinstance(a, UsedVolume) else default_paths[a.name])
                                 for c_name, c_config in m
                                 for a in c_config.attaches)
                map_users.update(('{0}.{1}'.format(c_name, a.name),
                                  v_users.get(a.name) or c_config.user)
                                 for c_name, c_config in m
                                 for a in c_config.attaches)
                map_permissions.update(('{0}.{1}'.format(c_name, a.name),
                                       v_permissions.get(a.name) or c_config.permissions)
                                       for c_name, c_config in m
                                       for a in c_config.attaches)
            else:
                map_paths.update((a.name,
                                  a.path if isinstance(a, UsedVolume) else default_paths[a.name])
                                 for c_name, c_config in m
                                 for a in c_config.attaches)
                map_users.update((a.name,
                                  v_users.get(a.name) or c_config.user)
                                 for c_name, c_config in m
                                 for a in c_config.attaches)
                map_permissions.update((a.name,
                                       v_permissions.get(a.name) or c_config.permissions)
                                       for c_name, c_config in m
                                       for a in c_config.attaches)

    @classmethod
    def cname(cls, map_name, container, instance=None):
        """
        Generates a container name that should be used for creating new containers and checking the status of existing
        containers.

        In this implementation, the format will be ``<map name>.<container name>.<instance>``. If no instance is
        provided, it is just ``<map name>.<container name>``.

        :param map_name: Container map name.
        :type map_name: unicode | str
        :param container: Container configuration name.
        :type container: unicode | str
        :param instance: Instance name (optional).
        :type instance: unicode | str
        :return: Container name.
        :rtype: unicode | str
        """
        if instance:
            return '{0}.{1}.{2}'.format(map_name, container, instance)
        return '{0}.{1}'.format(map_name, container)

    @classmethod
    def aname(cls, map_name, attached_name, parent_name=None):
        """
        Generates a container name that should be used for creating new attached volume containers and checking the
        status of existing containers.

        In this implementation, the format will be ``<map name>.<attached>``, or ``<map name>.<parent name>.<attached>``
        if the parent container configuration name is provided.

        :param map_name: Container map name.
        :type map_name: unicode | str
        :param attached_name: Attached container alias.
        :type attached_name: unicode | str
        :param parent_name: Container configuration name that has contains attached container.
        :type parent_name: unicode | str
        :return: Container name.
        :rtype: unicode | str
        """
        if parent_name:
            return '{0}.{1}.{2}'.format(map_name, parent_name, attached_name)
        return '{0}.{1}'.format(map_name, attached_name)

    @classmethod
    def nname(cls, map_name, network_name):
        """
        Generates a network name that should be used for creating new networks and checking the status of existing
        networks on the client.

        In this implementation, the format will be ``<map name>.<network name>``.

        :param map_name: Container map name.
        :type map_name: unicode | str
        :param network_name: Network configuration name.
        :type network_name: unicode | str
        :return: Network name.
        :rtype: unicode | str
        """
        if network_name in DEFAULT_PRESET_NETWORKS:
            return network_name
        return '{0}.{1}'.format(map_name, network_name)

    @classmethod
    def get_hostname(cls, container_name, client_name=None):
        """
        Determines the host name of a container. In this implementation, replaces all dots and underscores of a
        container name with a dash; then attaches another dash with the client name, unless there is just one default
        client.

        :param container_name: Name of the container.
        :type container_name: unicode | str
        :param client_name: Name of the client configuration, where applicable.
        :type client_name: unicode | str
        :return: Host name.
        :rtype: unicode | str
        """
        base_name = container_name
        for old, new in cls.hostname_replace:
            base_name = base_name.replace(old, new)
        if not client_name or client_name == cls.default_client_name:
            return base_name
        client_suffix = client_name
        for old, new in cls.hostname_replace:
            client_suffix = client_suffix.replace(old, new)
        return '{0}-{1}'.format(base_name, client_suffix)

    def get_dependencies(self, config_id):
        """
        Generates the list of dependency containers, in reverse order (i.e. the last dependency coming first).

        :param config_id: MapConfigId tuple.
        :type config_id: dockermap.map.input.MapConfigId
        :return: Dependency configuration types, container map names, configuration names, and instances.
        :rtype: collections.Iterable[(unicode | str, unicode | str, unicode | str, unicode | str)]
        """
        return self._f_resolver.get_dependencies(config_id)

    def get_dependents(self, config_id):
        """
        Generates the list of dependent containers, in reverse order (i.e. the last dependent coming first).

        :param config_id: MapConfigId tuple.
        :type config_id: dockermap.map.input.MapConfigId
        :return: Dependent configuration types, container map names, configuration names, and instances.
        :rtype: collections.Iterable[(unicode | str, unicode | str, unicode | str, unicode | str)]
        """
        return self._r_resolver.get_dependencies(config_id)

    @property
    def container_maps(self):
        """
        Container maps with container configurations to base actions on.

        :return: Dictionary of container maps.
        :rtype: dict[unicode | str, dockermap.map.config.main.ContainerMap]
        """
        return self._maps

    @property
    def clients(self):
        """
        Docker client objects and configurations.

        :return: Dictionary of Docker client objects.
        :rtype: dict[unicode | str, dockermap.map.config.client.ClientConfiguration]
        """
        return self._clients

    @property
    def option_defaults(self):
        """
        Default values for options of state, action, and runner implementations, for overriding the
        class-implemented defaults.

        :return: Dictionary with option name and default value to use.
        :rtype: dict
        """
        return self._option_defaults

    @property
    def container_names(self):
        """
        Names of existing containers on each client.

        :return: Dictionary of container names.
        :rtype: dict[unicode | str, dockermap.map.policy.cache.CachedContainerNames]
        """
        return self._container_names

    @property
    def images(self):
        """
        Names of images on each client.

        :return: Dictionary of image names per client.
        :rtype: dict[unicode | str, dockermap.map.policy.cache.CachedImages]
        """
        return self._images

    @property
    def network_names(self):
        """
        Names of existing networks on each client.

        :return: Dictionary of network names.
        :rtype: dict[unicode | str, dockermap.map.policy.cache.CachedNetworkNames]
        """
        return self._network_names

    @property
    def volume_names(self):
        """
        Names of existing volumes on each client.

        :return: Dictionary of volume names.
        :rtype: dict[unicode | str, dockermap.map.policy.cache.CachedVolumeNames]
        """
        return self._volume_names

    @property
    def default_volume_paths(self):
        """
        Defined volume names of each map, with a dictionary of default container paths per volume alias. Also includes
        paths of attached volumes that are defined directly on container configurations.

        :return: Default volume paths.
        :rtype: dict[unicode | str, dict]
        """
        return self._default_volume_paths

    @property
    def volume_users(self):
        """
        Defined volume names of each map, with a dictionary of the configured user per volume alias. Only applies
        to attached volumes.

        :return: Configured volume paths.
        :rtype: dict[unicode | str, dict]
        """
        return self._volume_users

    @property
    def volume_permissions(self):
        """
        Defined volume names of each map, with a dictionary of the configured permissions per volume alias. Only
        applies to attached volumes.

        :return: Configured volume permissions.
        :rtype: dict[unicode | str, dict]
        """
        return self._volume_permissions


text:
class Encounter
  module CuratesMoves
    extend ActiveSupport::Concern

    included do
      has_many :encounter_moves
      has_many :moves, through: :encounter_moves
    end

    def available_player_moves
      encounter_moves.for_player.map(&:move)
    end

    def available_partner_moves
      encounter_moves.for_partner.map(&:move)
    end

    def legal_player_moves
      options = {
        position: position,
        actor: player,
        actor_state: state[:player],
        target: partner,
        target_state: state[:partner]
      }

      available_player_moves.select do |move|
        move.is_legal? options
      end
    end

    def legal_partner_moves
      options = {
        position: position,
        actor: partner,
        actor_state: state[:partner],
        target: player,
        target_state: state[:player]
      }

      available_partner_moves.select do |move|
        move.is_legal? options
      end
    end

    def build_move_libraries!
      Move.all.each do |move|
        if move.include_in_library? player, partner
          encounter_moves.build(move:move, for:'player')
        end
        if move.include_in_library? partner, player
          encounter_moves.build(move:move, for:'partner')
        end
      end
    end

  end
end