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

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

    <title>20.10. imaplib — IMAP4 protocol client — Pythonista Documentation</title>
    <link rel="stylesheet" href="../_static/pythonista.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />

    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Pythonista Documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="top" title="Pythonista Documentation" href="../index.html" />
    <link rel="up" title="20. Internet Protocols and Support" href="internet.html" />
    <link rel="next" title="20.11. nntplib — NNTP protocol client" href="nntplib.html" />
    <link rel="prev" title="20.9. poplib — POP3 protocol client" href="poplib.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <meta name = "viewport" content = "width=device-width,initial-scale=1.0,user-scalable=no;">

Navigation

          index

          modules |

          next |

          previous |

Pythonista Documentation »

The Python Standard Library »

20. Internet Protocols and Support »

20.10. <tt class="xref py py-mod docutils literal">imaplib</tt> — IMAP4 protocol client¶

Source code: Lib/imaplib.py

This module defines three classes, <tt class="xref py py-class docutils literal">IMAP4</tt>, <tt class="xref py py-class docutils literal">IMAP4_SSL</tt> and
<tt class="xref py py-class docutils literal">IMAP4_stream</tt>, which encapsulate a connection to an IMAP4 server and
implement a large subset of the IMAP4rev1 client protocol as defined in
RFC 2060. It is backward compatible with IMAP4 (RFC 1730) servers, but
note that the <tt class="docutils literal">STATUS</tt> command is not supported in IMAP4.

Three classes are provided by the <tt class="xref py py-mod docutils literal">imaplib</tt> module, <tt class="xref py py-class docutils literal">IMAP4</tt> is the
base class:

class <tt class="descclassname">imaplib.</tt><tt class="descname">IMAP4</tt><big>(</big>[host[, port]]<big>)</big>¶

This class implements the actual IMAP4 protocol.  The connection is created and
protocol version (IMAP4 or IMAP4rev1) is determined when the instance is
initialized. If host is not specified, <tt class="docutils literal">''</tt> (the local host) is used. If
port is omitted, the standard IMAP4 port (143) is used.

Three exceptions are defined as attributes of the <tt class="xref py py-class docutils literal">IMAP4</tt> class:

exception <tt class="descclassname">IMAP4.</tt><tt class="descname">error</tt>¶

Exception raised on any errors.  The reason for the exception is passed to the
constructor as a string.

exception <tt class="descclassname">IMAP4.</tt><tt class="descname">abort</tt>¶

IMAP4 server errors cause this exception to be raised.  This is a sub-class of
<tt class="xref py py-exc docutils literal">IMAP4.error</tt>.  Note that closing the instance and instantiating a new one
will usually allow recovery from this exception.

exception <tt class="descclassname">IMAP4.</tt><tt class="descname">readonly</tt>¶

This exception is raised when a writable mailbox has its status changed by the
server.  This is a sub-class of <tt class="xref py py-exc docutils literal">IMAP4.error</tt>.  Some other client now has
write permission, and the mailbox will need to be re-opened to re-obtain write
permission.

There’s also a subclass for secure connections:

class <tt class="descclassname">imaplib.</tt><tt class="descname">IMAP4_SSL</tt><big>(</big>[host[, port[, keyfile[, certfile]]]]<big>)</big>¶

This is a subclass derived from <tt class="xref py py-class docutils literal">IMAP4</tt> that connects over an SSL
encrypted socket (to use this class you need a socket module that was compiled
with SSL support).  If host is not specified, <tt class="docutils literal">''</tt> (the local host) is used.
If port is omitted, the standard IMAP4-over-SSL port (993) is used.  keyfile
and certfile are also optional - they can contain a PEM formatted private key
and certificate chain file for the SSL connection.

The second subclass allows for connections created by a child process:

class <tt class="descclassname">imaplib.</tt><tt class="descname">IMAP4_stream</tt><big>(</big>command<big>)</big>¶

This is a subclass derived from <tt class="xref py py-class docutils literal">IMAP4</tt> that connects to the
<tt class="docutils literal">stdin/stdout</tt> file descriptors created by passing command to
<tt class="docutils literal">os.popen2()</tt>.

New in version 2.3.

The following utility functions are defined:

<tt class="descclassname">imaplib.</tt><tt class="descname">Internaldate2tuple</tt><big>(</big>datestr<big>)</big>¶

Parse an IMAP4 <tt class="docutils literal">INTERNALDATE</tt> string and return corresponding local
time.  The return value is a <tt class="xref py py-class docutils literal">time.struct_time</tt> instance or
None if the string has wrong format.

<tt class="descclassname">imaplib.</tt><tt class="descname">Int2AP</tt><big>(</big>num<big>)</big>¶

Converts an integer into a string representation using characters from the set
[<tt class="docutils literal">A</tt> .. <tt class="docutils literal">P</tt>].

<tt class="descclassname">imaplib.</tt><tt class="descname">ParseFlags</tt><big>(</big>flagstr<big>)</big>¶

Converts an IMAP4 <tt class="docutils literal">FLAGS</tt> response to a tuple of individual flags.

<tt class="descclassname">imaplib.</tt><tt class="descname">Time2Internaldate</tt><big>(</big>date_time<big>)</big>¶

Convert date_time to an IMAP4 <tt class="docutils literal">INTERNALDATE</tt> representation.  The
return value is a string in the form: <tt class="docutils literal">"DD-Mmm-YYYY HH:MM:SS
+HHMM"</tt> (including double-quotes).  The date_time argument can be a
number (int or float) representing seconds since epoch (as returned
by <tt class="xref py py-func docutils literal">time.time()</tt>), a 9-tuple representing local time (as returned by
<tt class="xref py py-func docutils literal">time.localtime()</tt>), or a double-quoted string.  In the last case, it
is assumed to already be in the correct format.

Note that IMAP4 message numbers change as the mailbox changes; in particular,
after an <tt class="docutils literal">EXPUNGE</tt> command performs deletions the remaining messages are
renumbered. So it is highly advisable to use UIDs instead, with the UID command.

At the end of the module, there is a test section that contains a more extensive
example of usage.

See also

