text:
package sttp.client3.curl

private[client3] object CurlOption extends Enumeration {
  type CurlOption = Value

  /** * This is the FILE * or void * the regular output should be written to.
    */
  val WriteData = Value(10000 + 1)

  /** The full URL to get/put */
  val Url = Value(10000 + 2)

  /** Port number to connect to, if other than default. */
  val Port = Value(3)

  /** Name of proxy to use. */
  val Proxy = Value(10000 + 4)

  /** "user:password;options" to use when fetching. */
  val UserPassword = Value(10000 + 5)

  /** "user:password" to use with proxy. */
  val ProxyUserPassword = Value(10000 + 6)

  /** Range to get, specified as an ASCII string. */
  val Range = Value(10000 + 7)

  /** Specified file stream to upload from (use as input): */
  val ReadData = Value(10000 + 9)

  /** Buffer to receive error messages in, must be at least CURL_ERROR_SIZE bytes big.
    */
  val ErrorBuffer = Value(10000 + 10)

  /** Function that will be called to store the output (instead of fwrite). The parameters will use fwrite() syntax,
    * make sure to follow them.
    */
  val WriteFunction = Value(20000 + 11)

  /** Function that will be called to read the input (instead of fread). The parameters will use fread() syntax, make
    * sure to follow them.
    */
  val ReadFunction = Value(10000 + 12)

  /** Time-out the read operation after this amount of seconds */
  val Timeout = Value(13)

  /** If the CURLOPT_INFILE is used, this can be used to inform libcurl about how large the file being sent really is.
    * That allows better error checking and better verifies that the upload was successful. -1 means unknown size.
    *
    * For large file support, there is also a _LARGE version of the key which takes an off_t type, allowing platforms
    * with larger off_t sizes to handle larger files. See below for INFILESIZE_LARGE.
    */
  val InFileSize = Value(14)

  /** POST static input fields. */
  val PostFields = Value(10000 + 15)

  /** Set the referrer page (needed by some CGIs) */
  val Referer = Value(10000 + 16)

  /** Set the FTP PORT string (interface name, named or numerical IP address) Use i.e '-' to use default address.
    */
  val FtpPort = Value(10000 + 17)

  /** Set the User-Agent string (examined by some CGIs) */
  val UserAgent = Value(10000 + 18)

  /** Set the "low speed limit" */
  val LowSpeedLimit = Value(19)

  /** Set the "low speed time" */
  val LowSpeedTime = Value(20)

  /** Set the continuation offset.
    *
    * Note there is also a _LARGE version of this key which uses off_t types, allowing for large file offsets on
    * platforms which use larger-than-32-bit off_t's. Look below for RESUME_FROM_LARGE.
    */
  val ResumeFrom = Value(21)

  /** Set cookie in request: */
  val Cookie = Value(10000 + 22)

  /** This points to a linked list of headers, struct curl_slist kind. This list is also used for RTSP (in spite of its
    * name)
    */
  val HttpHeader = Value(10000 + 23)

  /** This points to a linked list of post entries, struct curl_httppost */
  val HttpPost = Value(10000 + 24)

  /** name of the file keeping your private SSL-certificate */
  val SslCertificate = Value(10000 + 25)

  /** password for the SSL or SSH private key */
  val KeyPassword = Value(10000 + 26)

  /** send TYPE parameter? */
  val CrLf = Value(27)

  /** send linked-list of QUOTE commands */
  val Quote = Value(10000 + 28)

  /** send FILE * or void * to store headers to, if you use a callback it is simply passed to the callback unmodified
    */
  val HeaderData = Value(10000 + 29)

  /** point to a file to read the initial cookies from, also enables "cookie awareness"
    */
  val CookieFile = Value(10000 + 31)

  /** What version to specifically try to use. See CURL_SSLVERSION defines below.
    */
  val SslVersion = Value(32)

  /** Custom request, for customizing the get command like HTTP: DELETE, TRACE and others FTP: to use a different list
    * command
    */
  val CustomRequest = Value(10000 + 36)

  /** FILE handle to use instead of stderr */
  val StdErr = Value(10000 + 37)

  /** send linked-list of post-transfer QUOTE commands */
  val PostQuote = Value(10000 + 39)

  /** talk a lot */
  val Verbose = Value(41)

  /** throw the header out too */
  val Header = Value(42)

  /** shut off the progress meter */
  val NoProgress = Value(43)

  /** use HEAD to get http document */
  val Head = Value(44)

  /** no output on http error codes >= 400 */
  val FailOnError = Value(45)

  /** this is an upload */
  val Upload = Value(46)

  /** HTTP POST method */
  val Post = Value(47)

  /** bare names when listing directories */
  val DirListOnly = Value(48)

  /** Append instead of overwrite on upload! */
  val Append = Value(50)

  /** Specify whether to read the user+password from the .netrc or the URL. This must be one of the CURL_NETRC_* enums
    * below.
    */
  val Netrc = Value(51)

  /** use Location: Luke! */
  val FollowLocation = Value(52)

  /** transfer data in text/ASCII format */
  val TransferText = Value(53)

  /** HTTP PUT */
  val Put = Value(54)

  /** Data passed to the CURLOPT_PROGRESSFUNCTION and CURLOPT_XFERINFOFUNCTION callbacks
    */
  val ProgressData = Value(10000 + 57)

  /** We want the referrer field set automatically when following locations */
  val AutoReferer = Value(58)

  /** Port of the proxy, can be set in the proxy string as well with: "[host]:[port]"
    */
  val ProxyPort = Value(59)

  /** size of the POST input data, if strlen() is not good to use */
  val PostFieldSize = Value(60)

  /** tunnel non-http operations through a HTTP proxy */
  val HttpProxyTunnel = Value(61)

  /** Set the interface string to use as outgoing network interface */
  val Interface = Value(10000 + 62)

  /** Set the krb4/5 security level, this also enables krb4/5 awareness. This is a string, 'clear', 'safe',
    * 'confidential' or 'private'. If the string is set but doesn't match one of these, 'private' will be used.
    */
  val KrbLevel = Value(10000 + 63)

  /** Set if we should verify the peer in ssl handshake, set 1 to verify. */
  val SslVerifyPeer = Value(64)

  /** The CApath or CAfile used to validate the peer certificate this option is used only if SSL_VERIFYPEER is true
    */
  val CaInfo = Value(10000 + 65)

  /** Maximum number of http redirects to follow */
  val MaxRedirects = Value(68)

  /** Pass a long set to 1 to get the date of the requested document (if possible)! Pass a zero to shut it off.
    */
  val FileTime = Value(69)

  /** This points to a linked list of telnet options */
  val TelnetOptions = Value(10000 + 70)

  /** Max amount of cached alive connections */
  val MaxConnects = Value(71)

  /** Set to explicitly use a new connection for the upcoming transfer. Do not use this unless you're absolutely sure of
    * this, as it makes the operation slower and is less friendly for the network.
    */
  val FreshConnect = Value(74)

  /** Set to explicitly forbid the upcoming transfer's connection to be re-used when done. Do not use this unless you're
    * absolutely sure of this, as it makes the operation slower and is less friendly for the network.
    */
  val ForbidReuse = Value(75)

  /** Set to a file name that contains random data for libcurl to use to seed the random engine when doing SSL connects.
    */
  val RandomFile = Value(10000 + 76)

  /** Set to the Entropy Gathering Daemon socket pathname */
  val EntropyGatheringDaemonSocket = Value(10000 + 77)

  /** Time-out connect operations after this amount of seconds, if connects are OK within this time, then fine... This
    * only aborts the connect phase.
    */
  val ConnectTimeout = Value(78)

  /** Function that will be called to store headers (instead of fwrite). The parameters will use fwrite() syntax, make
    * sure to follow them.
    */
  val HeaderFunction = Value(20000 + 79)

  /** Set this to force the HTTP request to get back to GET. Only really usable if POST, PUT or a custom request have
    * been used first.
    */
  val HttpGet = Value(80)

  /** Set if we should verify the Common name from the peer certificate in ssl handshake, set 1 to check existence, 2 to
    * ensure that it matches the provided hostname.
    */
  val SslVerifyHost = Value(81)

  /** Specify which file name to write all known cookies in after completed operation. Set file name to "-" (dash) to
    * make it go to stdout.
    */
  val CookieJar = Value(10000 + 82)

  /** Specify which SSL ciphers to use */
  val SslCipherList = Value(10000 + 83)

  /** Specify which HTTP version to use! This must be set to one of the CURL_HTTP_VERSION* enums set below.
    */
  val HttpVersion = Value(84)

  /** Specifically switch on or off the FTP engine's use of the EPSV command. By default, that one will always be
    * attempted before the more traditional PASV command.
    */
  val FtpUseEpsv = Value(85)

  /** type of the file keeping your SSL-certificate ("DER", "PEM", "ENG") */
  val Sslcerttype = Value(10000 + 86)

  /** name of the file keeping your private SSL-key */
  val Sslkey = Value(10000 + 87)

  /** type of the file keeping your private SSL-key ("DER", "PEM", "ENG") */
  val Sslkeytype = Value(10000 + 88)

  /** crypto engine for the SSL-sub system */
  val Sslengine = Value(10000 + 89)

  /** set the crypto engine for the SSL-sub system as default the param has no meaning...
    */
  val SslengineDefault = Value(90)

  /** DNS cache timeout */
  val DnsCacheTimeout = Value(92)

  /** send linked-list of pre-transfer QUOTE commands */
  val Prequote = Value(10000 + 93)

  /** set the debug function */
  val Debugfunction = Value(20000 + 94)

  /** set the data for the debug function */
  val Debugdata = Value(10000 + 95)

  /** mark this as start of a cookie session */
  val Cookiesession = Value(96)

  /** The CApath directory used to validate the peer certificate this option is used only if SSL_VERIFYPEER is true
    */
  val Capath = Value(10000 + 97)

  /** Instruct libcurl to use a smaller receive buffer */
  val Buffersize = Value(98)

  /** Instruct libcurl to not use any signal/alarm handlers, even when using timeouts. This option is useful for
    * multi-threaded applications. See libcurl-the-guide for more background information.
    */
  val Nosignal = Value(99)

  /** Provide a CURLShare for mutexing non-ts data */
  val Share = Value(10000 + 100)

  /** indicates type of proxy. accepted values are CURLPROXY_HTTP (default), CURLPROXY_HTTPS, CURLPROXY_SOCKS4,
    * CURLPROXY_SOCKS4A and CURLPROXY_SOCKS5.
    */
  val Proxytype = Value(101)

  /** Set the Accept-Encoding string. Use this to tell a server you would like the response to be compressed. Before
    * 7.21.6, this was known as CURLOPT_ENCODING
    */
  val AcceptEncoding = Value(10000 + 102)

  /** Set pointer to private data */
  val Private = Value(10000 + 103)

  /** Set aliases for HTTP 200 in the HTTP Response header */
  val Http200aliases = Value(10000 + 104)

  /** Continue to send authentication (user+password) when following locations, even when hostname changed. This can
    * potentially send off the name and password to whatever host the server decides.
    */
  val UnrestrictedAuth = Value(105)

  /** Specifically switch on or off the FTP engine's use of the EPRT command ( it also disables the LPRT attempt). By
    * default, those ones will always be attempted before the good old traditional PORT command.
    */
  val FtpUseEprt = Value(106)

  /** Set this to a bitmask value to enable the particular authentications methods you like. Use this in combination
    * with CURLOPT_USERPWD. Note that setting multiple bits may cause extra network round-trips.
    */
  val Httpauth = Value(107)

  /** Set the ssl context callback function, currently only for OpenSSL ssl_ctx in second argument. The function must be
    * matching the curl_ssl_ctx_callback proto.
    */
  val SslCtxFunction = Value(20000 + 108)

  /** Set the userdata for the ssl context callback function's third argument
    */
  val SslCtxData = Value(10000 + 109)

  /** FTP Option that causes missing dirs to be created on the remote server. In 7.19.4 we introduced the convenience
    * enums for this option using the CURLFTP_CREATE_DIR prefix.
    */
  val FtpCreateMissingDirs = Value(110)

  /** Set this to a bitmask value to enable the particular authentications methods you like. Use this in combination
    * with CURLOPT_PROXYUSERPWD. Note that setting multiple bits may cause extra network round-trips.
    */
  val Proxyauth = Value(111)

  /** FTP option that changes the timeout, in seconds, associated with getting a response. This is different from
    * transfer timeout time and essentially places a demand on the FTP server to acknowledge commands in a timely
    * manner.
    */
  val FtpResponseTimeout = Value(112)

  /** Set this option to one of the CURL_IPRESOLVE_* defines (see below) to tell libcurl to resolve names to those IP
    * versions only. This only has affect on systems with support for more than one, i.e IPv4 _and_ IPv6.
    */
  val Ipresolve = Value(113)

  /** Set this option to limit the size of a file that will be downloaded from an HTTP or FTP server. Note there is also
    * _LARGE version which adds large file support for platforms which have larger off_t sizes. See MAXFILESIZE_LARGE
    * below.
    */
  val Maxfilesize = Value(114)

  /** See the comment for INFILESIZE above, but in short, specifies the size of the file being uploaded. -1 means
    * unknown.
    */
  val InfilesizeLarge = Value(30000 + 115)

  /** Sets the continuation offset. There is also a LONG version of this; look above for RESUME_FROM.
    */
  val ResumeFromLarge = Value(30000 + 116)

  /** Sets the maximum size of data that will be downloaded from an HTTP or FTP server. See MAXFILESIZE above for the
    * LONG version.
    */
  val MaxfilesizeLarge = Value(30000 + 117)

  /** Set this option to the file name of your .netrc file you want libcurl to parse (using the CURLOPT_NETRC option).
    * If not set, libcurl will do a poor attempt to find the user's home directory and check for a .netrc file in there.
    */
  val NetrcFile = Value(10000 + 118)

  /** Enable SSL/TLS for FTP, pick one of: CURLUSESSL_TRY - try using SSL, proceed anyway otherwise CURLUSESSL_CONTROL -
    * SSL for the control connection or fail CURLUSESSL_ALL - SSL for all communication or fail
    */
  val UseSsl = Value(119)

  /** The _LARGE version of the standard POSTFIELDSIZE option */
  val PostfieldsizeLarge = Value(30000 + 120)

  /** Enable/disable the TCP Nagle algorithm */
  val TcpNoDelay = Value(121)

  /** When FTP over SSL/TLS is selected (with CURLOPT_USE_SSL), this option can be used to change libcurl's default
    * action which is to first try "AUTH SSL" and then "AUTH TLS" in this order, and proceed when a OK response has been
    * received. Available parameters are: CURLFTPAUTH_DEFAULT - let libcurl decide CURLFTPAUTH_SSL - try "AUTH SSL"
    * first, then TLS CURLFTPAUTH_TLS - try "AUTH TLS" first, then SSL
    */
  val Ftpsslauth = Value(129)

  val Ioctlfunction = Value(20000 + 130)
  val Ioctldata = Value(10000 + 131)

  /** zero terminated string for pass on to the FTP server when asked for "account" info
    */
  val FtpAccount = Value(10000 + 134)

  /** feed cookie into cookie engine */
  val Cookielist = Value(10000 + 135)

  /** ignore Content-Length */
  val IgnoreContentLength = Value(136)

  /** Set to non-zero to skip the IP address received in a 227 PASV FTP server response. Typically used for FTP-SSL
    * purposes but is not restricted to that. libcurl will then instead use the same IP address it used for the control
    * connection.
    */
  val FtpSkipPasvIp = Value(137)

  /** Select "file method" to use when doing FTP, see the curl_ftpmethod above.
    */
  val FtpFilemethod = Value(138)

  /** Local port number to bind the socket to */
  val LocalPort = Value(139)

  /** Number of ports to try, including the first one set with LOCALPORT. Thus, setting it to 1 will make no additional
    * attempts but the first.
    */
  val Localportrange = Value(140)

  /** no transfer, set up connection and let application use the socket by extracting it with CURLINFO_LASTSOCKET
    */
  val ConnectOnly = Value(141)

  /** Function that will be called to convert from the network encoding (instead of using the iconv calls in libcurl)
    */
  val ConvFromNetworkFunction = Value(20000 + 142)

  /** Function that will be called to convert to the network encoding (instead of using the iconv calls in libcurl)
    */
  val ConvToNetworkFunction = Value(20000 + 143)

  /** Function that will be called to convert from UTF8 (instead of using the iconv calls in libcurl) Note that this is
    * used only for SSL certificate processing
    */
  val ConvFromUtf8Function = Value(20000 + 144)

  /** if the connection proceeds too quickly then need to slow it down */
  /** limit-rate: maximum number of bytes per second to send or receive */
  val MaxSendSpeedLarge = Value(30000 + 145)
  val MaxRecvSpeedLarge = Value(30000 + 146)

  /** Pointer to command string to send if USER/PASS fails. */
  val FtpAlternativeToUser = Value(10000 + 147)

  /** callback function for setting socket options */
  val Sockoptfunction = Value(20000 + 148)
  val Sockoptdata = Value(10000 + 149)

  /** set to 0 to disable session ID re-use for this transfer, default is enabled (== 1)
    */
  val SslSessionidCache = Value(150)

  /** allowed SSH authentication methods */
  val SshAuthTypes = Value(151)

  /** Used by scp/sftp to do public/private key authentication */
  val SshPublicKeyfile = Value(10000 + 152)
  val SshPrivateKeyfile = Value(10000 + 153)

  /** Send CCC (Clear Command Channel) after authentication */
  val FtpSslCcc = Value(154)

  /** Same as TIMEOUT and CONNECTTIMEOUT, but with ms resolution */
  val TimeoutMs = Value(155)
  val ConnectTimeoutMs = Value(156)

  /** set to zero to disable the libcurl's decoding and thus pass the raw body data to the application even when it is
    * encoded/compressed
    */
  val HttpTransferDecoding = Value(157)
  val HttpContentDecoding = Value(158)

  /** Permission used when creating new files and directories on the remote server for protocols that support it,
    * SFTP/SCP/FILE
    */
  val NewFilePerms = Value(159)
  val NewDirectoryPerms = Value(160)

  /** Set the behaviour of POST when redirecting. Values must be set to one of CURL_REDIR* defines below. This used to
    * be called CURLOPT_POST301
    */
  val Postredir = Value(161)

  /** used by scp/sftp to verify the host's public key */
  val SshHostPublicKeyMd5 = Value(10000 + 162)

  /** Callback function for opening socket (instead of socket(2)). Optionally, callback is able change the address or
    * refuse to connect returning CURL_SOCKET_BAD. The callback should have type curl_opensocket_callback
    */
  val Opensocketfunction = Value(20000 + 163)
  val Opensocketdata = Value(10000 + 164)

  /** POST volatile input fields. */
  val Copypostfields = Value(10000 + 165)

  /** set transfer mode (;type=<a|i>) when doing FTP via an HTTP proxy */
  val ProxyTransferMode = Value(166)

  /** Callback function for seeking in the input stream */
  val Seekfunction = Value(20000 + 167)
  val Seekdata = Value(10000 + 168)

  /** CRL file */
  val Crlfile = Value(10000 + 169)

  /** Issuer certificate */
  val Issuercert = Value(10000 + 170)

  /** (IPv6) Address scope */
  val AddressScope = Value(171)

  /** Collect certificate chain info and allow it to get retrievable with CURLINFO_CERTINFO after the transfer is
    * complete.
    */
  val Certinfo = Value(172)

  /** "name" and "pwd" to use when fetching. */
  val Username = Value(10000 + 173)
  val Password = Value(10000 + 174)

  /** "name" and "pwd" to use with Proxy when fetching. */
  val Proxyusername = Value(10000 + 175)
  val Proxypassword = Value(10000 + 176)

  /** Comma separated list of hostnames defining no-proxy zones. These should match both hostnames directly, and
    * hostnames within a domain. For example, local.com will match local.com and www.local.com, but NOT notlocal.com or
    * www.notlocal.com. For compatibility with other implementations of this, .local.com will be considered to be the
    * same as local.com. A single * is the only valid wildcard, and effectively disables the use of proxy.
    */
  val Noproxy = Value(10000 + 177)

  /** block size for TFTP transfers */
  val TftpBlksize = Value(178)

  /** Socks Service */
  val Socks5GssapiNec = Value(180)

  /** set the bitmask for the protocols that are allowed to be used for the transfer, which thus helps the app which
    * takes URLs from users or other external inputs and want to restrict what protocol(s) to deal with. Defaults to
    * CURLPROTO_ALL.
    */
  val Protocols = Value(181)

  /** set the bitmask for the protocols that libcurl is allowed to follow to, as a subset of the CURLOPT_PROTOCOLS ones.
    * That means the protocol needs to be set in both bitmasks to be allowed to get redirected to. Defaults to all
    * protocols except FILE and SCP.
    */
  val RedirProtocols = Value(182)

  /** set the SSH knownhost file name to use */
  val SshKnownhosts = Value(10000 + 183)

  /** set the SSH host key callback, must point to a curl_sshkeycallback function
    */
  val SshKeyfunction = Value(20000 + 184)

  /** set the SSH host key callback custom pointer */
  val SshKeydata = Value(10000 + 185)

  /** set the SMTP mail originator */
  val MailFrom = Value(10000 + 186)

  /** set the list of SMTP mail receiver(s) */
  val MailRcpt = Value(10000 + 187)

  /** FTP: send PRET before PASV */
  val FtpUsePret = Value(188)

  /** RTSP request method (OPTIONS, SETUP, PLAY, etc...) */
  val RtspRequest = Value(189)

  /** The RTSP session identifier */
  val RtspSessionId = Value(10000 + 190)

  /** The RTSP stream URI */
  val RtspStreamUri = Value(10000 + 191)

  /** The Transport: header to use in RTSP requests */
  val RtspTransport = Value(10000 + 192)

  /** Manually initialize the client RTSP CSeq for this handle */
  val RtspClientCseq = Value(193)

  /** Manually initialize the server RTSP CSeq for this handle */
  val RtspServerCseq = Value(194)

  /** The stream to pass to INTERLEAVEFUNCTION. */
  val Interleavedata = Value(10000 + 195)

  /** Let the application define a custom write method for RTP data */
  val Interleavefunction = Value(20000 + 196)

  /** Turn on wildcard matching */
  val Wildcardmatch = Value(197)

  /** Directory matching callback called before downloading of an individual file (chunk) started
    */
  val ChunkBgnFunction = Value(20000 + 198)

  /** Directory matching callback called after the file (chunk) was downloaded, or skipped
    */
  val ChunkEndFunction = Value(20000 + 199)

  /** Change match (fnmatch-like) callback for wildcard matching */
  val FnmatchFunction = Value(20000 + 200)

  /** Let the application define custom chunk data pointer */
  val ChunkData = Value(10000 + 201)

  /** FNMATCH_FUNCTION user pointer */
  val FnmatchData = Value(10000 + 202)

  /** send linked-list of name:port:address sets */
  val Resolve = Value(10000 + 203)

  /** Set a username for authenticated TLS */
  val TlsauthUsername = Value(10000 + 204)

  /** Set a password for authenticated TLS */
  val TlsauthPassword = Value(10000 + 205)

  /** Set authentication type for authenticated TLS */
  val TlsauthType = Value(10000 + 206)

  /** Set to 1 to enable the "TE:" header in HTTP requests to ask for compressed transfer-encoded responses. Set to 0 to
    * disable the use of TE: in outgoing requests. The current default is 0, but it might change in a future libcurl
    * release. libcurl will ask for the compressed methods it knows of, and if that isn't any, it will not ask for
    * transfer-encoding at all even if this option is set to 1.
    */
  val TransferEncoding = Value(207)

  /** Callback function for closing socket (instead of close(2)). The callback should have type
    * curl_closesocket_callback
    */
  val Closesocketfunction = Value(20000 + 208)
  val Closesocketdata = Value(10000 + 209)

  /** allow GSSAPI credential delegation */
  val GssapiDelegation = Value(210)

  /** Set the name servers to use for DNS resolution */
  val DnsServers = Value(10000 + 211)

  /** Time-out accept operations (currently for FTP only) after this amount of milliseconds.
    */
  val AccepttimeoutMs = Value(212)

  /** Set TCP keepalive */
  val TcpKeepalive = Value(213)

  /** non-universal keepalive knobs (Linux, AIX, HP-UX, more) */
  val TcpKeepidle = Value(214)
  val TcpKeepintvl = Value(215)

  /** Enable/disable specific SSL features with a bitmask, see CURLSSLOPT_* */
  val SslOptions = Value(216)

  /** Set the SMTP auth originator */
  val MailAuth = Value(10000 + 217)

  /** Enable/disable SASL initial response */
  val SaslIr = Value(218)

  /** Function that will be called instead of the internal progress display function. This function should be defined as
    * the curl_xferinfo_callback prototype defines. (Deprecates CURLOPT_PROGRESSFUNCTION)
    */
  val Xferinfofunction = Value(20000 + 219)

  /** The XOAUTH2 bearer token */
  val Xoauth2Bearer = Value(10000 + 220)

  /** Set the interface string to use as outgoing network interface for DNS requests. Only supported by the c-ares DNS
    * backend
    */
  val DnsInterface = Value(10000 + 221)

  /** Set the local IPv4 address to use for outgoing DNS requests. Only supported by the c-ares DNS backend
    */
  val DnsLocalIp4 = Value(10000 + 222)

  /** Set the local IPv6 address to use for outgoing DNS requests. Only supported by the c-ares DNS backend
    */
  val DnsLocalIp6 = Value(10000 + 223)

  /** Set authentication options directly */
  val LoginOptions = Value(10000 + 224)

  /** Enable/disable TLS NPN extension (http2 over ssl might fail without) */
  val SslEnableNpn = Value(225)

  /** Enable/disable TLS ALPN extension (http2 over ssl might fail without) */
  val SslEnableAlpn = Value(226)

  /** Time to wait for a response to a HTTP request containing an Expect: 100-continue header before sending the data
    * anyway.
    */
  val Expect_100TimeoutMs = Value(227)

  /** This points to a linked list of headers used for proxy requests only, struct curl_slist kind
    */
  val Proxyheader = Value(10000 + 228)

  /** Pass in a bitmask of "header options" */
  val Headeropt = Value(229)

  /** The public key in DER form used to validate the peer public key this option is used only if SSL_VERIFYPEER is true
    */
  val Pinnedpublickey = Value(10000 + 230)

  /** Path to Unix domain socket */
  val UnixSocketPath = Value(10000 + 231)

  /** Set if we should verify the certificate status. */
  val SslVerifystatus = Value(232)

  /** Set if we should enable TLS false start. */
  val SslFalsestart = Value(233)

  /** Do not squash dot-dot sequences */
  val PathAsIs = Value(234)

  /** Proxy Service Name */
  val ProxyServiceName = Value(10000 + 235)

  /** Service Name */
  val ServiceName = Value(10000 + 236)

  /** Wait/don't wait for pipe/mutex to clarify */
  val Pipewait = Value(237)

  /** Set the protocol used when curl is given a URL without a protocol */
  val DefaultProtocol = Value(10000 + 238)

  /** Set stream weight, 1 - 256 (default is 16) */
  val StreamWeight = Value(239)

  /** Set stream dependency on another CURL handle */
  val StreamDepends = Value(10000 + 240)

  /** Set E-xclusive stream dependency on another CURL handle */
  val StreamDependsE = Value(10000 + 241)

  /** Do not send any tftp option requests to the server */
  val TftpNoOptions = Value(242)

  /** Linked-list of host:port:connect-to-host:connect-to-port, overrides the URL's host:port (only for the network
    * layer)
    */
  val ConnectTo = Value(10000 + 243)

  /** Set TCP Fast Open */
  val TcpFastopen = Value(244)

  /** Continue to send data if the server responds early with an HTTP status code >= 300
    */
  val KeepSendingOnError = Value(245)

  /** The CApath or CAfile used to validate the proxy certificate this option is used only if PROXY_SSL_VERIFYPEER is
    * true
    */
  val ProxyCainfo = Value(10000 + 246)

  /** The CApath directory used to validate the proxy certificate this option is used only if PROXY_SSL_VERIFYPEER is
    * true
    */
  val ProxyCapath = Value(10000 + 247)

  /** Set if we should verify the proxy in ssl handshake, set 1 to verify.
    */
  val ProxySslVerifypeer = Value(248)

  /** Set if we should verify the Common name from the proxy certificate in ssl handshake, set 1 to check existence, 2
    * to ensure that it matches the provided hostname.
    */
  val ProxySslVerifyhost = Value(249)

  /** What version to specifically try to use for proxy. See CURL_SSLVERSION defines below.
    */
  val ProxySslversion = Value(250)

  /** Set a username for authenticated TLS for proxy */
  val ProxyTlsauthUsername = Value(10000 + 251)

  /** Set a password for authenticated TLS for proxy */
  val ProxyTlsauthPassword = Value(10000 + 252)

  /** Set authentication type for authenticated TLS for proxy */
  val ProxyTlsauthType = Value(10000 + 253)

  /** name of the file keeping your private SSL-certificate for proxy */
  val ProxySslcert = Value(10000 + 254)

  /** type of the file keeping your SSL-certificate ("DER", "PEM", "ENG") for proxy
    */
  val ProxySslcerttype = Value(10000 + 255)

  /** name of the file keeping your private SSL-key for proxy */
  val ProxySslkey = Value(10000 + 256)

  /** type of the file keeping your private SSL-key ("DER", "PEM", "ENG") for proxy
    */
  val ProxySslkeytype = Value(10000 + 257)

  /** password for the SSL private key for proxy */
  val ProxyKeypasswd = Value(10000 + 258)

  /** Specify which SSL ciphers to use for proxy */
  val ProxySslCipherList = Value(10000 + 259)

  /** CRL file for proxy */
  val ProxyCrlfile = Value(10000 + 260)

  /** Enable/disable specific SSL features with a bitmask for proxy, see CURLSSLOPT_*
    */
  val ProxySslOptions = Value(261)

  /** Name of pre proxy to use. */
  val PreProxy = Value(10000 + 262)

  /** The public key in DER form used to validate the proxy public key this option is used only if PROXY_SSL_VERIFYPEER
    * is true
    */
  val ProxyPinnedpublickey = Value(10000 + 263)

  /** Path to an abstract Unix domain socket */
  val AbstractUnixSocket = Value(10000 + 264)

  /** Suppress proxy CONNECT response headers from user callbacks */
  val SuppressConnectHeaders = Value(265)

  /** The request target, instead of extracted from the URL */
  val RequestTarget = Value(10000 + 266)

  /** bitmask of allowed auth methods for connections to SOCKS5 proxies */
  val Socks5Auth = Value(267)

  /** Enable/disable SSH compression */
  val SshCompression = Value(268)

  /** Post MIME data. */
  val Mimepost = Value(10000 + 269)

  /** Time to use with the CURLOPT_TIMECONDITION. Specified in number of seconds since 1 Jan 1970.
    */
  val TimevalueLarge = Value(30000 + 270)

  /** Head start in milliseconds to give happy eyeballs. */
  val HappyEyeballsTimeoutMs = Value(271)

  /** Function that will be called before a resolver request is made */
  val ResolverStartFunction = Value(20000 + 272)

  /** User data to pass to the resolver start callback. */
  val ResolverStartData = Value(10000 + 273)

  /** send HAProxy PROXY protocol header? */
  val Haproxyprotocol = Value(274)

  /** shuffle addresses before use when DNS returns multiple */
  val DnsShuffleAddresses = Value(275)

  /** Specify which TLS 1.3 ciphers suites to use */
  val Tls13Ciphers = Value(10000 + 276)

  val ProxyTls13Ciphers = Value(10000 + 277)
}