Documents describing the protocol, and sources and binaries  for servers
implementing it, can all be found at the University of Washington’s IMAP
Information Center (http://www.washington.edu/imap/).

20.10.1. IMAP4 Objects¶

All IMAP4rev1 commands are represented by methods of the same name, either
upper-case or lower-case.

All arguments to commands are converted to strings, except for <tt class="docutils literal">AUTHENTICATE</tt>,
and the last argument to <tt class="docutils literal">APPEND</tt> which is passed as an IMAP4 literal.  If
necessary (the string contains IMAP4 protocol-sensitive characters and isn’t
enclosed with either parentheses or double quotes) each string is quoted.
However, the password argument to the <tt class="docutils literal">LOGIN</tt> command is always quoted. If
you want to avoid having an argument string quoted (eg: the flags argument to
<tt class="docutils literal">STORE</tt>) then enclose the string in parentheses (eg: <tt class="docutils literal">r'(\Deleted)'</tt>).

Each command returns a tuple: <tt class="docutils literal">(type, [data, ...])</tt> where type is usually
<tt class="docutils literal">'OK'</tt> or <tt class="docutils literal">'NO'</tt>, and data is either the text from the command response,
or mandated results from the command. Each data is either a string, or a
tuple. If a tuple, then the first part is the header of the response, and the
second part contains the data (ie: ‘literal’ value).

The message_set options to commands below is a string specifying one or more
messages to be acted upon.  It may be a simple message number (<tt class="docutils literal">'1'</tt>), a range
of message numbers (<tt class="docutils literal">'2:4'</tt>), or a group of non-contiguous ranges separated by
commas (<tt class="docutils literal">'1:3,6:9'</tt>).  A range can contain an asterisk to indicate an infinite
upper bound (<tt class="docutils literal">'3:*'</tt>).

An <tt class="xref py py-class docutils literal">IMAP4</tt> instance has the following methods:

<tt class="descclassname">IMAP4.</tt><tt class="descname">append</tt><big>(</big>mailbox, flags, date_time, message<big>)</big>¶

Append message to named mailbox.

<tt class="descclassname">IMAP4.</tt><tt class="descname">authenticate</tt><big>(</big>mechanism, authobject<big>)</big>¶

Authenticate command — requires response processing.

mechanism specifies which authentication mechanism is to be used - it should
appear in the instance variable <tt class="docutils literal">capabilities</tt> in the form <tt class="docutils literal">AUTH=mechanism</tt>.

authobject must be a callable object:

data = authobject(response)

It will be called to process server continuation responses. It should return
<tt class="docutils literal">data</tt> that will be encoded and sent to server. It should return <tt class="xref docutils literal">None</tt> if
the client abort response <tt class="docutils literal">*</tt> should be sent instead.

<tt class="descclassname">IMAP4.</tt><tt class="descname">check</tt><big>(</big><big>)</big>¶

Checkpoint mailbox on server.

<tt class="descclassname">IMAP4.</tt><tt class="descname">close</tt><big>(</big><big>)</big>¶

Close currently selected mailbox. Deleted messages are removed from writable
mailbox. This is the recommended command before <tt class="docutils literal">LOGOUT</tt>.

<tt class="descclassname">IMAP4.</tt><tt class="descname">copy</tt><big>(</big>message_set, new_mailbox<big>)</big>¶

Copy message_set messages onto end of new_mailbox.

<tt class="descclassname">IMAP4.</tt><tt class="descname">create</tt><big>(</big>mailbox<big>)</big>¶

Create new mailbox named mailbox.

<tt class="descclassname">IMAP4.</tt><tt class="descname">delete</tt><big>(</big>mailbox<big>)</big>¶

Delete old mailbox named mailbox.

<tt class="descclassname">IMAP4.</tt><tt class="descname">deleteacl</tt><big>(</big>mailbox, who<big>)</big>¶

Delete the ACLs (remove any rights) set for who on mailbox.

New in version 2.4.

<tt class="descclassname">IMAP4.</tt><tt class="descname">expunge</tt><big>(</big><big>)</big>¶

Permanently remove deleted items from selected mailbox. Generates an <tt class="docutils literal">EXPUNGE</tt>
response for each deleted message. Returned data contains a list of <tt class="docutils literal">EXPUNGE</tt>
message numbers in order received.

<tt class="descclassname">IMAP4.</tt><tt class="descname">fetch</tt><big>(</big>message_set, message_parts<big>)</big>¶

Fetch (parts of) messages.  message_parts should be a string of message part
names enclosed within parentheses, eg: <tt class="docutils literal">"(UID BODY[TEXT])"</tt>.  Returned data
are tuples of message part envelope and data.

<tt class="descclassname">IMAP4.</tt><tt class="descname">getacl</tt><big>(</big>mailbox<big>)</big>¶

Get the <tt class="docutils literal">ACL</tt>s for mailbox. The method is non-standard, but is supported
by the <tt class="docutils literal">Cyrus</tt> server.

<tt class="descclassname">IMAP4.</tt><tt class="descname">getannotation</tt><big>(</big>mailbox, entry, attribute<big>)</big>¶

Retrieve the specified <tt class="docutils literal">ANNOTATION</tt>s for mailbox. The method is
non-standard, but is supported by the <tt class="docutils literal">Cyrus</tt> server.

New in version 2.5.

<tt class="descclassname">IMAP4.</tt><tt class="descname">getquota</tt><big>(</big>root<big>)</big>¶

Get the <tt class="docutils literal">quota</tt> root‘s resource usage and limits. This method is part of the
IMAP4 QUOTA extension defined in rfc2087.

New in version 2.3.

<tt class="descclassname">IMAP4.</tt><tt class="descname">getquotaroot</tt><big>(</big>mailbox<big>)</big>¶

Get the list of <tt class="docutils literal">quota</tt> <tt class="docutils literal">roots</tt> for the named mailbox. This method is part
of the IMAP4 QUOTA extension defined in rfc2087.

New in version 2.3.

<tt class="descclassname">IMAP4.</tt><tt class="descname">list</tt><big>(</big>[directory[, pattern]]<big>)</big>¶

List mailbox names in directory matching pattern.  directory defaults to
the top-level mail folder, and pattern defaults to match anything.  Returned
data contains a list of <tt class="docutils literal">LIST</tt> responses.

<tt class="descclassname">IMAP4.</tt><tt class="descname">login</tt><big>(</big>user, password<big>)</big>¶

Identify the client using a plaintext password. The password will be quoted.

<tt class="descclassname">IMAP4.</tt><tt class="descname">login_cram_md5</tt><big>(</big>user, password<big>)</big>¶

Force use of <tt class="docutils literal">CRAM-MD5</tt> authentication when identifying the client to protect
the password.  Will only work if the server <tt class="docutils literal">CAPABILITY</tt> response includes the
phrase <tt class="docutils literal">AUTH=CRAM-MD5</tt>.

New in version 2.3.

<tt class="descclassname">IMAP4.</tt><tt class="descname">logout</tt><big>(</big><big>)</big>¶

Shutdown connection to server. Returns server <tt class="docutils literal">BYE</tt> response.

<tt class="descclassname">IMAP4.</tt><tt class="descname">lsub</tt><big>(</big>[directory[, pattern]]<big>)</big>¶

List subscribed mailbox names in directory matching pattern. directory
defaults to the top level directory and pattern defaults to match any mailbox.
Returned data are tuples of message part envelope and data.

<tt class="descclassname">IMAP4.</tt><tt class="descname">myrights</tt><big>(</big>mailbox<big>)</big>¶

Show my ACLs for a mailbox (i.e. the rights that I have on mailbox).

New in version 2.4.

<tt class="descclassname">IMAP4.</tt><tt class="descname">namespace</tt><big>(</big><big>)</big>¶

Returns IMAP namespaces as defined in RFC2342.

New in version 2.3.

<tt class="descclassname">IMAP4.</tt><tt class="descname">noop</tt><big>(</big><big>)</big>¶

Send <tt class="docutils literal">NOOP</tt> to server.

<tt class="descclassname">IMAP4.</tt><tt class="descname">open</tt><big>(</big>host, port<big>)</big>¶

Opens socket to port at host.  This method is implicitly called by
the <tt class="xref py py-class docutils literal">IMAP4</tt> constructor.  The connection objects established by this
method will be used in the <tt class="docutils literal">read</tt>, <tt class="docutils literal">readline</tt>, <tt class="docutils literal">send</tt>, and <tt class="docutils literal">shutdown</tt>
methods.  You may override this method.

<tt class="descclassname">IMAP4.</tt><tt class="descname">partial</tt><big>(</big>message_num, message_part, start, length<big>)</big>¶

Fetch truncated part of a message. Returned data is a tuple of message part
envelope and data.

<tt class="descclassname">IMAP4.</tt><tt class="descname">proxyauth</tt><big>(</big>user<big>)</big>¶

Assume authentication as user. Allows an authorised administrator to proxy
into any user’s mailbox.

New in version 2.3.

<tt class="descclassname">IMAP4.</tt><tt class="descname">read</tt><big>(</big>size<big>)</big>¶

Reads size bytes from the remote server. You may override this method.

<tt class="descclassname">IMAP4.</tt><tt class="descname">readline</tt><big>(</big><big>)</big>¶

Reads one line from the remote server. You may override this method.

<tt class="descclassname">IMAP4.</tt><tt class="descname">recent</tt><big>(</big><big>)</big>¶

Prompt server for an update. Returned data is <tt class="xref docutils literal">None</tt> if no new messages, else
value of <tt class="docutils literal">RECENT</tt> response.

<tt class="descclassname">IMAP4.</tt><tt class="descname">rename</tt><big>(</big>oldmailbox, newmailbox<big>)</big>¶

Rename mailbox named oldmailbox to newmailbox.

<tt class="descclassname">IMAP4.</tt><tt class="descname">response</tt><big>(</big>code<big>)</big>¶

Return data for response code if received, or <tt class="xref docutils literal">None</tt>. Returns the given
code, instead of the usual type.

<tt class="descclassname">IMAP4.</tt><tt class="descname">search</tt><big>(</big>charset, criterion[, ...]<big>)</big>¶

Search mailbox for matching messages.  charset may be <tt class="xref docutils literal">None</tt>, in which case
no <tt class="docutils literal">CHARSET</tt> will be specified in the request to the server.  The IMAP
protocol requires that at least one criterion be specified; an exception will be
raised when the server returns an error.

Example:

# M is a connected IMAP4 instance...
typ, msgnums = M.search(None, 'FROM', '"LDJ"')

# or:
typ, msgnums = M.search(None, '(FROM "LDJ")')

<tt class="descclassname">IMAP4.</tt><tt class="descname">select</tt><big>(</big>[mailbox[, readonly]]<big>)</big>¶

Select a mailbox. Returned data is the count of messages in mailbox
(<tt class="docutils literal">EXISTS</tt> response).  The default mailbox is <tt class="docutils literal">'INBOX'</tt>.  If the readonly
flag is set, modifications to the mailbox are not allowed.

<tt class="descclassname">IMAP4.</tt><tt class="descname">send</tt><big>(</big>data<big>)</big>¶

Sends <tt class="docutils literal">data</tt> to the remote server. You may override this method.

<tt class="descclassname">IMAP4.</tt><tt class="descname">setacl</tt><big>(</big>mailbox, who, what<big>)</big>¶

Set an <tt class="docutils literal">ACL</tt> for mailbox. The method is non-standard, but is supported by
the <tt class="docutils literal">Cyrus</tt> server.

<tt class="descclassname">IMAP4.</tt><tt class="descname">setannotation</tt><big>(</big>mailbox, entry, attribute[, ...]<big>)</big>¶

Set <tt class="docutils literal">ANNOTATION</tt>s for mailbox. The method is non-standard, but is
supported by the <tt class="docutils literal">Cyrus</tt> server.

New in version 2.5.

<tt class="descclassname">IMAP4.</tt><tt class="descname">setquota</tt><big>(</big>root, limits<big>)</big>¶

Set the <tt class="docutils literal">quota</tt> root‘s resource limits. This method is part of the IMAP4
QUOTA extension defined in rfc2087.

New in version 2.3.

<tt class="descclassname">IMAP4.</tt><tt class="descname">shutdown</tt><big>(</big><big>)</big>¶

Close connection established in <tt class="docutils literal">open</tt>.  This method is implicitly
called by <tt class="xref py py-meth docutils literal">IMAP4.logout()</tt>.  You may override this method.

<tt class="descclassname">IMAP4.</tt><tt class="descname">socket</tt><big>(</big><big>)</big>¶

Returns socket instance used to connect to server.

<tt class="descclassname">IMAP4.</tt><tt class="descname">sort</tt><big>(</big>sort_criteria, charset, search_criterion[, ...]<big>)</big>¶

The <tt class="docutils literal">sort</tt> command is a variant of <tt class="docutils literal">search</tt> with sorting semantics for the
results.  Returned data contains a space separated list of matching message
numbers.

Sort has two arguments before the search_criterion argument(s); a
parenthesized list of sort_criteria, and the searching charset.  Note that
unlike <tt class="docutils literal">search</tt>, the searching charset argument is mandatory.  There is also
a <tt class="docutils literal">uid sort</tt> command which corresponds to <tt class="docutils literal">sort</tt> the way that <tt class="docutils literal">uid search</tt>
corresponds to <tt class="docutils literal">search</tt>.  The <tt class="docutils literal">sort</tt> command first searches the mailbox for
messages that match the given searching criteria using the charset argument for
the interpretation of strings in the searching criteria.  It then returns the
numbers of matching messages.

This is an <tt class="docutils literal">IMAP4rev1</tt> extension command.

<tt class="descclassname">IMAP4.</tt><tt class="descname">status</tt><big>(</big>mailbox, names<big>)</big>¶

Request named status conditions for mailbox.

<tt class="descclassname">IMAP4.</tt><tt class="descname">store</tt><big>(</big>message_set, command, flag_list<big>)</big>¶

Alters flag dispositions for messages in mailbox.  command is specified by
section 6.4.6 of RFC 2060 as being one of “FLAGS”, “+FLAGS”, or “-FLAGS”,
optionally with a suffix of ”.SILENT”.

For example, to set the delete flag on all messages:

typ, data = M.search(None, 'ALL')
for num in data[0].split():
   M.store(num, '+FLAGS', '\\Deleted')
M.expunge()

<tt class="descclassname">IMAP4.</tt><tt class="descname">subscribe</tt><big>(</big>mailbox<big>)</big>¶

Subscribe to new mailbox.

<tt class="descclassname">IMAP4.</tt><tt class="descname">thread</tt><big>(</big>threading_algorithm, charset, search_criterion[, ...]<big>)</big>¶

The <tt class="docutils literal">thread</tt> command is a variant of <tt class="docutils literal">search</tt> with threading semantics for
the results.  Returned data contains a space separated list of thread members.

Thread members consist of zero or more messages numbers, delimited by spaces,
indicating successive parent and child.

Thread has two arguments before the search_criterion argument(s); a
threading_algorithm, and the searching charset.  Note that unlike
<tt class="docutils literal">search</tt>, the searching charset argument is mandatory.  There is also a
<tt class="docutils literal">uid thread</tt> command which corresponds to <tt class="docutils literal">thread</tt> the way that <tt class="docutils literal">uid
search</tt> corresponds to <tt class="docutils literal">search</tt>.  The <tt class="docutils literal">thread</tt> command first searches the
mailbox for messages that match the given searching criteria using the charset
argument for the interpretation of strings in the searching criteria. It then
returns the matching messages threaded according to the specified threading
algorithm.

This is an <tt class="docutils literal">IMAP4rev1</tt> extension command.

New in version 2.4.

<tt class="descclassname">IMAP4.</tt><tt class="descname">uid</tt><big>(</big>command, arg[, ...]<big>)</big>¶

Execute command args with messages identified by UID, rather than message
number.  Returns response appropriate to command.  At least one argument must be
supplied; if none are provided, the server will return an error and an exception
will be raised.

<tt class="descclassname">IMAP4.</tt><tt class="descname">unsubscribe</tt><big>(</big>mailbox<big>)</big>¶

Unsubscribe from old mailbox.

<tt class="descclassname">IMAP4.</tt><tt class="descname">xatom</tt><big>(</big>name[, arg[, ...]]<big>)</big>¶

Allow simple extension commands notified by server in <tt class="docutils literal">CAPABILITY</tt> response.

Instances of <tt class="xref py py-class docutils literal">IMAP4_SSL</tt> have just one additional method:

<tt class="descclassname">IMAP4_SSL.</tt><tt class="descname">ssl</tt><big>(</big><big>)</big>¶

Returns SSLObject instance used for the secure connection with the server.

The following attributes are defined on instances of <tt class="xref py py-class docutils literal">IMAP4</tt>:

<tt class="descclassname">IMAP4.</tt><tt class="descname">PROTOCOL_VERSION</tt>¶

The most recent supported protocol in the <tt class="docutils literal">CAPABILITY</tt> response from the
server.

<tt class="descclassname">IMAP4.</tt><tt class="descname">debug</tt>¶

Integer value to control debugging output.  The initialize value is taken from
the module variable <tt class="docutils literal">Debug</tt>.  Values greater than three trace each command.

20.10.2. IMAP4 Example¶

Here is a minimal example (without error checking) that opens a mailbox and
retrieves and prints all messages:

import getpass, imaplib

M = imaplib.IMAP4()
M.login(getpass.getuser(), getpass.getpass())
M.select()
typ, data = M.search(None, 'ALL')
for num in data[0].split():
    typ, data = M.fetch(num, '(RFC822)')
    print 'Message %s\n%s\n' % (num, data[0][1])
M.close()
M.logout()

    © Copyright 1990-2016, Python Software Foundation.

    The Python Software Foundation is a non-profit corporation.
    Please donate.

    Last updated on May 03, 2016.
    Found a bug?

    Created using Sphinx 1.0.7.


text:
import React from 'react';

var ListToggle = React.createClass({
  options: ['Food Processor', 'Fondue Set', 'Cuddly Toy', 'Dinner Service'],
  getInitialState() {
    var n = parseInt(this.props.default);
    return { current: n >= 0 ? n : 2 };
  },
  render() {
    var current = this.state.current;
    return (
      <ul className="list-group">
        {this.options.map((o, i) =>
          <li
            key={i}
            className={`list-group-item ${current == i ? 'active' : ''}`}
            onClick={() => this.setState({ current: i })}
          >
            {o}
          </li>
        )}
      </ul>
    );
  }
});

export default ListToggle;

redpajama_set_name: RedPajamaGithub


text:
namespace AE
{

DeviceMemoryManager::DeviceMemoryManager( Engine * engine, Renderer * renderer )
{
	p_engine		= engine;
	p_renderer		= renderer;
	assert( nullptr != p_engine );
	assert( nullptr != p_renderer );
	p_logger		= p_engine->GetLogger();
	assert( nullptr != p_logger );

	ref_vk_instance							= p_renderer->GetVulkanInstance();
	ref_vk_device							= p_renderer->GetVulkanDevice();
	ref_vk_physical_device					= p_renderer->GetVulkanPhysicalDevice();
	vkGetPhysicalDeviceMemoryProperties( ref_vk_physical_device, &vk_physical_device_memory_properties );
}

DeviceMemoryManager::~DeviceMemoryManager()
{
}

VkBuffer DeviceMemoryManager::CreateBuffer( VkBufferCreateFlags flags, VkDeviceSize buffer_size, VkBufferUsageFlags usage_flags, UsedQueuesFlags shared_between_queues )
{
	auto sharing_mode_info		= p_renderer->GetSharingModeInfo( shared_between_queues );

	VkBufferCreateInfo CI {};
	CI.sType					= VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
	CI.pNext					= nullptr;
	CI.flags					= flags;
	CI.size						= buffer_size;
	CI.usage					= usage_flags;
	CI.sharingMode				= sharing_mode_info.sharing_mode;
	CI.queueFamilyIndexCount	= uint32_t( sharing_mode_info.shared_queue_family_indices.size() );
	CI.pQueueFamilyIndices		= sharing_mode_info.shared_queue_family_indices.data();

	LOCK_GUARD( *ref_vk_device.mutex );
	VkBuffer ret = VK_NULL_HANDLE;
	VulkanResultCheck( vkCreateBuffer( ref_vk_device.object, &CI, VULKAN_ALLOC, &ret ) );
	return ret;
}

DeviceMemoryInfo DeviceMemoryManager::AllocateImageMemory( VkImage image, VkMemoryPropertyFlags memory_properties )
{
	VkMemoryRequirements memory_requirements {};
	{
		LOCK_GUARD( *ref_vk_device.mutex );
		vkGetImageMemoryRequirements( ref_vk_device.object, image, &memory_requirements );
	}
	return AllocateMemory( memory_requirements, memory_properties );
}

DeviceMemoryInfo DeviceMemoryManager::AllocateAndBindImageMemory( VkImage image, VkMemoryPropertyFlags memory_properties )
{
	auto memory_info = AllocateImageMemory( image, memory_properties );
	{
		LOCK_GUARD( *ref_vk_device.mutex );
		VulkanResultCheck( vkBindImageMemory( ref_vk_device.object, image, memory_info.memory, memory_info.offset ) );
	}
	return memory_info;
}

DeviceMemoryInfo DeviceMemoryManager::AllocateBufferMemory( VkBuffer buffer, VkMemoryPropertyFlags memory_properties )
{
	VkMemoryRequirements memory_requirements {};
	{
		LOCK_GUARD( *ref_vk_device.mutex );
		vkGetBufferMemoryRequirements( ref_vk_device.object, buffer, &memory_requirements );
	}
	return AllocateMemory( memory_requirements, memory_properties );
}

DeviceMemoryInfo DeviceMemoryManager::AllocateAndBindBufferMemory( VkBuffer buffer, VkMemoryPropertyFlags memory_properties )
{
	auto memory_info = AllocateBufferMemory( buffer, memory_properties );
	{
		LOCK_GUARD( *ref_vk_device.mutex );
		VulkanResultCheck( vkBindBufferMemory( ref_vk_device.object, buffer, memory_info.memory, memory_info.offset ) );
	}
	return memory_info;
}

void DeviceMemoryManager::FreeMemory( DeviceMemoryInfo & memory )
{
	TODO( "Memory pooling, we only have limited number of memory allocation times left" );
	{
		LOCK_GUARD( *ref_vk_device.mutex );
		vkFreeMemory( ref_vk_device.object, memory.memory, VULKAN_ALLOC );
	}
	memory		= {};
}

DeviceMemoryInfo DeviceMemoryManager::AllocateMemory( VkMemoryRequirements & requirements, VkMemoryPropertyFlags memory_properties )
{
	TODO( "Memory pooling, we only have limited number of memory allocation times left" );

	DeviceMemoryInfo ret {};

	uint32_t memory_index		= FindMemoryTypeIndex( requirements, memory_properties );

	VkMemoryAllocateInfo memory_AI {};
	memory_AI.sType				= VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
	memory_AI.pNext				= nullptr;
	memory_AI.allocationSize	= requirements.size;
	memory_AI.memoryTypeIndex	= memory_index;
	{
		LOCK_GUARD( *ref_vk_device.mutex );
		vkAllocateMemory( ref_vk_device.object, &memory_AI, VULKAN_ALLOC, &ret.memory );
		ret.offset				= 0;
		ret.size				= requirements.size;
		ret.alignment			= requirements.alignment;
	}
	if( !ret.memory ) {
		p_logger->LogError( "Couldn't allocate device memory" );
	}

	return ret;
}

uint32_t DeviceMemoryManager::FindMemoryTypeIndex( VkMemoryRequirements & requirements, VkMemoryPropertyFlags property_flags )
{
	for( uint32_t i=0; i < vk_physical_device_memory_properties.memoryTypeCount; ++i ) {
		if( requirements.memoryTypeBits & ( 1 << i ) ) {
			if( ( vk_physical_device_memory_properties.memoryTypes[ i ].propertyFlags & property_flags ) == property_flags ) {
				return i;
			}
		}
	}
	p_logger->LogError( "Couldn't find memory type index for resource" );
	return UINT32_MAX;
}

}


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Organization_model extends CI_Model {

	public function get_organization()
	{
		$query = "SELECT * FROM organization";
		$query = $this->db->query($query);
		$result = $query->result_array();

		return $result;
	}
}


text:
<?php

App::uses('CakePlugin', 'Core');
App::uses('ClassRegistry', 'Utility');
App::uses('ConnectionManager', 'Model');
App::uses('Folder', 'Utility');
App::uses('Inflector', 'Utility');
App::uses('MigrationException', 'Migrations.Model/Exception');

/**
 * Class Migrations
 */
class Migrations {

/**
 * The db connection to use.
 *
 * @var string
 */
	public $connection = 'default';

/**
 * Default migration settings.
 *
 * @var array
 */
	protected $_defaults = array(
		'scope' => 'app',
		'direction' => 'up',
		'steps' => false,
		'version' => false,
		'forceAll' => false
	);

/**
 * Holds all available migrations for the different scopes.
 *
 * @var array
 */
	protected $_migrations = array();

/**
 * Holds an instance of SchemaMigration.
 *
 * @var SchemaMigration
 */
	protected $SchemaMigration;

/**
 * Constructor
 *
 * @param string $connection the db connection to be used
 * @param boolean $autoInit If true, the schema_migrations table will be initialized automatically.
 * @return Migrations
 */
	public function __construct($connection = 'default', $autoInit = true) {
		$this->connection = $connection;

		$this->SchemaMigration = ClassRegistry::init('Migrations.SchemaMigration');
		$this->SchemaMigration->setDataSource($this->connection);

		if ($autoInit !== false) {
			$this->_initSchemaMigrations();
		}
	}

/**
 * Migrate a scope in either up or down direction.
 * steps -> the number of migration steps to perform (optional)
 * version -> up until what version you want to migrate (ignored if steps are provided)
 * forceAll -> force to run all migrations (optional) (skips version check)
 *
 * @param array $options
 * @throws InvalidArgumentException
 * @throws Exception
 * @return void
 */
	public function migrate($options = array()) {
		if (!isset($options['direction'])) {
			throw new InvalidArgumentException(__d('migration', 'Missing "direction" option. Provide it with either "up" or "down".'));
		}
		if (isset($options['direction']) && !in_array($options['direction'], array('up', 'down'))) {
			throw new InvalidArgumentException(__d('migration', 'Invalid migration direction "%s". Use either "up" or "down".', $options['direction']));
		}
		if (isset($options['scope']) && $options['scope'] !== 'app') {
			$this->_checkScope($options['scope']);
		}

		/**
		 * @var string  $direction
		 * @var string  $scope
		 * @var integer $steps
		 * @var string  $version
		 * @var boolean $forceAll
		 */
		extract(array_merge($this->_defaults, $options));

		$availableMigrations = $this->_getAvailableMigrations($scope, $direction);
		$offset = 0;

		if ($forceAll === true) {
			$steps = false;
		} else {
			$currentVersion = $this->SchemaMigration->getCurrentVersion($scope);
			if ($currentVersion !== false) {
				$offset = array_search($currentVersion, array_keys($availableMigrations), true) + 1;
			}
		}

		if ($direction === 'down') {
			$offset--;
		}

		if ($version !== false && $version !== 'latest') {
			if (!array_key_exists($version, $availableMigrations)) {
				throw new InvalidArgumentException(__d('migration', 'Invalid migration version "%s".', $version));
			}
			$steps = array_search($version, array_keys($availableMigrations));
			if ($direction === 'up') {
				$steps++;
			}
		}

		if ($steps >= 1) {
			$migrationsToRun = array_slice($availableMigrations, $offset, $steps, true);
		} else {
			$migrationsToRun = array_slice($availableMigrations, $offset, null, true);
		}

		/** @var DboSource $db */
		$db = ConnectionManager::getDataSource($this->connection);

		$db->begin();
		try {
			foreach ($migrationsToRun as $v => $m) {
				echo 'Migrating to: ' . $v . "\n\n";
				$migration = $this->_getMigrationInstance($m);
				$migration->{$direction}();
				$this->SchemaMigration->{$direction}($scope, $v, $m['className']);
			}
		} catch (Exception $e) {
			$db->rollback();

			throw $e;
		}
		$db->commit();

	}

/**
 * Initialize schema_migrations table and run all new migrations of the Migrations plugin.
 *
 * @return void
 */
	protected function _initSchemaMigrations() {
		$options = array(
			'direction' => 'up',
			'scope' => 'Migrations'
		);
		/** @var DboSource $db */
		$db = ConnectionManager::getDataSource($this->connection);

		$this->clearCache();

		if (!in_array($db->fullTableName('schema_migrations', false, false), $db->listSources())) {
			$options['forceAll'] = true;
		}

		$this->migrate($options);
	}

/**
 * Check if a scope is available by looking at all registered plugin folders.
 *
 * A plugin has not to be loaded before running its migrations.
 *
 * @param string $scope The scope (plugin name) that should be checked for availability.
 * @throws InvalidArgumentException if the scope is not available
 * @return void
 */
	protected function _checkScope($scope) {
		if (!CakePlugin::loaded(Inflector::camelize($scope))) {
			$pluginPaths = App::path('Plugin');
			$availablePlugins = array();
			foreach ($pluginPaths as $pluginPath) {
				$folder = new Folder($pluginPath, false);
				$pluginDirs = $folder->read();
				$pluginDirs = $pluginDirs[0];
				$availablePlugins = array_merge($availablePlugins, $pluginDirs);
			}
			if (!in_array(Inflector::camelize($scope), $availablePlugins)) {
				throw new InvalidArgumentException(__d('migration', 'The scope "%s" is not available. Use one of the available scopes instead: %s', array(
					$scope,
					implode(', ', $availablePlugins)
				)));
			}
		}
	}

/**
 * Get all available migrations for a scope from file system.
 * If direction equals "down" then additionally check against migrated versions in schema_migration
 * to only migrate existing ones down.
 * This makes it possible to insert new migrations in between already existing and migrated ones.
 *
 * @param string $scope The scope (app or plugin name) that you want to get migrations from.
 * @param string $direction The migration direction for which to order the available migrations array.
 * @return array all available migrations for this scope
 */
	protected function _getAvailableMigrations($scope, $direction = 'up') {
		if (!isset($this->_migrations[$scope]) || empty($this->_migrations[$scope])) {
			$folder = $this->_getMigrationsFolder($scope);
			if (!$folder) {
				return array();
			}

			$this->_migrations[$scope] = array();
			foreach ($folder->find("^\d+_.*\.php$", true) as $mf) {
				if (preg_match("/^(\d+)_(.*)\.php$/", $mf, $matches) === 1) {
					list($fileName, $version, $name) = $matches;
					$this->_migrations[$scope][$version] = array(
						'path' => $folder->path,
						'fileName' => $fileName,
						'className' => Inflector::camelize($name)
					);
				}
			}
		}

		$migrations = $this->_migrations[$scope];

		if ($direction === 'down') {
			$migrations = array_reverse($migrations);
			$existingMigrations = $this->SchemaMigration->getMigrationsForDown($scope);
			foreach (array_keys($migrations) as $key) {
				if (!array_key_exists($key, $existingMigrations)) {
					unset($migrations[$key]);
				}
			}
		}

		return $migrations;
	}

/**
 * Get a migration folder instance for $scope.
 * If the plugin is not loaded, all available plugin paths will be checked.
 *
 * @param string $scope either `app` or a plugin name
 * @return bool|Folder false if no migration folder has been found or the actual folder instance
 */
	protected function _getMigrationsFolder($scope) {
		$path = APP . 'Config' . DS . 'Migration';

		if ($scope !== 'app') {
			$plugin = Inflector::camelize($scope);

			if (CakePlugin::loaded($plugin)) {
				$path = CakePlugin::path($plugin) . 'Config' . DS . 'Migration' . DS;
			} else {
				foreach (App::path('Plugin') as $pluginPath) {
					$folder = new Folder($pluginPath, false);
					$pluginDirs = $folder->read();
					$pluginDirs = $pluginDirs[0];
					if (in_array($plugin, $pluginDirs)) {
						$path = $folder->path . $plugin . DS . 'Config' . DS . 'Migration' . DS;
						break;
					}
				}
			}
		}

		if (!is_dir($path)) {
			return false;
		}

		return new Folder($path, false);
	}

/**
 * Get an instance of a migration class.
 *
 * @param array $availableMigration
 * @throws MigrationException
 * @return Migration
 */
	protected function _getMigrationInstance($availableMigration) {
		/**
		 * @var string $path
		 * @var string $fileName
		 * @var string $className
		 */
		extract($availableMigration);
		if (!class_exists($className)) {
			$file = $path . DS . $fileName;
			if (!file_exists($file)) {
				throw new MigrationException(__d('migration', 'File %s not found in path %s.', array(
					$fileName,
					$path
				)));
			}
			include $file;
		}
		if (!class_exists($className)) {
			throw new MigrationException(__d('migration', 'Class %s not found in file %s at path %s.', array(
				$className,
				$fileName,
				$path
			)));
		}

		return new $className(array(
			'connection' => $this->connection
		));
	}

/**
 * Clear all possible caches.
 */
	public function clearCache() {
		Cache::clear();
		clearCache();

		$files = array();
		$files = array_merge($files, glob(CACHE . '*'));
		$files = array_merge($files, glob(CACHE . 'css' . DS . '*')); // remove cached css
		$files = array_merge($files, glob(CACHE . 'js' . DS . '*')); // remove cached js
		$files = array_merge($files, glob(CACHE . 'models' . DS . '*')); // remove cached models
		$files = array_merge($files, glob(CACHE . 'persistent' . DS . '*')); // remove cached persistent

		foreach ($files as $f) {
			if (is_file($f)) {
				@@unlink($f);
			}
		}

		if (function_exists('apc_clear_cache')) {
			apc_clear_cache();
			apc_clear_cache('user');
		}
	}

}


text:
package org.hisp.dhis.webapi.service;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author Morten Olav Hansen <mortenoh@gmail.com>
 */
public interface ContextService
{
    /**
     * Get full path of servlet.
     *
     * @return Full HREF to servlet
     * @see javax.servlet.http.HttpServletRequest
     */
    String getServletPath();

    /**
     * Get HREF to context.
     *
     * @return Full HREF to context (context root)
     * @see javax.servlet.http.HttpServletRequest
     */
    String getContextPath();

    /**
     * Get HREF to Web-API.
     *
     * @return Full HREF to Web-API
     * @see javax.servlet.http.HttpServletRequest
     */
    String getApiPath();

    /**
     * Get active HttpServletRequest
     *
     * @return HttpServletRequest
     */
    HttpServletRequest getRequest();

    /**
     * Returns a list of values from a parameter, if the parameter doesn't exist, it will
     * return a empty list.
     *
     * @param name Parameter to get
     * @return List of parameter values, or empty if not found
     */
    Set<String> getParameterValues( String name );

    /**
     * Get all parameters as a map of key => values, supports more than one pr key (so values is a collection)
     */
    Map<String, List<String>> getParameterValuesMap();
}


text:
class RegKey
{
public:
    RegKey(HKEY scope, const wchar_t* keyName, bool createIfNotExist = false);

    bool IsExist() const
    {
        return isExist;
    }
    bool IsCreated() const
    {
        return isCreated;
    }

    //TODO: replace on Optional<String>
    DAVA::WideString QueryString(const wchar_t* valueName) const;
    bool SetValue(const DAVA::WideString& valName, const DAVA::WideString& val);

    //TODO: replace on Optional<DWORD>
    DWORD QueryDWORD(const wchar_t* valueName) const;
    bool SetValue(const DAVA::WideString& valName, DWORD val);

    template <typename T>
    //TODO: replace on Optional<T>
    T QueryValue(const wchar_t* valueName);

private:
    bool isExist = false;
    bool isCreated = false;
    HKEY key;
};

template <>
inline DAVA::WideString RegKey::QueryValue<DAVA::WideString>(const wchar_t* valueName)
{
    return QueryString(valueName);
}

template <>
inline DWORD RegKey::QueryValue<DWORD>(const wchar_t* valueName)
{
    return QueryDWORD(valueName);
}

#endif // REGKEY_H


text:
A gem for your rails project that suggests indices for you to add in your database. It looks for unindexed foreign keys, and what columns actually get queried.

http://www.youtube.com/watch?v=FTt5mVdGVXQ

## Installation

Add this line to your application's Gemfile:

    gem 'suggest-db-indices'

And then execute:

    $ bundle

## Usage

    bundle exec rake suggest_db_indices

Also see: http://www.youtube.com/watch?v=FTt5mVdGVXQ

## Changes
0.1.0 (July 8, 2012) - Added the rake task.

0.0.3 (July 4, 2012) - Added justification for each index added, made log file handling more robust


text:
const path = require('path');

const {
  DefinePlugin,
  ProgressPlugin,
  NoEmitOnErrorsPlugin,
  HotModuleReplacementPlugin
} = require('webpack');

import HtmlWebpackPlugin from 'html-webpack-plugin';
import NamedModulesPlugin from 'webpack/lib/NamedModulesPlugin';
import UglifyJsPlugin from 'uglifyjs-webpack-plugin';

const nodeEnv = process.env.NODE_ENV || 'development';
const isProd = nodeEnv === 'production';

const paths = {
  src: path.join(__dirname, '/src/'),
  output: path.join(__dirname, '/dist/'),
  public: '/'
}

console.log("production build: ", isProd);

module.exports = {
  devtool: isProd ? 'nosources-source-map' : 'cheap-module-eval-source-map',
  mode: nodeEnv,
  output: {
    path: paths.output,
    publicPath: paths.public,
    ...(isProd ? {
      filename: '[name]-[hash].min.js',
    } : {
      pathinfo: true,
      filename: '[name].js',
      }
    )
  },
  plugins: [
    new ProgressPlugin(),
    new HtmlWebpackPlugin({
      template: 'src/index.html',
      inject: 'body',
      filename: 'index.html',
      minify: {
        collapseWhitespace: isProd
      }
    }),
    new DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify(nodeEnv)
    }),
    new NamedModulesPlugin(),
    new HotModuleReplacementPlugin(),
    ...(isProd ? [
          new NoEmitOnErrorsPlugin(),
          new UglifyJsPlugin({
            sourceMap: false,
            beautify: false,
            comments: false,
            compress: {
              drop_console: true,
              dead_code: true,
              warnings: false
            }
          })
        ] : []
      )
  ],
  entry: [
    path.join(__dirname, 'src/main.js')
  ],
  resolve: {
    extensions: [ '.js', '.purs']
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /(node_modules|bower_components)/,
        loader: 'babel-loader'
      },
      {
        test: /\.purs$/,
        loader: 'purs-loader',
        exclude: /node_modules/,

        query: {
          psc: 'psa',
          src: [
            path.join('src', '**', '*.purs'),
            path.join('bower_components', 'purescript-*', 'src', '**', '*.purs')
          ],
          bundle: isProd,
          watch: !isProd
        }
      }
    ]
  },
  devServer: {
    hot: !isProd,
    contentBase: paths.src,
    port: 3000,
    host: 'localhost',
    historyApiFallback: true,
    watchOptions: {
      aggregateTimeout: 300,
      poll: 1000
    },
    stats: 'minimal',
  }
};


text:
define([ 'require','config','core/AbstractPlugin.vlib','core/Utils.vlib', 'three' ],
	function(require,Config, AbstractPlugin,UTILS, THREE) {
	/**
		TODO<br />
		@class Plugin Light
		@constructor
		@extends AbstractPlugin
	**/
	var Plugin = (function() {
		var name = 'light';
		Plugin.superClass.constuctor.call(this,name);
		Plugin.superClass.setContext.call(this,Config.PLUGINTYPE.CONTEXT_3D);
		Plugin.superClass.setType.call(this,Config.PLUGINTYPE.LIGHT);
		/** path to plugin-template file * */
		Plugin.superClass.setTemplates.call(this,Config.getPluginPath()+ '/plugins_3d/light/templates.js');
		Plugin.superClass.setIcon.call(this,Config.getPluginPath()+ '/plugins_3d/light/icon.png');
		Plugin.superClass.setAccepts.call(this,{
			predecessors : [ Config.PLUGINTYPE.CONTEXT_3D ],
			successors : []
		});
		Plugin.superClass.setDescription.call(this,'Requires: [ '+this.accepts.predecessors.join(', ')+' ] Accepts: [ '+this.accepts.successors.join(', ')+' ]');

		var config = null;
		this.exec = function(c, childs) {
			config = c;
			console.log("[ light ] \t\t EXEC");
			if(config === undefined || config == ""){
				config = {};
			}
			var light = null;
			var type, color, pos, intensity, distance;
			color = config.color === undefined ? 'FF0000' : config.color;
			intensity = config.intensity === undefined ? 10 : config.intensity;
			distance = config.distance === undefined ? 10 : config.distance;
			if(config.type === undefined){
				config.type = 'ambient';
			}

			switch(config.type){
				case 'point':
					light = new THREE.PointLight('#' + color, intensity, distance);
					break;
				case 'ambient':
					light = new THREE.AmbientLight('#' + color);
				break;
				default:
					light = new THREE.AmbientLight('#' + color);
				break;
			}

			var posX, posY, posZ;
			if (config.hasOwnProperty('pos')) {
				posX = config.pos.x == undefined ? 0 : config.pos.x;
				posY = config.pos.y == undefined ? 0 : config.pos.y;
				posZ = config.pos.z == undefined ? 0 : config.pos.z;
			}

			// set its position
			light.position.x = posX;
			light.position.y = posY;
			light.position.z = posZ;

//			console.log("[ light ][ type ] "+config.type+" "+light);
//			console.log("[ light ][ color ] "+color);
//			console.log("[ light ][ intensity ] "+intensity);
//			console.log("[ light ][ distance ] "+distance);
//			console.log("[ light ][ x ] "+posX);
//			console.log("[ light ][ y ] "+posY);
//			console.log("[ light ][ z ] "+posZ);

			return {
				pId : this.getId(),
				pType : this.type,
				response : light
			};
		}

	});
	UTILS.CLASS.extend(Plugin,AbstractPlugin);
	return Plugin;

});