text:
import os
from setuptools import find_packages
from setuptools import setup

version = '1.0.dev0'
shortdesc = "Checkout"
longdesc = open(os.path.join(os.path.dirname(__file__), 'README.rst')).read()
longdesc += open(os.path.join(os.path.dirname(__file__), 'CHANGES.rst')).read()
longdesc += open(os.path.join(os.path.dirname(__file__), 'LICENSE.rst')).read()

setup(
    name='bda.plone.checkout',
    version=version,
    description=shortdesc,
    long_description=longdesc,
    classifiers=[
        'Environment :: Web Environment',
        'License :: OSI Approved :: GNU General Public License (GPL)',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
    ],
    author='BlueDynamics Alliance',
    author_email='dev@bluedynamics.com',
    license='GNU General Public Licence',
    packages=find_packages('src'),
    package_dir={'': 'src'},
    namespace_packages=['bda', 'bda.plone'],
    include_package_data=True,
    zip_safe=False,
    install_requires=[
        'setuptools',
        'Plone',
        'bda.plone.cart',
        'bda.plone.payment',
        'pycountry',
        'yafowil.plone',
    ],
    extras_require={
        'test': [
            'plone.app.testing',
        ]
    },
    entry_points="""
    [z3c.autoinclude.plugin]
    target = plone
    """,
)

redpajama_set_name: RedPajamaGithub


text:
package com.sun.tools.example.debug.bdi;

public interface InputListener {
    String getLine();
}


text:
using LibExpat

filename = ARGS[1]

node_ids = Set{String}()
used_node_ids = Set{String}()

cbs = XPCallbacks()
cbs.start_element = function (handler::XPStreamHandler, name::String, attrs::Dict{String,String})
    if name == "edge"
        push!(used_node_ids, attrs["source"])
        push!(used_node_ids, attrs["target"])
    end

    if name == "node"
        push!(node_ids, attrs["id"])
    end
end

xp_streaming_parsefile(filename, cbs)

unused_nodes = setdiff(node_ids, used_node_ids)
@printf("Removing %d vertices\n", length(unused_nodes))

mv(filename, string(filename,"-tmp"))
infile = open(string(filename,"-tmp"), "r")
outfile = open(filename, "w")

node_re = r"\<node id=\"([^\"]*)\""

while !eof(infile)
    line = readline(infile)

    # We are exploiting the fact that we know how the generated XML looks like
    m = match(node_re, line)
    if m != nothing
        id = m.captures[1]
        if in(id, unused_nodes)
            continue
        end
    end

    write(outfile, line)
end

close(infile)
close(outfile)
rm(string(filename,"-tmp"))


text:
namespace Quoteversation.Web.Areas.Administration.ViewModels
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.Linq;
    using System.Web;

    using Quoteversation.Models;
    using Quoteversation.Web.Infrastructure.Mapping;

    public class PostQuoteViewModel : IMapFrom<PostContentQuote>, IHaveCustomMappings
    {
        public int Id { get; set; }

        public string QuoteText { get; set; }

        public string QuoteAuthor { get; set; }

        public bool IsApproved { get; set; }

        public bool IsDeleted { get; set; }

        public string UploaderName { get; set; }

        public DateTime CreatedOn { get; set; }

        public DateTime? ModifiedOn { get; set; }

        public void CreateMappings(AutoMapper.IConfiguration configuration)
        {
            configuration.CreateMap<PostContentQuote, PostQuoteViewModel>()
                .ForMember(q => q.UploaderName, opt => opt.MapFrom(m => m.Uploader.UserName));
        }
    }
}


text:
/* eslint-disable */

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';