text:
import { expect } from 'chai';
import gqlV2 from 'fake-tag';
import sinon from 'sinon';

import * as transferwise from '../../../../../server/lib/transferwise';
import models from '../../../../../server/models';
import { fakeCollective, fakeConnectedAccount, fakeUser } from '../../../../test-helpers/fake-data';
import { graphqlQueryV2 } from '../../../../utils';
import * as utils from '../../../../utils';

describe('server/graphql/v2/mutation/ConnectedAccountMutations', () => {
  const sandbox = sinon.createSandbox();
  beforeEach(() => {
    sandbox.restore();
    sandbox.stub(transferwise, 'getProfiles').resolves();
  });
  beforeEach(utils.resetTestDB);

  describe('createConnectedAccount', () => {
    const createConnectedAccountMutation = gqlV2/* GraphQL */ `
      mutation CreateConnectedAccount(
        $connectedAccount: ConnectedAccountCreateInput!
        $account: AccountReferenceInput!
      ) {
        createConnectedAccount(connectedAccount: $connectedAccount, account: $account) {
          id
          legacyId
          settings
          service
        }
      }
    `;
    let user, collective;
    beforeEach(async () => {
      user = await fakeUser();
      collective = await fakeCollective({
        admin: user.collective,
      });
    });

    it('should create a new connected account', async () => {
      const connectedAccount = {
        refreshToken: 'fakeRefreshToken',
        settings: { a: true },
        token: 'fakeToken',
        service: 'transferwise',
        username: 'kewitz',
        data: { secret: true },
      };

      const result = await graphqlQueryV2(
        createConnectedAccountMutation,
        {
          connectedAccount,
          account: { legacyId: collective.id },
        },
        user,
      );

      result.errors && console.error(result.errors);
      expect(result.errors).to.not.exist;
      expect(result.data).to.exist;
      expect(result.data.createConnectedAccount).to.exist;

      const createdConnectedAccount = await models.ConnectedAccount.findByPk(
        result.data.createConnectedAccount.legacyId,
      );
      expect(createdConnectedAccount.toJSON()).to.deep.include(connectedAccount);
    });

    it('should fail if token already exists', async () => {
      const connectedAccount = {
        token: 'fakeToken',
        service: 'transferwise',
      };

      await graphqlQueryV2(
        createConnectedAccountMutation,
        {
          connectedAccount,
          account: { legacyId: collective.id },
        },
        user,
      );

      const result = await graphqlQueryV2(
        createConnectedAccountMutation,
        {
          connectedAccount,
          account: { legacyId: collective.id },
        },
        user,
      );

      expect(result.errors).to.exist;
      expect(result.errors[0].extensions.code).to.equal('ValidationFailed');
      expect(result.errors[0].message).to.include('This token is already being used');
    });

    it('should fail if token is not valid', async () => {
      const connectedAccount = {
        token: 'fakeToken',
        service: 'transferwise',
      };

      (transferwise.getProfiles as sinon.stub).rejects();

      const result = await graphqlQueryV2(
        createConnectedAccountMutation,
        {
          connectedAccount,
          account: { legacyId: collective.id },
        },
        user,
      );

      expect(result.errors).to.exist;
      expect(result.errors[0].extensions.code).to.equal('ValidationFailed');
      expect(result.errors[0].message).to.include('The token is not a valid TransferWise token');
    });
  });

  describe('deleteConnectedAccount', () => {
    const deleteConnectedAccountMutation = gqlV2/* GraphQL */ `
      mutation DeleteConnectedAccount($connectedAccount: ConnectedAccountReferenceInput!) {
        deleteConnectedAccount(connectedAccount: $connectedAccount) {
          id
        }
      }
    `;

    let user, collective, connectedAccount;
    beforeEach(async () => {
      user = await fakeUser();
      collective = await fakeCollective({
        admin: user.collective,
      });
      connectedAccount = await fakeConnectedAccount({ CollectiveId: collective.id });
    });

    it('should force delete the connected account', async () => {
      const result = await graphqlQueryV2(
        deleteConnectedAccountMutation,
        {
          connectedAccount: {
            legacyId: connectedAccount.id,
          },
        },
        user,
      );

      result.errors && console.error(result.errors);
      expect(result.errors).to.not.exist;
      expect(result.data).to.exist;

      const createdConnectedAccount = await models.ConnectedAccount.findByPk(connectedAccount.id, { paranoid: false });
      expect(createdConnectedAccount).to.be.null;
    });
  });
});