class App extends Component {
  render() {
    return (

Future Bank

            <form id="search" action="" method="post">

                <input type="submit" className="submit" value=""/>
                <input type="text" className="input"/>

            </form>

Home

About

Projects

Contacts

Sitemap

              Welcome to the Bank of Future
              read more

More Website Templates at TemplateMonster.com!

Company History

Lorem ipsum doloamet consect etuer adipiscing.

Our Capabilities

Sed ut perspiciatis unde omnis iste naturror voluptatem.

Where We Deliver

Nam libero tempore cum soluta nobis est eligendi optio.

Operations Consulting

Temporibus autem quibusdam et aut officiis.

Take the best business deal

                    Smart Biz Template is one of free website templates created by Templates.com team. This website template is optimized for 1024X768 screen resolution. It is also XHTML & CSS valid.

This Free Business Website Template goes with two packages – with PSD source files and without them. PSD source files are available for free for the registered members of Templates.com. The basic package (without PSD is available for anyone without registration).

This website template has several pages: Home, About, Projects, Contacts (note that contact us form – doesn't work), Sitemap.

At vero eos et accusamus iusto

Odio dignissimos ducimus

Blanditiis praesentium voluptatum

Deleniti atque corrupti quos dolores

Sint occaecati cuditate nongd

Provident similque suxpin culpa qui

Officia deserunt mollitia animidt

Etharum quidem rerum facili

Latest projects

Sed peraspiciatis unde omnis iste natus eraror sit voluptatem accusantium doloremque.

Laudantiuam totam aperiam, eaque ipsa quaae ab illo inventore veritatais quasi.

Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit sed.

          Website template designed by TemplateMonster.com

          3D Models provided by Templates.com

    );
  }
}

export default App;


text:
Scripts to setup a new Mac from scratch.

## Command Line Tools

It installs:

* Homebrew
* Homebrew Cask
* Chef (which it then uses to manage config files)
* Java
* Go
* NGrok
* JQ
* Mutt
* Terraform
* DockUtil (cli for managing dock icons)
* Docker Toolbox

## Applications

Installs them via Homebrew Cask and adds them to the Dock (except Robomongo):

* Google Chrome
* Atom
* Intellij Community Edition
* Atlassian SourceTree
* Slack
* Robomongo

Additionally, it adds the following Apple apps to the dock:

* Mail
* Calendar
* Notes
* Reminders
* Terminal
* System Preferences

## OSX Preferences

The mac-preferences script sets up a number of OS X tweaks (showing hidden files, dock size etc.). See the in-line comments for more details.


text:
<!DOCTYPE html>

<TITLE>Manpage of IFCFG</TITLE>
<meta charset="utf-8">
<link rel="stylesheet" href="/css/main.css" type="text/css">

linux manpages

{"type":"documentation"}

IFCFG

Section: Linux (8)
Updated: September 24 2009
Index
Return to Main Contents

NAME

ifcfg - simplistic script which replaces ifconfig IP managment

SYNOPSIS

ifcfg

[ DEVICE [ :ALIAS: ] ] [ command ] ADDRESS [ LENGTH ] [ PEER ]

DESCRIPTION

This manual page documents briefly the
ifcfg

command.

This is a simplistic script replacing one option of
ifconfig

, namely, IP address management. It not only adds
addresses, but also carries out Duplicate Address Detection RFC-DHCP,
sends unsolicited ARP to update the caches of other hosts sharing
the interface, adds some control routes and restarts Router Discovery
when it is necessary.

I strongly recommend using it
instead

of
ifconfig

both on hosts and on routers.

IFCONFIG - COMMAND SYNTAX

DEVICE

- it may have alias, suffix, separated by colon.

command

- add, delete or stop.

address

- optionally followed by prefix length.

peer

- optional peer address for pointpoint interfaces.

EXAMPLE

This function determines, whether this is router or host.
It returns 0, if the host is apparently not router.

SEE ALSO

ip-cref.dvi

Index

NAME

SYNOPSIS

DESCRIPTION

IFCONFIG - COMMAND SYNTAX

DEVICE

EXAMPLE

SEE ALSO

This document was created by
man2html,
using the manual pages.

Time: 05:34:26 GMT, December 24, 2015


text:
class NewMapState :
        public StiGame::Gui::GuiState,
        public StiGame::EventListener
{
public:
    static const int BTN_WIDTH = 200;
    static const int BTN_HEIGHT = 25;

    NewMapState();
    virtual ~NewMapState();
    void onResize(int m_width, int m_height);
    bool handleEvent(StiGame::EventThrower *src, StiGame::EventArgs *evt);
    void unload(void);
protected:
    void initComponents(void);
    int mapWidth;
    int mapHeight;
    std::vector<MapSizeVO*> mapSizes;
    StiGame::Gui::Label lblSizes;
    StiGame::Gui::List listSizes;
    StiGame::Gui::Label lblTitle;
    StiGame::Gui::Button btnBack;
    StiGame::Gui::Button btnCreate;
};

#endif // NEWMAPSTATE_H


text:
package org.foxbpm.engine.task;

public class TaskType {

	/**
	 * foxbpm流程引擎产生的任务
	 */
	public static final String FOXBPMTASK="foxbpmtask";

	/**
	 * foxbpm产生的通知型任务
	 */
	public static final String NOTICETASK="noticetask";

	/**
	 * 调用节点状态记录
	 */
	public static final String CALLACTIVITYTASK="callactivitytask";

	/**
	 * 启动任务
	 */
	public static final String STARTEVENTTASK="starteventtask";

	/**
	 * 提醒
	 */
	public static final String REMINDTASK="remindtask";

	/**
	 * 结束任务
	 */
	public static final String ENDEVENTTASK="endeventtask";

	/**
	 * 捕获型任务记录
	 */
	public static final String INTERMEDIATECATCHEVENT="intermediatecatchevent";

	/**
	 * 等待任务
	 */
	public static final String RECEIVETASK="receivetask";

	/**
	 * 其他流程引擎产生的任务
	 */
	public static final String OTHERFLOWTASK="otherflowtask";

	/**
	 * 其他系统产生的通知型任务
	 */
	public static final String OTHERNOTICETASK="othernoticetask";

}


text:
FOUNDATION_EXPORT double SimpleDataKitVersionNumber;
FOUNDATION_EXPORT const unsigned char SimpleDataKitVersionString[];


text:
package cat.contesencatala.client.place;

public class NameTokens {

	public static final String about = "/about";
	public static final String reader = "/reader";
	public static final String talelist = "/talelist";
	public static final String error = "/error";

	// General Pages
	public static final String home = "/home";
	public static final String login = "/login";