text:
using System;
using NodaTime.Test.TimeZones.IO;
using NodaTime.TimeZones;
using NUnit.Framework;

namespace NodaTime.Test.TimeZones
{
    [TestFixture]
    public class ZoneYearOffsetTest
    {
        [Test]
        public void Construct_InvalidMonth_Exception()
        {
            Assert.Throws(typeof(ArgumentOutOfRangeException), () => new ZoneYearOffset(TransitionMode.Standard, 0, 1, 1, true, LocalTime.Midnight), "Month 0");
            Assert.Throws(typeof(ArgumentOutOfRangeException), () => new ZoneYearOffset(TransitionMode.Standard, 34, 1, 1, true, LocalTime.Midnight), "Month 34");
            Assert.Throws(typeof(ArgumentOutOfRangeException), () => new ZoneYearOffset(TransitionMode.Standard, -3, 1, 1, true, LocalTime.Midnight), "Month -3");
        }

        [Test]
        public void Construct_InvalidDayOfMonth_Exception()
        {
            Assert.Throws(typeof(ArgumentOutOfRangeException), () => new ZoneYearOffset(TransitionMode.Standard, 2, 0, 1, true, LocalTime.Midnight), "Day of Month 0");
            Assert.Throws(typeof(ArgumentOutOfRangeException), () => new ZoneYearOffset(TransitionMode.Standard, 2, 32, 1, true, LocalTime.Midnight), "Day of Month 32");
            Assert.Throws(typeof(ArgumentOutOfRangeException), () => new ZoneYearOffset(TransitionMode.Standard, 2, 475, 1, true, LocalTime.Midnight),
                          "Day of Month 475");
            Assert.Throws(typeof(ArgumentOutOfRangeException), () => new ZoneYearOffset(TransitionMode.Standard, 2, -32, 1, true, LocalTime.Midnight),
                          "Day of Month -32");
        }

        [Test]
        public void Construct_InvalidDayOfWeek_Exception()
        {
            Assert.Throws(typeof(ArgumentOutOfRangeException), () => new ZoneYearOffset(TransitionMode.Standard, 2, 3, -1, true, LocalTime.Midnight), "Day of Week -1");
            Assert.Throws(typeof(ArgumentOutOfRangeException), () => new ZoneYearOffset(TransitionMode.Standard, 2, 3, 8, true, LocalTime.Midnight), "Day of Week 8");
            Assert.Throws(typeof(ArgumentOutOfRangeException), () => new ZoneYearOffset(TransitionMode.Standard, 2, 3, 5756, true, LocalTime.Midnight),
                          "Day of Week 5856");
            Assert.Throws(typeof(ArgumentOutOfRangeException), () => new ZoneYearOffset(TransitionMode.Standard, 2, 3, -347, true, LocalTime.Midnight),
                          "Day of Week -347");
        }

        [Test]
        public void Construct_ValidMonths()
        {
            for (int month = 1; month <= 12; month++)
            {
                Assert.NotNull(new ZoneYearOffset(TransitionMode.Standard, month, 1, 1, true, LocalTime.Midnight), "Month " + month);
            }
        }

        [Test]
        public void Construct_ValidDays()
        {
            for (int day = 1; day <= 31; day++)
            {
                Assert.NotNull(new ZoneYearOffset(TransitionMode.Standard, 1, day, 1, true, LocalTime.Midnight), "Day " + day);
            }
            for (int day = -1; day >= -31; day--)
            {
                Assert.NotNull(new ZoneYearOffset(TransitionMode.Standard, 1, day, 1, true, LocalTime.Midnight), "Day " + day);
            }
        }

        [Test]
        public void Construct_ValidDaysOfWeek()
        {
            for (int dayOfWeek = 0; dayOfWeek <= 7; dayOfWeek++)
            {
                Assert.NotNull(new ZoneYearOffset(TransitionMode.Standard, 1, 1, dayOfWeek, true, LocalTime.Midnight), "Day of week " + dayOfWeek);
            }
        }

        [Test]
        public void GetOccurrenceForYear_Defaults_Epoch()
        {
            var offset = new ZoneYearOffset(TransitionMode.Utc, 1, 1, 0, true, LocalTime.Midnight);
            var actual = offset.GetOccurrenceForYear(1970);
            var expected = new LocalDateTime(1970, 1, 1, 0, 0).ToLocalInstant();
            Assert.AreEqual(expected, actual);
        }

        [Test]
        public void GetOccurrenceForYear_Year_1971()
        {
            var offset = new ZoneYearOffset(TransitionMode.Utc, 1, 1, 0, true, LocalTime.Midnight);
            var actual = offset.GetOccurrenceForYear(1971);
            var expected = new LocalDateTime(1971, 1, 1, 0, 0).ToLocalInstant();
            Assert.AreEqual(expected, actual);
        }

        [Test]
        public void GetOccurrenceForYear_Milliseconds()
        {
            var offset = new ZoneYearOffset(TransitionMode.Utc, 1, 1, 0, true, new LocalTime(0, 0, 0, 1));
            var actual = offset.GetOccurrenceForYear(1970);
            var expected = new LocalDateTime(1970, 1, 1, 0, 0, 0, 1).ToLocalInstant();
            Assert.AreEqual(expected, actual);
        }

        [Test]
        public void GetOccurrenceForYear_WednesdayForward()
        {
            var offset = new ZoneYearOffset(TransitionMode.Utc, 1, 1, (int)DayOfWeek.Wednesday, true, LocalTime.Midnight);
            var actual = offset.GetOccurrenceForYear(1970);
            var expected = new LocalDateTime(1970, 1, 7, 0, 0).ToLocalInstant(); // 1970-01-01 was a Thursday
            Assert.AreEqual(expected, actual);
        }

        [Test]
        public void GetOccurrenceForYear_WednesdayBackward()
        {
            var offset = new ZoneYearOffset(TransitionMode.Utc, 1, 15, (int)DayOfWeek.Wednesday, false, LocalTime.Midnight);
            var actual = offset.GetOccurrenceForYear(1970);
            var expected = new LocalDateTime(1970, 1, 14, 0, 0).ToLocalInstant(); // 1970-01-15 was a Thursday
            Assert.AreEqual(expected, actual);
        }

        [Test]
        public void GetOccurrenceForYear_JanMinusTwo()
        {
            var offset = new ZoneYearOffset(TransitionMode.Utc, 1, -2, 0, true, LocalTime.Midnight);
            var actual = offset.GetOccurrenceForYear(1970);
            var expected = new LocalDateTime(1970, 1, 30, 0, 0).ToLocalInstant();
            Assert.AreEqual(expected, actual);
        }

        [Test]
        public void GetOccurrenceForYear_JanFive()
        {
            var offset = new ZoneYearOffset(TransitionMode.Utc, 1, 5, 0, true, LocalTime.Midnight);
            var actual = offset.GetOccurrenceForYear(1970);
            var expected = new LocalDateTime(1970, 1, 5, 0, 0).ToLocalInstant();
            Assert.AreEqual(expected, actual);
        }

        [Test]
        public void GetOccurrenceForYear_Feb()
        {
            var offset = new ZoneYearOffset(TransitionMode.Utc, 2, 1, 0, true, LocalTime.Midnight);
            var actual = offset.GetOccurrenceForYear(1970);
            var expected = new LocalDateTime(1970, 2, 1, 0, 0).ToLocalInstant();
            Assert.AreEqual(expected, actual);
        }

        [Test]
        public void GetOccurrenceForYear_LastSundayInOctober()
        {
            ZoneYearOffset offset = new ZoneYearOffset(TransitionMode.Utc, 10, -1, (int)IsoDayOfWeek.Sunday, false, LocalTime.Midnight);
            var actual = offset.GetOccurrenceForYear(1996);
            var expected = new LocalDateTime(1996, 10, 27, 0, 0).ToLocalInstant();
            Assert.AreEqual(expected, actual);
        }

        [Test]
        public void GetOccurrenceForYear_ExactlyFeb29th_LeapYear()
        {
            ZoneYearOffset offset = new ZoneYearOffset(TransitionMode.Utc, 2, 29, 0, false, LocalTime.Midnight);
            var actual = offset.GetOccurrenceForYear(2012);
            var expected = new LocalDateTime(2012, 2, 29, 0, 0).ToLocalInstant();
            Assert.AreEqual(expected, actual);
        }

        [Test]
        public void GetOccurrenceForYear_ExactlyFeb29th_NotLeapYear()
        {
            ZoneYearOffset offset = new ZoneYearOffset(TransitionMode.Utc, 2, 29, 0, false, LocalTime.Midnight);
            Assert.Throws<InvalidOperationException>(() => offset.GetOccurrenceForYear(2013));
        }

        [Test]
        public void GetOccurrenceForYear_AtLeastFeb29th_LeapYear()
        {
            ZoneYearOffset offset = new ZoneYearOffset(TransitionMode.Utc, 2, 29, (int) IsoDayOfWeek.Sunday, true, LocalTime.Midnight);
            var actual = offset.GetOccurrenceForYear(2012);
            var expected = new LocalDateTime(2012, 3, 4, 0, 0).ToLocalInstant(); // March 4th is the first Sunday after 2012-02-29
            Assert.AreEqual(expected, actual);
        }

        [Test]
        public void GetOccurrenceForYear_AtLeastFeb29th_NotLeapYear()
        {
            ZoneYearOffset offset = new ZoneYearOffset(TransitionMode.Utc, 2, 29, (int) IsoDayOfWeek.Sunday, true, LocalTime.Midnight);
            Assert.Throws<InvalidOperationException>(() => offset.GetOccurrenceForYear(2013));
        }

        [Test]
        public void GetOccurrenceForYear_AtMostFeb29th_LeapYear()
        {
            ZoneYearOffset offset = new ZoneYearOffset(TransitionMode.Utc, 2, 29, (int) IsoDayOfWeek.Sunday, false, LocalTime.Midnight);
            var actual = offset.GetOccurrenceForYear(2012);
            var expected = new LocalDateTime(2012, 2, 26, 0, 0).ToLocalInstant(); // Feb 26th is the last Sunday before 2012-02-29
            Assert.AreEqual(expected, actual);
        }

        [Test]
        public void GetOccurrenceForYear_AtMostFeb29th_NotLeapYear()
        {
            ZoneYearOffset offset = new ZoneYearOffset(TransitionMode.Utc, 2, 29, (int) IsoDayOfWeek.Sunday, false, LocalTime.Midnight);
            var actual = offset.GetOccurrenceForYear(2013);
            var expected = new LocalDateTime(2013, 2, 24, 0, 0).ToLocalInstant(); // Feb 24th is the last Sunday is February 2013
            Assert.AreEqual(expected, actual);
        }

        [Test]
        public void GetOccurrenceForYear_WithAddDay()
        {
            // Last Thursday in October, then add 24 hours. The last Thursday in October 2013 is the 31st, so
            // we should get the start of November 1st.
            var offset = new ZoneYearOffset(TransitionMode.Utc, 10, -1, (int) IsoDayOfWeek.Thursday, false, LocalTime.Midnight, true);
            var actual = offset.GetOccurrenceForYear(2013);
            var expected = new LocalDateTime(2013, 11, 1, 0, 0).ToLocalInstant();
            Assert.AreEqual(expected, actual);
        }

        [Test]
        public void GetOccurrenceForYear_WithAddDay_December31st9999()
        {
            var offset = new ZoneYearOffset(TransitionMode.Utc, 12, 31, 0, false, LocalTime.Midnight, true);
            var actual = offset.GetOccurrenceForYear(9999);
            var expected = LocalInstant.AfterMaxValue;
            Assert.AreEqual(expected, actual);
        }

        [Test]
        public void Serialization()
        {
            var dio = DtzIoHelper.CreateNoStringPool();
            var expected = new ZoneYearOffset(TransitionMode.Utc, 10, 31, (int)IsoDayOfWeek.Wednesday, true,
                new LocalTime(12, 34, 45, 678));
            dio.TestZoneYearOffset(expected);

            dio.Reset();
            expected = new ZoneYearOffset(TransitionMode.Utc, 10, -31, (int)IsoDayOfWeek.Wednesday, true, LocalTime.Midnight);
            dio.TestZoneYearOffset(expected);
        }

        [Test]
        public void IEquatable_Tests()
        {
            var value = new ZoneYearOffset(TransitionMode.Utc, 10, 31, (int)IsoDayOfWeek.Wednesday, true, LocalTime.Midnight);
            var equalValue = new ZoneYearOffset(TransitionMode.Utc, 10, 31, (int)IsoDayOfWeek.Wednesday, true, LocalTime.Midnight);
            var unequalValue = new ZoneYearOffset(TransitionMode.Utc, 9, 31, (int)IsoDayOfWeek.Wednesday, true, LocalTime.Midnight);

            TestHelper.TestEqualsClass(value, equalValue, unequalValue);
        }
    }
}