	public static String getAbout() {
		return about;
	}

}


text:
.chart-legend {
  display: inline-block;
  padding: 0;
  width: auto !important; }
  .chart-legend .legend-title {
    white-space: nowrap;
    overflow: hidden;
    margin-left: 10px;
    margin-bottom: 5px;
    font-size: 14px;
    font-weight: bold; }
  .chart-legend ul, .chart-legend li {
    padding: 0;
    margin: 0;
    list-style: none; }
  .chart-legend .horizontal-legend li {
    display: inline-block; }
  .chart-legend .legend-wrap {
    width: calc(100% - 10px); }
  .chart-legend .legend-labels {
    line-height: 85%;
    list-style: none;
    text-align: left;
    float: left;
    width: 100%;
    border-radius: 3px;
    overflow-y: auto;
    overflow-x: hidden;
    white-space: nowrap;
    background: rgba(0, 0, 0, 0.05); }
  .chart-legend .legend-label {
    cursor: pointer;
    font-size: 90%;
    margin: 8px;
    color: #AFB7C8; }
    .chart-legend .legend-label:hover {
      color: #000;
      -webkit-transition: 0.2s;
      -moz-transition: 0.2s;
      transition: 0.2s; }
    .chart-legend .legend-label .active .legend-label-text {
      color: #000; }
  .chart-legend .legend-label-color {
    display: inline-block;
    height: 15px;
    width: 15px;
    margin-right: 5px;
    color: #5b646b;
    border-radius: 3px; }
  .chart-legend .legend-label-text {
    display: inline-block;
    vertical-align: top;
    line-height: 15px;
    font-size: 12px;
    width: calc(100% - 20px);
    text-overflow: ellipsis;
    white-space: nowrap;
    overflow: hidden; }
  .chart-legend .legend-title-text {
    vertical-align: bottom;
    display: inline-block;
    line-height: 16px;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis; }


text:
<?php

/**
 * A collection of dashboard panels with a specific layout.
 */
final class PhabricatorDashboard extends PhabricatorDashboardDAO
  implements
    PhabricatorApplicationTransactionInterface,
    PhabricatorPolicyInterface,
    PhabricatorFlaggableInterface,
    PhabricatorDestructibleInterface,
    PhabricatorProjectInterface,
    PhabricatorNgramsInterface {

  protected $name;
  protected $authorPHID;
  protected $viewPolicy;
  protected $editPolicy;
  protected $status;
  protected $icon;
  protected $layoutConfig = array();

  const STATUS_ACTIVE = 'active';
  const STATUS_ARCHIVED = 'archived';

  private $panelPHIDs = self::ATTACHABLE;
  private $panels = self::ATTACHABLE;
  private $edgeProjectPHIDs = self::ATTACHABLE;

  public static function initializeNewDashboard(PhabricatorUser $actor) {
    return id(new PhabricatorDashboard())
      ->setName('')
      ->setIcon('fa-dashboard')
      ->setViewPolicy(PhabricatorPolicies::getMostOpenPolicy())
      ->setEditPolicy($actor->getPHID())
      ->setStatus(self::STATUS_ACTIVE)
      ->setAuthorPHID($actor->getPHID())
      ->attachPanels(array())
      ->attachPanelPHIDs(array());
  }

  public static function getStatusNameMap() {
    return array(
      self::STATUS_ACTIVE => pht('Active'),
      self::STATUS_ARCHIVED => pht('Archived'),
    );
  }

  protected function getConfiguration() {
    return array(
      self::CONFIG_AUX_PHID => true,
      self::CONFIG_SERIALIZATION => array(
        'layoutConfig' => self::SERIALIZATION_JSON,
      ),
      self::CONFIG_COLUMN_SCHEMA => array(
        'name' => 'sort255',
        'status' => 'text32',
        'icon' => 'text32',
        'authorPHID' => 'phid',
      ),
    ) + parent::getConfiguration();
  }

  public function generatePHID() {
    return PhabricatorPHID::generateNewPHID(
      PhabricatorDashboardDashboardPHIDType::TYPECONST);
  }

  public function getLayoutConfigObject() {
    return PhabricatorDashboardLayoutConfig::newFromDictionary(
      $this->getLayoutConfig());
  }

  public function setLayoutConfigFromObject(
    PhabricatorDashboardLayoutConfig $object) {

    $this->setLayoutConfig($object->toDictionary());

    // See PHI385. Dashboard panel mutations rely on changes to the Dashboard
    // object persisting when transactions are applied, but this assumption is
    // no longer valid after T13054. For now, just save the dashboard
    // explicitly.
    $this->save();

    return $this;
  }

  public function getProjectPHIDs() {
    return $this->assertAttached($this->edgeProjectPHIDs);
  }

  public function attachProjectPHIDs(array $phids) {
    $this->edgeProjectPHIDs = $phids;
    return $this;
  }

  public function attachPanelPHIDs(array $phids) {
    $this->panelPHIDs = $phids;
    return $this;
  }

  public function getPanelPHIDs() {
    return $this->assertAttached($this->panelPHIDs);
  }

  public function attachPanels(array $panels) {
    assert_instances_of($panels, 'PhabricatorDashboardPanel');
    $this->panels = $panels;
    return $this;
  }

  public function getPanels() {
    return $this->assertAttached($this->panels);
  }

  public function isArchived() {
    return ($this->getStatus() == self::STATUS_ARCHIVED);
  }

  public function getViewURI() {
    return '/dashboard/view/'.$this->getID().'/';
  }

/* -(  PhabricatorApplicationTransactionInterface  )------------------------- */

  public function getApplicationTransactionEditor() {
    return new PhabricatorDashboardTransactionEditor();
  }

  public function getApplicationTransactionObject() {
    return $this;
  }

  public function getApplicationTransactionTemplate() {
    return new PhabricatorDashboardTransaction();
  }

  public function willRenderTimeline(
    PhabricatorApplicationTransactionView $timeline,
    AphrontRequest $request) {

    return $timeline;
  }

/* -(  PhabricatorPolicyInterface  )----------------------------------------- */

  public function getCapabilities() {
    return array(
      PhabricatorPolicyCapability::CAN_VIEW,
      PhabricatorPolicyCapability::CAN_EDIT,
    );
  }

  public function getPolicy($capability) {
    switch ($capability) {
      case PhabricatorPolicyCapability::CAN_VIEW:
        return $this->getViewPolicy();
      case PhabricatorPolicyCapability::CAN_EDIT:
        return $this->getEditPolicy();
    }
  }

  public function hasAutomaticCapability($capability, PhabricatorUser $viewer) {
    return false;
  }

/* -(  PhabricatorDestructibleInterface  )----------------------------------- */

  public function destroyObjectPermanently(
    PhabricatorDestructionEngine $engine) {

    $this->openTransaction();
      $installs = id(new PhabricatorDashboardInstall())->loadAllWhere(
        'dashboardPHID = %s',
        $this->getPHID());
      foreach ($installs as $install) {
        $install->delete();
      }

      $this->delete();
    $this->saveTransaction();
  }

/* -(  PhabricatorNgramInterface  )------------------------------------------ */

  public function newNgrams() {
    return array(
      id(new PhabricatorDashboardNgrams())
        ->setValue($this->getName()),
    );
  }

}


text:
package com.hp.hpl.jena.rdf.arp.states;

import com.hp.hpl.jena.rdf.arp.impl.ANode;

public interface HasSubjectFrameI extends FrameI {
  void aPredAndObj(ANode p, ANode o);

  /**
   * Create a triple r rdf:subj * .
   * The structure of the parser means that three triples
   * in the quad are produced by the property element code,
   * but the final triple is produced by its parent.
   * @param r The node that is the reification.
   */
  void makeSubjectReificationWith(ANode r);
}


text:
package org.jetbrains.plugins.scala.lang.psi.api.expr

import com.intellij.openapi.progress.ProgressManager
import com.intellij.psi._
import org.jetbrains.plugins.scala.ScalaBundle
import org.jetbrains.plugins.scala.extensions.{ElementText, PsiElementExt, PsiNamedElementExt, StringExt}
import org.jetbrains.plugins.scala.lang.psi.{ElementScope, ScalaPsiElement, ScalaPsiUtil}
import org.jetbrains.plugins.scala.lang.psi.ScalaPsiUtil.{MethodValue, isAnonymousExpression}
import org.jetbrains.plugins.scala.lang.psi.api.{ImplicitParametersOwner, InferUtil}
import org.jetbrains.plugins.scala.lang.psi.api.InferUtil.{SafeCheckException, extractImplicitParameterType}
import org.jetbrains.plugins.scala.lang.psi.api.base.types.ScTypeElement
import org.jetbrains.plugins.scala.lang.psi.api.base.{ScIntLiteral, ScLiteral}
import org.jetbrains.plugins.scala.lang.psi.api.toplevel.imports.usages.ImportUsed
import org.jetbrains.plugins.scala.lang.psi.impl.ScalaPsiElementFactory.createExpressionFromText
import org.jetbrains.plugins.scala.lang.psi.implicits.{ImplicitCollector, ImplicitResolveResult, ScImplicitlyConvertible}
import org.jetbrains.plugins.scala.lang.psi.types.api._
import org.jetbrains.plugins.scala.lang.psi.types.api.designator.ScDesignatorType
import org.jetbrains.plugins.scala.lang.psi.types.nonvalue.{Parameter, ScMethodType, ScTypePolymorphicType}
import org.jetbrains.plugins.scala.lang.psi.types.result._
import org.jetbrains.plugins.scala.lang.psi.types.{api, _}
import org.jetbrains.plugins.scala.lang.resolve.processor.MethodResolveProcessor
import org.jetbrains.plugins.scala.lang.resolve.{ScalaResolveResult, StdKinds}
import org.jetbrains.plugins.scala.macroAnnotations.{CachedWithRecursionGuard, ModCount}
import org.jetbrains.plugins.scala.project.ProjectPsiElementExt
import org.jetbrains.plugins.scala.project.ScalaLanguageLevel.Scala_2_11

import scala.annotation.tailrec
import scala.collection.mutable.ArrayBuffer
import scala.collection.{Seq, Set}

/**
  * @author ilyas, Alexander Podkhalyuzin
  */

trait ScExpression extends ScBlockStatement with PsiAnnotationMemberValue with ImplicitParametersOwner
  with ScModificationTrackerOwner with Typeable {

  import org.jetbrains.plugins.scala.lang.psi.api.expr.ScExpression._

  override def `type`(): TypeResult =
    this.getTypeAfterImplicitConversion().tr

  @volatile
  private var implicitParameters: Option[Seq[ScalaResolveResult]] = None

  @volatile
  private var implicitParametersFromUnder: Option[Seq[ScalaResolveResult]] = None

  final protected def setImplicitParameters(results: Option[Seq[ScalaResolveResult]],
                                            fromUnderscore: Boolean = ScUnderScoreSectionUtil.isUnderscoreFunction(this)): Unit = {
    if (fromUnderscore)
      implicitParametersFromUnder = results
    else
      implicitParameters = results
  }

  /**
    * Warning! There is a hack in scala compiler for ClassManifest and ClassTag.
    * In case of implicit parameter with type ClassManifest[T]
    * this method will return ClassManifest with substitutor of type T.
    *
    * @return implicit parameters used for this expression
    */
  def findImplicitParameters: Option[Seq[ScalaResolveResult]] = {
    ProgressManager.checkCanceled()

    if (ScUnderScoreSectionUtil.isUnderscoreFunction(this)) {
      this.getTypeWithoutImplicits(fromUnderscore = true) //to update implicitParametersFromUnder
      implicitParametersFromUnder
    } else {
      `type`() //to update implicitParameters field
      implicitParameters
    }
  }

  protected def innerType: TypeResult =
    Failure(ScalaBundle.message("no.type.inferred", getText))

  /**
    * Some expression may be replaced only with another one
    */
  def replaceExpression(expr: ScExpression, removeParenthesis: Boolean): ScExpression = {
    val oldParent = getParent
    if (oldParent == null) throw new PsiInvalidElementAccessException(this)
    if (removeParenthesis && oldParent.isInstanceOf[ScParenthesisedExpr]) {
      return oldParent.asInstanceOf[ScExpression].replaceExpression(expr, removeParenthesis = true)
    }
    val newExpr = if (ScalaPsiUtil.needParentheses(this, expr)) {
      createExpressionFromText(expr.getText.parenthesize(needParenthesis = true))
    } else expr
    val parentNode = oldParent.getNode
    val newNode = newExpr.copy.getNode
    parentNode.replaceChild(this.getNode, newNode)
    newNode.getPsi.asInstanceOf[ScExpression]
  }

  @volatile
  private var additionalExpression: Option[(ScExpression, ScType)] = None

  def setAdditionalExpression(additionalExpression: Option[(ScExpression, ScType)]) {
    this.additionalExpression = additionalExpression
  }

  /**
    * This method should be used to get implicit conversions and used imports, while eta expanded method return was
    * implicitly converted
    *
    * @return mirror for this expression, in case if it exists
    */
  def getAdditionalExpression: Option[(ScExpression, ScType)] = {
    `type`()
    additionalExpression
  }

  def implicitElement(fromUnderscore: Boolean = false,
                      expectedOption: => Option[ScType] = this.smartExpectedType()): Option[PsiNamedElement] = {
    implicitConversion(fromUnderscore, expectedOption).map(_.element)
  }

  def implicitConversion(fromUnderscore: Boolean = false,
                         expectedOption: => Option[ScType] = this.smartExpectedType()): Option[ScalaResolveResult] = {

    def conversionForReference(reference: ScReferenceExpression) = reference.multiResolve(false) match {
      case Array(result: ScalaResolveResult) => result.implicitConversion
      case _ => None
    }

    def inner(element: ScalaPsiElement): Option[ScalaResolveResult] = element.getParent match {
      case reference: ScReferenceExpression =>
        conversionForReference(reference)
      case infix: ScInfixExpr if this == infix.getBaseExpr =>
        conversionForReference(infix.operation)
      case call: ScMethodCall => call.getImplicitFunction
      case generator: ScGenerator => inner(generator)
      case _ =>
        this.getTypeAfterImplicitConversion(expectedOption = expectedOption, fromUnderscore = fromUnderscore).implicitConversion
    }

    inner(this)
  }

  def getAllImplicitConversions(fromUnderscore: Boolean = false): Seq[PsiNamedElement] = {
    new ScImplicitlyConvertible(this, fromUnderscore)
      .implicitMap(arguments = this.expectedTypes(fromUnderscore).toSeq)
      .map(_.element)
      .sortWith {
        case (first, second) =>
          val firstName = first.name
          val secondName = second.name

          def isAnyTo(string: String): Boolean =
            string.matches("^[a|A]ny(2|To|to).+$")

          val isSecondAnyTo = isAnyTo(secondName)

          if (isAnyTo(firstName) ^ isSecondAnyTo) isSecondAnyTo
          else firstName.compareTo(secondName) < 0
      }
  }

  final def calculateReturns(withBooleanInfix: Boolean = false): Seq[PsiElement] = {
    val res = new ArrayBuffer[PsiElement]

    def calculateReturns0(el: PsiElement) {
      el match {
        case tr: ScTryStmt =>
          calculateReturns0(tr.tryBlock)
          tr.catchBlock match {
            case Some(ScCatchBlock(caseCl)) =>
              caseCl.caseClauses.flatMap(_.expr).foreach(calculateReturns0)
            case _ =>
          }
        case block: ScBlock =>
          block.lastExpr match {
            case Some(expr) => calculateReturns0(expr)
            case _ => res += block
          }
        case pe: ScParenthesisedExpr =>
          pe.expr.foreach(calculateReturns0)
        case m: ScMatchStmt =>
          m.getBranches.foreach(calculateReturns0)
        case i: ScIfStmt =>
          i.elseBranch match {
            case Some(e) =>
              calculateReturns0(e)
              i.thenBranch match {
                case Some(thenBranch) => calculateReturns0(thenBranch)
                case _ =>
              }
            case _ => res += i
          }
        case ScInfixExpr(left, ElementText(op), right)
          if withBooleanInfix && (op == "&&" || op == "||") &&
            left.`type`().exists(_ == api.Boolean) &&
            right.`type`().exists(_ == api.Boolean) => calculateReturns0(right)
        //TODO "!contains" is a quick fix, function needs unit testing to validate its behavior
        case _ => if (!res.contains(el)) res += el
      }
    }

    calculateReturns0(this)
    res
  }
}

object ScExpression {

  case class ExpressionTypeResult(tr: TypeResult,
                                  importsUsed: scala.collection.Set[ImportUsed] = Set.empty,
                                  implicitConversion: Option[ScalaResolveResult] = None) {
    def implicitFunction: Option[PsiNamedElement] = implicitConversion.map(_.element)
  }

  object Type {
    def unapply(exp: ScExpression): Option[ScType] = exp.`type`().toOption
  }

  implicit class Ext(val expr: ScExpression) extends AnyVal {
    private implicit def elementScope: ElementScope = expr.elementScope
    private def project = elementScope.projectContext

    def expectedType(fromUnderscore: Boolean = true): Option[ScType] =
      expectedTypeEx(fromUnderscore).map(_._1)

    def expectedTypeEx(fromUnderscore: Boolean = true): Option[(ScType, Option[ScTypeElement])] =
      ExpectedTypes.expectedExprType(expr, fromUnderscore)

    def expectedTypes(fromUnderscore: Boolean = true): Array[ScType] = expectedTypesEx(fromUnderscore).map(_._1)

    @CachedWithRecursionGuard(expr, Array.empty[(ScType, Option[ScTypeElement])], ModCount.getBlockModificationCount)
    def expectedTypesEx(fromUnderscore: Boolean = true): Array[(ScType, Option[ScTypeElement])] = {
      ExpectedTypes.expectedExprTypes(expr, fromUnderscore = fromUnderscore)
    }

    @CachedWithRecursionGuard(expr, None, ModCount.getBlockModificationCount)
    def smartExpectedType(fromUnderscore: Boolean = true): Option[ScType] = ExpectedTypes.smartExpectedType(expr, fromUnderscore)

    def getTypeIgnoreBaseType: TypeResult = getTypeAfterImplicitConversion(ignoreBaseTypes = true).tr

    @CachedWithRecursionGuard(expr, Failure("Recursive getNonValueType"), ModCount.getBlockModificationCount)
    def getNonValueType(ignoreBaseType: Boolean = false,
                        fromUnderscore: Boolean = false): TypeResult = {
      ProgressManager.checkCanceled()
      if (fromUnderscore) expr.innerType
      else {
        val unders = ScUnderScoreSectionUtil.underscores(expr)
        if (unders.isEmpty) expr.innerType
        else {
          val params = unders.zipWithIndex.map {
            case (u, index) =>
              val tpe = u.getNonValueType(ignoreBaseType).getOrAny.inferValueType.unpackedType
              Parameter(tpe, isRepeated = false, index = index)
          }
          val methType =
            ScMethodType(expr.getTypeAfterImplicitConversion(ignoreBaseTypes = ignoreBaseType,
              fromUnderscore = true).tr.getOrAny,
              params, isImplicit = false)
          Right(methType)
        }
      }
    }

    /**
      * This method returns real type, after using implicit conversions.
      * Second parameter to return is used imports for this conversion.
      *
      * @param expectedOption  to which type we trying to convert
      * @param ignoreBaseTypes parameter to avoid value discarding, literal narrowing, widening
      *                        this parameter is useful for refactorings (introduce variable)
      */
    @CachedWithRecursionGuard(expr, ExpressionTypeResult(Failure("Recursive getTypeAfterImplicitConversion")), ModCount.getBlockModificationCount)
    def getTypeAfterImplicitConversion(checkImplicits: Boolean = true,
                                       isShape: Boolean = false,
                                       expectedOption: Option[ScType] = None,
                                       ignoreBaseTypes: Boolean = false,
                                       fromUnderscore: Boolean = false): ExpressionTypeResult = {

      def isJavaReflectPolymorphic = ScalaPsiUtil.isJavaReflectPolymorphicSignature(expr)

      val expected = expectedOption.orElse {
        expectedType(fromUnderscore = fromUnderscore)
      }

      if (isShape) ExpressionTypeResult(Right(shape(expr).getOrElse(Nothing)))
      else {
        val tr = getTypeWithoutImplicits(ignoreBaseTypes, fromUnderscore)
        (expected, tr.toOption) match {
          case (Some(expType), Some(tp))
            if checkImplicits && !tp.conforms(expType) => //do not try implicit conversions for shape check or already correct type

            val samType = tryConvertToSAM(fromUnderscore, expType, tp)

            if (samType.nonEmpty) samType.get
            else if (isJavaReflectPolymorphic) ExpressionTypeResult(Right(expType))
            else {
              val functionType = FunctionType(expType, Seq(tp))
              val implicitCollector = new ImplicitCollector(expr, functionType, functionType, None, isImplicitConversion = true)
              val fromImplicit = implicitCollector.collect() match {
                case Seq(res) =>
                  val `type` = extractImplicitParameterType(res).flatMap {
                    case FunctionType(rt, Seq(_)) => Some(rt)
                    case paramType =>
                      expr.elementScope.cachedFunction1Type.flatMap { functionType =>
                        val (_, substitutor) = paramType.conforms(functionType, ScUndefinedSubstitutor())
                        substitutor.getSubstitutor.map {
                          _.subst(functionType.typeArguments(1))
                        }.filter {
                          !_.isInstanceOf[UndefinedType]
                        }
                      }
                  }

                  `type`.map((_, res))
                case _ => None
              }
              fromImplicit match {
                case Some((mr, result)) =>
                  ExpressionTypeResult(Right(mr), result.importsUsed, Some(result))
                case _ =>
                  ExpressionTypeResult(tr)
              }
            }
          case _ => ExpressionTypeResult(tr)
        }
      }
    }

    @CachedWithRecursionGuard(expr, Failure("Recursive getTypeWithoutImplicits"),
      ModCount.getBlockModificationCount)
    def getTypeWithoutImplicits(ignoreBaseTypes: Boolean = false, fromUnderscore: Boolean = false): TypeResult = {
      ProgressManager.checkCanceled()
      val fromNullLiteral = expr match {
        case lit: ScLiteral =>
          val typeForNull = lit.getTypeForNullWithoutImplicits
          if (typeForNull.nonEmpty) Option(Right(typeForNull.get))
          else None
        case _ => None
      }

      if (fromNullLiteral.nonEmpty) fromNullLiteral.get
      else {
        val inner = expr.getNonValueType(ignoreBaseTypes, fromUnderscore)
        inner match {
          case Right(rtp) =>
            var res = rtp

            val expType = expectedType(fromUnderscore)

            def updateExpected(oldRes: ScType): ScType = {
              try {
                val updatedWithExpected =
                  InferUtil.updateAccordingToExpectedType(Right(rtp), fromImplicitParameters = true,
                    filterTypeParams = false, expectedType = expType, expr = expr, canThrowSCE = true)
                updatedWithExpected match {
                  case Right(newRes) =>
                    updateWithImplicitParameters(newRes, checkExpectedType = true, fromUnderscore)
                  case _ =>
                    updateWithImplicitParameters(oldRes, checkExpectedType = true, fromUnderscore)
                }
              } catch {
                case _: SafeCheckException =>
                  updateWithImplicitParameters(oldRes, checkExpectedType = false, fromUnderscore)
              }
            }

            if (!isMethodInvocation(expr)) {
              //it is not updated according to expected type, let's do it
              res = updateExpected(rtp)
            }

            def removeMethodType(retType: ScType, updateType: ScType => ScType = t => t) {
              expType match {
                case Some(expected) =>
                  expected.removeAbstracts match {
                    case FunctionType(_, _) =>
                    case expect if ScalaPsiUtil.isSAMEnabled(expr) =>
                      if (ScalaPsiUtil.toSAMType(expect, expr).isEmpty) {
                        res = updateType(retType)
                      }
                    case _ => res = updateType(retType)
                  }
                case _ => res = updateType(retType)
              }
            }

            res match {
              case ScTypePolymorphicType(ScMethodType(retType, params, _), tp) if params.isEmpty &&
                !ScUnderScoreSectionUtil.isUnderscore(expr) =>
                removeMethodType(retType, t => ScTypePolymorphicType(t, tp))
              case ScMethodType(retType, params, _) if params.isEmpty &&
                !ScUnderScoreSectionUtil.isUnderscore(expr) =>
                removeMethodType(retType)
              case _ =>
            }

            val valType = res.inferValueType.unpackedType

            if (ignoreBaseTypes) Right(valType)
            else {
              expType match {
                case None =>
                  Right(valType)
                case Some(expected) if expected.removeAbstracts equiv Unit =>
                  //value discarding
                  Right(Unit)
                case Some(expected) =>
                  val narrowing = isNarrowing(expected)
                  if (narrowing.isDefined) narrowing.get
                  else {
                    val widening = isWidening(valType, expected)
                    if (widening.isDefined) widening.get
                    else Right(valType)
                  }
              }
            }
          case _ => inner
        }
      }
    }

    @CachedWithRecursionGuard(expr, Array.empty[ScalaResolveResult], ModCount.getBlockModificationCount)
    def applyShapeResolveForExpectedType(tp: ScType, exprs: Seq[ScExpression], call: Option[MethodInvocation]): Array[ScalaResolveResult] = {
      val applyProc =
        new MethodResolveProcessor(expr, "apply", List(exprs), Seq.empty, Seq.empty /* todo: ? */ ,
          StdKinds.methodsOnly, isShapeResolve = true)
      applyProc.processType(tp, expr)
      var cand = applyProc.candidates
      if (cand.length == 0 && call.isDefined) {
        val expr = call.get.getEffectiveInvokedExpr
        ScalaPsiUtil.findImplicitConversion(expr, "apply", expr, applyProc, noImplicitsForArgs = false, Some(tp)).foreach { result =>
          val builder = new ImplicitResolveResult.ResolverStateBuilder(result).withImplicitFunction
          applyProc.processType(result.typeWithDependentSubstitutor, expr, builder.state)
          cand = applyProc.candidates
        }
      }
      if (cand.length == 0 && ScalaPsiUtil.approveDynamic(tp, expr.getProject, expr.resolveScope) && call.isDefined) {
        cand = ScalaPsiUtil.processTypeForUpdateOrApplyCandidates(call.get, tp, isShape = true, isDynamic = true)
      }
      cand
    }

    //has side effect!
    private def updateWithImplicitParameters(tpe: ScType, checkExpectedType: Boolean, fromUnderscore: Boolean): ScType = {
      val (newType, params) = updatedWithImplicitParameters(tpe, checkExpectedType)

      expr.setImplicitParameters(params, fromUnderscore)

      newType
    }

    def updatedWithImplicitParameters(tpe: ScType, checkExpectedType: Boolean): (ScType, Option[Seq[ScalaResolveResult]]) = {
      val checkImplicitParameters = ScalaPsiUtil.withEtaExpansion(expr)
      if (checkImplicitParameters)
        InferUtil.updateTypeWithImplicitParameters(tpe, expr, None, checkExpectedType, fullInfo = false)
      else (tpe, None)
    }

    //numeric literal narrowing
    def isNarrowing(expected: ScType): Option[TypeResult] = {
      import expr.projectContext

      def isByte(v: Long)  = v >= scala.Byte.MinValue  && v <= scala.Byte.MaxValue
      def isChar(v: Long)  = v >= scala.Char.MinValue  && v <= scala.Char.MaxValue
      def isShort(v: Long) = v >= scala.Short.MinValue && v <= scala.Short.MaxValue

      def success(t: ScType) = Some(Right(t))

      val intLiteralValue: Int = expr match {
        case ScIntLiteral(value) => value
        case ScPrefixExpr(op, ScIntLiteral(value)) if Set("+", "-").contains(op.refName) =>
          val mult = if (op.refName == "-") -1 else 1
          mult * value
        case _ => return None
      }

      val stdTypes = StdTypes.instance
      import stdTypes._

      expected.removeAbstracts match {
        case Char  if isChar(intLiteralValue)  => success(Char)
        case Byte  if isByte(intLiteralValue)  => success(Byte)
        case Short if isShort(intLiteralValue) => success(Short)
        case _ => None
      }
    }

    //numeric widening
    private def isWidening(valueType: ScType, expected: ScType): Option[TypeResult] = {
      val (l, r) = (getStdType(valueType), getStdType(expected)) match {
        case (Some(left), Some(right)) => (left, right)
        case _ => return None
      }
      val stdTypes = project.stdTypes
      import stdTypes._

      (l, r) match {
        case (Byte, Short | Int | Long | Float | Double) => Some(Right(expected))
        case (Short, Int | Long | Float | Double) => Some(Right(expected))
        case (Char, Byte | Short | Int | Long | Float | Double) => Some(Right(expected))
        case (Int, Long | Float | Double) => Some(Right(expected))
        case (Long, Float | Double) => Some(Right(expected))
        case (Float, Double) => Some(Right(expected))
        case _ => None
      }
    }

    private def getStdType(t: ScType): Option[StdType] = {
      val stdTypes = project.stdTypes
      import stdTypes._

      t match {
        case AnyVal => Some(AnyVal)
        case valType: ValType => Some(valType)
        case designatorType: ScDesignatorType => designatorType.getValType
        case _ => None
      }
    }

    @tailrec
    private def isMethodInvocation(expr: ScExpression): Boolean = {
      expr match {
        case _: ScPrefixExpr => false
        case _: ScPostfixExpr => false
        case _: MethodInvocation => true
        case p: ScParenthesisedExpr =>
          p.expr match {
            case Some(exp) => isMethodInvocation(exp)
            case _ => false
          }
        case _ => false
      }
    }

    private def tryConvertToSAM(fromUnderscore: Boolean, expected: ScType, tp: ScType) = {
      def checkForSAM(etaExpansionHappened: Boolean = false): Option[ExpressionTypeResult] = {
        def expectedResult = Some(ExpressionTypeResult(Right(expected)))

        tp match {
          case FunctionType(_, params) if ScalaPsiUtil.isSAMEnabled(expr) =>
            ScalaPsiUtil.toSAMType(expected, expr) match {
              case Some(methodType) if tp.conforms(methodType) => expectedResult
              case Some(methodType@FunctionType(retTp, _)) if etaExpansionHappened && retTp.equiv(Unit) =>
                val newTp = FunctionType(Unit, params)
                if (newTp.conforms(methodType)) expectedResult
                else None
              case _ => None
            }
          case _ => None
        }
      }

      expr match {
        case ScFunctionExpr(_, _) if fromUnderscore => checkForSAM()
        case _ if !fromUnderscore && ScalaPsiUtil.isAnonExpression(expr) => checkForSAM()
        case MethodValue(method) if method.getParameterList.getParametersCount > 0 =>
          checkForSAM(etaExpansionHappened = true)
        case _ => None
      }
    }

    private def removeMethodType(tp: ScType, expected: ScType): ScType = {
      def inner(retType: ScType, updateType: ScType => ScType): ScType = {
        expected.removeAbstracts match {
          case FunctionType(_, _) => tp
          case expect if ScalaPsiUtil.isSAMEnabled(expr) =>
            if (ScalaPsiUtil.toSAMType(expect, expr).isEmpty) {
              updateType(retType)
            }
            else tp
          case _ => updateType(retType)
        }
      }

      tp match {
        case ScTypePolymorphicType(ScMethodType(retType, params, _), typeParams) if params.isEmpty &&
          !ScUnderScoreSectionUtil.isUnderscore(expr) =>
          inner(retType, t => ScTypePolymorphicType(t, typeParams))
        case ScMethodType(retType, params, _) if params.isEmpty &&
          !ScUnderScoreSectionUtil.isUnderscore(expr) =>
          inner(retType, t => t)
        case _ => tp
      }
    }
  }

  private def shape(expression: ScExpression, ignoreAssign: Boolean = false): Option[ScType] = {
    import expression.projectContext

    def shapeIgnoringAssign(maybeExpression: Option[ScExpression]) = maybeExpression.flatMap {
      shape(_, ignoreAssign = true)
    }

    expression match {
      case assign: ScAssignStmt if !ignoreAssign && assign.assignName.isDefined =>
        shapeIgnoringAssign(assign.getRExpression)
      case _ =>
        val arityAndResultType = Option(isAnonymousExpression(expression)).filter {
          case (-1, _) => false
          case _ => true
        }.map {
          case (i, expr: ScFunctionExpr) => (i, shapeIgnoringAssign(expr.result))
          case (i, _) => (i, None)
        }

        arityAndResultType.map {
          case (i, tp) => (Seq.fill(i)(Any), tp)
        }.map {
          case (argumentsTypes, maybeResultType) =>
            FunctionType(maybeResultType.getOrElse(Nothing), argumentsTypes)(expression.elementScope)
        }
    }
  }
}

object ExpectedType {
  def unapply(e: ScExpression): Option[ScType] = e.expectedType()
}

object NonValueType {
  def unapply(e: ScExpression): Option[ScType] = e.getNonValueType().toOption
}


text: wget -r --no-parent --convert-links http://designshack.net/tutorialexamples/bootstrap/


text:
module Kitchen
  module Salt
    module States
      private

      def prepare_state_top
        info('Preparing state_top')

        sandbox_state_top_path = File.join(sandbox_path, config[:salt_state_top])

        if config[:state_top_from_file] == false
          # use the top.sls embedded in .kitchen.yml

          # we get a hash with all the keys converted to symbols, salt doesn't like this
          # to convert all the keys back to strings again
          state_top_content = unsymbolize(config[:state_top]).to_yaml
          # .to_yaml will produce ! '*' for a key, Salt doesn't like this either
          state_top_content.gsub!(/(!\s'\*')/, "'*'")
        else
          # load a top.sls from disk
          if config[:local_salt_root].nil?
            top_file = 'top.sls'
            unless config[:state_collection].nil?
              top_file = File.join(config[:state_collection], top_file)
            end
          else
            top_file = File.join(config[:local_salt_root], 'salt/top.sls')
          end
          state_top_content = File.read(top_file)
        end

        write_raw_file(sandbox_state_top_path, state_top_content)
      end

      def prepare_states
        if config[:state_collection] || config[:is_file_root] || !config[:local_salt_root].nil?
          prepare_state_collection
        elsif config[:remote_states]
          prepare_remote_states
        else
          prepare_formula config[:kitchen_root], config[:formula]
          prepare_vendor_states
        end
      end

      def prepare_vendor_states
        vendor_path = config[:vendor_path]

        unless vendor_path.nil?
          if Pathname.new(vendor_path).exist?
            Dir[File.join(vendor_path, '*')].each do |d|
              prepare_formula vendor_path, File.basename(d)
            end
          else
            # :vendor_path was set, but not valid
            raise UserError, "kitchen-salt: Invalid vendor_path set: #{vendor_path}"
          end
        end
      end

      def prepare_formula_dir(path, subdir)
        src = File.join(path, subdir)

        if File.directory?(src)
          debug("prepare_formula_dir: #{src} exists, copying..")
          subdir_path = File.join(sandbox_path, config[:salt_file_root], subdir)
          FileUtils.mkdir_p(subdir_path)
          cp_r_with_filter(src, subdir_path, config[:salt_copy_filter])
        else
          debug("prepare_formula_dir: #{src} doesn't exist, skipping.")
        end
      end

      def prepare_formula(path, formula)
        info("Preparing formula: #{formula} from #{path}")
        debug("Using config #{config}")

        formula_dir = File.join(sandbox_path, config[:salt_file_root], formula)
        FileUtils.mkdir_p(formula_dir)
        cp_r_with_filter(File.join(path, formula), formula_dir, config[:salt_copy_filter])

        # copy across the _modules etc directories for python implementation
        %w(_modules _states _grains _renderers _returners _runners _utils).each do |extrapath|
          prepare_formula_dir(path, extrapath)
        end
      end

      def prepare_state_collection
        info('Preparing state collection')
        collection_name = config[:collection_name]
        formula = config[:formula]

        if collection_name.nil? && formula.nil?
          info('neither collection_name or formula have been set, assuming this is a pre-built collection')
          collection_name = ''
        elsif collection_name.nil?
          collection_name = formula
        end

        if config[:local_salt_root].nil?
          states_location = config[:kitchen_root]
          if config[:state_collection]
            states_location = File.join(states_location, config[:state_collection])
          end
        else
          states_location = File.join(config[:local_salt_root], 'salt')
        end
        collection_dir = File.join(sandbox_path, config[:salt_file_root], collection_name)
        FileUtils.mkdir_p(collection_dir)
        cp_r_with_filter(states_location, collection_dir, config[:salt_copy_filter])
      end

      def prepare_remote_states
        info('Preparing remote states')
        remoteconf = config[:remote_states]
        if remoteconf[:repo] == 'git'
          debug("Cloning #{remoteconf[:name]}")
          require 'git'
          repo = Git.clone(remoteconf[:name], File.join(sandbox_path, config[:salt_file_root]), opts={:branch => remoteconf[:branch]})
        end
        if remoteconf[:testingdir]
          dest = File.join(sandbox_path, remoteconf[:testingdir])
          FileUtils.mkdir_p(dest)
          cp_r_with_filter(config[:kitchen_root], dest, config[:salt_copy_filter])
        end
      end
    end
  end
end


text:
> Project Archived: The browsers are discontinuing the Appcache support so this library no longer needs to exist and users should move to a ServiceWorker architecture instead.

---

# gwt-appcache

[![Build Status](https://secure.travis-ci.org/realityforge/gwt-appcache.svg?branch=master)](http://travis-ci.org/realityforge/gwt-appcache)
[<img src="https://img.shields.io/maven-central/v/org.realityforge.gwt.appcache/gwt-appcache-client.svg?label=latest%20release"/>](https://search.maven.org/search?q=g:org.realityforge.gwt.appcache)

The HTML5 Appcache specification is a mechanism for enabling offline
HTML5 applications. This library provides a simple way to generate the
required cache manifests and serve a separate manifest for each separate
permutation. The library also provides support for the browser side aspects
of the appcache specification. See the appendix section includes further
references concerning the appcache spec.

## Quick Start

The simplest way to appcache enable a GWT application is to;

* add the following dependencies into the build system. i.e.

```xml
<dependency>
   <groupId>org.realityforge.gwt.appcache</groupId>
   <artifactId>gwt-appcache-client</artifactId>
   <version>1.0.12</version>
   <scope>provided</scope>
</dependency>
<dependency>
   <groupId>org.realityforge.gwt.appcache</groupId>
   <artifactId>gwt-appcache-linker</artifactId>
   <version>1.0.12</version>
   <scope>provided</scope>
</dependency>
<dependency>
   <groupId>org.realityforge.gwt.appcache</groupId>
   <artifactId>gwt-appcache-server</artifactId>
   <version>1.0.12</version>
</dependency>
```

* add the following snippet into the .gwt.xml file.

```xml
<module rename-to='myapp'>
  ...

  <!-- Enable the client-side library -->
  <inherits name="org.realityforge.gwt.appcache.Appcache"/>

  <!-- Enable the linker -->
  <inherits name="org.realityforge.gwt.appcache.linker.Linker"/>

  <!-- enable the linker that generates the manifest -->
  <add-linker name="appcache"/>

  <!-- configure all the static files not managed by the GWT compiler -->
  <extend-configuration-property name="appcache_static_files" value="./"/>
  <extend-configuration-property name="appcache_static_files" value="index.html"/>

  <!-- configure fallback rules used by the client when offline -->
  <extend-configuration-property name="appcache_fallback_files" value="online.png offline.png"/>
  <extend-configuration-property name="appcache_fallback_files" value="myDynamicService.jsp  myOfflineData.json"/>
</module>
```

* configure html that launches the application to look for the manifest.

```xml
<!doctype html>
<html manifest="myapp.appcache">
   ...
</html>
```

* declare the servlet that serves the manifest.

```java
@WebServlet( urlPatterns = { "/myapp.appcache" } )
public class ManifestServlet
  extends AbstractManifestServlet
{
  public ManifestServlet()
  {
    addPropertyProvider( new UserAgentPropertyProvider() );
  }
}
```

* interact with the application from within the browser.

```java
final ApplicationCache cache = ApplicationCache.getApplicationCacheIfSupported();
if ( null != cache )
{
  cache.addUpdateReadyHandler( new UpdateReadyEvent.Handler()
  {
    @Override
    public void onUpdateReadyEvent( @Nonnull final UpdateReadyEvent event )
    {
      //Force a cache update if new version is available
      cache.swapCache();
    }
  } );

  // Ask the browser to recheck the cache
  cache.requestUpdate();

  ...
```

This should be sufficient to get your application using the appcache. If you
load the application in a modern browser you should see it making use of the
cache in the console.

A very simple example of this code is available in the
[gwt-appcache-example](https://github.com/realityforge/gwt-appcache-example)
project.

## Quick Start with Elemental2

[Elemental2](https://github.com/google/elemental2) is Is a library from Google
that provides type checked access to all browser APIs for Java code. It is generated
from externs files and is a much more up to date library.

This is the recommended approach for modern applications. To use it you need to follow
the above quick start with the following modifications.

* Remove the `gwt-appcache-client` artifact from your build system.
* Remove `<inherits name="org.realityforge.gwt.appcache.Appcache"/>` from the .gwt.xml file.
* Interact with the applicationCache using Elemental2 APIs.

```java
import static elemental2.dom.DomGlobal.*;

...

if ( null != applicationCache )
{
  //Force a cache update if new version is available
  applicationCache.addEventListener( "updateready", e -> applicationCache.swapCache() );

  // Ask the browser to recheck the cache
  applicationCache.update();

  ...
```

## How does it work?

For every permutation generated by the GWT compiler, a separate manifest file
is generated. The manifest includes almost all public resources generated by
GWT with the exception of some used during debugging and development (i.e.
`myapp.devmode.js` and `compilation-mappings.txt`). The manifest also includes
any additional files declared using the "`appcache_static_files`" configuration
setting. (It should be noted that the "`appcache_static_files`" files are
relative to the manifest file).

After the GWT compiler has generated all the different permutations, a single
xml descriptor `permutations.xml` is generated that lists all the permutations
and the  deferred-binding properties that were used to uniquely identify the
permutations. Typically these include values of properties such as "`user.agent`".

If the compiler is using soft permutations then it is possible that multiple
deferred-binding properties will be served using a single permutation, in which
case the descriptor will have comma separated values in the `permutations.xml`
for that permutation.

The manifest servlet is then responsible for reading the `permutations.xml` and
inspecting the incoming request and generating properties that enable it to select
the correct permutation and thus the correct manifest file. The selected manifest
file is returned to the requester.

## How To: Define a new Selection Configuration

Sometimes it is useful to define a new configuration property in the gwt module
descriptors that will define new permutations. A fairly typical example would
be to define a configuration property that defines different view modalities.
i.e. Is the device phone-like, tablet-like or a desktop. This would drive the
ui and workflow in the application.

Step 1 is to define the configuration in the gwt module descriptor. i.e.

```xml
<define-property name="ui.modality" values="phone, tablet, desktop"/>
  <property-provider name="ui.modality"><![CDATA[
  {
    var ua = window.navigator.userAgent.toLowerCase();
    if ( ua.indexOf('android') != -1 ) { return 'phone'; }
    if ( ua.indexOf('iphone') != -1 ) { return 'phone'; }
    if ( ua.indexOf('ipad') != -1 ) { return 'tablet'; }
    return 'desktop';
  }
]]></property-provider>
```

Step 2 is to use the new configuration property to control the deferred binding
rules in gwt modules. For example, the following could be added to a .gwt.xml
module file;

```xml
<replace-with class="com.biz.client.gin.DesktopInjectorWrapper">
  <when-type-is class="com.biz.client.gin.InjectorWrapper"/>
  <when-property-is name="ui.modality" value="desktop"/>
</replace-with>

<replace-with class="com.biz.client.gin.TabletInjectorWrapper">
  <when-type-is class="com.biz.client.gin.InjectorWrapper"/>
  <when-property-is name="ui.modality" value="tablet"/>
</replace-with>

<replace-with class="com.biz.client.gin.PhoneInjectorWrapper">
  <when-type-is class="com.biz.client.gin.InjectorWrapper"/>
  <when-property-is name="ui.modality" value="phone"/>
</replace-with>
```

Step 3 is to define a property provider for your new configuration property and
add it to the manifest servlet. i.e.

```java
public class UIModalityPropertyProvider
  implements PropertyProvider
{
  @Override
  public String getPropertyValue( final HttpServletRequest request )
  {
    final String ua = request.getHeader( "User-Agent" ).toLowerCase();
    if ( ua.contains( "android" ) || ua.contains( "phone" ) ) { return "phone"; }
    else if ( ua.contains( "ipad" ) ) { return "tablet"; }
    else { return "desktop"; }
  }

  @Override
  public String getPropertyName()
  {
    return "ui.modality";
  }
}
```

```java
@WebServlet( urlPatterns = { "/myapp.appcache" } )
public class ManifestServlet
  extends AbstractManifestServlet
{
  public ManifestServlet()
  {
    addPropertyProvider( new UIModalityPropertyProvider() );
    addPropertyProvider( new UserAgentPropertyProvider() );
  }
}
```

This example demonstrates a simple mechanism for supporting server-side derivable
configuration properties to select a permutation. In some cases, the selection
property can only be determined on the client. This scenario is more complex and
requires a combination of cookies and dynamic host pages to address.

## How To: Define a new client-side selection Configuration

Sometimes configuration properties can only be determined on the client. A good
example is the device pixel density that can be determined by inspecting the
"window.devicePixelRatio" property in the browser.

```xml
<define-property name="pixel.density" values="high, low"/>
  <property-provider name="pixel.density"><![CDATA[
  {
  if(window.devicePixelRatio >= 2) { return 'high'; }
  return 'low';
  }
]]></property-provider>
```

The gwt-appcache library can defer the selection of the property to the client-side
by merging the manifests of the high and low density permutations and returning
the merged manifest to the client. This is done by marking the "pixel.density"
 property as client-side via;

```java
@WebServlet( urlPatterns = { "/myapp.appcache" } )
public class ManifestServlet
  extends AbstractManifestServlet
{
  public ManifestServlet()
  {
    addPropertyProvider( new UserAgentPropertyProvider() );
    ...
    addClientSideSelectionProperty( "pixel.density" );
  }
}
```

This will mean that the client ultimately caches extra data that may not be used
by the client. This may be acceptable for small applications but a better approach
is to detect the pixel density and set a cookie prior to navigating to the page
that hosts the application. The server can then attempt to determine the value of
the configuration property using the cookie name like;

```java
public class PixelDensityPropertyProvider
  implements PropertyProvider
{
  @Override
  public String getPropertyName() { return "pixel.density"; }

  @Override
  public String getPropertyValue( HttpServletRequest request )
  {
    final Cookie[] cookies = request.getCookies();
    if ( null != cookies )
    {
      for ( final Cookie cookie : cookies )
      {
        if ( "pixel.density".equals( cookie.getName() ) )
        {
          return cookie.getValue();
        }
      }
    }
    return null;
  }
}
```

```java
@WebServlet( urlPatterns = { "/myapp.appcache" } )
public class ManifestServlet
  extends AbstractManifestServlet
{
  public ManifestServlet()
  {
    addPropertyProvider( new UserAgentPropertyProvider() );
    addPropertyProvider( new PixelDensityPropertyProvider() );
    ...
    addClientSideSelectionProperty( "pixel.density" );
  }
}
```

## How To: Integrate into existing framework

The gwt-appcache library was designed to be easy to integrate into any other
gwt framework. A good example is the wonderful [MGWT](https://github.com/dankurka/mgwt)
library from which this project was initially derived. MGWT selects the permutation
based on the following configuration properties;

* `mgwt.os` - `iphone`, `iphone_retina`, `ipad`, `ipad_retina`, `android`, `android_tablet`, `blackberry` etc.
* `mobile.user.agent` - `mobilesafari` vs `not_mobile`.
* `user.agent` - A standard gwt configuration property.
* `phonegap.env` - Always `no` for web applications.

It is important to the MGWT framework to distinguish between retina and non-retina versions of
the iphone and ipad variants. The retina versions inspect the `window.devicePixelRatio` browser property
similarly to the above `pixel.density` example. Rather than making this a separate configuration
property, MGWT conflates this with operating system. As a result it uses a custom strategy to
merge the multiple permutations manifests as can be observed at [AbstractMgwtManifestServlet](https://github.com/realityforge/gwt-appcache/blob/master/server/src/main/java/org/realityforge/gwt/appcache/server/mgwt/AbstractMgwtManifestServlet.java#L15-L62).
MGWT also defines several [property providers](https://github.com/realityforge/gwt-appcache/tree/master/server/src/main/java/org/realityforge/gwt/appcache/server/mgwt).
There is a [pull request](https://github.com/dankurka/mgwt/pull/37) where you can look at the
work required to re-integrate the functionality back into the MGWT framework. This is a good
example of complex integration of `gwt-appcache`.

## How To: Configure the url for the Manifest servlet in web.xml

The above examples assume that annotations are used to configure the url for the manifest servlet. It
is also possible to explicitly configure the url pattern in web.xml via a snippet similar to the
following. This will configure the appcache manifest to be at the path "/somedir/example.appcache"
relative to the application root. The manifest servlet will expect to find the permutations.xml file
at the path "/somedir/example/permutations.xml" relative to the application root.

```xml
  <servlet>
    <servlet-name>org.realityforge.gwt.appcache.example.server.ManifestServlet</servlet-name>
  </servlet>

  <servlet-mapping>
    <servlet-name>org.realityforge.gwt.appcache.example.server.ManifestServlet</servlet-name>
    <url-pattern>/somedir/example.appcache</url-pattern>
  </servlet-mapping>
```

## Frequently Asked Questions

### Why do I get a 404 from the Manifest servlet when I specify a configuration property in .gwt.xml?

If you specify a configuration property in your .gwt.xml file such as below, the manifest servlet may
start returning a 404. Why is this and how do I fix it?

```xml
  <set-property name="user.agent" value="safari" />
```

The Manifest servlet uses the permutations.xml to determine how to select the permutation(s)
to serve. The properties generated by the PropertyProvider instances added to the manifest must
match the set of properties that are in the permutations.xml. If you add a property provider
that generates a property that is not present in permutations.xml then the manifest servlet will
never be able to find a permutation that matches that property and thus a 404 will be returned.

When you specified a single value for the user.agent property above, the user.agent configuration was
made into a constant and thus it could not be used to distinguish between permutations. As a result, the
property no longer appears in the permutations.xml file. At this point it is necessary to remove the
UserAgentPropertyProvider from the manifest servlet.

## Appendix

* [A Beginner's Guide to Using the Application Cache](http://www.html5rocks.com/en/tutorials/appcache/beginner/)
* [Appcache Facts](http://appcachefacts.info/)
* [Offline Web Application Standard](http://www.whatwg.org/specs/web-apps/current-work/multipage/offline.html)

## Credit

This library began as a enhancement of similar functionality in the
[MGWT](https://github.com/dankurka/mgwt) project by Daniel Kurka. All
credit goes to Daniel for the initial code and idea. The library is also
inspired by work done by the [rebar](https://github.com/bedatadriven/rebar)
project. Thanks goes out to them as well.


text:
layout: post
author: "Greg Wilson"
title: "A Project Inception Deck for Research Coding"
date: 2015-04-11
time: "18:00:00"
category: ["Opinion"]
---

  I've never seen the point of comparing programmers to ninjas or samurai,
  but the people who do so often have good ideas.
  One that I particularly like is
  the Agile Inception Deck
  from Jonathan Rasmusson's The Agile Samurai,
  which sets out a ten-step process for making sure that everyone involved in a new project
  is actually trying to build the same thing.
  The ten steps are:

    Why are we here?

    Create an elevator pitch.

    Design a product box.

    Create a NOT list.

    Meet your neighbors.

    Show the solution.

    Ask what keeps us up at night.

    Size it up.

    Be clear on what's going to give.

    Show what it's going to take.

  It's a good process,
  but some steps need to be translated to use it for research coding projects—for example,
  I think step #3 should be to design the project's first poster,
  and "see if someone has already built what you need" ought to be on the list as well.
  What would you change or replace, and why?


text:
/**
 * Module dependencies.
 */

var Emitter = require('emitter');
var render = require('render');
var events = require('events');
var empty = require('empty');
var filter = require('laws-filter');
var template = require('./filter-container');
var o = require('query');
var closest = require('closest');
var classes = require('classes');

function FilterView() {
  if (!(this instanceof FilterView)) {
    return new FilterView();
  };

  // Prep event handlers
  this.refresh = this.refresh.bind(this);

  this.build();
  this.switchOn();
}

Emitter(FilterView.prototype);

FilterView.prototype.build = function() {
  this.el = render.dom(template, { filter: filter });
};

FilterView.prototype.switchOn = function() {
  // View events
  this.events = events(this.el, this);
  this.events.bind('click #status-filter a.btn', 'onstatusclick');
  this.events.bind('click #sort-filter ul li', 'onsortclick');
  this.events.bind('click #hide-voted-filter input[name=hide-voted]', 'onhidevotedclick');

  // Behavior events
  filter.on('change', this.refresh);
}

FilterView.prototype.switchOff = function() {
  this.events.unbind();
  filter.off('change', this.refresh);
}

FilterView.prototype.refresh = function() {
  var old = this.el;
  this.switchOff();
  this.build();
  this.switchOn();
  if (old.parentNode) old.parentNode.replaceChild(this.el, old);
  old.remove();
  var obj = o('li[data-sort="closing-soon"]', this.el);
  if (filter.get('status') == 'closed') {
    classes(obj).add('hide');
    if (filter.get('sort') == 'closing-soon') filter.set('sort', 'newest-first');
  } else {
    classes(obj).remove('hide');
  }
};

FilterView.prototype.onstatusclick = function(ev) {
  ev.preventDefault();

  var target = ev.delegateTarget || closest(ev.target, '[data-status]', true);
  var status = target.getAttribute('data-status');

  filter.set('status', status);
}

FilterView.prototype.onsortclick = function(ev) {
  ev.preventDefault();

  var target = ev.delegateTarget || closest(ev.target, '[data-sort]', true);
  var sort = target.getAttribute('data-sort');

  filter.set('sort', sort);
}

FilterView.prototype.onhidevotedclick = function(ev) {
  ev.preventDefault();

  var target = ev.delegateTarget || closest(ev.target, '[type=checkbox]', true);
  var checked = !!target.checked;

  filter.set('hide-voted', checked);
}

FilterView.prototype.ready = function(fn) {
  filter.ready(fn);
  filter.ready(this.refresh);
}

FilterView.prototype.render = function(el) {
  if (1 === arguments.length) {

    // if string, then query element
    if ('string' === typeof el) {
      el = o(el);
    };

    // if it's not currently inserted
    // at `el`, then append to `el`
    if (el !== this.el.parentNode) {
      el.appendChild(this.el);
    };

    // !!!: Should we return different things
    // on different conditions?
    // Or should we be consistent with
    // render returning always `this.el`
    return this;
  };

  return this.el;
}

module.exports = new FilterView();


text:
node.default['monitor']['freemem']['warn']=500
node.default['monitor']['freemem']['critical']=250
node.default['monitor']['freedisk']['warning']='85%'
node.default['monitor']['freedisk']['critical']='95%'
default['monitor']['procs']['warn'] = 500
default['monitor']['procs']['critical'] = 800