text:
- ##### Docs
  - [Dev roadmap](https://github.com/kamranahmedse/developer-roadmap)
  - [Awesome NodeJS](https://github.com/kamranahmedse/awesome-nodejs)
  - [You dont know JS](https://github.com/getify/You-Dont-Know-JS)
  - [Composition over inheritance](https://www.youtube.com/watch?v=wfMtDGfHWpA)
  - [Functional Programming](https://github.com/hemanth/functional-programming-jargon)
  - [javascriptallongesix](https://leanpub.com/javascriptallongesix/read)
  - [Yarn vs npm](https://shift.infinite.red/npm-vs-yarn-cheat-sheet-8755b092e5cc#.zan26kdby)
  - [JS from scratch](https://github.com/verekia/js-stack-from-scratch)
  - [ES6](https://github.com/DrkSephy/es6-cheatsheet)
  - [More ES6](https://engineering.haus.com/dumb-es6-tricks-53ecadd1b29f#.i3ggpwde9)
  - [Little more ES6](http://adrianmejia.com/blog/2016/10/19/Overview-of-JavaScript-ES6-features-a-k-a-ECMAScript-6-and-ES2015/#.WA4G-3dZebs.hackernews)
  - [How to start with JavaScript](https://github.com/verekia/js-stack-from-scratch)
  - [for in vs for of](https://bitsofco.de/for-in-vs-for-of/?utm_source=codropscollective)
  - [How to yield Generators](https://strongloop.com/strongblog/how-to-generators-node-js-yield-use-cases/)
  - [Learn rx](http://reactivex.io/learnrx/)
  - [Pure functions](https://medium.com/javascript-scene/master-the-javascript-interview-what-is-a-pure-function-d1c076bec976)
  - [2 pillars of JS Pt-1](https://medium.com/javascript-scene/the-two-pillars-of-javascript-ee6f3281e7f3)
  - [2 pillars of JS Pt-2](https://medium.com/javascript-scene/the-two-pillars-of-javascript-pt-2-functional-programming-a63aa53a41a4)

- ##### Videos
  - [Monads](https://www.youtube.com/watch?v=cB0vpg9-YMQ)
  - [Code for Humans](https://www.youtube.com/watch?v=loj3CLHovt0)


text:
#import "SpatialConnect.h"

@interface SCGeopackageHelper : NSObject

+ (RACSignal *)loadGPKGDataStore:(SpatialConnect *)sc;
+ (RACSignal *)loadGPKGRasterStore:(SpatialConnect *)sc;
+ (RACSignal *)downloadGpkgFile;

@end


text:
"""Keras-like layers and utilities that implement Spectral Normalization.

Based on "Spectral Normalization for Generative Adversarial Networks" by Miyato,
et al in ICLR 2018. https://openreview.net/pdf?id=B1QRgziT-
"""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

from tensorflow.contrib.gan.python.features.python import spectral_normalization_impl
# pylint: disable=wildcard-import
from tensorflow.contrib.gan.python.features.python.spectral_normalization_impl import *
# pylint: enable=wildcard-import
from tensorflow.python.util.all_util import remove_undocumented

__all__ = spectral_normalization_impl.__all__
remove_undocumented(__name__, __all__)


text:
(function(){
    var app = window.app;
    var drugAndDrop = app('drag-and-drop');
    var geolocation = app('geolocation');
    var storage = app('storage');
    var MapClass = app('map');
    var editorModule = app('editor', {});

    var placemarkerTemplate;
    var editor;
    var map;
    var list;
    var myCircle;
    var curPosition;

    editorModule.init = function() {
        initEditListModule();
        MapClass.ready(function(){
            map = new MapClass("map");
            initGeolocationModule();
            initAddNewPlaceModule();
            initDragAndDropModule();
            initShowInRadiusModule();
            initSaveInLocalStorageModule();
        });
    };

    function initShowInRadiusModule() {
        var previousRadius;
        editor.find(".pm-radius-input").on("input", function() {
            var radius = parseInt($(this).val());

            if (myCircle != null) {
                map.yaMap.geoObjects.remove(myCircle);
                myCircle = null
            }

            if (radius != previousRadius) {
                previousRadius = radius;
                if (radius > 0) {
                    // Создаем круг.
                    myCircle = new ymaps.Circle([
                        // Координаты центра круга.
                        [curPosition.latitude, curPosition.longitude],
                        // Радиус круга в метрах.
                        radius
                    ], {
                        // Описываем свойства круга.
                        // Содержимое балуна.
                        balloonContent: "Радиус круга - " + radius + " км",
                        // Содержимое хинта.
                        hintContent: "Подвинь меня"
                    }, {
                        // Задаем опции круга.
                        // Включаем возможность перетаскивания круга.
                        draggable: false,
                        // Цвет заливки.
                        // Последний байт (77) определяет прозрачность.
                        // Прозрачность заливки также можно задать используя опцию "fillOpacity".
                        fillColor: "#DB709377",
                        // Цвет обводки.
                        strokeColor: "#990066",
                        // Прозрачность обводки.
                        strokeOpacity: 0.8,
                        // Ширина обводки в пикселях.
                        strokeWidth: 1
                    });

                    map.yaMap.geoObjects.add(myCircle);

                    // Геобъекты, попадающие в круг, будут красными.
                    var objectsInsideCircle = ymaps.geoQuery(map.yaMap.geoObjects).searchInside(myCircle);

                    objectsInsideCircle.setOptions({
                        preset: 'islands#redStretchyIcon'
                    });

                    // Оставшиеся объекты - синими.
                    ymaps.geoQuery(map.yaMap.geoObjects).remove(objectsInsideCircle).setOptions({
                        preset: 'islands#blueStretchyIcon'
                    });
                } else {
                    map.yaMap.geoObjects.remove(myCircle);
                    myCircle = null
                }
            }
        });
    }

    function initSaveInLocalStorageModule() {
        map.setUpdateListener(function(changedPlaceId) {
            var data = storage.get('map-data') || {};
            var updatedPlace = map.getPlace(changedPlaceId);
            data[changedPlaceId] = updatedPlace;
            storage.set('map-data', data);
        });

        loadFromStorage();
    }

    function loadFromStorage() {
        var data = storage.get('map-data');
        if (data) {
            storage.remove('map-data');
            map.clean();

            for (var key in data) {
                var place = data[key];
                addPlace(place.lat, place.lng, place.name);
            }
        }
    }

    function initDragAndDropModule() {
        var holder = document.getElementById('holder');
        drugAndDrop(holder, function(data) {
            data.forEach(function(place) {
                var coords = place.coordinates || {};
                var name = place.name || "";
                var lat = coords.latitude;
                var lng = coords.longitude;
                if ((lat && lng) && !placeExists(lat, lng)) {
                    addPlace(lat, lng, name);
                }
            });
        });
    }

    function placeExists(lat, lng) {
        return !!map.getPlaceByCoords(lat, lng);
    }

    function initGeolocationModule() {
        geolocation.getCurrentPosition(function(position) {
            var coords = position.coords;
            curPosition = position.coords;
            map.setMyLocation(coords.latitude, coords.longitude);
            map.showMe();
        }, function(code, message) {
            alert(message);
        });
    }

    function initAddNewPlaceModule() {
        var button = $(".pm-add-item");
        var addPlaceByClik = false;

        button.on('click', function(e){
            if (!addPlaceByClik) {
                addPlaceByClik = true;
                $(this).text("Сlick on map where you want to create place...")
            } else {
                reset();
            }
        });

        function reset() {
            addPlaceByClik = false;
            button.text("Add new place");
        }

        map.setClickListener(function(lat, lng) {
            if (addPlaceByClik) {
                reset();
                addPlaceByClik = false;
                var name = prompt("Please enter place name", "New place");
                if (name) {
                    addPlace(lat, lng, name);
                }
            }
        });
    }

    function initEditListModule() {
        editor = $('#placemarker-editor');
        list = editor.find(".pm-list");
        placemarkerTemplate = list.html();
        list.html("");

        list.on('click', '.pm-remove-btn', function(ev) {
            var target = $(ev.target);
            var item = target.closest(".pm-item");
            if (item) {
                var id = item.data("id");
                removePlacemarkerById(id);
                item.remove();
            }
        });

        list.on('click', '.pm-hide-show-btn', function(ev) {
            var target = $(ev.target);
            var item = target.closest(".pm-item");
            if (item) {
                var id = item.data("id");
                map.showPlace(id, !map.isPlaceShow(id));
            }
        });

        list.on('keyup paste cut', '.pm-item-name', function(ev){
            var target = $(this);
            var item = target.closest(".pm-item");
            if (item) {
                var id = item.data("id");
                var text = target.text();
                map.setPlaceName(id, text);
            }
        });

    }

    function removePlacemarkerById(id) {
        if (id || id == 0) {
            map.removePlace(id);
        }
    }

    function addToEditor(id, name, lat, long) {
        var item = $($.parseHTML(placemarkerTemplate));
        item.data("id", id);
        item.find(".pm-item-name").text(name);
		item.find(".pm-item-lat").text("lat: " + lat);
		item.find(".pm-item-long").text("long: " + long);
        list.append(item);
    }

    function addPlace(latitude, longitude, name, isShow) {
        var id = map.addPlace(latitude, longitude, name, isShow);
        addToEditor(id, name, latitude, longitude);
    }

})();


text:
<?php
/** @var $callbackName string */
use Ffcms\Core\Helper\Type\Str;
use Ffcms\Apps\Api\Ckeditor\Editor;

/** @var $callbackId int */
/** @var $files array|null */
/** @var $type string */
?>
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="<?php echo \App::$Alias->getVendor('css', 'bootstrap'); ?>"/>
    <link rel="stylesheet" href="<?php echo \App::$Alias->getVendor('css', 'fa'); ?>"/>
    <title><?= __('FFCMS file browser') ?></title>

<?= __('File browser') ?>

        <?php echo \Ffcms\Core\Helper\HTML\Bootstrap\Nav::display([
            'property' => ['class' => 'nav-tabs'],
            'tabAnchor' => 'n',
            'items' => [
                ['type' => 'link', 'text' => __('Images'), 'link' => ['ckbrowser/browse', 'images', null, ['CKEditor' => $callbackName, 'CKEditorFuncNum' => $callbackId]]],
                ['type' => 'link', 'text' => __('Flash'), 'link' => ['ckbrowser/browse', 'flash', null, ['CKEditor' => $callbackName, 'CKEditorFuncNum' => $callbackId]]],
                ['type' => 'link', 'text' => __('Files'), 'link' => ['ckbrowser/browse', 'files', null, ['CKEditor' => $callbackName, 'CKEditorFuncNum' => $callbackId]]],
            ]
        ]); ?>

    <?php if ($files !== null && count($files) > 0): ?>
        <?php foreach ($files as $file): ?>

<?= Str::lastIn($file, '/', true) ?>

                <?php if ($type === 'images'): ?>
                <img src="<?= \App::$Alias->scriptUrl . '/' . $file ?>" class="img-responsive image-item" />
                <?php elseif ($type === 'flash'): ?>

                <?php else: ?>

                <?php endif; ?>

                    <a href="javascript::void(0)" onclick="return callCkeditor('<?= \App::$Alias->scriptUrl . '/' . $file ?>')" class="btn btn-success btn-sm"> <?= __('Select') ?>
                    <a href="<?= \App::$Alias->scriptUrl . '/' . $file ?>" target="_blank" class="btn btn-default btn-sm"> <?= __('Preview') ?>

        <?php endforeach; ?>
    <?php else: ?>

<?= __('Files not found') ?>

    <?php endif; ?>


text:
<!doctype html>
<title>@container: selection using name and implicit selection</title>
<link rel="help" href="https://drafts.csswg.org/css-contain-3/#container-rule">


text:
using namespace std;
class Shell
{
    private:
        vector<Command> queue;
        vector<PipeCommand> pipeQueue;
    public:
        void read();
        void priorityParse(string); //For usage of ()
        void parse(string);
        void pipeParse(string); //For commands with | being the only connector
};


text:
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/screen"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="center_vertical"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/add_team_member_new_member"
            android:labelFor="@+id/playerName"
            android:textAppearance="?android:attr/textAppearanceMedium"/>

        <EditText
            android:id="@+id/playerName"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:ems="10"
            android:hint="@string/add_team_member_new_member"
            android:inputType="text"
            android:textAppearance="?android:attr/textAppearanceMedium">
        </EditText>

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/add_team_member_batting_skill" >
        </TextView>

        <SeekBar
            android:id="@+id/battingSkill"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="left"
            android:layout_marginLeft="5dp"
            android:layout_marginRight="5dp"
            android:max="10"
            android:progress="5" />

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/add_team_member_bowling_skill"
            android:textAppearance="?android:attr/textAppearanceMedium">
        </TextView>

        <SeekBar
            android:id="@+id/BowlingSkill"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="left"
            android:layout_marginLeft="5dp"
            android:layout_marginRight="5dp"
            android:max="10"
            android:progress="5" />

        <Button
            android:id="@+id/btn_create_new"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:onClick="updateTeamMemberClick"
            android:text="@string/add_team_member_update_team_member"
            android:textAppearance="?android:attr/textAppearanceMedium"/>
    </LinearLayout>

</ScrollView>


text:
package javax.swing.event;

import java.util.EventObject;

/**
 * ChangeEvent is used to notify interested parties that
 * state has changed in the event source.
 *

 * Warning:
 * Serialized objects of this class will not be compatible with
 * future Swing releases. The current serialization support is
 * appropriate for short term storage or RMI between applications running
 * the same version of Swing.  As of 1.4, support for long term storage
 * of all JavaBeansTM
 * has been added to the java.beans package.
 * Please see {@link java.beans.XMLEncoder}.
 *
 * @author Jeff Dinkins
 */
public class ChangeEvent extends EventObject {
    /**
     * Constructs a ChangeEvent object.
     *
     * @param source  the Object that is the source of the event
     *                (typically this)
     */
    public ChangeEvent(Object source) {
        super(source);
    }
}


text:
import React from 'react';

const GeorgiaSpan = (props) => {
    const style = {};
    let fontClass = 'georgia-font-bold';

    const {
        textTransform,
        slim,
        customText
    } = props;

    if(textTransform === 'uppercase' || textTransform === 'lowercase' || textTransform === 'capitalize')
        style['textTransform'] = textTransform;

    if(slim)
        fontClass = 'georgia-font';

    return (
        { customText || 'Instytut PL 590' }
    );
};

export default GeorgiaSpan;


text:
package com.github.j5ik2o.dddbase.skinny

import cats.data.ReaderT
import com.github.j5ik2o.dddbase.{ AggregateMultiHardDeletable, AggregateMultiWriter }
import monix.eval.Task
import scalikejdbc.DBSession

trait AggregateMultiHardDeleteFeature
    extends AggregateMultiHardDeletable[ReaderT[Task, DBSession, ?]]
    with AggregateBaseReadFeature {
  this: AggregateMultiWriter[ReaderT[Task, DBSession, ?]] with AggregateSingleHardDeleteFeature =>

  override def hardDeleteMulti(ids: Seq[IdType]): ReaderT[Task, DBSession, Long] = ReaderT { implicit dbSession =>
    Task {
      dao.deleteBy(byConditions(ids)).toLong
    }
  }

}


text:
package com.ctrip.xpipe.redis.meta.server.cluster;

import com.ctrip.xpipe.api.lifecycle.Lifecycle;

import java.util.Set;

/**
 * @author wenchao.meng
 *
 * Jul 25, 2016
 */
public interface CurrentClusterServer extends ClusterServer, Lifecycle{

	int ORDER = SlotManager.ORDER + 1;

	Set<Integer>  slots();

	boolean isLeader();

	boolean hasKey(Object key);

}


text:
namespace paddle {
namespace operators {
namespace detail {

enum WireType {
  WIRETYPE_VARINT = 0,
  WIRETYPE_LENGTH_DELIMITED = 2,
};

inline int GetTagFieldNumber(uint32_t tag) { return tag >> 3; }

inline WireType GetTagWireType(uint32_t tag) {
  return static_cast<WireType>(tag & 0x7);
}

bool ReadVarintSizeAsInt(::google::protobuf::io::CodedInputStream* input,
                         int* result) {
  uint64_t v;
  if (input->ReadVarint64(&v) && v <= static_cast<uint64_t>(INT_MAX)) {
    *result = static_cast<int>(v);
    return true;
  } else {
    return false;
  }
}

bool ReadRaw(::google::protobuf::io::CodedInputStream* input,
             const platform::DeviceContext& dev_ctx, platform::Place place,
             void* dest, int size) {
  const void* data = NULL;
  int size_to_write = 0;
  int length = size;
  int total_written = 0;

  if (platform::is_gpu_place(place)) {
#ifdef PADDLE_WITH_CUDA
    auto& gpu_dev_ctx =
        static_cast<const platform::CUDADeviceContext&>(dev_ctx);
    platform::CPUPlace cpu;

    char* p = reinterpret_cast<char*>(dest);
    while (total_written < length) {
      if (!input->GetDirectBufferPointer(&data, &size_to_write)) {
        return false;
      }
      // NOTE: if raw buffer is large and have two neighbor fields of raw
      // buffers GetDirectBufferPointer can get all of them, use length to
      // truncate it.
      if (total_written + size_to_write > length) {
        size_to_write = length - total_written;
      }
      memory::Copy(boost::get<platform::CUDAPlace>(place),
                   reinterpret_cast<void*>(p), cpu, data, size_to_write,
                   gpu_dev_ctx.stream());
      p += size_to_write;
      total_written += size_to_write;

      input->Skip(size_to_write);
    }
    gpu_dev_ctx.Wait();
#else
    PADDLE_THROW("Unexpected branch");
#endif
    return true;
  }

  char* p = reinterpret_cast<char*>(dest);
  while (total_written < length) {
    if (!input->GetDirectBufferPointer(&data, &size_to_write)) {
      return false;
    }
    // NOTE: if raw buffer is large and have two neighbor fields of raw buffers
    // GetDirectBufferPointer can get all of them, use length to truncate it.
    if (total_written + size_to_write > length) {
      size_to_write = length - total_written;
    }
    // TODO(gongwb): can we avoid copy?
    platform::CPUPlace cpu;
    memory::Copy(cpu, reinterpret_cast<void*>(p), cpu, data, size_to_write);

    p += size_to_write;
    total_written += size_to_write;

    input->Skip(size_to_write);
  }

  return true;
}

bool VariableResponse::CopyLodTensorData(
    ::google::protobuf::io::CodedInputStream* input,
    const platform::DeviceContext& ctx, const framework::DDim& dims,
    int length) {
  auto* tensor = GetVar()->GetMutable<framework::LoDTensor>();
  tensor->Resize(dims);

  framework::LoD lod;
  for (int i = 0; i < meta_.lod_level(); ++i) {
    framework::Vector<size_t> v;
    for (int j = 0; j < meta_.lod(i).lod_data_size(); ++j) {
      v.push_back(meta_.lod(i).lod_data(j));
    }
    lod.push_back(v);
  }
  tensor->set_lod(lod);

  void* tensor_data =
      tensor->mutable_data(ctx.GetPlace(), ToTypeIndex(meta_.data_type()));

  if (!ReadRaw(input, ctx, tensor->place(), tensor_data, length)) {
    return false;
  }

  return true;
}

inline framework::DDim GetDims(
    const ::google::protobuf::RepeatedField<::google::protobuf::int64>& dims) {
  std::vector<int> vecdims;
  for (auto& d : dims) {
    vecdims.push_back(d);
  }
  return framework::make_ddim(vecdims);
}

bool VariableResponse::CopySelectRowsTensorData(
    ::google::protobuf::io::CodedInputStream* input,
    const platform::DeviceContext& ctx, const framework::DDim& dims,
    int length) {
  auto* slr = GetVar()->GetMutable<framework::SelectedRows>();
  slr->set_height(meta_.slr_height());
  auto* tensor = slr->mutable_value();
  tensor->Resize(dims);
  PADDLE_ENFORCE_EQ(
      static_cast<size_t>(tensor->numel()),
      length / framework::SizeOfType(
                   paddle::operators::detail::ToTypeIndex(meta_.data_type())));
  void* tensor_data = tensor->mutable_data(
      ctx.GetPlace(),
      paddle::operators::detail::ToTypeIndex(meta_.data_type()));

  if (!ReadRaw(input, ctx, tensor->place(), tensor_data, length)) {
    return false;
  }

  return true;
}

bool VariableResponse::CopySelectRowsData(
    ::google::protobuf::io::CodedInputStream* input,
    const platform::DeviceContext& ctx, int length) {
  auto* slr = GetVar()->GetMutable<framework::SelectedRows>();
  slr->mutable_rows()->resize(length /
                              framework::SizeOfType(typeid(int64_t)));  // int64
  int64_t* rows_data = slr->mutable_rows()->data();

  // copy rows CPU data, GPU data will be copied lazily.
  platform::CPUPlace cpu;
  if (!ReadRaw(input, ctx, cpu, rows_data, length)) {
    return false;
  }

  return true;
}

bool ParseLodData(::google::protobuf::io::CodedInputStream* input,
                  std::vector<int64_t>* lod) {
  while (true) {
    auto p = input->ReadTagWithCutoff(127);
    int tag = GetTagFieldNumber(p.first);
    WireType wt = GetTagWireType(p.first);

    if (!p.second) {
      return (tag == 0);
    }

    switch (tag) {
      case sendrecv::VariableMessage_LodData::kLodDataFieldNumber: {
        uint64_t v;
        if (wt == WIRETYPE_VARINT) {
          if (!input->ReadVarint64(&v)) {
            return false;
          }
          lod->push_back(v);
          break;
        }

        if (wt == WIRETYPE_LENGTH_DELIMITED) {
          int num_bytes = 0;
          if (!input->ReadVarintSizeAsInt(&num_bytes)) {
            return tag;
          }
          int start_pos = input->CurrentPosition();
          while (input->CurrentPosition() - start_pos < num_bytes) {
            uint64_t v;
            if (!input->ReadVarint64(&v)) {
              return tag;
            }
            lod->push_back(v);
          }
          break;
        }

        return false;
      }
      default: { return false; }
    }
  }

  return true;
}

int VariableResponse::Parse(const ::grpc::ByteBuffer& byte_buffer) {
  GrpcByteBufferSource source;
  source.Init(byte_buffer);
  GrpcByteBufferSourceWrapper r(&source);

  return Parse(&r);
}

int VariableResponse::Parse(Source* source) {
  ::google::protobuf::io::ZeroCopyInputStream* input_stream =
      source->contents();
  ::google::protobuf::io::CodedInputStream input(input_stream);
  input.SetTotalBytesLimit(INT_MAX, INT_MAX);

  while (true) {
    auto p = input.ReadTagWithCutoff(127);
    int tag = GetTagFieldNumber(p.first);
    WireType wt = GetTagWireType(p.first);
    if (!p.second) {
      if (tag != 0) {
        return -1;
      }
      return 0;
    }

    switch (tag) {
      case sendrecv::VariableMessage::kVarnameFieldNumber: {
        uint32_t length;
        if ((wt != WIRETYPE_LENGTH_DELIMITED) || !input.ReadVarint32(&length)) {
          return tag;
        }

        std::string temp;
        if (!input.ReadString(&temp, length)) {
          return tag;
        }

        meta_.set_varname(temp);
        break;
      }
      case sendrecv::VariableMessage::kTypeFieldNumber: {
        uint32_t v;
        if ((wt != WIRETYPE_VARINT) || !input.ReadVarint32(&v)) {
          return tag;
        }

        meta_.set_type(static_cast<::sendrecv::VarType>(v));
        break;
      }
      case sendrecv::VariableMessage::kDataTypeFieldNumber: {
        uint32_t v = 0;
        if ((wt != WIRETYPE_VARINT) || !input.ReadVarint32(&v)) {
          return tag;
        }

        meta_.set_data_type(static_cast<::sendrecv::VariableMessage_Type>(v));
        break;
      }
      case sendrecv::VariableMessage::kDimsFieldNumber: {
        // not packed
        if (wt == WIRETYPE_VARINT) {
          uint64_t v;
          if (!input.ReadVarint64(&v)) {
            return tag;
          }
          meta_.add_dims(v);
          break;
        }

        // packed
        if (wt == WIRETYPE_LENGTH_DELIMITED) {
          int num_bytes = 0;
          if (!input.ReadVarintSizeAsInt(&num_bytes)) {
            return tag;
          }
          int start_pos = input.CurrentPosition();
          while (input.CurrentPosition() - start_pos < num_bytes) {
            uint64_t v;
            if (!input.ReadVarint64(&v)) {
              return tag;
            }
            meta_.add_dims(v);
          }
          break;
        }
        return tag;
      }
      case sendrecv::VariableMessage::kLodLevelFieldNumber: {
        uint64_t v = 0;
        if ((wt != WIRETYPE_VARINT) || !input.ReadVarint64(&v)) {
          return tag;
        }
        meta_.set_lod_level(static_cast<int64_t>(v));
        break;
      }
      case sendrecv::VariableMessage::kLodFieldNumber: {
        int length = 0;
        if (wt != WIRETYPE_LENGTH_DELIMITED ||
            !ReadVarintSizeAsInt(&input, &length)) {
          return tag;
        }

        std::pair<::google::protobuf::io::CodedInputStream::Limit, int> p =
            input.IncrementRecursionDepthAndPushLimit(length);

        std::vector<int64_t> lod_data;
        if (p.second < 0 || !ParseLodData(&input, &lod_data)) {
          return tag;
        }

        if (!input.DecrementRecursionDepthAndPopLimit(p.first)) {
          return false;
        }

        if (lod_data.size() == 0) {
          break;
        }

        auto lod = meta_.add_lod();
        for (uint32_t i = 0; i < lod_data.size(); i++) {
          lod->add_lod_data(lod_data[i]);
        }
        break;
      }
      case sendrecv::VariableMessage::kSlrHeightFieldNumber: {
        uint64_t v = 0;
        if ((wt != WIRETYPE_VARINT) || !input.ReadVarint64(&v)) {
          return tag;
        }
        meta_.set_slr_height(static_cast<int64_t>(v));
        break;
      }
      case sendrecv::VariableMessage::kSerializedFieldNumber: {
        PADDLE_ENFORCE((meta_.type() == sendrecv::SELECTED_ROWS ||
                        meta_.type() == sendrecv::LOD_TENSOR ||
                        meta_.type() == sendrecv::NCCL_ID) &&
                           meta_.varname() != "",
                       "meta info should be got first!");

        int num_bytes = 0;
        if (wt != WIRETYPE_LENGTH_DELIMITED ||
            !ReadVarintSizeAsInt(&input, &num_bytes)) {
          return tag;
        }

        if (meta_.type() == sendrecv::NCCL_ID) {
#ifdef PADDLE_WITH_CUDA
          auto* var = scope_->FindVar(meta_.varname());
          if (var != nullptr) {
            ncclUniqueId* id = var->GetMutable<ncclUniqueId>();
            if (!ReadRaw(&input, *dev_ctx_, platform::CPUPlace(), id->internal,
                         num_bytes)) {
              return tag;
            }
          }
          break;
#else
          PADDLE_THROW("Not compiled with CUDA!");
#endif
        }

        framework::DDim dims = GetDims(meta_.dims());
        if (meta_.type() == sendrecv::LOD_TENSOR) {
          PADDLE_ENFORCE(meta_.lod_size() >= 0,
                         "lod info should be got first!");
          if (!CopyLodTensorData(&input, *dev_ctx_, dims, num_bytes)) {
            return tag;
          }
          break;
        }

        if (meta_.type() == sendrecv::SELECTED_ROWS) {
          if (!CopySelectRowsTensorData(&input, *dev_ctx_, dims, num_bytes)) {
            return tag;
          }
          break;
        }

        return tag;
      }
      case sendrecv::VariableMessage::kRowsFieldNumber: {
        PADDLE_ENFORCE((meta_.type() == sendrecv::SELECTED_ROWS ||
                        meta_.type() == sendrecv::LOD_TENSOR) &&
                           meta_.varname() != "",
                       "meta info should be got first!");

        int num_bytes = 0;
        if (wt != WIRETYPE_LENGTH_DELIMITED ||
            !ReadVarintSizeAsInt(&input, &num_bytes)) {
          return tag;
        }

        if (!CopySelectRowsData(&input, *dev_ctx_, num_bytes)) {
          return tag;
        }
        break;
      }
      case sendrecv::VariableMessage::kOutVarnameFieldNumber: {
        uint32_t length;
        if ((wt != WIRETYPE_LENGTH_DELIMITED) || !input.ReadVarint32(&length)) {
          return tag;
        }

        std::string temp;
        if (!input.ReadString(&temp, length)) {
          return tag;
        }

        meta_.set_out_varname(temp);
        break;
      }
      case sendrecv::VariableMessage::kProfileFieldNumber: {
        bool profiling;
        if (!input.ReadRaw(reinterpret_cast<void*>(&profiling), 1)) {
          return tag;
        }
        meta_.set_profile(profiling);
        int64_t listener_id = platform::ListenerId();
        if (listener_id <= 0) {
          break;
        }
        if (profiling && !platform::IsProfileEnabled()) {
          platform::EnableProfiler(platform::ProfilerState::kCPU);
        } else if (!profiling && platform::IsProfileEnabled()) {
          // TODO(panyx0718): Should we allow to customize file dir.
          platform::DisableProfiler(
              platform::EventSortingKey::kDefault,
              string::Sprintf("/tmp/profile_ps_%lld", listener_id));
        }
        break;
      }
      default: {
        // Unknown tag, return unknown error.
        return -1;
      }
    }
  }

  return 0;
}

};  // namespace detail
};  // namespace operators
};  // namespace paddle


text:
require 'spec_helper'

describe SpreeAvatax::Calculator do
  let(:calculator) { SpreeAvatax::Calculator.new }

  describe '.description' do
    it 'should not be nil' do
      expect(SpreeAvatax::Calculator.description).to eq Spree.t(:avatax_description)
    end
  end

  describe '#compute' do
    it 'should raise DoNotUseCompute' do
      lambda {
        calculator.compute(nil)
      }.should raise_error(SpreeAvatax::Calculator::DoNotUseCompute)
    end
  end

end


text:
class AddBirthdateToUsers < ActiveRecord::Migration
  def change
  	add_column :users, :birthdate, :date
  end
end


text:
template <typename T> struct empty
{
   // allow success case to build (not relevant to bug)
   operator bool() { return true; }
};

template <typename T> struct from_int
{
   from_int(int) {}

   // allow success case to build (not relevant to bug)
   operator bool() { return true; }
};

template <typename T>
from_int<T> via_function(T v)
{
   return from_int<T>(v);
}

template <typename T>
void f()
{
   // ********* this section compiles ***********

   // these plain initializers work fine
   from_int<int> a = 7;
   from_int<int> b = from_int<int>(7);
   empty<int>    c = empty<int>();
   from_int<T> ta = 7;
   from_int<T> tb = from_int<T>(7);
   empty<T>    tc = empty<T>();

   // these dependent condition decls work fine
   if (empty<T> x = empty<T>())
      ;
   if (from_int<T> x = 7)
      ;
   if (from_int<T> x = from_int<T>(7))
      ;
   if (from_int<T> x = via_function(T()))
      ;

   // this non-dependent condition decl using conversion works fine
   if (from_int<int> x = 7)
      ;

   // these non-dependent condition decls using conversion or braced-
   // initialization work fine (in c++0x mode only course)
   #if __GXX_EXPERIMENTAL_CXX0X__
   if (empty<int> x {})
      ;
   if (from_int<int> x {7})
      ;
   #endif

   // ********** this section fails in C++0x ***********

   // the following non-dependent condition decls cause an assertion
   // failure in
   //
   //   tsubst_copy_and_build, at cp/pt.c:13370
   //
   // in C++0x mode
   //
   if (empty<int> x = empty<int>())
      ;
   if (from_int<int> x = from_int<int>(7))
      ;
   if (from_int<int> x = via_function(7))
      ;
}

int main()
{
   f<int>();
}


text:
package com.awplab.core.common;

import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * Created by andyphillips404 on 6/20/17.
 */
public class DelayRequestManager {
    private DelayQueue<DelayQueueItem> delayQueue = new DelayQueue<>();

    private TimeUnit timeUnit;
    private long delay;

    public DelayRequestManager(long delay, TimeUnit timeUnit) {
        this.timeUnit = timeUnit;
        this.delay = delay;
    }

    public void waitForClear() throws InterruptedException {
        delayQueue.add(new DelayQueueItem(delay, timeUnit));
        delayQueue.take();
    }

    public void clear() {
        delayQueue.clear();
    }

    private static class DelayQueueItem implements Delayed {
        private long startTime;

        public DelayQueueItem(long delay, TimeUnit timeUnit) {
            this.startTime = System.currentTimeMillis() + timeUnit.toMillis(delay);
        }

        @Override
        public long getDelay(TimeUnit unit) {
            long diff = startTime - System.currentTimeMillis();
            return unit.convert(diff, TimeUnit.MILLISECONDS);
        }

        @Override
        public int compareTo(Delayed o) {
            if (this.startTime < ((DelayQueueItem) o).startTime) {
                return -1;
            }
            if (this.startTime > ((DelayQueueItem) o).startTime) {
                return 1;
            }
            return 0;
        }

    }

}