answer
stringlengths
15
1.25M
require 'spec_helper' describe "Find the modulepath" do it 'using puppet agent --configprint' do file('/root/.bash_history').should contain "puppet agent --configprint modulepath" end end describe "The directory for the new users module" do it 'should be created' do file('/etc/puppetlabs/puppet/modules/users').should be_directory end end describe "The directories for manifests and tests" do it 'should be created' do file('/etc/puppetlabs/puppet/modules/users/manifests').should be_directory file('/etc/puppetlabs/puppet/modules/users/tests').should be_directory end end describe 'The manifest with the users class' do it 'should be created' do file('/etc/puppetlabs/puppet/modules/users/manifests/init.pp').should contain 'class users' end end describe 'The test manifest for the users class' do it 'should be created' do file('/etc/puppetlabs/puppet/modules/users/tests/init.pp').should contain 'include users' end end
#include <aws/workspaces/model/<API key>.h> #include <aws/core/utils/json/JsonSerializer.h> #include <aws/core/<API key>.h> #include <aws/core/utils/StringUtils.h> #include <aws/core/utils/UnreferencedParam.h> #include <utility> using namespace Aws::WorkSpaces::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; using namespace Aws; <API key>::<API key>() { } <API key>::<API key>(const Aws::<API key><JsonValue>& result) { *this = result; } <API key>& <API key>::operator =(const Aws::<API key><JsonValue>& result) { <API key>(result); return *this; }
package org.apereo.cas.ws.idp.metadata; import org.apereo.cas.configuration.<API key>; import org.apereo.cas.ws.idp.<API key>; import lombok.<API key>; import lombok.extern.slf4j.Slf4j; import lombok.val; import org.apache.wss4j.common.util.DOM2Writer; import org.springframework.http.MediaType; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * This is {@link <API key>}. * * @author Misagh Moayyed * @since 5.1.0 */ @Controller("<API key>") @Slf4j @<API key> public class <API key> { private final <API key> casProperties; /** * Get Metadata. * * @param request the request * @param response the response * @throws Exception the exception */ @GetMapping(path = <API key>.<API key>) public void doGet(final HttpServletRequest request, final HttpServletResponse response) throws Exception { try { response.setContentType(MediaType.TEXT_HTML_VALUE); val out = response.getWriter(); val mw = new <API key>(); val metadata = mw.<API key>(casProperties); out.write(DOM2Writer.nodeToString(metadata)); } catch (final Exception ex) { LOGGER.error("Failed to get metadata document", ex); response.sendError(HttpServletResponse.<API key>); } } }
<?xml version="1.0" encoding="UTF-8"?> <html xmlns="http: <style> * { font-family : helvetica;} .font33 { font-size : 33; } .font23 { font-size : 23; } .font40 { font-size : 40; } .font26 { font-size : 26; } .font43 { font-size : 43; } .font30 { font-size : 30; }</style> <body> <p> <span class="font43">RVFV </span> <span class="font43">Rift </span> <span class="font43">Valley </span> <span class="font40">fever </span> <span class="font33">Kedougou </span> <span class="font33">RVF </span> <span class="font30">RNA </span> <span class="font26">Senegal, </span> <span class="font26">surveillance </span> <span class="font23">Faye </span> <span class="font23">October </span> <span class="font23">acute </span> <span class="font23">blood </span> <span class="font23">febrile </span> <span class="font23">field </span> <span class="font23">human </span> <span class="font23">patient </span> <span class="font23">sampled </span> <span class="font23">samples </span> </p> </body> </html>
<html> <head> <script type="text/javascript" src="https://unpkg.com/pxt-blockly@2.1.12/blockly_compressed.js"></script> <script type="text/javascript" src="https://unpkg.com/pxt-blockly@2.1.12/blocks_compressed.js"></script> <script type="text/javascript" src="https://unpkg.com/pxt-blockly@2.1.12/msg/messages.js"></script> <script type="text/javascript" src="../../../playgrounds/screenshot.js"></script> </head> <body> <div id="blocklyDiv"></div> <script> Blockly.utils.userAgent.IE = true; var blocklyDiv = document.getElementById('blocklyDiv'); var workspace; window.addEventListener('message', function (msg) { var data = msg.data; if (data.type !== 'post') { return; } var xml = data.xml; try { if (workspace) { workspace.dispose(); blocklyDiv.innerHTML = ''; } } catch { } workspace = Blockly.inject(blocklyDiv, { move: { scrollbars: true, drag: true, wheel: false, }, zoom: { wheel: true, startScale: 2, } }); Blockly.Xml.domToWorkspace(Blockly.Xml.textToDom(xml), workspace); function postChange() { try { var topBlock = workspace.getTopBlocks()[0]; workspaceToSvg_(workspace, function (datauri) { window.parent.postMessage({ type: 'svg', from: 'pxtblockly', text: datauri }, '*'); }); } catch { } } workspace.addChangeListener(function(e) { if (e.type != 'ui') { postChange(); } }); postChange(); }); </script> </body> </html>
## Installation Quickstart [Scala 2.9](http: Install with `git clone https://github.com/twitter/zipkin.git && cd zipkin` or [download](https://github.com/twitter/zipkin/archive/master.zip) Zipkin to your preferred directory and unzip. Run (in separate bash windows): bin/collector bin/query bin/web Now you can access the Zipkin UI at http://localhost:8080/ Advanced Setup By default, Zipkin runs on SQLite because it doesn't require additional setup. However, Zipkin is typically used with other databases (most often Cassandra) in production. For a quickstart with Cassandra, see the [Ubuntu Quickstart](https://github.com/twitter/zipkin/blob/master/doc/ubuntu-quickstart.txt) and [Mac Quickstart](https://github.com/twitter/zipkin/blob/master/doc/mac-quickstart.md) guides. These will help you get a somewhat more advanced Zipkin installation running on a single machine so that you can experiment with it. For larger deployments, Zipkin works with several other services, and you may want to apply additional configuration. Some of those services and configurations are described below. Feeding trace data to Zipkin The next step after installation is to collect trace data to view in Zipkin. To do this, you must interface with the collector daemon to record trace data. There are several libraries to make this easier to do in different environments. Twitter uses [Finagle](https://github.com/twitter/finagle/tree/master/finagle-zipkin); external libraries (currently for Python, REST, node, and Java) are listed in the [wiki](https://github.com/twitter/zipkin/wiki#<API key>); and there is also a [Ruby gem](https://rubygems.org/gems/finagle-thrift) and [Ruby Thrift client](https://github.com/twitter/thrift_client). Running the Daemons with Other Databases The default Zipkin collector configuration is `<API key>/config/collector-dev.scala` and the default Zipkin query configuration is `<API key>/config/query-dev.scala`. These are set up to work with SQLite by default. To use Zipkin with a different SQL database, we recommend changing those configurations as described in the [SQL guide](https://github.com/twitter/zipkin/blob/master/doc/sql-databases.md). For NoSQL databases, you can pass the name of your preferred database to the collector and query daemons. For example, with Cassandra: bin/collector cassandra bin/query cassandra bin/web Storage: Cassandra Zipkin runs on SQLite by default to make it easier to test out of the box. Running Zipkin on SQLite requires no additional setup. However, in production, Zipkin is most commonly used with [Cassandra](http://cassandra.apache.org/) for the collector's storage. There are also plugins for [Redis](https://github.com/twitter/zipkin/blob/master/doc/redis.md), HBase, and [other SQL databases](https://github.com/twitter/zipkin/blob/master/doc/sql-databases.md). 1. See Cassandra's <a href="http://cassandra.apache.org/">site</a> for instructions on how to start a cluster. 2. Use the Zipkin Cassandra schema attached to this project. You can create the schema with the following command: `cassandra-cli -host localhost -port 9160 -f zipkin-cassandra/src/schema/cassandra-schema.txt` Coordination: ZooKeeper Zipkin can use ZooKeeper for coordination. That's where we store the server side sample rate and register the servers. 1. See ZooKeeper's <a href="http://zookeeper.apache.org/">site</a> for instructions on how to install it. Collecting Data: Scribe <a href="https://github.com/facebook/scribe">Scribe</a> is the logging framework we use at Twitter to transport the trace data. There are several other ways to tell Zipkin what trace data to collect; in particular, if you are just trying out Zipkin you can skip this step entirely and point the ZipkinTracer directly at the collector. To use Scribe with Zipkin, you need to set up a network store that points to the Zipkin collector daemon. A Scribe store for Zipkin might look something like this: <store> category=zipkin type=network remote_host=123.123.123.123 remote_port=9410 use_conn_pool=yes <API key>=50000 <API key>=12500 must_succeed=no </store> If you don't want to hardcode the IP address of your collector there are a few options. One is to use an internal DNS entry for the collectors so that you only have one place to change the addresses when you add or remove collectors. Alternatively, if you want to get all fancy you can use a [modified version of Scribe](https://github.com/traviscrawford/scribe) that picks up the collectors via ZooKeeper. When each collector starts up it adds itself to ZooKeeper and when a collector shuts down it is automatically removed. The modified Scribe gets notified when the set of collectors change. To use this mode you change `remote_host` in the configuration to `zk://zookeeper-hostname:2181/scribe/zipkin` or something similar. We're hoping that others might add non-Scribe transports for the tracing data; there is no reason why Scribe has to be the only one. Zipkin UI To develop on the ui start it with bin/web.sh To run zipkin ui on a server do sbt zipkin-web/package-dist cd zipkin-web/dist/zipkin-web java -cp libs/ -jar zipkin-web-1.2.0-SNAPSHOT.jar -zipkin.web.resourcesRoot=resources/ For a list of available options do java -cp libs/ -jar zipkin-web-1.2.0-SNAPSHOT.jar -h # zipkin-tracer gem The `zipkin-tracer` gem adds tracing to a Rails application through the use of a Rack Handler. In `config.ru`: ruby use ZipkinTracer::RackHandler run <YOUR_APPLICATION> If the application's static assets are served through Rails, those requests will be traced.
#ifndef <API key> #define <API key> #include "dirent.h" #include <errno.h> #include <stdlib.h> #include <string.h> #include <io.h> #ifdef __cplusplus extern "C" { #endif struct DIR { intptr_t hnd; struct _finddata_t fileinfo; long telldir; char *findstr; char end_of_stream; struct dirent *g_dirent; }; #ifdef __cplusplus } /*** extern "C" ***/ #endif #endif /*** <API key> ***/
test_run = require('test_run') inspector = test_run.new() engine = inspector:get_cfg('engine') iterations = 100000 math.randomseed(1) delete_insert(engine, iterations)
class Texshop < Cask version '3.45' sha256 '<SHA256-like>' url "http://pages.uoregon.edu/koch/texshop/texshop-64/texshop#{version.gsub('.','')}.zip" appcast 'http://pages.uoregon.edu/koch/texshop/texshop-64/texshopappcast.xml', :sha256 => '<SHA256-like>' homepage 'http://pages.uoregon.edu/koch/texshop' license :unknown app 'TexShop.app' end
class Bamtools < Formula desc "C++ API and command-line toolkit for BAM data" homepage "https://github.com/pezmaster31/bamtools" url "https://github.com/pezmaster31/bamtools/archive/v2.5.2.tar.gz" sha256 "<SHA256-like>" license "MIT" head "https://github.com/pezmaster31/bamtools.git" bottle do sha256 cellar: :any_skip_relocation, arm64_big_sur: "<SHA256-like>" sha256 cellar: :any_skip_relocation, big_sur: "<SHA256-like>" sha256 cellar: :any_skip_relocation, catalina: "<SHA256-like>" sha256 cellar: :any_skip_relocation, mojave: "<SHA256-like>" sha256 cellar: :any_skip_relocation, x86_64_linux: "<SHA256-like>" end depends_on "cmake" => :build uses_from_macos "zlib" def install mkdir "build" do system "cmake", "..", *std_cmake_args system "make", "install" end end test do (testpath/"test.cpp").write <<~EOS #include "api/BamWriter.h" using namespace BamTools; int main() { BamWriter writer; writer.Close(); } EOS system ENV.cxx, "test.cpp", "-I#{include}/bamtools", "-L#{lib}", "-lbamtools", "-lz", "-o", "test" system "./test" end end
# modification, are permitted provided that the following conditions are # met: # documentation and/or other materials provided with the distribution. # IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED # TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """HTTP module. """ import logging import mimetools import OpenSSL import select import socket import errno from cStringIO import StringIO from ganeti import constants from ganeti import utils HTTP_GANETI_VERSION = "Ganeti %s" % constants.RELEASE_VERSION HTTP_OK = 200 HTTP_NO_CONTENT = 204 HTTP_NOT_MODIFIED = 304 HTTP_0_9 = "HTTP/0.9" HTTP_1_0 = "HTTP/1.0" HTTP_1_1 = "HTTP/1.1" HTTP_GET = "GET" HTTP_HEAD = "HEAD" HTTP_POST = "POST" HTTP_PUT = "PUT" HTTP_DELETE = "DELETE" HTTP_ETAG = "ETag" HTTP_HOST = "Host" HTTP_SERVER = "Server" HTTP_DATE = "Date" HTTP_USER_AGENT = "User-Agent" HTTP_CONTENT_TYPE = "Content-Type" HTTP_CONTENT_LENGTH = "Content-Length" HTTP_CONNECTION = "Connection" HTTP_KEEP_ALIVE = "Keep-Alive" <API key> = "WWW-Authenticate" HTTP_AUTHORIZATION = "Authorization" <API key> = "Authentication-Info" HTTP_ALLOW = "Allow" <API key> = "application/octet-stream" HTTP_APP_JSON = "application/json" _SSL_UNEXPECTED_EOF = "Unexpected EOF" # Socket operations (SOCKOP_SEND, SOCKOP_RECV, SOCKOP_SHUTDOWN, SOCKOP_HANDSHAKE) = range(4) # send/receive quantum SOCK_BUF_SIZE = 32768 class HttpError(Exception): """Internal exception for HTTP errors. This should only be used for internal error reporting. """ class <API key>(Exception): """Internal exception for a closed connection. This should only be used for internal error reporting. Only use it if there's no other way to report this condition. """ class <API key>(HttpError): """Internal exception for errors during SSL handshake. This should only be used for internal error reporting. """ class HttpSocketTimeout(Exception): """Internal exception for socket timeouts. This should only be used for internal error reporting. """ class HttpException(Exception): code = None message = None def __init__(self, message=None, headers=None): Exception.__init__(self) self.message = message self.headers = headers class HttpBadRequest(HttpException): """400 Bad Request RFC2616, 10.4.1: The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repeat the request without modifications. """ code = 400 class HttpUnauthorized(HttpException): """401 Unauthorized RFC2616, section 10.4.2: The request requires user authentication. The response MUST include a WWW-Authenticate header field (section 14.47) containing a challenge applicable to the requested resource. """ code = 401 class HttpForbidden(HttpException): """403 Forbidden RFC2616, 10.4.4: The server understood the request, but is refusing to fulfill it. Authorization will not help and the request SHOULD NOT be repeated. """ code = 403 class HttpNotFound(HttpException): """404 Not Found RFC2616, 10.4.5: The server has not found anything matching the Request-URI. No indication is given of whether the condition is temporary or permanent. """ code = 404 class <API key>(HttpException): """405 Method Not Allowed RFC2616, 10.4.6: The method specified in the Request-Line is not allowed for the resource identified by the Request-URI. The response MUST include an Allow header containing a list of valid methods for the requested resource. """ code = 405 class HttpNotAcceptable(HttpException): """406 Not Acceptable RFC2616, 10.4.7: The resource identified by the request is only capable of generating response entities which have content characteristics not acceptable according to the accept headers sent in the request. """ code = 406 class HttpRequestTimeout(HttpException): """408 Request Timeout RFC2616, 10.4.9: The client did not produce a request within the time that the server was prepared to wait. The client MAY repeat the request without modifications at any later time. """ code = 408 class HttpConflict(HttpException): """409 Conflict RFC2616, 10.4.10: The request could not be completed due to a conflict with the current state of the resource. This code is only allowed in situations where it is expected that the user might be able to resolve the conflict and resubmit the request. """ code = 409 class HttpGone(HttpException): """410 Gone RFC2616, 10.4.11: The requested resource is no longer available at the server and no forwarding address is known. This condition is expected to be considered permanent. """ code = 410 class HttpLengthRequired(HttpException): """411 Length Required RFC2616, 10.4.12: The server refuses to accept the request without a defined Content-Length. The client MAY repeat the request if it adds a valid Content-Length header field containing the length of the message-body in the request message. """ code = 411 class <API key>(HttpException): """412 Precondition Failed RFC2616, 10.4.13: The precondition given in one or more of the request-header fields evaluated to false when it was tested on the server. """ code = 412 class <API key>(HttpException): """415 Unsupported Media Type RFC2616, 10.4.16: The server is refusing to service the request because the entity of the request is in a format not supported by the requested resource for the requested method. """ code = 415 class <API key>(HttpException): """500 Internal Server Error RFC2616, 10.5.1: The server encountered an unexpected condition which prevented it from fulfilling the request. """ code = 500 class HttpNotImplemented(HttpException): """501 Not Implemented RFC2616, 10.5.2: The server does not support the functionality required to fulfill the request. """ code = 501 class HttpBadGateway(HttpException): """502 Bad Gateway RFC2616, 10.5.3: The server, while acting as a gateway or proxy, received an invalid response from the upstream server it accessed in attempting to fulfill the request. """ code = 502 class <API key>(HttpException): """503 Service Unavailable RFC2616, 10.5.4: The server is currently unable to handle the request due to a temporary overloading or maintenance of the server. """ code = 503 class HttpGatewayTimeout(HttpException): """504 Gateway Timeout RFC2616, 10.5.5: The server, while acting as a gateway or proxy, did not receive a timely response from the upstream server specified by the URI (e.g. HTTP, FTP, LDAP) or some other auxiliary server (e.g. DNS) it needed to access in attempting to complete the request. """ code = 504 class <API key>(HttpException): """505 HTTP Version Not Supported RFC2616, 10.5.6: The server does not support, or refuses to support, the HTTP protocol version that was used in the request message. """ code = 505 def ParseHeaders(buf): """Parses HTTP headers. @note: This is just a trivial wrapper around C{mimetools.Message} """ return mimetools.Message(buf, 0) def SocketOperation(sock, op, arg1, timeout): """Wrapper around socket functions. This function abstracts error handling for socket operations, especially for the complicated interaction with OpenSSL. @type sock: socket @param sock: Socket for the operation @type op: int @param op: Operation to execute (SOCKOP_* constants) @type arg1: any @param arg1: Parameter for function (if needed) @type timeout: None or float @param timeout: Timeout in seconds or None @return: Return value of socket function """ # TODO: event_poll/event_check/override if op in (SOCKOP_SEND, SOCKOP_HANDSHAKE): event_poll = select.POLLOUT elif op == SOCKOP_RECV: event_poll = select.POLLIN elif op == SOCKOP_SHUTDOWN: event_poll = None # The timeout is only used when OpenSSL requests polling for a condition. # It is not advisable to have no timeout for shutdown. assert timeout else: raise AssertionError("Invalid socket operation") # Handshake is only supported by SSL sockets if (op == SOCKOP_HANDSHAKE and not isinstance(sock, OpenSSL.SSL.ConnectionType)): return # No override by default event_override = 0 while True: # Poll only for certain operations and when asked for by an override if event_override or op in (SOCKOP_SEND, SOCKOP_RECV, SOCKOP_HANDSHAKE): if event_override: wait_for_event = event_override else: wait_for_event = event_poll event = utils.WaitForFdCondition(sock, wait_for_event, timeout) if event is None: raise HttpSocketTimeout() if event & (select.POLLNVAL | select.POLLHUP | select.POLLERR): # Let the socket functions handle these break if not event & wait_for_event: continue # Reset override event_override = 0 try: try: if op == SOCKOP_SEND: return sock.send(arg1) elif op == SOCKOP_RECV: return sock.recv(arg1) elif op == SOCKOP_SHUTDOWN: if isinstance(sock, OpenSSL.SSL.ConnectionType): # PyOpenSSL's shutdown() doesn't take arguments return sock.shutdown() else: return sock.shutdown(arg1) elif op == SOCKOP_HANDSHAKE: return sock.do_handshake() except OpenSSL.SSL.WantWriteError: # OpenSSL wants to write, poll for POLLOUT event_override = select.POLLOUT continue except OpenSSL.SSL.WantReadError: # OpenSSL wants to read, poll for POLLIN event_override = select.POLLIN | select.POLLPRI continue except OpenSSL.SSL.WantX509LookupError: continue except OpenSSL.SSL.ZeroReturnError, err: # SSL Connection has been closed. In SSL 3.0 and TLS 1.0, this only # occurs if a closure alert has occurred in the protocol, i.e. the # connection has been closed cleanly. Note that this does not # necessarily mean that the transport layer (e.g. a socket) has been # closed. if op == SOCKOP_SEND: # Can happen during a renegotiation raise <API key>(err.args) elif op == SOCKOP_RECV: return "" # SSL_shutdown shouldn't return <API key> raise socket.error(err.args) except OpenSSL.SSL.SysCallError, err: if op == SOCKOP_SEND: # arg1 is the data when writing if err.args and err.args[0] == -1 and arg1 == "": # errors when writing empty strings are expected # and can be ignored return 0 if err.args == (-1, _SSL_UNEXPECTED_EOF): if op == SOCKOP_RECV: return "" elif op == SOCKOP_HANDSHAKE: # Can happen if peer disconnects directly after the connection is # opened. raise <API key>(err.args) raise socket.error(err.args) except OpenSSL.SSL.Error, err: raise socket.error(err.args) except socket.error, err: if err.args and err.args[0] == errno.EAGAIN: # Ignore EAGAIN continue raise def ShutdownConnection(sock, close_timeout, write_timeout, msgreader, force): """Closes the connection. @type sock: socket @param sock: Socket to be shut down @type close_timeout: float @param close_timeout: How long to wait for the peer to close the connection @type write_timeout: float @param write_timeout: Write timeout for shutdown @type msgreader: http.HttpMessageReader @param msgreader: Request message reader, used to determine whether peer should close connection @type force: bool @param force: Whether to forcibly close the connection without waiting for peer """ #print msgreader.peer_will_close, force if msgreader and msgreader.peer_will_close and not force: # Wait for peer to close try: # Check whether it's actually closed if not SocketOperation(sock, SOCKOP_RECV, 1, close_timeout): return except (socket.error, HttpError, HttpSocketTimeout): # Ignore errors at this stage pass # Close the connection from our side try: # We don't care about the return value, see NOTES in SSL_shutdown(3). SocketOperation(sock, SOCKOP_SHUTDOWN, socket.SHUT_RDWR, write_timeout) except HttpSocketTimeout: raise HttpError("Timeout while shutting down connection") except socket.error, err: # Ignore ENOTCONN if not (err.args and err.args[0] == errno.ENOTCONN): raise HttpError("Error while shutting down connection: %s" % err) def Handshake(sock, write_timeout): """Shakes peer's hands. @type sock: socket @param sock: Socket to be shut down @type write_timeout: float @param write_timeout: Write timeout for handshake """ try: return SocketOperation(sock, SOCKOP_HANDSHAKE, None, write_timeout) except HttpSocketTimeout: raise HttpError("Timeout during SSL handshake") except socket.error, err: raise HttpError("Error in SSL handshake: %s" % err) class HttpSslParams(object): """Data class for SSL key and certificate. """ def __init__(self, ssl_key_path, ssl_cert_path): """Initializes this class. @type ssl_key_path: string @param ssl_key_path: Path to file containing SSL key in PEM format @type ssl_cert_path: string @param ssl_cert_path: Path to file containing SSL certificate in PEM format """ self.ssl_key_pem = utils.ReadFile(ssl_key_path) self.ssl_cert_pem = utils.ReadFile(ssl_cert_path) self.ssl_cert_path = ssl_cert_path def GetKey(self): return OpenSSL.crypto.load_privatekey(OpenSSL.crypto.FILETYPE_PEM, self.ssl_key_pem) def GetCertificate(self): return OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, self.ssl_cert_pem) class HttpBase(object): """Base class for HTTP server and client. """ def __init__(self): self.using_ssl = None self._ssl_params = None self._ssl_key = None self._ssl_cert = None def _CreateSocket(self, ssl_params, ssl_verify_peer, family, ssl_verify_callback): """Creates a TCP socket and initializes SSL if needed. @type ssl_params: HttpSslParams @param ssl_params: SSL key and certificate @type ssl_verify_peer: bool @param ssl_verify_peer: Whether to require client certificate and compare it with our certificate @type family: int @param family: socket.AF_INET | socket.AF_INET6 """ assert family in (socket.AF_INET, socket.AF_INET6) if ssl_verify_peer: assert ssl_verify_callback is not None self._ssl_params = ssl_params sock = socket.socket(family, socket.SOCK_STREAM) # Should we enable SSL? self.using_ssl = ssl_params is not None if not self.using_ssl: return sock self._ssl_key = ssl_params.GetKey() self._ssl_cert = ssl_params.GetCertificate() ctx = OpenSSL.SSL.Context(OpenSSL.SSL.SSLv23_METHOD) ctx.set_options(OpenSSL.SSL.OP_NO_SSLv2) ciphers = self.GetSslCiphers() logging.debug("Setting SSL cipher string %s", ciphers) ctx.set_cipher_list(ciphers) ctx.use_privatekey(self._ssl_key) ctx.use_certificate(self._ssl_cert) ctx.check_privatekey() if ssl_verify_peer: ctx.set_verify(OpenSSL.SSL.VERIFY_PEER | OpenSSL.SSL.<API key>, ssl_verify_callback) # Also add our certificate as a trusted CA to be sent to the client. # This is required at least for GnuTLS clients to work. try: # This will fail for PyOpenssl versions before 0.10 ctx.add_client_ca(self._ssl_cert) except AttributeError: # Fall back to letting OpenSSL read the certificate file directly. ctx.load_client_ca(ssl_params.ssl_cert_path) return OpenSSL.SSL.Connection(ctx, sock) def GetSslCiphers(self): # pylint: disable=R0201 """Returns the ciphers string for SSL. """ return constants.OPENSSL_CIPHERS def _SSLVerifyCallback(self, conn, cert, errnum, errdepth, ok): """Verify the certificate provided by the peer We only compare fingerprints. The client must use the same certificate as we do on our side. """ # some parameters are unused, but this is the API # pylint: disable=W0613 assert self._ssl_params, "SSL not initialized" return (self._ssl_cert.digest("sha1") == cert.digest("sha1") and self._ssl_cert.digest("md5") == cert.digest("md5")) class HttpMessage(object): """Data structure for HTTP message. """ def __init__(self): self.start_line = None self.headers = None self.body = None class <API key>(object): """Data structure for HTTP request start line. """ def __init__(self, method, path, version): self.method = method self.path = path self.version = version def __str__(self): return "%s %s %s" % (self.method, self.path, self.version) class <API key>(object): """Data structure for HTTP response start line. """ def __init__(self, version, code, reason): self.version = version self.code = code self.reason = reason def __str__(self): return "%s %s %s" % (self.version, self.code, self.reason) class HttpMessageWriter(object): """Writes an HTTP message to a socket. """ def __init__(self, sock, msg, write_timeout): """Initializes this class and writes an HTTP message to a socket. @type sock: socket @param sock: Socket to be written to @type msg: http.HttpMessage @param msg: HTTP message to be written @type write_timeout: float @param write_timeout: Write timeout for socket """ self._msg = msg self._PrepareMessage() buf = self._FormatMessage() pos = 0 end = len(buf) while pos < end: # Send only SOCK_BUF_SIZE bytes at a time data = buf[pos:(pos + SOCK_BUF_SIZE)] sent = SocketOperation(sock, SOCKOP_SEND, data, write_timeout) # Remove sent bytes pos += sent assert pos == end, "Message wasn't sent completely" def _PrepareMessage(self): """Prepares the HTTP message by setting mandatory headers. """ # RFC2616, section 4.3: "The presence of a message-body in a request is # signaled by the inclusion of a Content-Length or Transfer-Encoding header # field in the request's message-headers." if self._msg.body: self._msg.headers[HTTP_CONTENT_LENGTH] = len(self._msg.body) def _FormatMessage(self): """Serializes the HTTP message into a string. """ buf = StringIO() # Add start line buf.write(str(self._msg.start_line)) buf.write("\r\n") # Add headers if self._msg.start_line.version != HTTP_0_9: for name, value in self._msg.headers.iteritems(): buf.write("%s: %s\r\n" % (name, value)) buf.write("\r\n") # Add message body if needed if self.HasMessageBody(): buf.write(self._msg.body) elif self._msg.body: logging.warning("Ignoring message body") return buf.getvalue() def HasMessageBody(self): """Checks whether the HTTP message contains a body. Can be overridden by subclasses. """ return bool(self._msg.body) class HttpMessageReader(object): """Reads HTTP message from socket. """ # Length limits <API key> = None HEADER_LENGTH_MAX = None # Parser state machine PS_START_LINE = "start-line" PS_HEADERS = "headers" PS_BODY = "entity-body" PS_COMPLETE = "complete" def __init__(self, sock, msg, read_timeout): """Reads an HTTP message from a socket. @type sock: socket @param sock: Socket to be read from @type msg: http.HttpMessage @param msg: Object for the read message @type read_timeout: float @param read_timeout: Read timeout for socket """ self.sock = sock self.msg = msg self.start_line_buffer = None self.header_buffer = StringIO() self.body_buffer = StringIO() self.parser_status = self.PS_START_LINE self.content_length = None self.peer_will_close = None buf = "" eof = False while self.parser_status != self.PS_COMPLETE: # TODO: Don't read more than necessary (Content-Length), otherwise # data might be lost and/or an error could occur data = SocketOperation(sock, SOCKOP_RECV, SOCK_BUF_SIZE, read_timeout) if data: buf += data else: eof = True # Do some parsing and error checking while more data arrives buf = self._ContinueParsing(buf, eof) # Must be done only after the buffer has been evaluated # TODO: Content-Length < len(data read) and connection closed if (eof and self.parser_status in (self.PS_START_LINE, self.PS_HEADERS)): raise HttpError("Connection closed prematurely") # Parse rest buf = self._ContinueParsing(buf, True) assert self.parser_status == self.PS_COMPLETE assert not buf, "Parser didn't read full response" # Body is complete msg.body = self.body_buffer.getvalue() def _ContinueParsing(self, buf, eof): """Main function for HTTP message state machine. @type buf: string @param buf: Receive buffer @type eof: bool @param eof: Whether we've reached EOF on the socket @rtype: string @return: Updated receive buffer """ # TODO: Use offset instead of slicing when possible if self.parser_status == self.PS_START_LINE: # Expect start line while True: idx = buf.find("\r\n") # RFC2616, section 4.1: "In the interest of robustness, servers SHOULD # ignore any empty line(s) received where a Request-Line is expected. # In other words, if the server is reading the protocol stream at the # beginning of a message and receives a CRLF first, it should ignore # the CRLF." if idx == 0: # TODO: Limit number of CRLFs/empty lines for safety? buf = buf[2:] continue if idx > 0: self.start_line_buffer = buf[:idx] self.<API key>(len(self.start_line_buffer)) # Remove status line, including CRLF buf = buf[idx + 2:] self.msg.start_line = self.ParseStartLine(self.start_line_buffer) self.parser_status = self.PS_HEADERS else: # Check whether incoming data is getting too large, otherwise we just # fill our read buffer. self.<API key>(len(buf)) break # TODO: Handle messages without headers if self.parser_status == self.PS_HEADERS: # Wait for header end idx = buf.find("\r\n\r\n") if idx >= 0: self.header_buffer.write(buf[:idx + 2]) self._CheckHeaderLength(self.header_buffer.tell()) # Remove headers, including CRLF buf = buf[idx + 4:] self._ParseHeaders() self.parser_status = self.PS_BODY else: # Check whether incoming data is getting too large, otherwise we just # fill our read buffer. self._CheckHeaderLength(len(buf)) if self.parser_status == self.PS_BODY: # TODO: Implement max size for body_buffer self.body_buffer.write(buf) buf = "" # Check whether we've read everything # RFC2616, section 4.4: "When a message-body is included with a message, # the transfer-length of that body is determined by one of the following # [...] 5. By the server closing the connection. (Closing the connection # cannot be used to indicate the end of a request body, since that would # leave no possibility for the server to send back a response.)" # TODO: Error when buffer length > Content-Length header if (eof or self.content_length is None or (self.content_length is not None and self.body_buffer.tell() >= self.content_length)): self.parser_status = self.PS_COMPLETE return buf def <API key>(self, length): """Limits the start line buffer size. @type length: int @param length: Buffer size """ if (self.<API key> is not None and length > self.<API key>): raise HttpError("Start line longer than %d chars" % self.<API key>) def _CheckHeaderLength(self, length): """Limits the header buffer size. @type length: int @param length: Buffer size """ if (self.HEADER_LENGTH_MAX is not None and length > self.HEADER_LENGTH_MAX): raise HttpError("Headers longer than %d chars" % self.HEADER_LENGTH_MAX) def ParseStartLine(self, start_line): """Parses the start line of a message. Must be overridden by subclass. @type start_line: string @param start_line: Start line string """ raise NotImplementedError() def <API key>(self): """Evaluate whether peer will close the connection. @rtype: bool @return: Whether peer will close the connection """ # RFC2616, section 14.10: "HTTP/1.1 defines the "close" connection option # for the sender to signal that the connection will be closed after # completion of the response. For example, # Connection: close # in either the request or the response header fields indicates that the # connection SHOULD NOT be considered `persistent' (section 8.1) after the # current request/response is complete." hdr_connection = self.msg.headers.get(HTTP_CONNECTION, None) if hdr_connection: hdr_connection = hdr_connection.lower() # An HTTP/1.1 server is assumed to stay open unless explicitly closed. if self.msg.start_line.version == HTTP_1_1: return (hdr_connection and "close" in hdr_connection) # Some HTTP/1.0 implementations have support for persistent connections, # using rules different than HTTP/1.1. # For older HTTP, Keep-Alive indicates persistent connection. if self.msg.headers.get(HTTP_KEEP_ALIVE): return False # At least Akamai returns a "Connection: Keep-Alive" header, which was # supposed to be sent by the client. if hdr_connection and "keep-alive" in hdr_connection: return False return True def _ParseHeaders(self): """Parses the headers. This function also adjusts internal variables based on header values. RFC2616, section 4.3: The presence of a message-body in a request is signaled by the inclusion of a Content-Length or Transfer-Encoding header field in the request's message-headers. """ # Parse headers self.header_buffer.seek(0, 0) self.msg.headers = ParseHeaders(self.header_buffer) self.peer_will_close = self.<API key>() # Do we have a Content-Length header? hdr_content_length = self.msg.headers.get(HTTP_CONTENT_LENGTH, None) if hdr_content_length: try: self.content_length = int(hdr_content_length) except (TypeError, ValueError): self.content_length = None if self.content_length is not None and self.content_length < 0: self.content_length = None # if the connection remains open and a content-length was not provided, # then assume that the connection WILL close. if self.content_length is None: self.peer_will_close = True
from oonib.policy import handlers policyAPI = [ (r"/policy/nettest", handlers.<API key>), (r"/policy/input", handlers.InputPolicyHandler), ]
{-# LANGUAGE TemplateHaskell #-} {-# OPTIONS_GHC -fno-warn-orphans #-} {-| Unittests for ganeti-htools. -} {- Copyright (C) 2009, 2010, 2011, 2012, 2013 Google Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -} module Test.Ganeti.HTools.Instance ( testHTools_Instance , <API key> , <API key> , <API key> , genInstanceList , Instance.Instance(..) ) where import Prelude () import Ganeti.Prelude import Control.Arrow ((&&&)) import Control.Monad (liftM) import Test.QuickCheck hiding (Result) import Test.Ganeti.TestHTools (nullISpec) import Test.Ganeti.TestHelper import Test.Ganeti.TestCommon import Test.Ganeti.HTools.Types () import Ganeti.BasicTypes import qualified Ganeti.HTools.Instance as Instance import qualified Ganeti.HTools.Node as Node import qualified Ganeti.HTools.Container as Container import qualified Ganeti.HTools.Loader as Loader import qualified Ganeti.HTools.Types as Types -- * Arbitrary instances -- | Generates a random instance with maximum and minimum disk/mem/cpu values. genInstanceWithin :: Int -> Int -> Int -> Int -> Int -> Int -> Int -> Maybe Int -> Gen Instance.Instance genInstanceWithin min_mem min_dsk min_cpu min_spin max_mem max_dsk max_cpu max_spin = do name <- genFQDN mem <- choose (min_mem, max_mem) dsk <- choose (min_dsk, max_dsk) run_st <- arbitrary pn <- arbitrary sn <- arbitrary vcpus <- choose (min_cpu, max_cpu) dt <- arbitrary spindles <- case max_spin of Nothing -> genMaybe $ choose (min_spin, maxSpindles) Just ls -> liftM Just $ choose (min_spin, ls) forthcoming <- arbitrary let disk = Instance.Disk dsk spindles return $ Instance.create name mem dsk [disk] vcpus run_st [] True pn sn dt 1 [] forthcoming -- | Generate an instance with maximum disk/mem/cpu values. <API key> :: Int -> Int -> Int -> Maybe Int -> Gen Instance.Instance <API key> = genInstanceWithin 1 0 1 0 -- | Generates an instance smaller than a node. <API key> :: Node.Node -> Gen Instance.Instance <API key> node = <API key> (Node.availMem node `div` 2) (Node.availDisk node `div` 2) (Node.availCpu node `div` 2) (if Node.exclStorage node then Just $ Node.fSpindlesForth node `div` 2 else Nothing) -- | Generates an instance possibly bigger than a node. -- In any case, that instance will be bigger than the node's ipolicy's lower -- bound. <API key> :: Node.Node -> Gen Instance.Instance <API key> node = let minISpec = runListHead nullISpec Types.minMaxISpecsMinSpec . Types.iPolicyMinMaxISpecs $ Node.iPolicy node in genInstanceWithin (Types.iSpecMemorySize minISpec) (Types.iSpecDiskSize minISpec) (Types.iSpecCpuCount minISpec) (Types.iSpecSpindleUse minISpec) (Node.availMem node + Types.unitMem * 2) (Node.availDisk node + Types.unitDsk * 3) (Node.availCpu node + Types.unitCpu * 4) (if Node.exclStorage node then Just $ Node.fSpindles node + Types.unitSpindle * 5 else Nothing) -- | Generates an instance with nodes on a node list. -- The following rules are respected: -- 1. The instance is never bigger than its primary node -- 2. If possible the instance has different pnode and snode -- 3. Else disk templates which require secondary nodes are disabled <API key> :: Node.List -> Gen Instance.Instance <API key> nl = do let nsize = Container.size nl pnode <- choose (0, nsize-1) let (snodefilter, dtfilter) = if nsize >= 2 then ((/= pnode), const True) else (const True, not . Instance.hasSecondary) snode <- choose (0, nsize-1) `suchThat` snodefilter i <- <API key> (Container.find pnode nl) `suchThat` dtfilter return $ i { Instance.pNode = pnode, Instance.sNode = snode } -- | Generates an instance list given an instance generator. genInstanceList :: Gen Instance.Instance -> Gen Instance.List genInstanceList igen = fmap (snd . Loader.assignIndices) names_instances where names_instances = map (Instance.name &&& id) <$> listOf igen -- let's generate a random instance instance Arbitrary Instance.Instance where arbitrary = <API key> maxMem maxDsk maxCpu Nothing -- * Test cases -- Simple instance tests, we only have setter/getters prop_creat :: Instance.Instance -> Property prop_creat inst = Instance.name inst ==? Instance.alias inst prop_setIdx :: Instance.Instance -> Types.Idx -> Property prop_setIdx inst idx = Instance.idx (Instance.setIdx inst idx) ==? idx prop_setName :: Instance.Instance -> String -> Bool prop_setName inst name = Instance.name newinst == name && Instance.alias newinst == name where newinst = Instance.setName inst name prop_setAlias :: Instance.Instance -> String -> Bool prop_setAlias inst name = Instance.name newinst == Instance.name inst && Instance.alias newinst == name where newinst = Instance.setAlias inst name prop_setPri :: Instance.Instance -> Types.Ndx -> Property prop_setPri inst pdx = Instance.pNode (Instance.setPri inst pdx) ==? pdx prop_setSec :: Instance.Instance -> Types.Ndx -> Property prop_setSec inst sdx = Instance.sNode (Instance.setSec inst sdx) ==? sdx prop_setBoth :: Instance.Instance -> Types.Ndx -> Types.Ndx -> Bool prop_setBoth inst pdx sdx = Instance.pNode si == pdx && Instance.sNode si == sdx where si = Instance.setBoth inst pdx sdx prop_shrinkMG :: Instance.Instance -> Property prop_shrinkMG inst = Instance.mem inst >= 2 * Types.unitMem ==> case Instance.shrinkByType inst Types.FailMem of Ok inst' -> Instance.mem inst' ==? Instance.mem inst - Types.unitMem Bad msg -> failTest msg prop_shrinkMF :: Instance.Instance -> Property prop_shrinkMF inst = forAll (choose (0, 2 * Types.unitMem - 1)) $ \mem -> let inst' = inst { Instance.mem = mem} in isBad $ Instance.shrinkByType inst' Types.FailMem prop_shrinkCG :: Instance.Instance -> Property prop_shrinkCG inst = Instance.vcpus inst >= 2 * Types.unitCpu ==> case Instance.shrinkByType inst Types.FailCPU of Ok inst' -> Instance.vcpus inst' ==? Instance.vcpus inst - Types.unitCpu Bad msg -> failTest msg prop_shrinkCF :: Instance.Instance -> Property prop_shrinkCF inst = forAll (choose (0, 2 * Types.unitCpu - 1)) $ \vcpus -> let inst' = inst { Instance.vcpus = vcpus } in isBad $ Instance.shrinkByType inst' Types.FailCPU prop_shrinkDG :: Instance.Instance -> Property prop_shrinkDG inst = Instance.dsk inst >= 2 * Types.unitDsk ==> case Instance.shrinkByType inst Types.FailDisk of Ok inst' -> Instance.dsk inst' ==? Instance.dsk inst - Types.unitDsk Bad msg -> failTest msg prop_shrinkDF :: Instance.Instance -> Property prop_shrinkDF inst = forAll (choose (0, 2 * Types.unitDsk - 1)) $ \dsk -> let inst' = inst { Instance.dsk = dsk , Instance.disks = [Instance.Disk dsk Nothing] } in isBad $ Instance.shrinkByType inst' Types.FailDisk prop_setMovable :: Instance.Instance -> Bool -> Property prop_setMovable inst m = Instance.movable inst' ==? m where inst' = Instance.setMovable inst m testSuite "HTools/Instance" [ 'prop_creat , 'prop_setIdx , 'prop_setName , 'prop_setAlias , 'prop_setPri , 'prop_setSec , 'prop_setBoth , 'prop_shrinkMG , 'prop_shrinkMF , 'prop_shrinkCG , 'prop_shrinkCF , 'prop_shrinkDG , 'prop_shrinkDF , 'prop_setMovable ]
/* * Source file for all OpenSSL-specific code for the TLS/SSL layer. No code * but vtls.c should ever call or use these functions. */ /* * The original SSLeay-using code for curl was written by Linas Vepstas and * Sampo Kellomaki 1998. */ #include "curl_setup.h" #ifdef USE_OPENSSL #ifdef HAVE_LIMITS_H #include <limits.h> #endif #include "urldata.h" #include "sendf.h" #include "formdata.h" /* for the boundary function */ #include "url.h" /* for the ssl config check function */ #include "inet_pton.h" #include "openssl.h" #include "connect.h" #include "slist.h" #include "strequal.h" #include "select.h" #include "vtls.h" #include "rawstr.h" #include "hostcheck.h" #include "curl_printf.h" #include <openssl/ssl.h> #include <openssl/rand.h> #include <openssl/x509v3.h> #include <openssl/dsa.h> #include <openssl/dh.h> #include <openssl/err.h> #include <openssl/md5.h> #include <openssl/conf.h> #include <openssl/bn.h> #include <openssl/rsa.h> #ifdef <API key> #include <openssl/pkcs12.h> #endif #if (<API key> >= 0x0090808fL) && !defined(OPENSSL_NO_OCSP) #include <openssl/ocsp.h> #endif #include "warnless.h" #include "non-ascii.h" /* for <API key> prototype */ /* The last #include files should be: */ #include "curl_memory.h" #include "memdebug.h" #ifndef <API key> #error "<API key> not defined" #endif #if defined(<API key>) #include <openssl/ui.h> #endif #if <API key> >= 0x00909000L #define SSL_METHOD_QUAL const #else #define SSL_METHOD_QUAL #endif #if (<API key> >= 0x10000000L) #define <API key> 1 #if (<API key> >= 0x10100004L) /* OpenSSL 1.1.0-pre4 removed the argument! */ #define <API key> 1 #endif #endif #if !defined(<API key>) || \ <API key> >= 0x10100000L /* 1.1.0+ has no SSLv2 */ #undef OPENSSL_NO_SSL2 /* undef first to avoid compiler warnings */ #define OPENSSL_NO_SSL2 #endif #if (<API key> >= 0x10100000L) && /* OpenSSL 1.1.0+ */ \ !defined(<API key>) #define <API key>() SSL_library_init() #define <API key> <API key> #define <API key> 1 /* added in 1.1.0 -pre1 */ #define <API key> 1 /* since 1.1.0 -pre3 */ #endif #if (<API key> >= 0x1000200fL) && /* 1.0.2 or later */ \ !defined(<API key>) #define <API key> 1 #endif #if (<API key> < 0x0090808fL) /* not present in older OpenSSL */ #define <API key>(x) #endif #if defined(<API key>) #define OSSL_PACKAGE "LibreSSL" #elif defined(<API key>) #define OSSL_PACKAGE "BoringSSL" #else #define OSSL_PACKAGE "OpenSSL" #endif /* * Number of bytes to read from the random number seed file. This must be * a finite value (because some entropy "files" like /dev/urandom have * an infinite length), but must be large enough to provide enough * entopy to properly seed OpenSSL's PRNG. */ #define RAND_LOAD_LENGTH 1024 static int passwd_callback(char *buf, int num, int encrypting, void *global_passwd) { DEBUGASSERT(0 == encrypting); if(!encrypting) { int klen = curlx_uztosi(strlen((char *)global_passwd)); if(num > klen) { memcpy(buf, global_passwd, klen+1); return klen; } } return 0; } /* * rand_enough() is a function that returns TRUE if we have seeded the random * engine properly. We use some preprocessor magic to provide a seed_enough() * macro to use, just to prevent a compiler warning on this function if we * pass in an argument that is never used. */ #ifdef HAVE_RAND_STATUS #define seed_enough(x) rand_enough() static bool rand_enough(void) { return (0 != RAND_status()) ? TRUE : FALSE; } #else #define seed_enough(x) rand_enough(x) static bool rand_enough(int nread) { /* this is a very silly decision to make */ return (nread > 500) ? TRUE : FALSE; } #endif static int ossl_seed(struct SessionHandle *data) { char *buf = data->state.buffer; /* point to the big buffer */ int nread=0; /* Q: should we add support for a random file name as a libcurl option? A: Yes, it is here */ #ifndef RANDOM_FILE /* if RANDOM_FILE isn't defined, we only perform this if an option tells us to! */ if(data->set.ssl.random_file) #define RANDOM_FILE "" /* doesn't matter won't be used */ #endif { /* let the option override the define */ nread += RAND_load_file((data->set.str[<API key>]? data->set.str[<API key>]: RANDOM_FILE), RAND_LOAD_LENGTH); if(seed_enough(nread)) return nread; } #if defined(HAVE_RAND_EGD) /* only available in OpenSSL 0.9.5 and later */ /* EGD_SOCKET is set at configure time or not at all */ #ifndef EGD_SOCKET /* If we don't have the define set, we only do this if the egd-option is set */ if(data->set.str[<API key>]) #define EGD_SOCKET "" /* doesn't matter won't be used */ #endif { /* If there's an option and a define, the option overrides the define */ int ret = RAND_egd(data->set.str[<API key>]? data->set.str[<API key>]:EGD_SOCKET); if(-1 != ret) { nread += ret; if(seed_enough(nread)) return nread; } } #endif /* If we get here, it means we need to seed the PRNG using a "silly" approach! */ do { unsigned char randb[64]; int len = sizeof(randb); RAND_bytes(randb, len); RAND_add(randb, len, (len >> 1)); } while(!RAND_status()); /* generates a default path for the random seed file */ buf[0]=0; /* blank it first */ RAND_file_name(buf, BUFSIZE); if(buf[0]) { /* we got a file name to try */ nread += RAND_load_file(buf, RAND_LOAD_LENGTH); if(seed_enough(nread)) return nread; } infof(data, "libcurl is now using a weak random seed!\n"); return nread; } static void Curl_ossl_seed(struct SessionHandle *data) { /* we have the "SSL is seeded" boolean static to prevent multiple time-consuming seedings in vain */ static bool ssl_seeded = FALSE; if(!ssl_seeded || data->set.str[<API key>] || data->set.str[<API key>]) { ossl_seed(data); ssl_seeded = TRUE; } } #ifndef SSL_FILETYPE_ENGINE #define SSL_FILETYPE_ENGINE 42 #endif #ifndef SSL_FILETYPE_PKCS12 #define SSL_FILETYPE_PKCS12 43 #endif static int do_file_type(const char *type) { if(!type || !type[0]) return SSL_FILETYPE_PEM; if(Curl_raw_equal(type, "PEM")) return SSL_FILETYPE_PEM; if(Curl_raw_equal(type, "DER")) return SSL_FILETYPE_ASN1; if(Curl_raw_equal(type, "ENG")) return SSL_FILETYPE_ENGINE; if(Curl_raw_equal(type, "P12")) return SSL_FILETYPE_PKCS12; return -1; } #if defined(<API key>) /* * Supply default password to the engine user interface conversation. * The password is passed by OpenSSL engine from <API key>() * last argument to the ui and can be obtained by UI_get0_user_data(ui) here. */ static int ssl_ui_reader(UI *ui, UI_STRING *uis) { const char *password; switch(UI_get_string_type(uis)) { case UIT_PROMPT: case UIT_VERIFY: password = (const char*)UI_get0_user_data(ui); if(password && (UI_get_input_flags(uis) & <API key>)) { UI_set_result(ui, uis, password); return 1; } default: break; } return (<API key>(UI_OpenSSL()))(ui, uis); } /* * Suppress interactive request for a default password if available. */ static int ssl_ui_writer(UI *ui, UI_STRING *uis) { switch(UI_get_string_type(uis)) { case UIT_PROMPT: case UIT_VERIFY: if(UI_get0_user_data(ui) && (UI_get_input_flags(uis) & <API key>)) { return 1; } default: break; } return (<API key>(UI_OpenSSL()))(ui, uis); } #endif static int cert_stuff(struct connectdata *conn, SSL_CTX* ctx, char *cert_file, const char *cert_type, char *key_file, const char *key_type) { struct SessionHandle *data = conn->data; int file_type = do_file_type(cert_type); if(cert_file || (file_type == SSL_FILETYPE_ENGINE)) { SSL *ssl; X509 *x509; int cert_done = 0; if(data->set.str[STRING_KEY_PASSWD]) { /* set the password in the callback userdata */ <API key>(ctx, data->set.str[STRING_KEY_PASSWD]); /* Set passwd callback: */ <API key>(ctx, passwd_callback); } switch(file_type) { case SSL_FILETYPE_PEM: /* <API key>() only works on PEM files */ if(<API key>(ctx, cert_file) != 1) { failf(data, "could not load PEM client certificate, " OSSL_PACKAGE " error %s, " "(no key found, wrong pass phrase, or wrong file format?)", ERR_error_string(ERR_get_error(), NULL) ); return 0; } break; case SSL_FILETYPE_ASN1: /* <API key>() works with either PEM or ASN1, but we use the case above for PEM so this can only be performed with ASN1 files. */ if(<API key>(ctx, cert_file, file_type) != 1) { failf(data, "could not load ASN1 client certificate, " OSSL_PACKAGE " error %s, " "(no key found, wrong pass phrase, or wrong file format?)", ERR_error_string(ERR_get_error(), NULL) ); return 0; } break; case SSL_FILETYPE_ENGINE: #if defined(<API key>) && defined(<API key>) { if(data->state.engine) { const char *cmd_name = "LOAD_CERT_CTRL"; struct { const char *cert_id; X509 *cert; } params; params.cert_id = cert_file; params.cert = NULL; /* Does the engine supports LOAD_CERT_CTRL ? */ if(!ENGINE_ctrl(data->state.engine, <API key>, 0, (void *)cmd_name, NULL)) { failf(data, "ssl engine does not support loading certificates"); return 0; } /* Load the certificate from the engine */ if(!ENGINE_ctrl_cmd(data->state.engine, cmd_name, 0, &params, NULL, 1)) { failf(data, "ssl engine cannot load client cert with id" " '%s' [%s]", cert_file, ERR_error_string(ERR_get_error(), NULL)); return 0; } if(!params.cert) { failf(data, "ssl engine didn't initialized the certificate " "properly."); return 0; } if(<API key>(ctx, params.cert) != 1) { failf(data, "unable to set client certificate"); X509_free(params.cert); return 0; } X509_free(params.cert); /* we don't need the handle any more... */ } else { failf(data, "crypto engine not set, can't load certificate"); return 0; } } break; #else failf(data, "file type ENG for certificate not implemented"); return 0; #endif case SSL_FILETYPE_PKCS12: { #ifdef <API key> FILE *f; PKCS12 *p12; EVP_PKEY *pri; STACK_OF(X509) *ca = NULL; f = fopen(cert_file, "rb"); if(!f) { failf(data, "could not open PKCS12 file '%s'", cert_file); return 0; } p12 = d2i_PKCS12_fp(f, NULL); fclose(f); if(!p12) { failf(data, "error reading PKCS12 file '%s'", cert_file); return 0; } PKCS12_PBE_add(); if(!PKCS12_parse(p12, data->set.str[STRING_KEY_PASSWD], &pri, &x509, &ca)) { failf(data, "could not parse PKCS12 file, check password, " OSSL_PACKAGE " error %s", ERR_error_string(ERR_get_error(), NULL) ); PKCS12_free(p12); return 0; } PKCS12_free(p12); if(<API key>(ctx, x509) != 1) { failf(data, "could not load PKCS12 client certificate, " OSSL_PACKAGE " error %s", ERR_error_string(ERR_get_error(), NULL) ); goto fail; } if(<API key>(ctx, pri) != 1) { failf(data, "unable to use private key from PKCS12 file '%s'", cert_file); goto fail; } if(!<API key> (ctx)) { failf(data, "private key from PKCS12 file '%s' " "does not match certificate in same file", cert_file); goto fail; } /* Set Certificate Verification chain */ if(ca) { while(sk_X509_num(ca)) { /* * Note that sk_X509_pop() is used below to make sure the cert is * removed from the stack properly before getting passed to * <API key>(). Previously we used * sk_X509_value() instead, but then we'd clean it in the subsequent * sk_X509_pop_free() call. */ X509 *x = sk_X509_pop(ca); if(!<API key>(ctx, x)) { X509_free(x); failf(data, "cannot add certificate to certificate chain"); goto fail; } /* <API key>() seems to work with either sk_* function, * presumably because it duplicates what we pass to it. */ if(!<API key>(ctx, x)) { failf(data, "cannot add certificate to client CA list"); goto fail; } } } cert_done = 1; fail: EVP_PKEY_free(pri); X509_free(x509); sk_X509_pop_free(ca, X509_free); if(!cert_done) return 0; /* failure! */ break; #else failf(data, "file type P12 for certificate not supported"); return 0; #endif } default: failf(data, "not supported file type '%s' for certificate", cert_type); return 0; } file_type = do_file_type(key_type); switch(file_type) { case SSL_FILETYPE_PEM: if(cert_done) break; if(!key_file) /* cert & key can only be in PEM case in the same file */ key_file=cert_file; case SSL_FILETYPE_ASN1: if(<API key>(ctx, key_file, file_type) != 1) { failf(data, "unable to set private key file: '%s' type %s", key_file, key_type?key_type:"PEM"); return 0; } break; case SSL_FILETYPE_ENGINE: #ifdef <API key> { /* XXXX still needs some work */ EVP_PKEY *priv_key = NULL; if(data->state.engine) { UI_METHOD *ui_method = UI_create_method((char *)"cURL user interface"); if(!ui_method) { failf(data, "unable do create " OSSL_PACKAGE " user-interface method"); return 0; } <API key>(ui_method, <API key>(UI_OpenSSL())); <API key>(ui_method, <API key>(UI_OpenSSL())); <API key>(ui_method, ssl_ui_reader); <API key>(ui_method, ssl_ui_writer); /* the typecast below was added to please mingw32 */ priv_key = (EVP_PKEY *) <API key>(data->state.engine, key_file, ui_method, data->set.str[STRING_KEY_PASSWD]); UI_destroy_method(ui_method); if(!priv_key) { failf(data, "failed to load private key from crypto engine"); return 0; } if(<API key>(ctx, priv_key) != 1) { failf(data, "unable to set private key"); EVP_PKEY_free(priv_key); return 0; } EVP_PKEY_free(priv_key); /* we don't need the handle any more... */ } else { failf(data, "crypto engine not set, can't load private key"); return 0; } } break; #else failf(data, "file type ENG for private key not supported"); return 0; #endif case SSL_FILETYPE_PKCS12: if(!cert_done) { failf(data, "file type P12 for private key not supported"); return 0; } break; default: failf(data, "not supported file type for private key"); return 0; } ssl=SSL_new(ctx); if(!ssl) { failf(data, "unable to create an SSL structure"); return 0; } x509=SSL_get_certificate(ssl); if(x509) { EVP_PKEY *pktmp = X509_get_pubkey(x509); <API key>(pktmp, SSL_get_privatekey(ssl)); EVP_PKEY_free(pktmp); } SSL_free(ssl); /* If we are using DSA, we can copy the parameters from * the private key */ /* Now we know that a key and cert have been set against * the SSL context */ if(!<API key>(ctx)) { failf(data, "Private key does not match the certificate public key"); return 0; } } return 1; } /* returns non-zero on failure */ static int x509_name_oneline(X509_NAME *a, char *buf, size_t size) { #if 0 return X509_NAME_oneline(a, buf, size); #else BIO *bio_out = BIO_new(BIO_s_mem()); BUF_MEM *biomem; int rc; if(!bio_out) return 1; /* alloc failed! */ rc = X509_NAME_print_ex(bio_out, a, 0, <API key>); BIO_get_mem_ptr(bio_out, &biomem); if((size_t)biomem->length < size) size = biomem->length; else size--; /* don't overwrite the buffer end */ memcpy(buf, biomem->data, size); buf[size]=0; BIO_free(bio_out); return !rc; #endif } /* Return error string for last OpenSSL error */ static char *SSL_strerror(unsigned long error, char *buf, size_t size) { /* OpenSSL 0.9.6 and later has a function named ERR_error_string_n() that takes the size of the buffer as a third argument */ ERR_error_string_n(error, buf, size); return buf; } /** * Global SSL init * * @retval 0 error initializing SSL * @retval 1 SSL initialized successfully */ int Curl_ossl_init(void) { <API key>(); #ifdef <API key> <API key>(); #endif /* OPENSSL_config(NULL); is "strongly recommended" to use but unfortunately that function makes an exit() call on wrongly formatted config files which makes it hard to use in some situations. OPENSSL_config() itself calls <API key>() and we use that instead and we ignore its return code! */ /* <API key> introduced some time between 0.9.8b and 0.9.8e */ #ifndef <API key> #define <API key> 0x0 #endif <API key>(NULL, NULL, <API key>| <API key>); /* Lets get nice error messages */ <API key>(); /* Init the global ciphers and digests */ if(!<API key>()) return 0; <API key>(); return 1; } /* Global cleanup */ void Curl_ossl_cleanup(void) { /* Free ciphers and digests lists */ EVP_cleanup(); #ifdef HAVE_ENGINE_CLEANUP /* Free engine list */ ENGINE_cleanup(); #endif #ifdef <API key> /* Free OpenSSL ex_data table */ <API key>(); #endif /* Free OpenSSL error strings */ ERR_free_strings(); /* Free thread local error state, destroying hash upon zero refcount */ #ifdef <API key> <API key>(); #elif defined(<API key>) <API key>(NULL); #else ERR_remove_state(0); #endif /* Free all memory allocated by all configuration modules */ CONF_modules_free(); } /* * This function uses SSL_peek to determine connection status. * * Return codes: * 1 means the connection is still in place * 0 means the connection has been closed * -1 means the connection status is unknown */ int Curl_ossl_check_cxn(struct connectdata *conn) { int rc; char buf; rc = SSL_peek(conn->ssl[FIRSTSOCKET].handle, (void*)&buf, 1); if(rc > 0) return 1; /* connection still in place */ if(rc == 0) return 0; /* connection has been closed */ return -1; /* connection status unknown */ } /* Selects an OpenSSL crypto engine */ CURLcode <API key>(struct SessionHandle *data, const char *engine) { #if defined(USE_OPENSSL) && defined(<API key>) ENGINE *e; #if <API key> >= 0x00909000L e = ENGINE_by_id(engine); #else /* avoid memory leak */ for(e = ENGINE_get_first(); e; e = ENGINE_get_next(e)) { const char *e_id = ENGINE_get_id(e); if(!strcmp(engine, e_id)) break; } #endif if(!e) { failf(data, "SSL Engine '%s' not found", engine); return <API key>; } if(data->state.engine) { ENGINE_finish(data->state.engine); ENGINE_free(data->state.engine); data->state.engine = NULL; } if(!ENGINE_init(e)) { char buf[256]; ENGINE_free(e); failf(data, "Failed to initialise SSL Engine '%s':\n%s", engine, SSL_strerror(ERR_get_error(), buf, sizeof(buf))); return <API key>; } data->state.engine = e; return CURLE_OK; #else (void)engine; failf(data, "SSL Engine not supported"); return <API key>; #endif } /* Sets engine as default for all SSL operations */ CURLcode <API key>(struct SessionHandle *data) { #ifdef <API key> if(data->state.engine) { if(ENGINE_set_default(data->state.engine, ENGINE_METHOD_ALL) > 0) { infof(data, "set default crypto engine '%s'\n", ENGINE_get_id(data->state.engine)); } else { failf(data, "set default crypto engine '%s' failed", ENGINE_get_id(data->state.engine)); return <API key>; } } #else (void) data; #endif return CURLE_OK; } /* Return list of OpenSSL crypto engine names. */ struct curl_slist *<API key>(struct SessionHandle *data) { struct curl_slist *list = NULL; #if defined(USE_OPENSSL) && defined(<API key>) struct curl_slist *beg; ENGINE *e; for(e = ENGINE_get_first(); e; e = ENGINE_get_next(e)) { beg = curl_slist_append(list, ENGINE_get_id(e)); if(!beg) { curl_slist_free_all(list); return NULL; } list = beg; } #endif (void) data; return list; } /* * This function is called when an SSL connection is closed. */ void Curl_ossl_close(struct connectdata *conn, int sockindex) { struct ssl_connect_data *connssl = &conn->ssl[sockindex]; if(connssl->handle) { (void)SSL_shutdown(connssl->handle); <API key>(connssl->handle); SSL_free (connssl->handle); connssl->handle = NULL; } if(connssl->ctx) { SSL_CTX_free (connssl->ctx); connssl->ctx = NULL; } } /* * This function is called to shut down the SSL layer but keep the * socket open (CCC - Clear Command Channel) */ int Curl_ossl_shutdown(struct connectdata *conn, int sockindex) { int retval = 0; struct ssl_connect_data *connssl = &conn->ssl[sockindex]; struct SessionHandle *data = conn->data; char buf[120]; /* We will use this for the OpenSSL error buffer, so it has to be at least 120 bytes long. */ unsigned long sslerror; ssize_t nread; int buffsize; int err; int done = 0; /* This has only been tested on the proftpd server, and the mod_tls code sends a close notify alert without waiting for a close notify alert in response. Thus we wait for a close notify alert from the server, but we do not send one. Let's hope other servers do the same... */ if(data->set.ftp_ccc == <API key>) (void)SSL_shutdown(connssl->handle); if(connssl->handle) { buffsize = (int)sizeof(buf); while(!done) { int what = Curl_socket_ready(conn->sock[sockindex], CURL_SOCKET_BAD, <API key>); if(what > 0) { ERR_clear_error(); /* Something to read, let's do it and hope that it is the close notify alert from the server */ nread = (ssize_t)SSL_read(conn->ssl[sockindex].handle, buf, buffsize); err = SSL_get_error(conn->ssl[sockindex].handle, (int)nread); switch(err) { case SSL_ERROR_NONE: /* this is not an error */ case <API key>: /* no more data */ /* This is the expected response. There was no data but only the close notify alert */ done = 1; break; case SSL_ERROR_WANT_READ: /* there's data pending, re-invoke SSL_read() */ infof(data, "SSL_ERROR_WANT_READ\n"); break; case <API key>: /* SSL wants a write. Really odd. Let's bail out. */ infof(data, "<API key>\n"); done = 1; break; default: /* openssl/ssl.h says "look at error stack/return value/errno" */ sslerror = ERR_get_error(); failf(conn->data, OSSL_PACKAGE " SSL read: %s, errno %d", ERR_error_string(sslerror, buf), SOCKERRNO); done = 1; break; } } else if(0 == what) { /* timeout */ failf(data, "SSL shutdown timeout"); done = 1; } else { /* anything that gets here is fatally bad */ failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO); retval = -1; done = 1; } } /* while()-loop for the select() */ if(data->set.verbose) { #ifdef <API key> switch(SSL_get_shutdown(connssl->handle)) { case SSL_SENT_SHUTDOWN: infof(data, "SSL_get_shutdown() returned SSL_SENT_SHUTDOWN\n"); break; case <API key>: infof(data, "SSL_get_shutdown() returned <API key>\n"); break; case SSL_SENT_SHUTDOWN|<API key>: infof(data, "SSL_get_shutdown() returned SSL_SENT_SHUTDOWN|" "<API key>\n"); break; } #endif } SSL_free (connssl->handle); connssl->handle = NULL; } return retval; } void <API key>(void *ptr) { /* free the ID */ SSL_SESSION_free(ptr); } /* * This function is called when the 'data' struct is going away. Close * down everything and free all resources! */ void Curl_ossl_close_all(struct SessionHandle *data) { #ifdef <API key> if(data->state.engine) { ENGINE_finish(data->state.engine); ENGINE_free(data->state.engine); data->state.engine = NULL; } #else (void)data; #endif } /* Quote from RFC2818 section 3.1 "Server Identity" If a subjectAltName extension of type dNSName is present, that MUST be used as the identity. Otherwise, the (most specific) Common Name field in the Subject field of the certificate MUST be used. Although the use of the Common Name is existing practice, it is deprecated and Certification Authorities are encouraged to use the dNSName instead. Matching is performed using the matching rules specified by [RFC2459]. If more than one identity of a given type is present in the certificate (e.g., more than one dNSName name, a match in any one of the set is considered acceptable.) Names may contain the wildcard character * which is considered to match any single domain name component or component fragment. E.g., *.a.com matches foo.a.com but not bar.foo.a.com. f*.com matches foo.com but not bar.com. In some cases, the URI is specified as an IP address rather than a hostname. In this case, the iPAddress subjectAltName must be present in the certificate and must exactly match the IP in the URI. */ static CURLcode verifyhost(struct connectdata *conn, X509 *server_cert) { bool matched = FALSE; int target = GEN_DNS; /* target type, GEN_DNS or GEN_IPADD */ size_t addrlen = 0; struct SessionHandle *data = conn->data; STACK_OF(GENERAL_NAME) *altnames; #ifdef ENABLE_IPV6 struct in6_addr addr; #else struct in_addr addr; #endif CURLcode result = CURLE_OK; #ifdef ENABLE_IPV6 if(conn->bits.ipv6_ip && Curl_inet_pton(AF_INET6, conn->host.name, &addr)) { target = GEN_IPADD; addrlen = sizeof(struct in6_addr); } else #endif if(Curl_inet_pton(AF_INET, conn->host.name, &addr)) { target = GEN_IPADD; addrlen = sizeof(struct in_addr); } /* get a "list" of alternative names */ altnames = X509_get_ext_d2i(server_cert, <API key>, NULL, NULL); if(altnames) { int numalts; int i; /* get amount of alternatives, RFC2459 claims there MUST be at least one, but we don't depend on it... */ numalts = sk_GENERAL_NAME_num(altnames); /* loop through all alternatives while none has matched */ for(i=0; (i<numalts) && !matched; i++) { /* get a handle to alternative name number i */ const GENERAL_NAME *check = <API key>(altnames, i); /* only check alternatives of the same type the target is */ if(check->type == target) { /* get data and length */ const char *altptr = (char *)ASN1_STRING_data(check->d.ia5); size_t altlen = (size_t) ASN1_STRING_length(check->d.ia5); switch(target) { case GEN_DNS: /* name/pattern comparison */ /* The OpenSSL man page explicitly says: "In general it cannot be assumed that the data returned by ASN1_STRING_data() is null terminated or does not contain embedded nulls." But also that "The actual format of the data will depend on the actual string type itself: for example for and IA5String the data will be ASCII" Gisle researched the OpenSSL sources: "I checked the 0.9.6 and 0.9.8 sources before my patch and it always 0-terminates an IA5String." */ if((altlen == strlen(altptr)) && /* if this isn't true, there was an embedded zero in the name string and we cannot match it. */ Curl_cert_hostcheck(altptr, conn->host.name)) { matched = TRUE; infof(data, " subjectAltName: host \"%s\" matched cert's \"%s\"\n", conn->host.dispname, altptr); } break; case GEN_IPADD: /* IP address comparison */ /* compare alternative IP address if the data chunk is the same size our server IP address is */ if((altlen == addrlen) && !memcmp(altptr, &addr, altlen)) { matched = TRUE; infof(data, " subjectAltName: host \"%s\" matched cert's IP address!\n", conn->host.dispname); } break; } } } GENERAL_NAMES_free(altnames); } if(matched) /* an alternative name matched */ ; else if(altnames) { /* an alternative name field existed, but didn't match and then we MUST fail */ infof(data, " subjectAltName does not match %s\n", conn->host.dispname); failf(data, "SSL: no alternative certificate subject name matches " "target host name '%s'", conn->host.dispname); result = <API key>; } else { /* we have to look to the last occurrence of a commonName in the distinguished one to get the most significant one. */ int j, i=-1; /* The following is done because of a bug in 0.9.6b */ unsigned char *nulstr = (unsigned char *)""; unsigned char *peer_CN = nulstr; X509_NAME *name = <API key>(server_cert); if(name) while((j = <API key>(name, NID_commonName, i))>=0) i=j; /* we have the name entry and we will now convert this to a string that we can use for comparison. Doing this we support BMPstring, UTF8 etc. */ if(i>=0) { ASN1_STRING *tmp = <API key>(X509_NAME_get_entry(name, i)); /* In OpenSSL 0.9.7d and earlier, ASN1_STRING_to_UTF8 fails if the input is already UTF-8 encoded. We check for this case and copy the raw string manually to avoid the problem. This code can be made conditional in the future when OpenSSL has been fixed. Work-around brought by Alexis S. L. Carvalho. */ if(tmp) { if(ASN1_STRING_type(tmp) == V_ASN1_UTF8STRING) { j = ASN1_STRING_length(tmp); if(j >= 0) { peer_CN = OPENSSL_malloc(j+1); if(peer_CN) { memcpy(peer_CN, ASN1_STRING_data(tmp), j); peer_CN[j] = '\0'; } } } else /* not a UTF8 name */ j = ASN1_STRING_to_UTF8(&peer_CN, tmp); if(peer_CN && (curlx_uztosi(strlen((char *)peer_CN)) != j)) { /* there was a terminating zero before the end of string, this cannot match and we return failure! */ failf(data, "SSL: illegal cert name field"); result = <API key>; } } } if(peer_CN == nulstr) peer_CN = NULL; else { /* convert peer_CN from UTF8 */ CURLcode rc = <API key>(data, peer_CN, strlen(peer_CN)); /* <API key> calls failf if unsuccessful */ if(rc) { OPENSSL_free(peer_CN); return rc; } } if(result) /* error already detected, pass through */ ; else if(!peer_CN) { failf(data, "SSL: unable to obtain common name from peer certificate"); result = <API key>; } else if(!Curl_cert_hostcheck((const char *)peer_CN, conn->host.name)) { failf(data, "SSL: certificate subject name '%s' does not match " "target host name '%s'", peer_CN, conn->host.dispname); result = <API key>; } else { infof(data, " common name: %s (matched)\n", peer_CN); } if(peer_CN) OPENSSL_free(peer_CN); } return result; } #if (<API key> >= 0x0090808fL) && !defined(OPENSSL_NO_TLSEXT) && \ !defined(OPENSSL_NO_OCSP) static CURLcode verifystatus(struct connectdata *conn, struct ssl_connect_data *connssl) { int i, ocsp_status; const unsigned char *p; CURLcode result = CURLE_OK; struct SessionHandle *data = conn->data; OCSP_RESPONSE *rsp = NULL; OCSP_BASICRESP *br = NULL; X509_STORE *st = NULL; STACK_OF(X509) *ch = NULL; long len = <API key>(connssl->handle, &p); if(!p) { failf(data, "No OCSP response received"); result = <API key>; goto end; } rsp = d2i_OCSP_RESPONSE(NULL, &p, len); if(!rsp) { failf(data, "Invalid OCSP response"); result = <API key>; goto end; } ocsp_status = <API key>(rsp); if(ocsp_status != <API key>) { failf(data, "Invalid OCSP response status: %s (%d)", <API key>(ocsp_status), ocsp_status); result = <API key>; goto end; } br = <API key>(rsp); if(!br) { failf(data, "Invalid OCSP response"); result = <API key>; goto end; } ch = <API key>(connssl->handle); st = <API key>(connssl->ctx); #if ((<API key> <= 0x1000201fL) /* Fixed after 1.0.2a */ || \ defined(<API key>)) /* The authorized responder cert in the OCSP response MUST be signed by the peer cert's issuer (see RFC6960 section 4.2.2.2). If that's a root cert, no problem, but if it's an intermediate cert OpenSSL has a bug where it expects this issuer to be present in the chain embedded in the OCSP response. So we add it if necessary. */ /* First make sure the peer cert chain includes both a peer and an issuer, and the OCSP response contains a responder cert. */ if(sk_X509_num(ch) >= 2 && sk_X509_num(br->certs) >= 1) { X509 *responder = sk_X509_value(br->certs, sk_X509_num(br->certs) - 1); /* Find issuer of responder cert and add it to the OCSP response chain */ for(i = 0; i < sk_X509_num(ch); i++) { X509 *issuer = sk_X509_value(ch, i); if(X509_check_issued(issuer, responder) == X509_V_OK) { if(!<API key>(br, issuer)) { failf(data, "Could not add issuer cert to OCSP response"); result = <API key>; goto end; } } } } #endif if(OCSP_basic_verify(br, ch, st, 0) <= 0) { failf(data, "OCSP response verification failed"); result = <API key>; goto end; } for(i = 0; i < OCSP_resp_count(br); i++) { int cert_status, crl_reason; OCSP_SINGLERESP *single = NULL; <API key> *rev, *thisupd, *nextupd; single = OCSP_resp_get0(br, i); if(!single) continue; cert_status = <API key>(single, &crl_reason, &rev, &thisupd, &nextupd); if(!OCSP_check_validity(thisupd, nextupd, 300L, -1L)) { failf(data, "OCSP response has expired"); result = <API key>; goto end; } infof(data, "SSL certificate status: %s (%d)\n", <API key>(cert_status), cert_status); switch(cert_status) { case <API key>: break; case <API key>: result = <API key>; failf(data, "SSL certificate revocation reason: %s (%d)", OCSP_crl_reason_str(crl_reason), crl_reason); goto end; case <API key>: result = <API key>; goto end; } } end: if(br) OCSP_BASICRESP_free(br); OCSP_RESPONSE_free(rsp); return result; } #endif #endif /* USE_OPENSSL */ /* The <API key> doesn't exist in ancient OpenSSL versions and thus this cannot be done there. */ #ifdef <API key> static const char *ssl_msg_type(int ssl_ver, int msg) { #ifdef SSL2_VERSION_MAJOR if(ssl_ver == SSL2_VERSION_MAJOR) { switch (msg) { case SSL2_MT_ERROR: return "Error"; case <API key>: return "Client hello"; case <API key>: return "Client key"; case <API key>: return "Client finished"; case <API key>: return "Server hello"; case <API key>: return "Server verify"; case <API key>: return "Server finished"; case <API key>: return "Request CERT"; case <API key>: return "Client CERT"; } } else #endif if(ssl_ver == SSL3_VERSION_MAJOR) { switch (msg) { case <API key>: return "Hello request"; case <API key>: return "Client hello"; case <API key>: return "Server hello"; #ifdef <API key> case <API key>: return "Newsession Ticket"; #endif case SSL3_MT_CERTIFICATE: return "Certificate"; case <API key>: return "Server key exchange"; case <API key>: return "Client key exchange"; case <API key>: return "Request CERT"; case SSL3_MT_SERVER_DONE: return "Server finished"; case <API key>: return "CERT verify"; case SSL3_MT_FINISHED: return "Finished"; #ifdef <API key> case <API key>: return "Certificate Status"; #endif } } return "Unknown"; } static const char *tls_rt_type(int type) { switch(type) { #ifdef SSL3_RT_HEADER case SSL3_RT_HEADER: return "TLS header"; #endif case <API key>: return "TLS change cipher"; case SSL3_RT_ALERT: return "TLS alert"; case SSL3_RT_HANDSHAKE: return "TLS handshake"; case <API key>: return "TLS app data"; default: return "TLS Unknown"; } } /* * Our callback from the SSL/TLS layers. */ static void ssl_tls_trace(int direction, int ssl_ver, int content_type, const void *buf, size_t len, SSL *ssl, void *userp) { struct SessionHandle *data; const char *msg_name, *tls_rt_name; char ssl_buf[1024]; char unknown[32]; int msg_type, txt_len; const char *verstr = NULL; struct connectdata *conn = userp; if(!conn || !conn->data || !conn->data->set.fdebug || (direction != 0 && direction != 1)) return; data = conn->data; switch(ssl_ver) { #ifdef SSL2_VERSION /* removed in recent versions */ case SSL2_VERSION: verstr = "SSLv2"; break; #endif #ifdef SSL3_VERSION case SSL3_VERSION: verstr = "SSLv3"; break; #endif case TLS1_VERSION: verstr = "TLSv1.0"; break; #ifdef TLS1_1_VERSION case TLS1_1_VERSION: verstr = "TLSv1.1"; break; #endif #ifdef TLS1_2_VERSION case TLS1_2_VERSION: verstr = "TLSv1.2"; break; #endif case 0: break; default: snprintf(unknown, sizeof(unknown), "(%x)", ssl_ver); verstr = unknown; break; } if(ssl_ver) { /* the info given when the version is zero is not that useful for us */ ssl_ver >>= 8; /* check the upper 8 bits only below */ /* SSLv2 doesn't seem to have TLS record-type headers, so OpenSSL * always pass-up content-type as 0. But the interesting message-type * is at 'buf[0]'. */ if(ssl_ver == SSL3_VERSION_MAJOR && content_type) tls_rt_name = tls_rt_type(content_type); else tls_rt_name = ""; msg_type = *(char*)buf; msg_name = ssl_msg_type(ssl_ver, msg_type); txt_len = snprintf(ssl_buf, sizeof(ssl_buf), "%s (%s), %s, %s (%d):\n", verstr, direction?"OUT":"IN", tls_rt_name, msg_name, msg_type); Curl_debug(data, CURLINFO_TEXT, ssl_buf, (size_t)txt_len, NULL); } Curl_debug(data, (direction == 1) ? <API key> : <API key>, (char *)buf, len, NULL); (void) ssl; } #endif #ifdef USE_OPENSSL #ifdef <API key> # define use_sni(x) sni = (x) #else # define use_sni(x) Curl_nop_stmt #endif /* Check for OpenSSL 1.0.2 which has ALPN support. */ #undef HAS_ALPN #if <API key> >= 0x10002000L \ && !defined(OPENSSL_NO_TLSEXT) # define HAS_ALPN 1 #endif /* Check for OpenSSL 1.0.1 which has NPN support. */ #undef HAS_NPN #if <API key> >= 0x10001000L \ && !defined(OPENSSL_NO_TLSEXT) \ && !defined(<API key>) # define HAS_NPN 1 #endif #ifdef HAS_NPN /* * in is a list of lenght prefixed strings. this function has to select * the protocol we want to use from the list and write its string into out. */ static int <API key>(unsigned char **out, unsigned char *outlen, const unsigned char *in, unsigned int inlen, const char *key, unsigned int keylen) { unsigned int i; for(i = 0; i + keylen <= inlen; i += in[i] + 1) { if(memcmp(&in[i + 1], key, keylen) == 0) { *out = (unsigned char *) &in[i + 1]; *outlen = in[i]; return 0; } } return -1; } static int <API key>(SSL *ssl, unsigned char **out, unsigned char *outlen, const unsigned char *in, unsigned int inlen, void *arg) { struct connectdata *conn = (struct connectdata*) arg; (void)ssl; #ifdef USE_NGHTTP2 if(conn->data->set.httpversion >= CURL_HTTP_VERSION_2 && !<API key>(out, outlen, in, inlen, <API key>, <API key>)) { infof(conn->data, "NPN, negotiated HTTP2 (%s)\n", <API key>); conn->negnpn = CURL_HTTP_VERSION_2; return SSL_TLSEXT_ERR_OK; } #endif if(!<API key>(out, outlen, in, inlen, ALPN_HTTP_1_1, <API key>)) { infof(conn->data, "NPN, negotiated HTTP1.1\n"); conn->negnpn = <API key>; return SSL_TLSEXT_ERR_OK; } infof(conn->data, "NPN, no overlap, use HTTP1.1\n"); *out = (unsigned char *)ALPN_HTTP_1_1; *outlen = <API key>; conn->negnpn = <API key>; return SSL_TLSEXT_ERR_OK; } #endif /* HAS_NPN */ static const char * get_ssl_version_txt(SSL *ssl) { if(!ssl) return ""; switch(SSL_version(ssl)) { #if <API key> >= 0x1000100FL case TLS1_2_VERSION: return "TLSv1.2"; case TLS1_1_VERSION: return "TLSv1.1"; #endif case TLS1_VERSION: return "TLSv1.0"; case SSL3_VERSION: return "SSLv3"; case SSL2_VERSION: return "SSLv2"; } return "unknown"; } static CURLcode ossl_connect_step1(struct connectdata *conn, int sockindex) { CURLcode result = CURLE_OK; char *ciphers; struct SessionHandle *data = conn->data; SSL_METHOD_QUAL SSL_METHOD *req_method = NULL; void *ssl_sessionid = NULL; X509_LOOKUP *lookup = NULL; curl_socket_t sockfd = conn->sock[sockindex]; struct ssl_connect_data *connssl = &conn->ssl[sockindex]; long ctx_options; #ifdef <API key> bool sni; #ifdef ENABLE_IPV6 struct in6_addr addr; #else struct in_addr addr; #endif #endif DEBUGASSERT(ssl_connect_1 == connssl->connecting_state); /* Make funny stuff to get random input */ Curl_ossl_seed(data); data->set.ssl.certverifyresult = !X509_V_OK; /* check to see if we've been told to use an explicit SSL/TLS version */ switch(data->set.ssl.version) { default: case <API key>: case <API key>: case <API key>: case <API key>: case <API key>: /* it will be handled later with the context options */ #if (<API key> >= 0x10100000L) && \ !defined(<API key>) req_method = TLS_client_method(); #else req_method = <API key>(); #endif use_sni(TRUE); break; case <API key>: #ifdef OPENSSL_NO_SSL2 failf(data, OSSL_PACKAGE " was built without SSLv2 support"); return CURLE_NOT_BUILT_IN; #else #ifdef USE_TLS_SRP if(data->set.ssl.authtype == CURL_TLSAUTH_SRP) return <API key>; #endif req_method = SSLv2_client_method(); use_sni(FALSE); break; #endif case <API key>: #ifdef <API key> failf(data, OSSL_PACKAGE " was built without SSLv3 support"); return CURLE_NOT_BUILT_IN; #else #ifdef USE_TLS_SRP if(data->set.ssl.authtype == CURL_TLSAUTH_SRP) return <API key>; #endif req_method = SSLv3_client_method(); use_sni(FALSE); break; #endif } if(connssl->ctx) SSL_CTX_free(connssl->ctx); connssl->ctx = SSL_CTX_new(req_method); if(!connssl->ctx) { failf(data, "SSL: couldn't create a context: %s", ERR_error_string(ERR_peek_error(), NULL)); return CURLE_OUT_OF_MEMORY; } #ifdef <API key> SSL_CTX_set_mode(connssl->ctx, <API key>); #endif #ifdef <API key> if(data->set.fdebug && data->set.verbose) { /* the SSL trace callback is only used for verbose logging */ <API key>(connssl->ctx, ssl_tls_trace); <API key>(connssl->ctx, conn); } #endif ctx_options = SSL_OP_ALL; #ifdef SSL_OP_NO_TICKET ctx_options |= SSL_OP_NO_TICKET; #endif #ifdef <API key> ctx_options |= <API key>; #endif #ifdef <API key> /* mitigate CVE-2010-4180 */ ctx_options &= ~<API key>; #endif #ifdef <API key> /* unless the user explicitly ask to allow the protocol vulnerability we use the work-around */ if(!conn->data->set.ssl_enable_beast) ctx_options &= ~<API key>; #endif switch(data->set.ssl.version) { case <API key>: #ifdef USE_TLS_SRP if(data->set.ssl.authtype == CURL_TLSAUTH_SRP) { infof(data, "Set version TLSv1.x for SRP authorisation\n"); } #endif ctx_options |= SSL_OP_NO_SSLv2; ctx_options |= SSL_OP_NO_TLSv1; #if <API key> >= 0x1000100FL ctx_options |= SSL_OP_NO_TLSv1_1; ctx_options |= SSL_OP_NO_TLSv1_2; #endif break; case <API key>: case <API key>: ctx_options |= SSL_OP_NO_SSLv2; ctx_options |= SSL_OP_NO_SSLv3; break; case <API key>: ctx_options |= SSL_OP_NO_SSLv2; ctx_options |= SSL_OP_NO_SSLv3; #if <API key> >= 0x1000100FL ctx_options |= SSL_OP_NO_TLSv1_1; ctx_options |= SSL_OP_NO_TLSv1_2; #endif break; #if <API key> >= 0x1000100FL case <API key>: ctx_options |= SSL_OP_NO_SSLv2; ctx_options |= SSL_OP_NO_SSLv3; ctx_options |= SSL_OP_NO_TLSv1; ctx_options |= SSL_OP_NO_TLSv1_2; break; case <API key>: ctx_options |= SSL_OP_NO_SSLv2; ctx_options |= SSL_OP_NO_SSLv3; ctx_options |= SSL_OP_NO_TLSv1; ctx_options |= SSL_OP_NO_TLSv1_1; break; #endif #ifndef OPENSSL_NO_SSL2 case <API key>: ctx_options |= SSL_OP_NO_SSLv3; ctx_options |= SSL_OP_NO_TLSv1; #if <API key> >= 0x1000100FL ctx_options |= SSL_OP_NO_TLSv1_1; ctx_options |= SSL_OP_NO_TLSv1_2; #endif break; #endif default: failf(data, "Unsupported SSL protocol version"); return <API key>; } SSL_CTX_set_options(connssl->ctx, ctx_options); #ifdef HAS_NPN if(data->set.ssl_enable_npn) <API key>(connssl->ctx, <API key>, conn); #endif #ifdef HAS_ALPN if(data->set.ssl_enable_alpn) { int cur = 0; unsigned char protocols[128]; #ifdef USE_NGHTTP2 if(data->set.httpversion >= CURL_HTTP_VERSION_2) { protocols[cur++] = <API key>; memcpy(&protocols[cur], <API key>, <API key>); cur += <API key>; infof(data, "ALPN, offering %s\n", <API key>); } #endif protocols[cur++] = <API key>; memcpy(&protocols[cur], ALPN_HTTP_1_1, <API key>); cur += <API key>; infof(data, "ALPN, offering %s\n", ALPN_HTTP_1_1); /* expects length prefixed preference ordered list of protocols in wire * format */ <API key>(connssl->ctx, protocols, cur); } #endif if(data->set.str[STRING_CERT] || data->set.str[STRING_CERT_TYPE]) { if(!cert_stuff(conn, connssl->ctx, data->set.str[STRING_CERT], data->set.str[STRING_CERT_TYPE], data->set.str[STRING_KEY], data->set.str[STRING_KEY_TYPE])) { /* failf() is already done in cert_stuff() */ return <API key>; } } ciphers = data->set.str[<API key>]; if(!ciphers) ciphers = (char *)<API key>; if(!<API key>(connssl->ctx, ciphers)) { failf(data, "failed setting cipher list: %s", ciphers); return CURLE_SSL_CIPHER; } infof(data, "Cipher selection: %s\n", ciphers); #ifdef USE_TLS_SRP if(data->set.ssl.authtype == CURL_TLSAUTH_SRP) { infof(data, "Using TLS-SRP username: %s\n", data->set.ssl.username); if(!<API key>(connssl->ctx, data->set.ssl.username)) { failf(data, "Unable to set SRP user name"); return <API key>; } if(!<API key>(connssl->ctx, data->set.ssl.password)) { failf(data, "failed setting SRP password"); return <API key>; } if(!data->set.str[<API key>]) { infof(data, "Setting cipher list SRP\n"); if(!<API key>(connssl->ctx, "SRP")) { failf(data, "failed setting SRP cipher list"); return CURLE_SSL_CIPHER; } } } #endif if(data->set.str[STRING_SSL_CAFILE] || data->set.str[STRING_SSL_CAPATH]) { /* tell SSL where to find CA certificates that are used to verify the servers certificate. */ if(!<API key>(connssl->ctx, data->set.str[STRING_SSL_CAFILE], data->set.str[STRING_SSL_CAPATH])) { if(data->set.ssl.verifypeer) { /* Fail if we insist on successfully verifying the server. */ failf(data, "error setting certificate verify locations:\n" " CAfile: %s\n CApath: %s", data->set.str[STRING_SSL_CAFILE]? data->set.str[STRING_SSL_CAFILE]: "none", data->set.str[STRING_SSL_CAPATH]? data->set.str[STRING_SSL_CAPATH] : "none"); return <API key>; } else { /* Just continue with a warning if no strict certificate verification is required. */ infof(data, "error setting certificate verify locations," " continuing anyway:\n"); } } else { /* Everything is fine. */ infof(data, "successfully set certificate verify locations:\n"); } infof(data, " CAfile: %s\n" " CApath: %s\n", data->set.str[STRING_SSL_CAFILE] ? data->set.str[STRING_SSL_CAFILE]: "none", data->set.str[STRING_SSL_CAPATH] ? data->set.str[STRING_SSL_CAPATH]: "none"); } #ifdef CURL_CA_FALLBACK else if(data->set.ssl.verifypeer) { /* verfying the peer without any CA certificates won't work so use openssl's built in default as fallback */ <API key>(connssl->ctx); } #endif if(data->set.str[STRING_SSL_CRLFILE]) { /* tell SSL where to find CRL file that is used to check certificate * revocation */ lookup=<API key>(<API key>(connssl->ctx), X509_LOOKUP_file()); if(!lookup || (!X509_load_crl_file(lookup, data->set.str[STRING_SSL_CRLFILE], X509_FILETYPE_PEM)) ) { failf(data, "error loading CRL file: %s", data->set.str[STRING_SSL_CRLFILE]); return <API key>; } else { /* Everything is fine. */ infof(data, "successfully load CRL file:\n"); <API key>(<API key>(connssl->ctx), <API key>|<API key>); } infof(data, " CRLfile: %s\n", data->set.str[STRING_SSL_CRLFILE] ? data->set.str[STRING_SSL_CRLFILE]: "none"); } #if defined(<API key>) && !defined(<API key>) if(data->set.ssl.verifypeer) { <API key>(<API key>(connssl->ctx), <API key>); } #endif /* SSL always tries to verify the peer, this only says whether it should * fail to connect if the verification fails, or if it should continue * anyway. In the latter case the result of the verification is checked with * <API key>() below. */ SSL_CTX_set_verify(connssl->ctx, data->set.ssl.verifypeer?SSL_VERIFY_PEER:SSL_VERIFY_NONE, NULL); /* give application a chance to interfere with SSL set up. */ if(data->set.ssl.fsslctx) { result = (*data->set.ssl.fsslctx)(data, connssl->ctx, data->set.ssl.fsslctxp); if(result) { failf(data, "error signaled by ssl ctx callback"); return result; } } /* Lets make an SSL structure */ if(connssl->handle) SSL_free(connssl->handle); connssl->handle = SSL_new(connssl->ctx); if(!connssl->handle) { failf(data, "SSL: couldn't create a context (handle)!"); return CURLE_OUT_OF_MEMORY; } #if (<API key> >= 0x0090808fL) && !defined(OPENSSL_NO_TLSEXT) && \ !defined(OPENSSL_NO_OCSP) if(data->set.ssl.verifystatus) <API key>(connssl->handle, <API key>); #endif <API key>(connssl->handle); connssl->server_cert = 0x0; #ifdef <API key> if((0 == Curl_inet_pton(AF_INET, conn->host.name, &addr)) && #ifdef ENABLE_IPV6 (0 == Curl_inet_pton(AF_INET6, conn->host.name, &addr)) && #endif sni && !<API key>(connssl->handle, conn->host.name)) infof(data, "WARNING: failed to configure server name indication (SNI) " "TLS extension\n"); #endif /* Check if there's a cached ID we can/should use here! */ if(!<API key>(conn, &ssl_sessionid, NULL)) { /* we got a session id, use it! */ if(!SSL_set_session(connssl->handle, ssl_sessionid)) { failf(data, "SSL: SSL_set_session failed: %s", ERR_error_string(ERR_get_error(), NULL)); return <API key>; } /* Informational message */ infof (data, "SSL re-using session ID\n"); } /* pass the raw socket into the SSL layers */ if(!SSL_set_fd(connssl->handle, (int)sockfd)) { failf(data, "SSL: SSL_set_fd failed: %s", ERR_error_string(ERR_get_error(), NULL)); return <API key>; } connssl->connecting_state = ssl_connect_2; return CURLE_OK; } static CURLcode ossl_connect_step2(struct connectdata *conn, int sockindex) { struct SessionHandle *data = conn->data; int err; struct ssl_connect_data *connssl = &conn->ssl[sockindex]; DEBUGASSERT(ssl_connect_2 == connssl->connecting_state || <API key> == connssl->connecting_state || <API key> == connssl->connecting_state); ERR_clear_error(); err = SSL_connect(connssl->handle); /* 1 is fine 0 is "not successful but was shut down controlled" <0 is "handshake was not successful, because a fatal error occurred" */ if(1 != err) { int detail = SSL_get_error(connssl->handle, err); if(SSL_ERROR_WANT_READ == detail) { connssl->connecting_state = <API key>; return CURLE_OK; } else if(<API key> == detail) { connssl->connecting_state = <API key>; return CURLE_OK; } else { /* untreated error */ unsigned long errdetail; char error_buffer[256]=""; /* OpenSSL documents that this must be at least 256 bytes long. */ CURLcode result; long lerr; int lib; int reason; /* the connection failed, we're not waiting for anything else. */ connssl->connecting_state = ssl_connect_2; /* Get the earliest error code from the thread's error queue and removes the entry. */ errdetail = ERR_get_error(); /* Extract which lib and reason */ lib = ERR_GET_LIB(errdetail); reason = ERR_GET_REASON(errdetail); if((lib == ERR_LIB_SSL) && (reason == <API key>)) { result = CURLE_SSL_CACERT; lerr = <API key>(connssl->handle); if(lerr != X509_V_OK) { snprintf(error_buffer, sizeof(error_buffer), "SSL certificate problem: %s", <API key>(lerr)); } else /* strcpy() is fine here as long as the string fits within error_buffer */ strcpy(error_buffer, "SSL certificate verification failed"); } else { result = <API key>; SSL_strerror(errdetail, error_buffer, sizeof(error_buffer)); } /* detail is already set to the SSL error above */ /* If we e.g. use SSLv2 request-method and the server doesn't like us * (RST connection etc.), OpenSSL gives no explanation whatsoever and * the SO_ERROR is also lost. */ if(<API key> == result && errdetail == 0) { failf(data, "Unknown SSL protocol error in connection to %s:%ld ", conn->host.name, conn->remote_port); return result; } /* Could be a CERT problem */ failf(data, "%s", error_buffer); return result; } } else { /* we have been connected fine, we're not waiting for anything else. */ connssl->connecting_state = ssl_connect_3; /* Informational message */ infof(data, "SSL connection using %s / %s\n", get_ssl_version_txt(connssl->handle), SSL_get_cipher(connssl->handle)); #ifdef HAS_ALPN /* Sets data and len to negotiated protocol, len is 0 if no protocol was * negotiated */ if(data->set.ssl_enable_alpn) { const unsigned char* neg_protocol; unsigned int len; <API key>(connssl->handle, &neg_protocol, &len); if(len != 0) { infof(data, "ALPN, server accepted to use %.*s\n", len, neg_protocol); #ifdef USE_NGHTTP2 if(len == <API key> && !memcmp(<API key>, neg_protocol, len)) { conn->negnpn = CURL_HTTP_VERSION_2; } else #endif if(len == <API key> && !memcmp(ALPN_HTTP_1_1, neg_protocol, <API key>)) { conn->negnpn = <API key>; } } else infof(data, "ALPN, server did not agree to a protocol\n"); } #endif return CURLE_OK; } } static int asn1_object_dump(ASN1_OBJECT *a, char *buf, size_t len) { int i, ilen; if((ilen = (int)len) < 0) return 1; /* buffer too big */ i = i2t_ASN1_OBJECT(buf, ilen, a); if(i >= ilen) return 1; /* buffer too small */ return 0; } #define push_certinfo(_label, _num) \ do { \ long info_len = BIO_get_mem_data(mem, &ptr); \ <API key>(data, _num, _label, ptr, info_len); \ if(1!=BIO_reset(mem)) \ break; \ } WHILE_FALSE static void pubkey_show(struct SessionHandle *data, BIO *mem, int num, const char *type, const char *name, BIGNUM *bn) { char *ptr; char namebuf[32]; snprintf(namebuf, sizeof(namebuf), "%s(%s)", type, name); BN_print(mem, bn); push_certinfo(namebuf, num); } #define print_pubkey_BN(_type, _name, _num) \ do { \ if(_type->_name) { \ pubkey_show(data, mem, _num, #_type, #_name, _type->_name); \ } \ } WHILE_FALSE static int X509V3_ext(struct SessionHandle *data, int certnum, STACK_OF(X509_EXTENSION) *exts) { int i; size_t j; if((int)<API key>(exts) <= 0) /* no extensions, bail out */ return 1; for(i=0; i < (int)<API key>(exts); i++) { ASN1_OBJECT *obj; X509_EXTENSION *ext = <API key>(exts, i); BUF_MEM *biomem; char buf[512]; char *ptr=buf; char namebuf[128]; BIO *bio_out = BIO_new(BIO_s_mem()); if(!bio_out) return 1; obj = <API key>(ext); asn1_object_dump(obj, namebuf, sizeof(namebuf)); if(!X509V3_EXT_print(bio_out, ext, 0, 0)) ASN1_STRING_print(bio_out, (ASN1_STRING *)<API key>(ext)); BIO_get_mem_ptr(bio_out, &biomem); for(j = 0; j < (size_t)biomem->length; j++) { const char *sep=""; if(biomem->data[j] == '\n') { sep=", "; j++; /* skip the newline */ }; while((j<(size_t)biomem->length) && (biomem->data[j] == ' ')) j++; if(j<(size_t)biomem->length) ptr+=snprintf(ptr, sizeof(buf)-(ptr-buf), "%s%c", sep, biomem->data[j]); } <API key>(data, certnum, namebuf, buf); BIO_free(bio_out); } return 0; /* all is fine */ } static CURLcode get_cert_chain(struct connectdata *conn, struct ssl_connect_data *connssl) { CURLcode result; STACK_OF(X509) *sk; int i; struct SessionHandle *data = conn->data; int numcerts; BIO *mem; sk = <API key>(connssl->handle); if(!sk) { return CURLE_OUT_OF_MEMORY; } numcerts = sk_X509_num(sk); result = <API key>(data, numcerts); if(result) { return result; } mem = BIO_new(BIO_s_mem()); for(i = 0; i < numcerts; i++) { ASN1_INTEGER *num; X509 *x = sk_X509_value(sk, i); EVP_PKEY *pubkey=NULL; int j; char *ptr; ASN1_BIT_STRING *psig; X509_NAME_print_ex(mem, <API key>(x), 0, XN_FLAG_ONELINE); push_certinfo("Subject", i); X509_NAME_print_ex(mem, <API key>(x), 0, XN_FLAG_ONELINE); push_certinfo("Issuer", i); BIO_printf(mem, "%lx", X509_get_version(x)); push_certinfo("Version", i); num = <API key>(x); if(num->type == V_ASN1_NEG_INTEGER) BIO_puts(mem, "-"); for(j = 0; j < num->length; j++) BIO_printf(mem, "%02x", num->data[j]); push_certinfo("Serial Number", i); #if defined(<API key>) && defined(<API key>) { X509_ALGOR *palg; ASN1_STRING *a = ASN1_STRING_new(); if(a) { X509_get0_signature(&psig, &palg, x); <API key>(mem, palg, a); ASN1_STRING_free(a); } i2a_ASN1_OBJECT(mem, palg->algorithm); push_certinfo("Public Key Algorithm", i); X509V3_ext(data, i, <API key>(x)); } #else { /* before OpenSSL 1.0.2 */ X509_CINF *cinf = x->cert_info; i2a_ASN1_OBJECT(mem, cinf->signature->algorithm); push_certinfo("Signature Algorithm", i); i2a_ASN1_OBJECT(mem, cinf->key->algor->algorithm); push_certinfo("Public Key Algorithm", i); X509V3_ext(data, i, cinf->extensions); psig = x->signature; } #endif ASN1_TIME_print(mem, X509_get_notBefore(x)); push_certinfo("Start date", i); ASN1_TIME_print(mem, X509_get_notAfter(x)); push_certinfo("Expire date", i); pubkey = X509_get_pubkey(x); if(!pubkey) infof(data, " Unable to load public key\n"); else { int pktype; #ifdef <API key> pktype = EVP_PKEY_id(pubkey); #else pktype = pubkey->type; #endif switch(pktype) { case EVP_PKEY_RSA: { RSA *rsa; #ifdef <API key> rsa = EVP_PKEY_get0_RSA(pubkey); #else rsa = pubkey->pkey.rsa; #endif BIO_printf(mem, "%d", BN_num_bits(rsa->n)); push_certinfo("RSA Public Key", i); print_pubkey_BN(rsa, n, i); print_pubkey_BN(rsa, e, i); print_pubkey_BN(rsa, d, i); print_pubkey_BN(rsa, p, i); print_pubkey_BN(rsa, q, i); print_pubkey_BN(rsa, dmp1, i); print_pubkey_BN(rsa, dmq1, i); print_pubkey_BN(rsa, iqmp, i); break; } case EVP_PKEY_DSA: { DSA *dsa; #ifdef <API key> dsa = EVP_PKEY_get0_DSA(pubkey); #else dsa = pubkey->pkey.dsa; #endif print_pubkey_BN(dsa, p, i); print_pubkey_BN(dsa, q, i); print_pubkey_BN(dsa, g, i); print_pubkey_BN(dsa, priv_key, i); print_pubkey_BN(dsa, pub_key, i); break; } case EVP_PKEY_DH: { DH *dh; #ifdef <API key> dh = EVP_PKEY_get0_DH(pubkey); #else dh = pubkey->pkey.dh; #endif print_pubkey_BN(dh, p, i); print_pubkey_BN(dh, g, i); print_pubkey_BN(dh, priv_key, i); print_pubkey_BN(dh, pub_key, i); break; } #if 0 case EVP_PKEY_EC: /* symbol not present in OpenSSL 0.9.6 */ /* left TODO */ break; #endif } EVP_PKEY_free(pubkey); } for(j = 0; j < psig->length; j++) BIO_printf(mem, "%02x:", psig->data[j]); push_certinfo("Signature", i); PEM_write_bio_X509(mem, x); push_certinfo("Cert", i); } BIO_free(mem); return CURLE_OK; } static CURLcode pkp_pin_peer_pubkey(struct SessionHandle *data, X509* cert, const char *pinnedpubkey) { /* Scratch */ int len1 = 0, len2 = 0; unsigned char *buff1 = NULL, *temp = NULL; /* Result is returned to caller */ CURLcode result = <API key>; /* if a path wasn't specified, don't pin */ if(!pinnedpubkey) return CURLE_OK; if(!cert) return result; do { /* Begin Gyrations to get the <API key> */ /* Thanks to Viktor Dukhovni on the OpenSSL mailing list */ len1 = i2d_X509_PUBKEY(<API key>(cert), NULL); if(len1 < 1) break; /* failed */ buff1 = temp = OPENSSL_malloc(len1); if(!buff1) break; /* failed */ len2 = i2d_X509_PUBKEY(<API key>(cert), &temp); /* * These checks are verifying we got back the same values as when we * sized the buffer. It's pretty weak since they should always be the * same. But it gives us something to test. */ if((len1 != len2) || !temp || ((temp - buff1) != len1)) break; /* failed */ /* End Gyrations */ /* The one good exit point */ result = <API key>(data, pinnedpubkey, buff1, len1); } while(0); if(buff1) OPENSSL_free(buff1); return result; } /* * Get the server cert, verify it and show it etc, only call failf() if the * 'strict' argument is TRUE as otherwise all this is for informational * purposes only! * * We check certificates to authenticate the server; otherwise we risk * man-in-the-middle attack. */ static CURLcode servercert(struct connectdata *conn, struct ssl_connect_data *connssl, bool strict) { CURLcode result = CURLE_OK; int rc; long lerr, len; struct SessionHandle *data = conn->data; X509 *issuer; FILE *fp; char *buffer = data->state.buffer; const char *ptr; BIO *mem = BIO_new(BIO_s_mem()); if(data->set.ssl.certinfo) /* we've been asked to gather certificate info! */ (void)get_cert_chain(conn, connssl); connssl->server_cert = <API key>(connssl->handle); if(!connssl->server_cert) { if(!strict) return CURLE_OK; failf(data, "SSL: couldn't get peer certificate!"); return <API key>; } infof(data, "Server certificate:\n"); rc = x509_name_oneline(<API key>(connssl->server_cert), buffer, BUFSIZE); infof(data, " subject: %s\n", rc?"[NONE]":buffer); ASN1_TIME_print(mem, X509_get_notBefore(connssl->server_cert)); len = BIO_get_mem_data(mem, (char **) &ptr); infof(data, " start date: %.*s\n", len, ptr); rc = BIO_reset(mem); ASN1_TIME_print(mem, X509_get_notAfter(connssl->server_cert)); len = BIO_get_mem_data(mem, (char **) &ptr); infof(data, " expire date: %.*s\n", len, ptr); rc = BIO_reset(mem); BIO_free(mem); if(data->set.ssl.verifyhost) { result = verifyhost(conn, connssl->server_cert); if(result) { X509_free(connssl->server_cert); connssl->server_cert = NULL; return result; } } rc = x509_name_oneline(<API key>(connssl->server_cert), buffer, BUFSIZE); if(rc) { if(strict) failf(data, "SSL: couldn't get X509-issuer name!"); result = <API key>; } else { infof(data, " issuer: %s\n", buffer); /* We could do all sorts of certificate verification stuff here before deallocating the certificate. */ /* e.g. match issuer name with provided issuer certificate */ if(data->set.str[<API key>]) { fp = fopen(data->set.str[<API key>], FOPEN_READTEXT); if(!fp) { if(strict) failf(data, "SSL: Unable to open issuer cert (%s)", data->set.str[<API key>]); X509_free(connssl->server_cert); connssl->server_cert = NULL; return <API key>; } issuer = PEM_read_X509(fp, NULL, ZERO_NULL, NULL); if(!issuer) { if(strict) failf(data, "SSL: Unable to read issuer cert (%s)", data->set.str[<API key>]); X509_free(connssl->server_cert); X509_free(issuer); fclose(fp); return <API key>; } fclose(fp); if(X509_check_issued(issuer, connssl->server_cert) != X509_V_OK) { if(strict) failf(data, "SSL: Certificate issuer check failed (%s)", data->set.str[<API key>]); X509_free(connssl->server_cert); X509_free(issuer); connssl->server_cert = NULL; return <API key>; } infof(data, " SSL certificate issuer check ok (%s)\n", data->set.str[<API key>]); X509_free(issuer); } lerr = data->set.ssl.certverifyresult = <API key>(connssl->handle); if(data->set.ssl.certverifyresult != X509_V_OK) { if(data->set.ssl.verifypeer) { /* We probably never reach this, because SSL_connect() will fail and we return earlier if verifypeer is set? */ if(strict) failf(data, "SSL certificate verify result: %s (%ld)", <API key>(lerr), lerr); result = <API key>; } else infof(data, " SSL certificate verify result: %s (%ld)," " continuing anyway.\n", <API key>(lerr), lerr); } else infof(data, " SSL certificate verify ok.\n"); } #if (<API key> >= 0x0090808fL) && !defined(OPENSSL_NO_TLSEXT) && \ !defined(OPENSSL_NO_OCSP) if(data->set.ssl.verifystatus) { result = verifystatus(conn, connssl); if(result) { X509_free(connssl->server_cert); connssl->server_cert = NULL; return result; } } #endif if(!strict) /* when not strict, we don't bother about the verify cert problems */ result = CURLE_OK; ptr = data->set.str[<API key>]; if(!result && ptr) { result = pkp_pin_peer_pubkey(data, connssl->server_cert, ptr); if(result) failf(data, "SSL: public key does not match pinned public key!"); } X509_free(connssl->server_cert); connssl->server_cert = NULL; connssl->connecting_state = ssl_connect_done; return result; } static CURLcode ossl_connect_step3(struct connectdata *conn, int sockindex) { CURLcode result = CURLE_OK; void *old_ssl_sessionid = NULL; struct SessionHandle *data = conn->data; struct ssl_connect_data *connssl = &conn->ssl[sockindex]; bool incache; SSL_SESSION *our_ssl_sessionid; DEBUGASSERT(ssl_connect_3 == connssl->connecting_state); our_ssl_sessionid = SSL_get1_session(connssl->handle); /* SSL_get1_session() will increment the reference count and the session will stay in memory until explicitly freed with SSL_SESSION_free(3), regardless of its state. */ incache = !(<API key>(conn, &old_ssl_sessionid, NULL)); if(incache) { if(old_ssl_sessionid != our_ssl_sessionid) { infof(data, "old SSL session ID is stale, removing\n"); <API key>(conn, old_ssl_sessionid); incache = FALSE; } } if(!incache) { result = <API key>(conn, our_ssl_sessionid, 0 /* unknown size */); if(result) { failf(data, "failed to store ssl session"); return result; } } else { /* Session was incache, so refcount already incremented earlier. * Avoid further increments with each SSL_get1_session() call. * This does not free the session as refcount remains > 0 */ SSL_SESSION_free(our_ssl_sessionid); } /* * We check certificates to authenticate the server; otherwise we risk * man-in-the-middle attack; NEVERTHELESS, if we're told explicitly not to * verify the peer ignore faults and failures from the server cert * operations. */ result = servercert(conn, connssl, (data->set.ssl.verifypeer || data->set.ssl.verifyhost)); if(!result) connssl->connecting_state = ssl_connect_done; return result; } static Curl_recv ossl_recv; static Curl_send ossl_send; static CURLcode ossl_connect_common(struct connectdata *conn, int sockindex, bool nonblocking, bool *done) { CURLcode result; struct SessionHandle *data = conn->data; struct ssl_connect_data *connssl = &conn->ssl[sockindex]; curl_socket_t sockfd = conn->sock[sockindex]; long timeout_ms; int what; /* check if the connection has already been established */ if(<API key> == connssl->state) { *done = TRUE; return CURLE_OK; } if(ssl_connect_1 == connssl->connecting_state) { /* Find out how much more time we're allowed */ timeout_ms = Curl_timeleft(data, NULL, TRUE); if(timeout_ms < 0) { /* no need to continue if time already is up */ failf(data, "SSL connection timeout"); return <API key>; } result = ossl_connect_step1(conn, sockindex); if(result) return result; } while(ssl_connect_2 == connssl->connecting_state || <API key> == connssl->connecting_state || <API key> == connssl->connecting_state) { /* check allowed time left */ timeout_ms = Curl_timeleft(data, NULL, TRUE); if(timeout_ms < 0) { /* no need to continue if time already is up */ failf(data, "SSL connection timeout"); return <API key>; } /* if ssl is expecting something, check if it's available. */ if(connssl->connecting_state == <API key> || connssl->connecting_state == <API key>) { curl_socket_t writefd = <API key>== connssl->connecting_state?sockfd:CURL_SOCKET_BAD; curl_socket_t readfd = <API key>== connssl->connecting_state?sockfd:CURL_SOCKET_BAD; what = Curl_socket_ready(readfd, writefd, nonblocking?0:timeout_ms); if(what < 0) { /* fatal error */ failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO); return <API key>; } else if(0 == what) { if(nonblocking) { *done = FALSE; return CURLE_OK; } else { /* timeout */ failf(data, "SSL connection timeout"); return <API key>; } } /* socket is readable or writable */ } /* Run transaction, and return to the caller if it failed or if this * connection is done nonblocking and this loop would execute again. This * permits the owner of a multi handle to abort a connection attempt * before step2 has completed while ensuring that a client using select() * or epoll() will always have a valid fdset to wait on. */ result = ossl_connect_step2(conn, sockindex); if(result || (nonblocking && (ssl_connect_2 == connssl->connecting_state || <API key> == connssl->connecting_state || <API key> == connssl->connecting_state))) return result; } /* repeat step2 until all transactions are done. */ if(ssl_connect_3 == connssl->connecting_state) { result = ossl_connect_step3(conn, sockindex); if(result) return result; } if(ssl_connect_done == connssl->connecting_state) { connssl->state = <API key>; conn->recv[sockindex] = ossl_recv; conn->send[sockindex] = ossl_send; *done = TRUE; } else *done = FALSE; /* Reset our connect state machine */ connssl->connecting_state = ssl_connect_1; return CURLE_OK; } CURLcode <API key>(struct connectdata *conn, int sockindex, bool *done) { return ossl_connect_common(conn, sockindex, TRUE, done); } CURLcode Curl_ossl_connect(struct connectdata *conn, int sockindex) { CURLcode result; bool done = FALSE; result = ossl_connect_common(conn, sockindex, FALSE, &done); if(result) return result; DEBUGASSERT(done); return CURLE_OK; } bool <API key>(const struct connectdata *conn, int connindex) { if(conn->ssl[connindex].handle) /* SSL is in use */ return (0 != SSL_pending(conn->ssl[connindex].handle)) ? TRUE : FALSE; else return FALSE; } static ssize_t ossl_send(struct connectdata *conn, int sockindex, const void *mem, size_t len, CURLcode *curlcode) { /* SSL_write() is said to return 'int' while write() and send() returns 'size_t' */ int err; char error_buffer[120]; /* OpenSSL documents that this must be at least 120 bytes long. */ unsigned long sslerror; int memlen; int rc; ERR_clear_error(); memlen = (len > (size_t)INT_MAX) ? INT_MAX : (int)len; rc = SSL_write(conn->ssl[sockindex].handle, mem, memlen); if(rc <= 0) { err = SSL_get_error(conn->ssl[sockindex].handle, rc); switch(err) { case SSL_ERROR_WANT_READ: case <API key>: /* The operation did not complete; the same TLS/SSL I/O function should be called again later. This is basically an EWOULDBLOCK equivalent. */ *curlcode = CURLE_AGAIN; return -1; case SSL_ERROR_SYSCALL: failf(conn->data, "SSL_write() returned SYSCALL, errno = %d", SOCKERRNO); *curlcode = CURLE_SEND_ERROR; return -1; case SSL_ERROR_SSL: /* A failure in the SSL library occurred, usually a protocol error. The OpenSSL error queue contains more information on the error. */ sslerror = ERR_get_error(); failf(conn->data, "SSL_write() error: %s", ERR_error_string(sslerror, error_buffer)); *curlcode = CURLE_SEND_ERROR; return -1; } /* a true error */ failf(conn->data, "SSL_write() return error %d", err); *curlcode = CURLE_SEND_ERROR; return -1; } *curlcode = CURLE_OK; return (ssize_t)rc; /* number of bytes */ } static ssize_t ossl_recv(struct connectdata *conn, /* connection data */ int num, /* socketindex */ char *buf, /* store read data here */ size_t buffersize, /* max amount to read */ CURLcode *curlcode) { char error_buffer[120]; /* OpenSSL documents that this must be at least 120 bytes long. */ unsigned long sslerror; ssize_t nread; int buffsize; ERR_clear_error(); buffsize = (buffersize > (size_t)INT_MAX) ? INT_MAX : (int)buffersize; nread = (ssize_t)SSL_read(conn->ssl[num].handle, buf, buffsize); if(nread <= 0) { /* failed SSL_read */ int err = SSL_get_error(conn->ssl[num].handle, (int)nread); switch(err) { case SSL_ERROR_NONE: /* this is not an error */ case <API key>: /* no more data */ break; case SSL_ERROR_WANT_READ: case <API key>: /* there's data pending, re-invoke SSL_read() */ *curlcode = CURLE_AGAIN; return -1; default: /* openssl/ssl.h for SSL_ERROR_SYSCALL says "look at error stack/return value/errno" */ sslerror = ERR_get_error(); if((nread < 0) || sslerror) { /* If the return code was negative or there actually is an error in the queue */ failf(conn->data, "SSL read: %s, errno %d", ERR_error_string(sslerror, error_buffer), SOCKERRNO); *curlcode = CURLE_RECV_ERROR; return -1; } } } return nread; } size_t Curl_ossl_version(char *buffer, size_t size) { #ifdef <API key> return snprintf(buffer, size, OSSL_PACKAGE); #else /* <API key> */ char sub[3]; unsigned long ssleay_value; sub[2]='\0'; sub[1]='\0'; ssleay_value=SSLeay(); if(ssleay_value < 0x906000) { ssleay_value=<API key>; sub[0]='\0'; } else { if(ssleay_value&0xff0) { int minor_ver = (ssleay_value >> 4) & 0xff; if(minor_ver > 26) { /* handle extended version introduced for 0.9.8za */ sub[1] = (char) ((minor_ver - 1) % 26 + 'a' + 1); sub[0] = 'z'; } else { sub[0]=(char)(((ssleay_value>>4)&0xff) + 'a' -1); } } else sub[0]='\0'; } return snprintf(buffer, size, "%s/%lx.%lx.%lx%s", OSSL_PACKAGE, (ssleay_value>>28)&0xf, (ssleay_value>>20)&0xff, (ssleay_value>>12)&0xff, sub); #endif /* <API key> */ } /* can be called with data == NULL */ int Curl_ossl_random(struct SessionHandle *data, unsigned char *entropy, size_t length) { if(data) { Curl_ossl_seed(data); /* Initiate the seed if not already done */ } RAND_bytes(entropy, curlx_uztosi(length)); return 0; /* 0 as in no problem */ } void Curl_ossl_md5sum(unsigned char *tmp, /* input */ size_t tmplen, unsigned char *md5sum /* output */, size_t unused) { MD5_CTX MD5pw; (void)unused; MD5_Init(&MD5pw); MD5_Update(&MD5pw, tmp, tmplen); MD5_Final(md5sum, &MD5pw); } #if (<API key> >= 0x0090800fL) && !defined(OPENSSL_NO_SHA256) void Curl_ossl_sha256sum(const unsigned char *tmp, /* input */ size_t tmplen, unsigned char *sha256sum /* output */, size_t unused) { SHA256_CTX SHA256pw; (void)unused; SHA256_Init(&SHA256pw); SHA256_Update(&SHA256pw, tmp, tmplen); SHA256_Final(sha256sum, &SHA256pw); } #endif bool <API key>(void) { #if (<API key> >= 0x0090808fL) && !defined(OPENSSL_NO_TLSEXT) && \ !defined(OPENSSL_NO_OCSP) return TRUE; #else return FALSE; #endif } #endif /* USE_OPENSSL */
class Openimageio < Formula desc "Library for reading, processing and writing images" homepage "http://openimageio.org/" url "https://github.com/OpenImageIO/oiio/archive/Release-1.8.17.tar.gz" sha256 "<SHA256-like>" head "https://github.com/OpenImageIO/oiio.git" bottle do sha256 "<SHA256-like>" => :mojave sha256 "<SHA256-like>" => :high_sierra sha256 "<SHA256-like>" => :sierra end depends_on "cmake" => :build depends_on "pkg-config" => :build depends_on "boost" depends_on "boost-python" depends_on "boost-python3" depends_on "ffmpeg" depends_on "freetype" depends_on "giflib" depends_on "ilmbase" depends_on "jpeg" depends_on "libpng" depends_on "libraw" depends_on "libtiff" depends_on "opencolorio" depends_on "openexr" depends_on "python" depends_on "webp" def install # -DUSE_OPENSSL=OFF can be removed in 1.9, see args = std_cmake_args + %w[ -DEMBEDPLUGINS=ON -DUSE_FIELD3D=OFF -DUSE_JPEGTURBO=OFF -DUSE_NUKE=OFF -DUSE_OPENCV=OFF -DUSE_OPENGL=OFF -DUSE_OPENJPEG=OFF -DUSE_OPENSSL=OFF -DUSE_PTEX=OFF -DUSE_QT=OFF ] mkdir "build-with-python2" do system "cmake", "..", "-<API key>=#{Formula["boost-python"].opt_lib}/<API key>.dylib", *args system "make", "install" end # CMake picks up the system's python dylib, even if we have a brewed one. py3ver = Language::Python.major_minor_version "python3" py3prefix = Formula["python3"].opt_frameworks/"Python.framework/Versions/#{py3ver}" ENV["PYTHONPATH"] = lib/"python#{py3ver}/site-packages" args << "-DPYTHON_EXECUTABLE=#{py3prefix}/bin/python3" args << "-DPYTHON_LIBRARY=#{py3prefix}/lib/libpython#{py3ver}.dylib" args << "-DPYTHON_INCLUDE_DIR=#{py3prefix}/include/python#{py3ver}m" # CMake picks up boost-python instead of boost-python3 args << "-DBOOST_ROOT=#{Formula["boost"].opt_prefix}" args << "-<API key>=#{Formula["boost-python3"].opt_lib}/libboost_python#{py3ver.to_s.delete(".")}-mt.dylib" # This is strange, but must be set to make the hack above work args << "-<API key>=''" args << "-<API key>=''" # Need to make a second build dir, otherwise cmake picks up cached files # and builds against `boost-python` mkdir "build-with-python3" do system "cmake", "..", *args system "make", "install" end end test do test_image = test_fixtures("test.jpg") assert_match "#{test_image} : 1 x 1, 3 channel, uint8 jpeg", shell_output("#{bin}/oiiotool --info #{test_image} 2>&1") ["python", "python3"].each do |python| output = <<~EOS from __future__ import print_function import OpenImageIO print(OpenImageIO.VERSION_STRING) EOS assert_match version.to_s, pipe_output(python, output, 0) end end end
package org.darkstorm.darkbot.minecraftbot.protocol.v74.packets; import java.io.*; import org.darkstorm.darkbot.minecraftbot.protocol.*; public class <API key> extends AbstractPacket implements ReadablePacket { public byte type; public int x, y, z; public <API key>() { } @Override public void readData(DataInputStream in) throws IOException { type = in.readByte(); x = in.readInt(); y = in.readInt(); z = in.readInt(); } @Override public int getId() { return 133; } }
OFFICIAL_CASK_TAPS = %w[ cask versions ].freeze OFFICIAL_CMD_TAPS = { "homebrew/bundle" => ["bundle"], "homebrew/test-bot" => ["test-bot"], "homebrew/services" => ["services"], }.freeze <API key> = %w[ apache binary completions devel-only dupes emacs fuse games gui head-only nginx php python science tex versions x11 ].freeze
#ifndef RetainPtr_h #define RetainPtr_h #include "wtf/<API key>.h" #include "wtf/HashTraits.h" #include "wtf/TypeTraits.h" #include <algorithm> #include <type_traits> #include <utility> #if USE(CF) #include <CoreFoundation/CoreFoundation.h> #endif #ifdef __OBJC__ #import <Foundation/Foundation.h> #endif #ifndef <API key> #define <API key> #endif #ifndef <API key> #define <API key> #endif namespace WTF { // Unlike most most of our smart pointers, RetainPtr can take either the pointer // type or the pointed-to type, so both RetainPtr<NSDictionary> and // RetainPtr<CFDictionaryRef> will work. enum AdoptCFTag { AdoptCF }; enum AdoptNSTag { AdoptNS }; #ifdef __OBJC__ inline void adoptNSReference(id ptr) { if (ptr) { CFRetain(ptr); [ptr release]; } } #endif template <typename T> class RetainPtr { public: typedef typename std::remove_pointer<T>::type ValueType; typedef ValueType* PtrType; RetainPtr() : m_ptr(nullptr) {} RetainPtr(PtrType ptr) : m_ptr(ptr) { if (ptr) CFRetain(ptr); } RetainPtr(AdoptCFTag, PtrType ptr) : m_ptr(ptr) {} RetainPtr(AdoptNSTag, PtrType ptr) : m_ptr(ptr) { adoptNSReference(ptr); } RetainPtr(const RetainPtr& o) : m_ptr(o.m_ptr) { if (PtrType ptr = m_ptr) CFRetain(ptr); } RetainPtr(RetainPtr&& o) : m_ptr(o.leakRef()) {} // Hash table deleted values, which are only constructed and never copied or // destroyed. RetainPtr(<API key>) : m_ptr(<API key>()) {} bool <API key>() const { return m_ptr == <API key>(); } ~RetainPtr() { if (PtrType ptr = m_ptr) CFRelease(ptr); } template <typename U> RetainPtr(const RetainPtr<U>&); void clear(); PtrType leakRef() WARN_UNUSED_RETURN; PtrType get() const { return m_ptr; } PtrType operator->() const { return m_ptr; } bool operator!() const { return !m_ptr; } explicit operator bool() const { return m_ptr; } RetainPtr& operator=(const RetainPtr&); template <typename U> RetainPtr& operator=(const RetainPtr<U>&); RetainPtr& operator=(PtrType); template <typename U> RetainPtr& operator=(U*); RetainPtr& operator=(RetainPtr&&); template <typename U> RetainPtr& operator=(RetainPtr<U>&&); RetainPtr& operator=(std::nullptr_t) { clear(); return *this; } void adoptCF(PtrType); void adoptNS(PtrType); void swap(RetainPtr&); private: static PtrType <API key>() { return reinterpret_cast<PtrType>(-1); } PtrType m_ptr; }; template <typename T> template <typename U> inline RetainPtr<T>::RetainPtr(const RetainPtr<U>& o) : m_ptr(o.get()) { if (PtrType ptr = m_ptr) CFRetain(ptr); } template <typename T> inline void RetainPtr<T>::clear() { if (PtrType ptr = m_ptr) { m_ptr = nullptr; CFRelease(ptr); } } template <typename T> inline typename RetainPtr<T>::PtrType RetainPtr<T>::leakRef() { PtrType ptr = m_ptr; m_ptr = nullptr; return ptr; } template <typename T> inline RetainPtr<T>& RetainPtr<T>::operator=(const RetainPtr<T>& o) { PtrType optr = o.get(); if (optr) CFRetain(optr); PtrType ptr = m_ptr; m_ptr = optr; if (ptr) CFRelease(ptr); return *this; } template <typename T> template <typename U> inline RetainPtr<T>& RetainPtr<T>::operator=(const RetainPtr<U>& o) { PtrType optr = o.get(); if (optr) CFRetain(optr); PtrType ptr = m_ptr; m_ptr = optr; if (ptr) CFRelease(ptr); return *this; } template <typename T> inline RetainPtr<T>& RetainPtr<T>::operator=(PtrType optr) { if (optr) CFRetain(optr); PtrType ptr = m_ptr; m_ptr = optr; if (ptr) CFRelease(ptr); return *this; } template <typename T> template <typename U> inline RetainPtr<T>& RetainPtr<T>::operator=(U* optr) { if (optr) CFRetain(optr); PtrType ptr = m_ptr; m_ptr = optr; if (ptr) CFRelease(ptr); return *this; } template <typename T> inline RetainPtr<T>& RetainPtr<T>::operator=(RetainPtr<T>&& o) { adoptCF(o.leakRef()); return *this; } template <typename T> template <typename U> inline RetainPtr<T>& RetainPtr<T>::operator=(RetainPtr<U>&& o) { adoptCF(o.leakRef()); return *this; } template <typename T> inline void RetainPtr<T>::adoptCF(PtrType optr) { PtrType ptr = m_ptr; m_ptr = optr; if (ptr) CFRelease(ptr); } template <typename T> inline void RetainPtr<T>::adoptNS(PtrType optr) { adoptNSReference(optr); PtrType ptr = m_ptr; m_ptr = optr; if (ptr) CFRelease(ptr); } template <typename T> inline void RetainPtr<T>::swap(RetainPtr<T>& o) { std::swap(m_ptr, o.m_ptr); } template <typename T> inline void swap(RetainPtr<T>& a, RetainPtr<T>& b) { a.swap(b); } template <typename T, typename U> inline bool operator==(const RetainPtr<T>& a, const RetainPtr<U>& b) { return a.get() == b.get(); } template <typename T, typename U> inline bool operator==(const RetainPtr<T>& a, U* b) { return a.get() == b; } template <typename T, typename U> inline bool operator==(T* a, const RetainPtr<U>& b) { return a == b.get(); } template <typename T, typename U> inline bool operator!=(const RetainPtr<T>& a, const RetainPtr<U>& b) { return a.get() != b.get(); } template <typename T, typename U> inline bool operator!=(const RetainPtr<T>& a, U* b) { return a.get() != b; } template <typename T, typename U> inline bool operator!=(T* a, const RetainPtr<U>& b) { return a != b.get(); } template <typename T> inline RetainPtr<T> adoptCF(T <API key>) WARN_UNUSED_RETURN; template <typename T> inline RetainPtr<T> adoptCF(T o) { return RetainPtr<T>(AdoptCF, o); } template <typename T> inline RetainPtr<T> adoptNS(T <API key>) WARN_UNUSED_RETURN; template <typename T> inline RetainPtr<T> adoptNS(T o) { return RetainPtr<T>(AdoptNS, o); } // Helper function for creating a RetainPtr using template argument deduction. template <typename T> inline RetainPtr<T> retainPtr(T) WARN_UNUSED_RETURN; template <typename T> inline RetainPtr<T> retainPtr(T o) { return RetainPtr<T>(o); } template <typename T> struct HashTraits<RetainPtr<T>> : <API key><RetainPtr<T>> {}; template <typename T> struct RetainPtrHash : PtrHash< typename std::remove_pointer<typename RetainPtr<T>::PtrType>::type> { using Base = PtrHash< typename std::remove_pointer<typename RetainPtr<T>::PtrType>::type>; using Base::hash; static unsigned hash(const RetainPtr<T>& key) { return hash(key.get()); } using Base::equal; static bool equal(const RetainPtr<T>& a, const RetainPtr<T>& b) { return a == b; } static bool equal(typename RetainPtr<T>::PtrType a, const RetainPtr<T>& b) { return a == b; } static bool equal(const RetainPtr<T>& a, typename RetainPtr<T>::PtrType b) { return a == b; } }; template <typename T> struct DefaultHash<RetainPtr<T>> { using Hash = RetainPtrHash<T>; }; } // namespace WTF using WTF::AdoptCF; using WTF::AdoptNS; using WTF::adoptCF; using WTF::adoptNS; using WTF::RetainPtr; using WTF::retainPtr; #endif // WTF_RetainPtr_h
cask :v1 => 'zendserver' do version '6.3.0' sha256 '<SHA256-like>' url "http://downloads.zend.com/zendserver/#{version}/ZendServer-#{version}-php-5.5.7.dmg" homepage 'http: license :unknown pkg 'Zend Server.pkg' uninstall :script => { :executable => '/usr/local/zend/bin/uninstall.sh', :args => ['--automatic'] }, :pkgutil => 'zenith.pkg.ZendServer' caveats do files_in_usr_local end end
import numpy as np import h5py from nideep.iow.file_system_utils import gen_paths, filter_is_h5 def id_loc_to_loc(fpath_src, key_dst, key_src='label_id_loc', has_void_bin=True): with h5py.File(fpath_src, 'r+') as h: if has_void_bin: l = np.sum(h[key_src][...,:-1], axis=1) else: l = np.sum(h[key_src], axis=1) l = np.expand_dims(l, 1) h[key_dst] = l def walk_id_loc_to_loc(dir_src, key_dst): def runner(fpath): if filter_is_h5(fpath): id_loc_to_loc(fpath, key_dst) return True # otherwise gen_paths won't append to list flist = gen_paths(dir_src, func_filter=runner) return flist if __name__ == '__main__': pass
#include <cmath> void initNaoModel (nao_igm& nao, double* ref_angles) { // joint angles nao.state_sensor.q[L_HIP_YAW_PITCH] = ref_angles[L_HIP_YAW_PITCH] = 0.0; nao.state_sensor.q[R_HIP_YAW_PITCH] = ref_angles[R_HIP_YAW_PITCH] = 0.0; nao.state_sensor.q[L_HIP_ROLL] = ref_angles[L_HIP_ROLL] = -0.000384; nao.state_sensor.q[L_HIP_PITCH] = ref_angles[L_HIP_PITCH] = -0.598291; nao.state_sensor.q[L_KNEE_PITCH] = ref_angles[L_KNEE_PITCH] = 1.009413; nao.state_sensor.q[L_ANKLE_PITCH] = ref_angles[L_ANKLE_PITCH] = -0.492352; nao.state_sensor.q[L_ANKLE_ROLL] = ref_angles[L_ANKLE_ROLL] = 0.000469; nao.state_sensor.q[R_HIP_ROLL] = ref_angles[R_HIP_ROLL] = -0.000384; nao.state_sensor.q[R_HIP_PITCH] = ref_angles[R_HIP_PITCH] = -0.598219; nao.state_sensor.q[R_KNEE_PITCH] = ref_angles[R_KNEE_PITCH] = 1.009237; nao.state_sensor.q[R_ANKLE_PITCH] = ref_angles[R_ANKLE_PITCH] = -0.492248; nao.state_sensor.q[R_ANKLE_ROLL] = ref_angles[R_ANKLE_ROLL] = 0.000469; nao.state_sensor.q[L_SHOULDER_PITCH] = 1.418908; nao.state_sensor.q[L_SHOULDER_ROLL] = 0.332836; nao.state_sensor.q[L_ELBOW_YAW] = -1.379108; nao.state_sensor.q[L_ELBOW_ROLL] = -1.021602; nao.state_sensor.q[L_WRIST_YAW] = -0.013848; nao.state_sensor.q[R_SHOULDER_PITCH] = 1.425128; nao.state_sensor.q[R_SHOULDER_ROLL] = -0.331386; nao.state_sensor.q[R_ELBOW_YAW] = 1.383626; nao.state_sensor.q[R_ELBOW_ROLL] = 1.029356; nao.state_sensor.q[R_WRIST_YAW] = -0.01078; nao.state_sensor.q[HEAD_PITCH] = 0.0; nao.state_sensor.q[HEAD_YAW] = 0.0; } class test_init_base { public: test_init_base(const string& test_name, const bool plot_ds_) { name = test_name; plot_ds = plot_ds_; if (!name.empty()) { cout << " cout << name << endl; cout << " fs_out_filename = name + "_fs.m"; } } ~test_init_base() { if (!name.empty()) { cout << " } } smpc::state_zmp X_tilde; WMG* wmg; smpc_parameters* par; nao_igm nao; double ref_angles[LOWER_JOINTS_NUM]; string name; string fs_out_filename; bool plot_ds; }; /** * @brief Walk straight */ class init_08 : public test_init_base { public: init_08 ( const string & test_name, const int <API key>, const bool plot_ds_ = true) : test_init_base (test_name, plot_ds_) { initNaoModel (nao, ref_angles); // support foot position and orientation nao.init ( IGM_SUPPORT_RIGHT, 0.0, -0.05, 0.0, 0.0, 0.0, 0.0); nao.getCoM(nao.state_sensor, nao.CoM_position); wmg = new WMG (40, <API key>, 0.02); par = new smpc_parameters (wmg->N, nao.CoM_position[2]); int ss_time_ms = 400; int ds_time_ms = 40; int ds_number = 3; // each step is defined relatively to the previous step double step_x = 0.04; // relative X position double step_y = wmg->def_constraints.support_distance_y; // relative Y position /* wmg-><API key> (0, 0, 0); wmg->addFootstep(0.0, -step_y/2, 0.0, FS_TYPE_SS_R); // Initial double support wmg-><API key> (3*ss_time_ms, 0, 0); wmg->addFootstep(0.0, step_y/2, 0.0, FS_TYPE_DS); // all subsequent steps have normal feet size wmg-><API key> (ss_time_ms, 0, 0); wmg->addFootstep(0.0 , step_y/2, 0.0); wmg-><API key> (ss_time_ms, ds_time_ms, ds_number); wmg->addFootstep(step_x, -step_y, 0.0); for (int i = 0; i < 3; i++) { wmg->addFootstep(step_x, step_y, 0.0); wmg->addFootstep(step_x, -step_y, 0.0); } // here we give many reference points, since otherwise we // would not have enough steps in preview window to reach // the last footsteps wmg-><API key> (5*ss_time_ms, 0, 0); wmg->addFootstep(0.0 , step_y/2, 0.0, FS_TYPE_DS); wmg-><API key> (0, 0, 0); wmg->addFootstep(0.0 , step_y/2, 0.0, FS_TYPE_SS_L); */ wmg-><API key>(0, 0, 0); wmg->addFootstep(0.0, step_y/2, 0.0, FS_TYPE_SS_L); // Initial double support wmg-><API key>(3*ss_time_ms, 0, 0); wmg->addFootstep(0.0, -step_y/2, 0.0, FS_TYPE_DS); // all subsequent steps have normal feet size wmg-><API key>(ss_time_ms, 0, 0); wmg->addFootstep(0.0 , -step_y/2, 0.0); wmg-><API key>(ss_time_ms, ds_time_ms, ds_number); wmg->addFootstep(step_x, step_y, 0.0); for (int i = 0; i < 4; i++) { wmg->addFootstep(step_x, -step_y, 0.0); wmg->addFootstep(step_x, step_y, 0.0); } // here we give many reference points, since otherwise we // would not have enough steps in preview window to reach // the last footsteps wmg-><API key>(5*ss_time_ms, 0, 0); wmg->addFootstep(0.0 , -step_y/2, 0.0, FS_TYPE_DS); wmg-><API key>(0, 0, 0); wmg->addFootstep(0.0 , -step_y/2, 0.0, FS_TYPE_SS_R); if (!name.empty()) { wmg->FS2file(fs_out_filename, plot_ds); } } }; /** * @brief Diagonal walk */ class init_09 : public test_init_base { public: init_09 ( const string & test_name, const int <API key>, const bool plot_ds_ = true) : test_init_base (test_name, plot_ds_) { initNaoModel (nao, ref_angles); // support foot position and orientation nao.init ( IGM_SUPPORT_LEFT, 0.0, 0.05, 0.0, 0.0, 0.0, 0.0); nao.getCoM(nao.state_sensor, nao.CoM_position); wmg = new WMG (40, <API key>, 0.02); par = new smpc_parameters (wmg->N, nao.CoM_position[2]); int ss_time_ms = 400; int ds_time_ms = 40; int ds_number = 3; // each step is defined relatively to the previous step double step_x = 0.04; // relative X position double step_y = wmg->def_constraints.support_distance_y; // relative Y position wmg-><API key> (0, 0, 0); wmg->addFootstep(0.0, step_y/2, 0.0, FS_TYPE_SS_L); // Initial double support wmg-><API key> (3*ss_time_ms, 0, 0); wmg->addFootstep(0.0, -step_y/2, 0.0, FS_TYPE_DS); // each step is defined relatively to the previous step double shift = -0.02; // all subsequent steps have normal feet size wmg-><API key> (ss_time_ms, ds_time_ms, ds_number); wmg->addFootstep(0.0 , -step_y/2, 0.0); wmg->addFootstep(step_x, step_y + shift, 0.0); wmg->addFootstep(step_x, -step_y + shift, 0.0); wmg->addFootstep(step_x, step_y + shift, 0.0); wmg->addFootstep(step_x, -step_y + shift, 0.0); wmg->addFootstep(step_x, step_y + shift, 0.0); wmg->addFootstep(step_x, -step_y + shift, 0.0); wmg->addFootstep(step_x, step_y + shift, 0.0); wmg->addFootstep(step_x, -step_y + shift, 0.0); wmg->addFootstep(step_x, step_y + shift, 0.0); // here we give many reference points, since otherwise we // would not have enough steps in preview window to reach // the last footsteps wmg-><API key> (5*ss_time_ms, 0, 0); wmg->addFootstep(0.0 , -step_y/2, 0.0, FS_TYPE_DS); wmg-><API key> (0, 0, 0); wmg->addFootstep(0.0 , -step_y/2, 0.0, FS_TYPE_SS_R); if (!name.empty()) { wmg->FS2file(fs_out_filename, plot_ds); } } }; /** * @brief Circular walk. // Doesn't work on the robot. */ class init_10 : public test_init_base { public: init_10 ( const string & test_name, const int <API key>, const bool plot_ds_ = true) : test_init_base (test_name, plot_ds_) { initNaoModel (nao, ref_angles); // support foot position and orientation nao.init ( IGM_SUPPORT_LEFT, 0.0, 0.05, 0.0, 0.0, 0.0, 0.0); nao.getCoM(nao.state_sensor, nao.CoM_position); wmg = new WMG (40, <API key>, 0.02); par = new smpc_parameters (wmg->N, nao.CoM_position[2]); int ss_time_ms = 400; int ds_time_ms = 40; int ds_number = 3; // each step is defined relatively to the previous step double step_x_ext = 0.04; // relative X position double step_y = wmg->def_constraints.support_distance_y; // relative Y position double R_ext = 0.55; double R_int = R_ext - step_y; // relative angle double a = asin (step_x_ext / R_ext); double step_x_int = step_x_ext * R_int / R_ext; // double step_x_int = step_x_ext; wmg-><API key> (0, 0, 0); wmg->addFootstep(0.0, step_y/2, 0.0, FS_TYPE_SS_L); // Initial double support wmg-><API key> (3*ss_time_ms, 0, 0); wmg->addFootstep(0.0, -step_y/2, 0.0, FS_TYPE_DS); wmg-><API key> (ss_time_ms, ds_time_ms, ds_number); wmg->addFootstep(0.0 , -step_y/2, 0.0); wmg->addFootstep(step_x_int, step_y, a); for (int i = 0; i < 10; i++) { wmg->addFootstep(step_x_ext, -step_y, a); wmg->addFootstep(step_x_int, step_y, a); } // here we give many reference points, since otherwise we // would not have enough steps in preview window to reach // the last footsteps wmg-><API key> (6*ss_time_ms, 0, 0); wmg->addFootstep(0.0 , -step_y/2, 0.0, FS_TYPE_DS); wmg-><API key> (0, 0, 0); wmg->addFootstep(0.0 , -step_y/2, 0.0, FS_TYPE_SS_R); if (!name.empty()) { wmg->FS2file(fs_out_filename, plot_ds); } } }; class init_11 : public test_init_base { public: init_11 ( const string & test_name, const int <API key>, const bool plot_ds_ = true) : test_init_base (test_name, plot_ds_) { initNaoModel (nao, ref_angles); // support foot position and orientation nao.init ( IGM_SUPPORT_LEFT, 0.0, 0.05, 0.0, 0.0, 0.0, 0.0); nao.getCoM(nao.state_sensor, nao.CoM_position); wmg = new WMG (40, <API key>, 0.02); par = new smpc_parameters (wmg->N, nao.CoM_position[2]); int ss_time_ms = 400; int ds_time_ms = 40; int ds_number = 3; // each step is defined relatively to the previous step double step_x = 0.04; // relative X position double step_y = wmg->def_constraints.support_distance_y; // relative Y position wmg-><API key>(0, 0, 0); wmg->addFootstep(0.0, step_y/2, 0.0, FS_TYPE_SS_L); // Initial double support wmg-><API key>(3*ss_time_ms, 0, 0); wmg->addFootstep(0.0, -step_y/2, 0.0, FS_TYPE_DS); // all subsequent steps have normal feet size wmg-><API key>(ss_time_ms, 0, 0); wmg->addFootstep(0.0 , -step_y/2, 0.0); wmg-><API key>(ss_time_ms, ds_time_ms, ds_number); wmg->addFootstep(step_x, step_y, 0.0); for (int i = 0; i < 2; i++) { wmg->addFootstep(step_x, -step_y, 0.0); wmg->addFootstep(step_x, step_y, 0.0); } // here we give many reference points, since otherwise we // would not have enough steps in preview window to reach // the last footsteps wmg-><API key>(5*ss_time_ms, 0, 0); wmg->addFootstep(0.0 , -step_y/2, 0.0, FS_TYPE_DS); wmg-><API key>(0, 0, 0); wmg->addFootstep(0.0 , -step_y/2, 0.0, FS_TYPE_SS_R); if (!name.empty()) { wmg->FS2file(fs_out_filename, plot_ds); } } };
#include <errno.h> #include <fcntl.h> #include <string.h> #include <sys/stat.h> #include <string> #include "dev_fs_for_testing.h" #include "gtest/gtest.h" #include "nacl_io/filesystem.h" #include "nacl_io/ioctl.h" #include "nacl_io/kernel_handle.h" #include "nacl_io/memfs/mem_fs.h" #include "nacl_io/osdirent.h" #include "nacl_io/osunistd.h" using namespace nacl_io; namespace { class MemFsForTesting : public MemFs { public: MemFsForTesting() { FsInitArgs args(1); EXPECT_EQ(0, Init(args)); } int num_nodes() { return (int)inode_pool_.size(); } }; } // namespace TEST(FilesystemTest, Sanity) { MemFsForTesting fs; ScopedNode file; ScopedNode root; ScopedNode result_node; size_t result_size = 0; int result_bytes = 0; char buf1[1024]; // A memory filesystem starts with one directory node: the root. EXPECT_EQ(1, fs.num_nodes()); // Fail to open non existent file EXPECT_EQ(ENOENT, fs.Access(Path("/foo"), R_OK | W_OK)); EXPECT_EQ(ENOENT, fs.Open(Path("/foo"), O_RDWR, &result_node)); EXPECT_EQ(NULL, result_node.get()); EXPECT_EQ(1, fs.num_nodes()); // Create a file EXPECT_EQ(0, fs.Open(Path("/foo"), O_RDWR | O_CREAT, &file)); ASSERT_NE(NULL_NODE, file.get()); // We now have a directory and a file. The file has a two references // one returned to the test, one for the name->inode map. EXPECT_EQ(2, fs.num_nodes()); EXPECT_EQ(2, file->RefCount()); EXPECT_EQ(0, fs.Access(Path("/foo"), R_OK | W_OK)); EXPECT_EQ(EACCES, fs.Access(Path("/foo"), X_OK)); // All access should be allowed on the root directory. EXPECT_EQ(0, fs.Access(Path("/"), R_OK | W_OK | X_OK)); // Open the root directory for write should fail. EXPECT_EQ(EISDIR, fs.Open(Path("/"), O_RDWR, &root)); EXPECT_EQ(2, fs.num_nodes()); // Open the root directory, should not create a new file EXPECT_EQ(0, fs.Open(Path("/"), O_RDONLY, &root)); EXPECT_EQ(2, fs.num_nodes()); ASSERT_NE(NULL_NODE, root.get()); struct dirent dirs[4]; int len; EXPECT_EQ(0, root->GetDents(0, dirs, sizeof(dirs), &len)); // 3 == "foo", ".", ".." EXPECT_EQ(3 * sizeof(struct dirent), len); // Fail to re-create the same file EXPECT_EQ(EEXIST, fs.Open(Path("/foo"), O_RDWR | O_CREAT | O_EXCL, &result_node)); EXPECT_EQ(NULL_NODE, result_node.get()); EXPECT_EQ(2, fs.num_nodes()); // Fail to create a directory with the same name EXPECT_EQ(EEXIST, fs.Mkdir(Path("/foo"), O_RDWR)); EXPECT_EQ(2, fs.num_nodes()); HandleAttr attrs; // Attempt to READ/WRITE EXPECT_EQ(0, file->GetSize(&result_size)); EXPECT_EQ(0, result_size); EXPECT_EQ(0, file->Write(attrs, buf1, sizeof(buf1), &result_bytes)); EXPECT_EQ(sizeof(buf1), result_bytes); EXPECT_EQ(0, file->GetSize(&result_size)); EXPECT_EQ(sizeof(buf1), result_size); EXPECT_EQ(0, file->Read(attrs, buf1, sizeof(buf1), &result_bytes)); EXPECT_EQ(sizeof(buf1), result_bytes); EXPECT_EQ(2, fs.num_nodes()); EXPECT_EQ(2, file->RefCount()); // Attempt to open the same file, create another ref to it, but does not // create a new file. EXPECT_EQ(0, fs.Open(Path("/foo"), O_RDWR | O_CREAT, &result_node)); EXPECT_EQ(3, file->RefCount()); EXPECT_EQ(2, fs.num_nodes()); EXPECT_EQ(file.get(), result_node.get()); EXPECT_EQ(0, file->GetSize(&result_size)); EXPECT_EQ(sizeof(buf1), result_size); // Remove our references so that only the Filesystem holds it file.reset(); result_node.reset(); EXPECT_EQ(2, fs.num_nodes()); // This should have deleted the object EXPECT_EQ(0, fs.Unlink(Path("/foo"))); EXPECT_EQ(1, fs.num_nodes()); // We should fail to find it EXPECT_EQ(ENOENT, fs.Unlink(Path("/foo"))); EXPECT_EQ(1, fs.num_nodes()); // Recreate foo as a directory EXPECT_EQ(0, fs.Mkdir(Path("/foo"), O_RDWR)); EXPECT_EQ(2, fs.num_nodes()); // Create a file (exclusively) EXPECT_EQ(0, fs.Open(Path("/foo/bar"), O_RDWR | O_CREAT | O_EXCL, &file)); ASSERT_NE(NULL_NODE, file.get()); EXPECT_EQ(2, file->RefCount()); EXPECT_EQ(3, fs.num_nodes()); // Attempt to delete the directory and fail EXPECT_EQ(ENOTEMPTY, fs.Rmdir(Path("/foo"))); EXPECT_EQ(2, root->RefCount()); EXPECT_EQ(2, file->RefCount()); EXPECT_EQ(3, fs.num_nodes()); // Unlink the file, we should have the only file ref at this point. EXPECT_EQ(0, fs.Unlink(Path("/foo/bar"))); EXPECT_EQ(2, root->RefCount()); EXPECT_EQ(1, file->RefCount()); EXPECT_EQ(3, fs.num_nodes()); // Deref the file, to make it go away file.reset(); EXPECT_EQ(2, fs.num_nodes()); // Deref the directory EXPECT_EQ(0, fs.Rmdir(Path("/foo"))); EXPECT_EQ(1, fs.num_nodes()); // Verify the directory is gone EXPECT_EQ(ENOENT, fs.Access(Path("/foo"), F_OK)); EXPECT_EQ(ENOENT, fs.Open(Path("/foo"), O_RDWR, &file)); EXPECT_EQ(NULL_NODE, file.get()); } TEST(FilesystemTest, OpenMode_TRUNC) { MemFsForTesting fs; ScopedNode file; ScopedNode root; ScopedNode result_node; HandleAttr attrs; int result_bytes; // Open a file and write something to it. const char* buf = "hello"; ASSERT_EQ(0, fs.Open(Path("/foo"), O_RDWR | O_CREAT, &file)); ASSERT_EQ(0, file->Write(attrs, buf, strlen(buf), &result_bytes)); ASSERT_EQ(strlen(buf), result_bytes); // Open it again with TRUNC and make sure it is empty char read_buf[10]; ASSERT_EQ(0, fs.Open(Path("/foo"), O_RDWR | O_TRUNC, &file)); ASSERT_EQ(0, file->Read(attrs, read_buf, sizeof(read_buf), &result_bytes)); ASSERT_EQ(0, result_bytes); } TEST(FilesystemTest, MemFsRemove) { MemFsForTesting fs; ScopedNode file; ScopedNode result_node; ASSERT_EQ(0, fs.Mkdir(Path("/dir"), O_RDWR)); ASSERT_EQ(0, fs.Open(Path("/file"), O_RDWR | O_CREAT | O_EXCL, &file)); EXPECT_NE(NULL_NODE, file.get()); EXPECT_EQ(3, fs.num_nodes()); file.reset(); EXPECT_EQ(0, fs.Remove(Path("/dir"))); EXPECT_EQ(2, fs.num_nodes()); EXPECT_EQ(0, fs.Remove(Path("/file"))); EXPECT_EQ(1, fs.num_nodes()); ASSERT_EQ(ENOENT, fs.Open(Path("/dir/foo"), O_CREAT | O_RDWR, &result_node)); ASSERT_EQ(NULL_NODE, result_node.get()); ASSERT_EQ(ENOENT, fs.Open(Path("/file"), O_RDONLY, &result_node)); ASSERT_EQ(NULL_NODE, result_node.get()); } TEST(FilesystemTest, MemFsRename) { MemFsForTesting fs; ASSERT_EQ(0, fs.Mkdir(Path("/dir1"), O_RDWR)); ASSERT_EQ(0, fs.Mkdir(Path("/dir2"), O_RDWR)); ASSERT_EQ(3, fs.num_nodes()); ScopedNode file; ASSERT_EQ(0, fs.Open(Path("/dir1/file"), O_RDWR | O_CREAT | O_EXCL, &file)); ASSERT_EQ(0, fs.Access(Path("/dir1/file"), R_OK)); ASSERT_EQ(4, fs.num_nodes()); // Move from one directory to another should ok ASSERT_EQ(0, fs.Rename(Path("/dir1/file"), Path("/dir2/new_file"))); ASSERT_NE(0, fs.Access(Path("/dir1/file"), R_OK)); ASSERT_EQ(0, fs.Access(Path("/dir2/new_file"), R_OK)); ASSERT_EQ(4, fs.num_nodes()); // Move within the same directory ASSERT_EQ(0, fs.Rename(Path("/dir2/new_file"), Path("/dir2/new_file2"))); ASSERT_NE(0, fs.Access(Path("/dir2/new_file"), R_OK)); ASSERT_EQ(0, fs.Access(Path("/dir2/new_file2"), R_OK)); ASSERT_EQ(4, fs.num_nodes()); // Move to another directory but without a filename ASSERT_EQ(0, fs.Rename(Path("/dir2/new_file2"), Path("/dir1"))); ASSERT_NE(0, fs.Access(Path("/dir2/new_file2"), R_OK)); ASSERT_EQ(0, fs.Access(Path("/dir1/new_file2"), R_OK)); ASSERT_EQ(4, fs.num_nodes()); } TEST(FilesystemTest, MemFsRenameDir) { MemFsForTesting fs; ASSERT_EQ(0, fs.Mkdir(Path("/dir1"), O_RDWR)); ASSERT_EQ(0, fs.Mkdir(Path("/dir2"), O_RDWR)); EXPECT_EQ(3, fs.num_nodes()); // Renaming one directory to another should work ASSERT_EQ(0, fs.Rename(Path("/dir1"), Path("/dir2"))); ASSERT_NE(0, fs.Access(Path("/dir1"), R_OK)); ASSERT_EQ(0, fs.Access(Path("/dir2"), R_OK)); EXPECT_EQ(2, fs.num_nodes()); // Reset to initial state ASSERT_EQ(0, fs.Mkdir(Path("/dir1"), O_RDWR)); EXPECT_EQ(3, fs.num_nodes()); // Renaming a directory to a new name within another ASSERT_EQ(0, fs.Rename(Path("/dir1"), Path("/dir2/foo"))); ASSERT_EQ(0, fs.Access(Path("/dir2"), R_OK)); ASSERT_EQ(0, fs.Access(Path("/dir2/foo"), R_OK)); EXPECT_EQ(3, fs.num_nodes()); // Reset to initial state ASSERT_EQ(0, fs.Rmdir(Path("/dir2/foo"))); ASSERT_EQ(0, fs.Mkdir(Path("/dir1"), O_RDWR)); EXPECT_EQ(3, fs.num_nodes()); // Renaming one directory to another should fail if the target is non-empty ASSERT_EQ(0, fs.Mkdir(Path("/dir2/dir3"), O_RDWR)); ASSERT_EQ(ENOTEMPTY, fs.Rename(Path("/dir1"), Path("/dir2"))); } TEST(FilesystemTest, DevAccess) { // Should not be able to open non-existent file. DevFsForTesting fs; ScopedNode invalid_node, valid_node; ASSERT_EQ(ENOENT, fs.Access(Path("/foo"), F_OK)); // Creating non-existent file should return EACCES ASSERT_EQ(EACCES, fs.Open(Path("/foo"), O_CREAT | O_RDWR, &invalid_node)); // We should be able to open all existing nodes with O_CREAT and O_RDWR. ASSERT_EQ(0, fs.Open(Path("/null"), O_CREAT | O_RDWR, &valid_node)); ASSERT_EQ(0, fs.Open(Path("/zero"), O_CREAT | O_RDWR, &valid_node)); ASSERT_EQ(0, fs.Open(Path("/urandom"), O_CREAT | O_RDWR, &valid_node)); ASSERT_EQ(0, fs.Open(Path("/console0"), O_CREAT | O_RDWR, &valid_node)); ASSERT_EQ(0, fs.Open(Path("/console1"), O_CREAT | O_RDWR, &valid_node)); ASSERT_EQ(0, fs.Open(Path("/console3"), O_CREAT | O_RDWR, &valid_node)); ASSERT_EQ(0, fs.Open(Path("/tty"), O_CREAT | O_RDWR, &valid_node)); ASSERT_EQ(0, fs.Open(Path("/stdin"), O_CREAT | O_RDWR, &valid_node)); ASSERT_EQ(0, fs.Open(Path("/stdout"), O_CREAT | O_RDWR, &valid_node)); ASSERT_EQ(0, fs.Open(Path("/stderr"), O_CREAT | O_RDWR, &valid_node)); } TEST(FilesystemTest, DevNull) { DevFsForTesting fs; ScopedNode dev_null; int result_bytes = 0; ASSERT_EQ(0, fs.Access(Path("/null"), R_OK | W_OK)); ASSERT_EQ(EACCES, fs.Access(Path("/null"), X_OK)); ASSERT_EQ(0, fs.Open(Path("/null"), O_RDWR, &dev_null)); ASSERT_NE(NULL_NODE, dev_null.get()); // Writing to /dev/null should write everything. const char msg[] = "Dummy test message."; HandleAttr attrs; EXPECT_EQ(0, dev_null->Write(attrs, &msg[0], strlen(msg), &result_bytes)); EXPECT_EQ(strlen(msg), result_bytes); // Reading from /dev/null should read nothing. const int kBufferLength = 100; char buffer[kBufferLength]; EXPECT_EQ(0, dev_null->Read(attrs, &buffer[0], kBufferLength, &result_bytes)); EXPECT_EQ(0, result_bytes); } TEST(FilesystemTest, DevZero) { DevFsForTesting fs; ScopedNode dev_zero; int result_bytes = 0; ASSERT_EQ(0, fs.Access(Path("/zero"), R_OK | W_OK)); ASSERT_EQ(EACCES, fs.Access(Path("/zero"), X_OK)); ASSERT_EQ(0, fs.Open(Path("/zero"), O_RDWR, &dev_zero)); ASSERT_NE(NULL_NODE, dev_zero.get()); // Writing to /dev/zero should write everything. HandleAttr attrs; const char msg[] = "Dummy test message."; EXPECT_EQ(0, dev_zero->Write(attrs, &msg[0], strlen(msg), &result_bytes)); EXPECT_EQ(strlen(msg), result_bytes); // Reading from /dev/zero should read all zeroes. const int kBufferLength = 100; char buffer[kBufferLength]; // First fill with all 1s. memset(&buffer[0], 0x1, kBufferLength); EXPECT_EQ(0, dev_zero->Read(attrs, &buffer[0], kBufferLength, &result_bytes)); EXPECT_EQ(kBufferLength, result_bytes); char zero_buffer[kBufferLength]; memset(&zero_buffer[0], 0, kBufferLength); EXPECT_EQ(0, memcmp(&buffer[0], &zero_buffer[0], kBufferLength)); } TEST(FilesystemTest, DISABLED_DevUrandom) { DevFsForTesting fs; ScopedNode dev_urandom; int result_bytes = 0; ASSERT_EQ(0, fs.Access(Path("/urandom"), R_OK | W_OK)); ASSERT_EQ(EACCES, fs.Access(Path("/urandom"), X_OK)); ASSERT_EQ(0, fs.Open(Path("/urandom"), O_RDWR, &dev_urandom)); ASSERT_NE(NULL_NODE, dev_urandom.get()); // Writing to /dev/urandom should write everything. const char msg[] = "Dummy test message."; HandleAttr attrs; EXPECT_EQ(0, dev_urandom->Write(attrs, &msg[0], strlen(msg), &result_bytes)); EXPECT_EQ(strlen(msg), result_bytes); // Reading from /dev/urandom should read random bytes. const int kSampleBatches = 1000; const int kSampleBatchSize = 1000; const int kTotalSamples = kSampleBatches * kSampleBatchSize; int byte_count[256] = {0}; unsigned char buffer[kSampleBatchSize]; for (int batch = 0; batch < kSampleBatches; ++batch) { int bytes_read = 0; EXPECT_EQ( 0, dev_urandom->Read(attrs, &buffer[0], kSampleBatchSize, &bytes_read)); EXPECT_EQ(kSampleBatchSize, bytes_read); for (int i = 0; i < bytes_read; ++i) { byte_count[buffer[i]]++; } } double expected_count = kTotalSamples / 256.; double chi_squared = 0; for (int i = 0; i < 256; ++i) { double difference = byte_count[i] - expected_count; chi_squared += difference * difference / expected_count; } // Approximate chi-squared value for p-value 0.05, 255 degrees-of-freedom. EXPECT_LE(chi_squared, 293.24); }
from cms.app_base import CMSApp from cms.apphook_pool import apphook_pool from django.utils.translation import ugettext_lazy as _ from .menu import ProposalsMenu class ProposalsApp(CMSApp): name = _("Proposals app") urls = ["pyconde.proposals.urls"] menus = [ProposalsMenu] apphook_pool.register(ProposalsApp)
@INCLUDE_COMMON@ echo echo ELEKTRA SPEC TESTS echo check_version set -x echo "Test specification get" ROOT_FILE=spec_tests.ecf ROOT_MOUNTPOINT=/test/script/spec if is_plugin_available dump && is_plugin_available list && is_plugin_available sync; then "$KDB" mount $ROOT_FILE $ROOT_MOUNTPOINT dump 1> /dev/null succeed_if "could not mount root: $ROOT_FILE at $ROOT_MOUNTPOINT" SYSTEM_FILE="$("$KDB" file -n system:$ROOT_MOUNTPOINT)" [ ! -f "$SYSTEM_FILE" ] exit_if_fail "System File $SYSTEM_FILE already exists" "$KDB" mount $ROOT_FILE spec:$ROOT_MOUNTPOINT dump 1> /dev/null succeed_if "could not mount spec root: $ROOT_FILE at spec:$ROOT_MOUNTPOINT" SPEC_FILE="$("$KDB" file -n spec:$ROOT_MOUNTPOINT)" [ ! -f "$SPEC_FILE" ] exit_if_fail "Spec File $SPEC_FILE already exists" "$KDB" get $ROOT_MOUNTPOINT [ $? != 0 ] succeed_if "getting cascading should fail if nothing is there" "$KDB" set spec:$ROOT_MOUNTPOINT/test "" > /dev/null succeed_if "could not create key" "$KDB" get $ROOT_MOUNTPOINT [ $? != 0 ] succeed_if "getting cascading should fail if nothing is there" "$KDB" meta-set spec:$ROOT_MOUNTPOINT/first default 20 succeed_if "could not set meta" [ "x$("$KDB" get $ROOT_MOUNTPOINT/first)" = "x20" ] succeed_if "could not get default value" "$KDB" umount $ROOT_MOUNTPOINT succeed_if "could not unmount previously mounted mountpoint" "$KDB" umount spec:$ROOT_MOUNTPOINT succeed_if "could not unmount previously mounted spec mountpoint" rm -f "$SYSTEM_FILE" rm -f "$SPEC_FILE" fi echo "Test mounting plugin stack" end_script spec tests
#include <stdio.h> #include <assert.h> #include "ppm.h" #include "mallocvar.h" #include "nstring.h" #include "ppmdfont.h" /* Stroke character definitions The following character definitions are derived from the (public domain) Hershey plotter font database, using the single-stroke Roman font. Each character definition begins with 3 bytes which specify the number of X, Y plot pairs which follow, the negative of the skip before starting to draw the characters, and the skip after the character. The first plot pair moves the pen to that location and subsequent pairs draw to the location given. A pair of 192, 0 raises the pen, moves to the location given by the following pair, and resumes drawing with the pair after that. The values in the definition tables are 8-bit two's complement signed numbers. We declare the table as "unsigned char" and manually sign-extend the values because C compilers differ as to whether the type "char" is signed or unsigned, and some compilers don't accept the qualifier "signed" which we would like to use for these items. We specify negative numbers as their unsigned two's complements to avoid complaints from compilers which don't like initialising unsigned data with signed values. Ahhh, portability. */ static unsigned char char32[] = { 0, 0, 21 }; static unsigned char char33[] = { 8, 251, 5, 0, 244, 0, 2, 192, 0, 0, 7, 255, 8, 0, 9, 1, 8, 0, 7 }; static unsigned char char34[] = { 17, 253, 15, 2, 244, 1, 245, 0, 244, 1, 243, 2, 244, 2, 246, 1, 248, 0, 249, 192, 0, 10, 244, 9, 245, 8, 244, 9, 243, 10, 244, 10, 246, 9, 248, 8, 249, }; static unsigned char char35[] = { 11, 246, 11, 1, 240, 250, 16, 192, 0, 7, 240, 0, 16, 192, 0, 250, 253, 8, 253, 192, 0, 249, 3, 7, 3 }; static unsigned char char36[] = { 26, 246, 10, 254, 240, 254, 13, 192, 0, 2, 240, 2, 13, 192, 0, 7, 247, 5, 245, 2, 244, 254, 244, 251, 245, 249, 247, 249, 249, 250, 251, 251, 252, 253, 253, 3, 255, 5, 0, 6, 1, 7, 3, 7, 6, 5, 8, 2, 9, 254, 9, 251, 8, 249, 6 }; static unsigned char char37[] = { 31, 244, 12, 9, 244, 247, 9, 192, 0, 252, 244, 254, 246, 254, 248, 253, 250, 251, 251, 249, 251, 247, 249, 247, 247, 248, 245, 250, 244, 252, 244, 254, 245, 1, 246, 4, 246, 7, 245, 9, 244, 192, 0, 5, 2, 3, 3, 2, 5, 2, 7, 4, 9, 6, 9, 8, 8, 9, 6, 9, 4, 7, 2, 5, 2 }; static unsigned char char38[] = { 34, 243, 13, 10, 253, 10, 252, 9, 251, 8, 251, 7, 252, 6, 254, 4, 3, 2, 6, 0, 8, 254, 9, 250, 9, 248, 8, 247, 7, 246, 5, 246, 3, 247, 1, 248, 0, 255, 252, 0, 251, 1, 249, 1, 247, 0, 245, 254, 244, 252, 245, 251, 247, 251, 249, 252, 252, 254, 255, 3, 6, 5, 8, 7, 9, 9, 9, 10, 8, 10, 7 }; static unsigned char char39[] = { 7, 251, 5, 0, 246, 255, 245, 0, 244, 1, 245, 1, 247, 0, 249, 255, 250 }; static unsigned char char40[] = { 10, 249, 7, 4, 240, 2, 242, 0, 245, 254, 249, 253, 254, 253, 2, 254, 7, 0, 11, 2, 14, 4, 16 }; static unsigned char char41[] = { 10, 249, 7, 252, 240, 254, 242, 0, 245, 2, 249, 3, 254, 3, 2, 2, 7, 0, 11, 254, 14, 252, 16 }; static unsigned char char42[] = { 8, 248, 8, 0, 250, 0, 6, 192, 0, 251, 253, 5, 3, 192, 0, 5, 253, 251, 3 }; static unsigned char char43[] = { 5, 243, 13, 0, 247, 0, 9, 192, 0, 247, 0, 9, 0 }; static unsigned char char44[] = { 8, 251, 5, 1, 8, 0, 9, 255, 8, 0, 7, 1, 8, 1, 10, 0, 12, 255, 13 }; static unsigned char char45[] = { 2, 243, 13, 247, 0, 9, 0 }; static unsigned char char46[] = { 5, 251, 5, 0, 7, 255, 8, 0, 9, 1, 8, 0, 7 }; static unsigned char char47[] = { 2, 245, 11, 9, 240, 247, 16 }; static unsigned char char48[] = { 17, 246, 10, 255, 244, 252, 245, 250, 248, 249, 253, 249, 0, 250, 5, 252, 8, 255, 9, 1, 9, 4, 8, 6, 5, 7, 0, 7, 253, 6, 248, 4, 245, 1, 244, 255, 244 }; static unsigned char char49[] = { 4, 246, 10, 252, 248, 254, 247, 1, 244, 1, 9 }; static unsigned char char50[] = { 14, 246, 10, 250, 249, 250, 248, 251, 246, 252, 245, 254, 244, 2, 244, 4, 245, 5, 246, 6, 248, 6, 250, 5, 252, 3, 255, 249, 9, 7, 9 }; static unsigned char char51[] = { 15, 246, 10, 251, 244, 6, 244, 0, 252, 3, 252, 5, 253, 6, 254, 7, 1, 7, 3, 6, 6, 4, 8, 1, 9, 254, 9, 251, 8, 250, 7, 249, 5 }; static unsigned char char52[] = { 6, 246, 10, 3, 244, 249, 2, 8, 2, 192, 0, 3, 244, 3, 9 }; static unsigned char char53[] = { 17, 246, 10, 5, 244, 251, 244, 250, 253, 251, 252, 254, 251, 1, 251, 4, 252, 6, 254, 7, 1, 7, 3, 6, 6, 4, 8, 1, 9, 254, 9, 251, 8, 250, 7, 249, 5 }; static unsigned char char54[] = { 23, 246, 10, 6, 247, 5, 245, 2, 244, 0, 244, 253, 245, 251, 248, 250, 253, 250, 2, 251, 6, 253, 8, 0, 9, 1, 9, 4, 8, 6, 6, 7, 3, 7, 2, 6, 255, 4, 253, 1, 252, 0, 252, 253, 253, 251, 255, 250, 2 }; static unsigned char char55[] = { 5, 246, 10, 7, 244, 253, 9, 192, 0, 249, 244, 7, 244 }; static unsigned char char56[] = { 29, 246, 10, 254, 244, 251, 245, 250, 247, 250, 249, 251, 251, 253, 252, 1, 253, 4, 254, 6, 0, 7, 2, 7, 5, 6, 7, 5, 8, 2, 9, 254, 9, 251, 8, 250, 7, 249, 5, 249, 2, 250, 0, 252, 254, 255, 253, 3, 252, 5, 251, 6, 249, 6, 247, 5, 245, 2, 244, 254, 244 }; static unsigned char char57[] = { 23, 246, 10, 6, 251, 5, 254, 3, 0, 0, 1, 255, 1, 252, 0, 250, 254, 249, 251, 249, 250, 250, 247, 252, 245, 255, 244, 0, 244, 3, 245, 5, 247, 6, 251, 6, 0, 5, 5, 3, 8, 0, 9, 254, 9, 251, 8, 250, 6 }; static unsigned char char58[] = { 11, 251, 5, 0, 251, 255, 252, 0, 253, 1, 252, 0, 251, 192, 0, 0, 7, 255, 8, 0, 9, 1, 8, 0, 7 }; static unsigned char char59[] = { 14, 251, 5, 0, 251, 255, 252, 0, 253, 1, 252, 0, 251, 192, 0, 1, 8, 0, 9, 255, 8, 0, 7, 1, 8, 1, 10, 0, 12, 255, 13 }; static unsigned char char60[] = { 3, 244, 12, 8, 247, 248, 0, 8, 9 }; static unsigned char char61[] = { 5, 243, 13, 247, 253, 9, 253, 192, 0, 247, 3, 9, 3 }; static unsigned char char62[] = { 3, 244, 12, 248, 247, 8, 0, 248, 9 }; static unsigned char char63[] = { 20, 247, 9, 250, 249, 250, 248, 251, 246, 252, 245, 254, 244, 2, 244, 4, 245, 5, 246, 6, 248, 6, 250, 5, 252, 4, 253, 0, 255, 0, 2, 192, 0, 0, 7, 255, 8, 0, 9, 1, 8, 0, 7 }; static unsigned char char64[] = { 55, 243, 14, 5, 252, 4, 250, 2, 249, 255, 249, 253, 250, 252, 251, 251, 254, 251, 1, 252, 3, 254, 4, 1, 4, 3, 3, 4, 1, 192, 0, 255, 249, 253, 251, 252, 254, 252, 1, 253, 3, 254, 4, 192, 0, 5, 249, 4, 1, 4, 3, 6, 4, 8, 4, 10, 2, 11, 255, 11, 253, 10, 250, 9, 248, 7, 246, 5, 245, 2, 244, 255, 244, 252, 245, 250, 246, 248, 248, 247, 250, 246, 253, 246, 0, 247, 3, 248, 5, 250, 7, 252, 8, 255, 9, 2, 9, 5, 8, 7, 7, 8, 6, 192, 0, 6, 249, 5, 1, 5, 3, 6, 4 }; static unsigned char char65[] = { 8, 247, 9, 0, 244, 248, 9, 192, 0, 0, 244, 8, 9, 192, 0, 251, 2, 5, 2 }; static unsigned char char66[] = { 23, 245, 10, 249, 244, 249, 9, 192, 0, 249, 244, 2, 244, 5, 245, 6, 246, 7, 248, 7, 250, 6, 252, 5, 253, 2, 254, 192, 0, 249, 254, 2, 254, 5, 255, 6, 0, 7, 2, 7, 5, 6, 7, 5, 8, 2, 9, 249, 9 }; static unsigned char char67[] = { 18, 246, 11, 8, 249, 7, 247, 5, 245, 3, 244, 255, 244, 253, 245, 251, 247, 250, 249, 249, 252, 249, 1, 250, 4, 251, 6, 253, 8, 255, 9, 3, 9, 5, 8, 7, 6, 8, 4 }; static unsigned char char68[] = { 15, 245, 10, 249, 244, 249, 9, 192, 0, 249, 244, 0, 244, 3, 245, 5, 247, 6, 249, 7, 252, 7, 1, 6, 4, 5, 6, 3, 8, 0, 9, 249, 9 }; static unsigned char char69[] = { 11, 246, 9, 250, 244, 250, 9, 192, 0, 250, 244, 7, 244, 192, 0, 250, 254, 2, 254, 192, 0, 250, 9, 7, 9 }; static unsigned char char70[] = { 8, 246, 8, 250, 244, 250, 9, 192, 0, 250, 244, 7, 244, 192, 0, 250, 254, 2, 254 }; static unsigned char char71[] = { 22, 246, 11, 8, 249, 7, 247, 5, 245, 3, 244, 255, 244, 253, 245, 251, 247, 250, 249, 249, 252, 249, 1, 250, 4, 251, 6, 253, 8, 255, 9, 3, 9, 5, 8, 7, 6, 8, 4, 8, 1, 192, 0, 3, 1, 8, 1 }; static unsigned char char72[] = { 8, 245, 11, 249, 244, 249, 9, 192, 0, 7, 244, 7, 9, 192, 0, 249, 254, 7, 254 }; static unsigned char char73[] = { 2, 252, 4, 0, 244, 0, 9 }; static unsigned char char74[] = { 10, 248, 8, 4, 244, 4, 4, 3, 7, 2, 8, 0, 9, 254, 9, 252, 8, 251, 7, 250, 4, 250, 2 }; static unsigned char char75[] = { 8, 245, 10, 249, 244, 249, 9, 192, 0, 7, 244, 249, 2, 192, 0, 254, 253, 7, 9 }; static unsigned char char76[] = { 3, 246, 7, 250, 244, 250, 9, 6, 9 }; static unsigned char char77[] = { 11, 244, 12, 248, 244, 248, 9, 192, 0, 248, 244, 0, 9, 192, 0, 8, 244, 0, 9, 192, 0, 8, 244, 8, 9 }; static unsigned char char78[] = { 8, 245, 11, 249, 244, 249, 9, 192, 0, 249, 244, 7, 9, 192, 0, 7, 244, 7, 9 }; static unsigned char char79[] = { 21, 245, 11, 254, 244, 252, 245, 250, 247, 249, 249, 248, 252, 248, 1, 249, 4, 250, 6, 252, 8, 254, 9, 2, 9, 4, 8, 6, 6, 7, 4, 8, 1, 8, 252, 7, 249, 6, 247, 4, 245, 2, 244, 254, 244 }; static unsigned char char80[] = { 13, 245, 10, 249, 244, 249, 9, 192, 0, 249, 244, 2, 244, 5, 245, 6, 246, 7, 248, 7, 251, 6, 253, 5, 254, 2, 255, 249, 255 }; static unsigned char char81[] = { 24, 245, 11, 254, 244, 252, 245, 250, 247, 249, 249, 248, 252, 248, 1, 249, 4, 250, 6, 252, 8, 254, 9, 2, 9, 4, 8, 6, 6, 7, 4, 8, 1, 8, 252, 7, 249, 6, 247, 4, 245, 2, 244, 254, 244, 192, 0, 1, 5, 7, 11 }; static unsigned char char82[] = { 16, 245, 10, 249, 244, 249, 9, 192, 0, 249, 244, 2, 244, 5, 245, 6, 246, 7, 248, 7, 250, 6, 252, 5, 253, 2, 254, 249, 254, 192, 0, 0, 254, 7, 9 }; static unsigned char char83[] = { 20, 246, 10, 7, 247, 5, 245, 2, 244, 254, 244, 251, 245, 249, 247, 249, 249, 250, 251, 251, 252, 253, 253, 3, 255, 5, 0, 6, 1, 7, 3, 7, 6, 5, 8, 2, 9, 254, 9, 251, 8, 249, 6 }; static unsigned char char84[] = { 5, 248, 8, 0, 244, 0, 9, 192, 0, 249, 244, 7, 244 }; static unsigned char char85[] = { 10, 245, 11, 249, 244, 249, 3, 250, 6, 252, 8, 255, 9, 1, 9, 4, 8, 6, 6, 7, 3, 7, 244 }; static unsigned char char86[] = { 5, 247, 9, 248, 244, 0, 9, 192, 0, 8, 244, 0, 9 }; static unsigned char char87[] = { 11, 244, 12, 246, 244, 251, 9, 192, 0, 0, 244, 251, 9, 192, 0, 0, 244, 5, 9, 192, 0, 10, 244, 5, 9 }; static unsigned char char88[] = { 5, 246, 10, 249, 244, 7, 9, 192, 0, 7, 244, 249, 9 }; static unsigned char char89[] = { 6, 247, 9, 248, 244, 0, 254, 0, 9, 192, 0, 8, 244, 0, 254 }; static unsigned char char90[] = { 8, 246, 10, 7, 244, 249, 9, 192, 0, 249, 244, 7, 244, 192, 0, 249, 9, 7, 9 }; static unsigned char char91[] = { 11, 249, 7, 253, 240, 253, 16, 192, 0, 254, 240, 254, 16, 192, 0, 253, 240, 4, 240, 192, 0, 253, 16, 4, 16 }; static unsigned char char92[] = { 2, 245, 11, 9, 16, 247, 240 }; static unsigned char char93[] = { 11, 249, 7, 2, 240, 2, 16, 192, 0, 3, 240, 3, 16, 192, 0, 252, 240, 3, 240, 192, 0, 252, 16, 3, 16 }; static unsigned char char94[] = { 7, 245, 11, 248, 2, 0, 253, 8, 2, 192, 0, 248, 2, 0, 254, 8, 2 }; static unsigned char char95[] = { 2, 253, 22, 0, 9, 20, 9 }; static unsigned char char96[] = { 7, 251, 5, 1, 244, 0, 245, 255, 247, 255, 249, 0, 250, 1, 249, 0, 248 }; static unsigned char char97[] = { 17, 247, 10, 6, 251, 6, 9, 192, 0, 6, 254, 4, 252, 2, 251, 255, 251, 253, 252, 251, 254, 250, 1, 250, 3, 251, 6, 253, 8, 255, 9, 2, 9, 4, 8, 6, 6 }; static unsigned char char98[] = { 17, 246, 9, 250, 244, 250, 9, 192, 0, 250, 254, 252, 252, 254, 251, 1, 251, 3, 252, 5, 254, 6, 1, 6, 3, 5, 6, 3, 8, 1, 9, 254, 9, 252, 8, 250, 6 }; static unsigned char char99[] = { 14, 247, 9, 6, 254, 4, 252, 2, 251, 255, 251, 253, 252, 251, 254, 250, 1, 250, 3, 251, 6, 253, 8, 255, 9, 2, 9, 4, 8, 6, 6 }; static unsigned char char100[] = { 17, 247, 10, 6, 244, 6, 9, 192, 0, 6, 254, 4, 252, 2, 251, 255, 251, 253, 252, 251, 254, 250, 1, 250, 3, 251, 6, 253, 8, 255, 9, 2, 9, 4, 8, 6, 6 }; static unsigned char char101[] = { 17, 247, 9, 250, 1, 6, 1, 6, 255, 5, 253, 4, 252, 2, 251, 255, 251, 253, 252, 251, 254, 250, 1, 250, 3, 251, 6, 253, 8, 255, 9, 2, 9, 4, 8, 6, 6 }; static unsigned char char102[] = { 8, 251, 7, 5, 244, 3, 244, 1, 245, 0, 248, 0, 9, 192, 0, 253, 251, 4, 251 }; static unsigned char char103[] = { 22, 247, 10, 6, 251, 6, 11, 5, 14, 4, 15, 2, 16, 255, 16, 253, 15, 192, 0, 6, 254, 4, 252, 2, 251, 255, 251, 253, 252, 251, 254, 250, 1, 250, 3, 251, 6, 253, 8, 255, 9, 2, 9, 4, 8, 6, 6 }; static unsigned char char104[] = { 10, 247, 10, 251, 244, 251, 9, 192, 0, 251, 255, 254, 252, 0, 251, 3, 251, 5, 252, 6, 255, 6, 9 }; static unsigned char char105[] = { 8, 252, 4, 255, 244, 0, 245, 1, 244, 0, 243, 255, 244, 192, 0, 0, 251, 0, 9 }; static unsigned char char106[] = { 11, 251, 5, 0, 244, 1, 245, 2, 244, 1, 243, 0, 244, 192, 0, 1, 251, 1, 12, 0, 15, 254, 16, 252, 16 }; static unsigned char char107[] = { 8, 247, 8, 251, 244, 251, 9, 192, 0, 5, 251, 251, 5, 192, 0, 255, 1, 6, 9 }; static unsigned char char108[] = { 2, 252, 4, 0, 244, 0, 9 }; static unsigned char char109[] = { 18, 241, 15, 245, 251, 245, 9, 192, 0, 245, 255, 248, 252, 250, 251, 253, 251, 255, 252, 0, 255, 0, 9, 192, 0, 0, 255, 3, 252, 5, 251, 8, 251, 10, 252, 11, 255, 11, 9 }; static unsigned char char110[] = { 10, 247, 10, 251, 251, 251, 9, 192, 0, 251, 255, 254, 252, 0, 251, 3, 251, 5, 252, 6, 255, 6, 9 }; static unsigned char char111[] = { 17, 247, 10, 255, 251, 253, 252, 251, 254, 250, 1, 250, 3, 251, 6, 253, 8, 255, 9, 2, 9, 4, 8, 6, 6, 7, 3, 7, 1, 6, 254, 4, 252, 2, 251, 255, 251 }; static unsigned char char112[] = { 17, 246, 9, 250, 251, 250, 16, 192, 0, 250, 254, 252, 252, 254, 251, 1, 251, 3, 252, 5, 254, 6, 1, 6, 3, 5, 6, 3, 8, 1, 9, 254, 9, 252, 8, 250, 6 }; static unsigned char char113[] = { 17, 247, 10, 6, 251, 6, 16, 192, 0, 6, 254, 4, 252, 2, 251, 255, 251, 253, 252, 251, 254, 250, 1, 250, 3, 251, 6, 253, 8, 255, 9, 2, 9, 4, 8, 6, 6 }; static unsigned char char114[] = { 8, 249, 6, 253, 251, 253, 9, 192, 0, 253, 1, 254, 254, 0, 252, 2, 251, 5, 251 }; static unsigned char char115[] = { 17, 248, 9, 6, 254, 5, 252, 2, 251, 255, 251, 252, 252, 251, 254, 252, 0, 254, 1, 3, 2, 5, 3, 6, 5, 6, 6, 5, 8, 2, 9, 255, 9, 252, 8, 251, 6 }; static unsigned char char116[] = { 8, 251, 7, 0, 244, 0, 5, 1, 8, 3, 9, 5, 9, 192, 0, 253, 251, 4, 251 }; static unsigned char char117[] = { 10, 247, 10, 251, 251, 251, 5, 252, 8, 254, 9, 1, 9, 3, 8, 6, 5, 192, 0, 6, 251, 6, 9 }; static unsigned char char118[] = { 5, 248, 8, 250, 251, 0, 9, 192, 0, 6, 251, 0, 9 }; static unsigned char char119[] = { 11, 245, 11, 248, 251, 252, 9, 192, 0, 0, 251, 252, 9, 192, 0, 0, 251, 4, 9, 192, 0, 8, 251, 4, 9 }; static unsigned char char120[] = { 5, 248, 9, 251, 251, 6, 9, 192, 0, 6, 251, 251, 9 }; static unsigned char char121[] = { 9, 248, 8, 250, 251, 0, 9, 192, 0, 6, 251, 0, 9, 254, 13, 252, 15, 250, 16, 249, 16 }; static unsigned char char122[] = { 8, 248, 9, 6, 251, 251, 9, 192, 0, 251, 251, 6, 251, 192, 0, 251, 9, 6, 9 }; static unsigned char char123[] = { 39, 249, 7, 2, 240, 0, 241, 255, 242, 254, 244, 254, 246, 255, 248, 0, 249, 1, 251, 1, 253, 255, 255, 192, 0, 0, 241, 255, 243, 255, 245, 0, 247, 1, 248, 2, 250, 2, 252, 1, 254, 253, 0, 1, 2, 2, 4, 2, 6, 1, 8, 0, 9, 255, 11, 255, 13, 0, 15, 192, 0, 255, 1, 1, 3, 1, 5, 0, 7, 255, 8, 254, 10, 254, 12, 255, 14, 0, 15, 2, 16 }; static unsigned char char124[] = { 2, 252, 4, 0, 240, 0, 16 }; static unsigned char char125[] = { 39, 249, 7, 254, 240, 0, 241, 1, 242, 2, 244, 2, 246, 1, 248, 0, 249, 255, 251, 255, 253, 1, 255, 192, 0, 0, 241, 1, 243, 1, 245, 0, 247, 255, 248, 254, 250, 254, 252, 255, 254, 3, 0, 255, 2, 254, 4, 254, 6, 255, 8, 0, 9, 1, 11, 1, 13, 0, 15, 192, 0, 1, 1, 255, 3, 255, 5, 0, 7, 1, 8, 2, 10, 2, 12, 1, 14, 0, 15, 254, 16 }; static unsigned char char126[] = { 23, 255, 21, 2, 1, 0, 255, 1, 253, 3, 251, 5, 251, 7, 252, 11, 255, 13, 0, 15, 0, 17, 255, 18, 254, 192, 0, 2, 0, 1, 254, 3, 253, 5, 253, 7, 254, 11, 1, 13, 2, 15, 2, 17, 1, 18, 255, 18, 252 }; /* Pointers to character definition tables. */ static unsigned char * fontData[] = { char32, char33, char34, char35, char36, char37, char38, char39, char40, char41, char42, char43, char44, char45, char46, char47, char48, char49, char50, char51, char52, char53, char54, char55, char56, char57, char58, char59, char60, char61, char62, char63, char64, char65, char66, char67, char68, char69, char70, char71, char72, char73, char74, char75, char76, char77, char78, char79, char80, char81, char82, char83, char84, char85, char86, char87, char88, char89, char90, char91, char92, char93, char94, char95, char96, char97, char98, char99, char100, char101, char102, char103, char104, char105, char106, char107, char108, char109, char110, char111, char112, char113, char114, char115, char116, char117, char118, char119, char120, char121, char122, char123, char124, char125, char126 }; static void writeGlyphCommand(FILE * const ofP, struct ppmd_glyphCommand const glyphCommand) { fputc(glyphCommand.verb, ofP); fputc(glyphCommand.x, ofP); fputc(glyphCommand.y, ofP); } static void writeMovePen(FILE * const ofP, const unsigned char * const glyphData) { struct ppmd_glyphCommand glyphCommand; glyphCommand.verb = CMD_MOVEPEN; glyphCommand.x = glyphData[0]; glyphCommand.y = glyphData[1]; writeGlyphCommand(ofP, glyphCommand); } static void writeMovePenNoop(FILE * const ofP, const unsigned char * const glyphData) { struct ppmd_glyphCommand glyphCommand; glyphCommand.verb = CMD_MOVEPEN; glyphCommand.x = glyphData[0]; glyphCommand.y = glyphData[1]; writeGlyphCommand(ofP, glyphCommand); glyphCommand.verb = CMD_NOOP; glyphCommand.x = 0; glyphCommand.y = 0; writeGlyphCommand(ofP, glyphCommand); } static void writeDrawLine(FILE * const ofP, const unsigned char * const glyphData) { struct ppmd_glyphCommand glyphCommand; glyphCommand.verb = CMD_DRAWLINE; glyphCommand.x = glyphData[0]; glyphCommand.y = glyphData[1]; writeGlyphCommand(ofP, glyphCommand); } static void writeGlyphHeader(FILE * const ofP, struct ppmd_glyphHeader const glyphHeader) { fputc(glyphHeader.commandCount, ofP); fputc(glyphHeader.skipBefore, ofP); fputc(glyphHeader.skipAfter, ofP); } static void <API key>(FILE * const ofP, unsigned int const relativeCodePoint) { const unsigned char * const glyphData = fontData[relativeCodePoint]; struct ppmd_glyphHeader glyphHeader; unsigned int commandNum; glyphHeader.commandCount = glyphData[0]; glyphHeader.skipBefore = glyphData[1]; glyphHeader.skipAfter = glyphData[2]; writeGlyphHeader(ofP, glyphHeader); commandNum = 0; while (commandNum < glyphHeader.commandCount) { if (commandNum == 0) { writeMovePen(ofP, &glyphData[3 + commandNum * 2]); commandNum += 1; } else if (glyphData[3 + commandNum*2] == 192) { assert(commandNum + 1 < glyphHeader.commandCount); writeMovePenNoop(ofP, &glyphData[3 + (commandNum + 1) * 2]); commandNum += 2; } else { writeDrawLine(ofP, &glyphData[3 + commandNum * 2]); commandNum += 1; } } } static void writeFontHeader(FILE * const ofP, struct ppmd_fontHeader const fontHeader) { fwrite(fontHeader.signature, 1, sizeof(fontHeader.signature), ofP); fputc(fontHeader.format, ofP); fputc(fontHeader.characterCount, ofP); fputc(fontHeader.firstCodePoint, ofP); } static void writeBuiltinFont(FILE * const ofP) { unsigned int relativeCodePoint; struct ppmd_fontHeader fontHeader; memcpy(fontHeader.signature, "ppmdfont", sizeof(fontHeader.signature)); fontHeader.format = 0x01; fontHeader.characterCount = 95; fontHeader.firstCodePoint = 32; writeFontHeader(ofP, fontHeader); for (relativeCodePoint = 0; relativeCodePoint < fontHeader.characterCount; ++relativeCodePoint) { <API key>(ofP,relativeCodePoint); } } int main(int argc, char **argv) { ppm_init(&argc, argv); writeBuiltinFont(stdout); return 0; }
<?php defined('SYSPATH') or die('No direct script access.'); class Kohana_Form { /** * Generates an opening HTML form tag. * * // Form will submit back to the current page using POST * echo Form::open(); * * // Form will submit to 'search' using GET * echo Form::open('search', array('method' => 'get')); * * // When "file" inputs are present, you must include the "enctype" * echo Form::open(NULL, array('enctype' => 'multipart/form-data')); * * @param mixed $action form action, defaults to the current request URI, or [Request] class to use * @param array $attributes html attributes * @return string * @uses Request * @uses URL::site * @uses HTML::attributes */ public static function open($action = NULL, array $attributes = NULL) { if ($action instanceof Request) { // Use the current URI $action = $action->uri(); } if ( ! $action) { // Allow empty form actions (submits back to the current url). $action = ''; } elseif (strpos($action, ': { // Make the URI absolute $action = URL::site($action); } // Add the form action to the attributes $attributes['action'] = $action; // Only accept the default character set $attributes['accept-charset'] = Kohana::$charset; if ( ! isset($attributes['method'])) { // Use POST method $attributes['method'] = 'post'; } return '<form'.HTML::attributes($attributes).'>'; } /** * Creates the closing form tag. * * echo Form::close(); * * @return string */ public static function close() { return '</form>'; } /** * Creates a form input. If no type is specified, a "text" type input will * be returned. * * echo Form::input('username', $username); * * @param string $name input name * @param string $value input value * @param array $attributes html attributes * @return string * @uses HTML::attributes */ public static function input($name, $value = NULL, array $attributes = NULL) { // Set the input name $attributes['name'] = $name; // Set the input value $attributes['value'] = $value; if ( ! isset($attributes['type'])) { // Default type is text $attributes['type'] = 'text'; } return '<input'.HTML::attributes($attributes).' />'; } /** * Creates a hidden form input. * * echo Form::hidden('csrf', $token); * * @param string $name input name * @param string $value input value * @param array $attributes html attributes * @return string * @uses Form::input */ public static function hidden($name, $value = NULL, array $attributes = NULL) { $attributes['type'] = 'hidden'; return Form::input($name, $value, $attributes); } /** * Creates a password form input. * * echo Form::password('password'); * * @param string $name input name * @param string $value input value * @param array $attributes html attributes * @return string * @uses Form::input */ public static function password($name, $value = NULL, array $attributes = NULL) { $attributes['type'] = 'password'; return Form::input($name, $value, $attributes); } /** * Creates a file upload form input. No input value can be specified. * * echo Form::file('image'); * * @param string $name input name * @param array $attributes html attributes * @return string * @uses Form::input */ public static function file($name, array $attributes = NULL) { $attributes['type'] = 'file'; return Form::input($name, NULL, $attributes); } /** * Creates a checkbox form input. * * echo Form::checkbox('remember_me', 1, (bool) $remember); * * @param string $name input name * @param string $value input value * @param boolean $checked checked status * @param array $attributes html attributes * @return string * @uses Form::input */ public static function checkbox($name, $value = NULL, $checked = FALSE, array $attributes = NULL) { $attributes['type'] = 'checkbox'; if ($checked === TRUE) { // Make the checkbox active $attributes['checked'] = 'checked'; } return Form::input($name, $value, $attributes); } /** * Creates a radio form input. * * echo Form::radio('like_cats', 1, $cats); * echo Form::radio('like_cats', 0, ! $cats); * * @param string $name input name * @param string $value input value * @param boolean $checked checked status * @param array $attributes html attributes * @return string * @uses Form::input */ public static function radio($name, $value = NULL, $checked = FALSE, array $attributes = NULL) { $attributes['type'] = 'radio'; if ($checked === TRUE) { // Make the radio active $attributes['checked'] = 'checked'; } return Form::input($name, $value, $attributes); } /** * Creates a textarea form input. * * echo Form::textarea('about', $about); * * @param string $name textarea name * @param string $body textarea body * @param array $attributes html attributes * @param boolean $double_encode encode existing HTML characters * @return string * @uses HTML::attributes * @uses HTML::chars */ public static function textarea($name, $body = '', array $attributes = NULL, $double_encode = TRUE) { // Set the input name $attributes['name'] = $name; // Add default rows and cols attributes (required) $attributes += array('rows' => 10, 'cols' => 50); return '<textarea'.HTML::attributes($attributes).'>'.HTML::chars($body, $double_encode).'</textarea>'; } /** * Creates a select form input. * * echo Form::select('country', $countries, $country); * * [!!] Support for multiple selected options was added in v3.0.7. * * @param string $name input name * @param array $options available options * @param mixed $selected selected option string, or an array of selected options * @param array $attributes html attributes * @return string * @uses HTML::attributes */ public static function select($name, array $options = NULL, $selected = NULL, array $attributes = NULL) { // Set the input name $attributes['name'] = $name; if (is_array($selected)) { // This is a multi-select, god save us! $attributes['multiple'] = 'multiple'; } if ( ! is_array($selected)) { if ($selected === NULL) { // Use an empty array $selected = array(); } else { // Convert the selected options to an array $selected = array( (string) $selected); } } if (empty($options)) { // There are no options $options = ''; } else { foreach ($options as $value => $name) { if (is_array($name)) { // Create a new optgroup $group = array('label' => $value); // Create a new list of options $_options = array(); foreach ($name as $_value => $_name) { // Force value to be string $_value = (string) $_value; // Create a new attribute set for this option $option = array('value' => $_value); if (in_array($_value, $selected)) { // This option is selected $option['selected'] = 'selected'; } // Change the option to the HTML string $_options[] = '<option'.HTML::attributes($option).'>'.HTML::chars($_name, FALSE).'</option>'; } // Compile the options into a string $_options = "\n".implode("\n", $_options)."\n"; $options[$value] = '<optgroup'.HTML::attributes($group).'>'.$_options.'</optgroup>'; } else { // Force value to be string $value = (string) $value; // Create a new attribute set for this option $option = array('value' => $value); if (in_array($value, $selected)) { // This option is selected $option['selected'] = 'selected'; } // Change the option to the HTML string $options[$value] = '<option'.HTML::attributes($option).'>'.HTML::chars($name, FALSE).'</option>'; } } // Compile the options into a single string $options = "\n".implode("\n", $options)."\n"; } return '<select'.HTML::attributes($attributes).'>'.$options.'</select>'; } /** * Creates a submit form input. * * echo Form::submit(NULL, 'Login'); * * @param string $name input name * @param string $value input value * @param array $attributes html attributes * @return string * @uses Form::input */ public static function submit($name, $value, array $attributes = NULL) { $attributes['type'] = 'submit'; return Form::input($name, $value, $attributes); } /** * Creates a image form input. * * echo Form::image(NULL, NULL, array('src' => 'media/img/login.png')); * * @param string $name input name * @param string $value input value * @param array $attributes html attributes * @param boolean $index add index file to URL? * @return string * @uses Form::input */ public static function image($name, $value, array $attributes = NULL, $index = FALSE) { if ( ! empty($attributes['src'])) { if (strpos($attributes['src'], ': { // Add the base URL $attributes['src'] = URL::base($index).$attributes['src']; } } $attributes['type'] = 'image'; return Form::input($name, $value, $attributes); } /** * Creates a button form input. Note that the body of a button is NOT escaped, * to allow images and other HTML to be used. * * echo Form::button('save', 'Save Profile', array('type' => 'submit')); * * @param string $name input name * @param string $body input value * @param array $attributes html attributes * @return string * @uses HTML::attributes */ public static function button($name, $body, array $attributes = NULL) { // Set the input name $attributes['name'] = $name; return '<button'.HTML::attributes($attributes).'>'.$body.'</button>'; } /** * Creates a form label. Label text is not automatically translated. * * echo Form::label('username', 'Username'); * * @param string $input target input * @param string $text label text * @param array $attributes html attributes * @return string * @uses HTML::attributes */ public static function label($input, $text = NULL, array $attributes = NULL) { if ($text === NULL) { // Use the input name as the text $text = ucwords(preg_replace('/[\W_]+/', ' ', $input)); } // Set the label target $attributes['for'] = $input; return '<label'.HTML::attributes($attributes).'>'.$text.'</label>'; } } // End form
<?php /** * @namespace */ namespace ZendTest\GData\YouTube; use Zend\GData\YouTube; /** * Test helper */ class CommentFeedTest extends \<API key> { public function setUp() { $this->feedText = file_get_contents( 'Zend/GData/YouTube/_files/<API key>.xml', true); $this->feed = new YouTube\CommentFeed(); } private function <API key> ($commentFeed) { $this->assertEquals('http://gdata.youtube.com/feeds/videos/Lnio-pqLPgg/comments', $commentFeed->id->text); $this->assertEquals('2007-09-21T02:32:55.032Z', $commentFeed->updated->text); $this->assertEquals('http://schemas.google.com/g/2005#kind', $commentFeed->category[0]->scheme); $this->assertEquals('http://gdata.youtube.com/schemas/2007#comment', $commentFeed->category[0]->term); $this->assertEquals('http: $this->assertEquals('text', $commentFeed->title->type); $this->assertEquals('Comments on \'"That Girl" - Original Song - Acoustic Version\'', $commentFeed->title->text); $this->assertEquals('self', $commentFeed->getLink('self')->rel); $this->assertEquals('application/atom+xml', $commentFeed->getLink('self')->type); $this->assertEquals('http://gdata.youtube.com/feeds/videos/Lnio-pqLPgg/comments?start-index=1&max-results=4', $commentFeed->getLink('self')->href); $this->assertEquals('YouTube', $commentFeed->author[0]->name->text); $this->assertEquals('http: $this->assertEquals(100, $commentFeed->totalResults->text); $this->assertEquals(1, $commentFeed->startIndex->text); $this->assertEquals(4, $commentFeed->itemsPerPage->text); } public function <API key>() { $this->assertTrue(is_array($this->feed->extensionElements)); $this->assertTrue(count($this->feed->extensionElements) == 0); } public function <API key>() { $this->assertTrue(is_array($this->feed->extensionAttributes)); $this->assertTrue(count($this->feed->extensionAttributes) == 0); } public function <API key>() { $this->feed->transferFromXML($this->feedText); $this->assertTrue(is_array($this->feed->extensionElements)); $this->assertTrue(count($this->feed->extensionElements) == 0); } public function <API key>() { $this->feed->transferFromXML($this->feedText); $this->assertTrue(is_array($this->feed->extensionAttributes)); $this->assertTrue(count($this->feed->extensionAttributes) == 0); } public function <API key>() { $entryXml = $this->feed->saveXML(); $newCommentFeed = new YouTube\CommentFeed(); $newCommentFeed->transferFromXML($entryXml); $newCommentFeedXml = $newCommentFeed->saveXML(); $this->assertTrue($entryXml == $newCommentFeedXml); } public function <API key> () { $this->feed->transferFromXML($this->feedText); $this-><API key>($this->feed); } public function <API key>() { $this->feed->transferFromXML($this->feedText); $entryXml = $this->feed->saveXML(); $newCommentFeed = new YouTube\CommentFeed(); $newCommentFeed->transferFromXML($entryXml); $this-><API key>($newCommentFeed); $newCommentFeedXml = $newCommentFeed->saveXML(); $this->assertEquals($entryXml, $newCommentFeedXml); } }
// modification, are permitted provided that the following conditions are // met: // with the distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef <API key> #define <API key> #include "utils.h" namespace double_conversion { class <API key> { public: // When calling ToFixed with a double > 10^<API key> // or a requested_digits parameter > <API key> then the // function returns false. static const int <API key> = 60; static const int <API key> = 100; // When calling ToExponential with a requested_digits // parameter > <API key> then the function returns false. static const int <API key> = 120; // When calling ToPrecision with a requested_digits // parameter < kMinPrecisionDigits or requested_digits > kMaxPrecisionDigits // then the function returns false. static const int kMinPrecisionDigits = 1; static const int kMaxPrecisionDigits = 120; // The maximal number of digits that are needed to emit a double in base 10. // A higher precision can be achieved by using more digits, but the shortest // accurate representation of any double will never use more digits than // <API key>. // Note that DoubleToAscii null-terminates its input. So the given buffer // should be at least <API key> + 1 characters long. static const int <API key> = 17; // The maximal number of digits that are needed to emit a single in base 10. // A higher precision can be achieved by using more digits, but the shortest // accurate representation of any single will never use more digits than // <API key>. static const int <API key> = 9; // The length of the longest string that 'ToShortest' can produce when the // converter is instantiated with EcmaScript defaults (see // 'EcmaScriptConverter') // This value does not include the trailing '\0' character. // This amount of characters is needed for negative values that hit the // '<API key>' limit. For example: "-0.<API key>" static const int <API key> = 25; enum Flags { NO_FLAGS = 0, <API key> = 1, <API key> = 2, <API key> = 4, UNIQUE_ZERO = 8, NO_TRAILING_ZERO = 16 }; // Flags should be a bit-or combination of the possible Flags-enum. // - NO_FLAGS: no special flags. // - <API key>: when the number is converted into exponent // form, emits a '+' for positive exponents. Example: 1.2e+2. // - <API key>: when the input number is an integer and is // converted into decimal format then a trailing decimal point is appended. // Example: 2345.0 is converted to "2345.". // - <API key>: in addition to a trailing decimal point // emits a trailing '0'-character. This flag requires the // <API key> flag. // Example: 2345.0 is converted to "2345.0". // - UNIQUE_ZERO: "-0.0" is converted to "0.0". // - NO_TRAILING_ZERO: Trailing zeros are removed from the fractional portion // of the result in precision mode. Matches printf's %g. // When <API key> is also given, one trailing zero is // preserved. // Infinity symbol and nan_symbol provide the string representation for these // special values. If the string is NULL and the special value is encountered // then the conversion functions return false. // The exponent_character is used in exponential representations. It is // usually 'e' or 'E'. // When converting to the shortest representation the converter will // represent input numbers in decimal format if they are in the interval // [10^<API key>; 10^<API key>[ // (lower boundary included, greater boundary excluded). // Example: with <API key> = -6 and // <API key> = 21: // ToShortest(0.000001) -> "0.000001" // ToShortest(0.0000001) -> "1e-7" // ToShortest(<API key>.0) -> "<API key>" // ToShortest(<API key>.0) -> "<API key>" // ToShortest(<API key>.0) -> "1.1111111111111111e+21" // When converting to precision mode the converter may add // <API key> before returning the number in exponential // format. // Example with <API key> = 6. // ToPrecision(0.0000012345, 2) -> "0.0000012" // ToPrecision(0.00000012345, 2) -> "1.2e-7" // Similarly the converter may add up to // <API key> in precision mode to avoid // returning an exponential representation. A zero added by the // <API key> flag is counted for this limit. // Examples for <API key> = 1: // ToPrecision(230.0, 2) -> "230" // ToPrecision(230.0, 2) -> "230." with <API key>. // ToPrecision(230.0, 2) -> "2.3e2" with <API key>. // The min_exponent_width is used for exponential representations. // The converter adds leading '0's to the exponent until the exponent // is at least min_exponent_width digits long. // The min_exponent_width is clamped to 5. // As such, the exponent may never have more than 5 digits in total. <API key>(int flags, const char* infinity_symbol, const char* nan_symbol, char exponent_character, int <API key>, int <API key>, int <API key>, int <API key>, int min_exponent_width = 0) : flags_(flags), infinity_symbol_(infinity_symbol), nan_symbol_(nan_symbol), exponent_character_(exponent_character), <API key>(<API key>), <API key>(<API key>), <API key>( <API key>), <API key>( <API key>), min_exponent_width_(min_exponent_width) { // When 'trailing zero after the point' is set, then 'trailing point' // must be set too. <API key>(((flags & <API key>) != 0) || !((flags & <API key>) != 0)); } // Returns a converter following the EcmaScript specification. // Flags: UNIQUE_ZERO and <API key>. // Special values: "Infinity" and "NaN". // Lower case 'e' for exponential values. // <API key>: -6 // <API key>: 21 // <API key>: 6 // <API key>: 0 static const <API key>& EcmaScriptConverter(); // Computes the shortest string of digits that correctly represent the input // number. Depending on <API key> and <API key> // (see constructor) it then either returns a decimal representation, or an // exponential representation. // Example with <API key> = -6, // <API key> = 21, // <API key> activated, and // <API key> deactivated: // ToShortest(0.000001) -> "0.000001" // ToShortest(0.0000001) -> "1e-7" // ToShortest(<API key>.0) -> "<API key>" // ToShortest(<API key>.0) -> "<API key>" // ToShortest(<API key>.0) -> "1.1111111111111111e+21" // Note: the conversion may round the output if the returned string // is accurate enough to uniquely identify the input-number. // For example the most precise representation of the double 9e59 equals // "<API key>", but // the converter will return the shorter (but still correct) "9e59". // Returns true if the conversion succeeds. The conversion always succeeds // except when the input value is special and no infinity_symbol or // nan_symbol has been given to the constructor. // The length of the longest result is the maximum of the length of the // following string representations (each with possible examples): // - NaN and negative infinity: "NaN", "-Infinity", "-inf". // - -10^(<API key> - 1): // "-<API key>", "-1000000000000000.0" // - the longest string in range [0; -10^<API key>]. Generally, // this string is 3 + <API key> - <API key>. // (Sign, '0', decimal point, padding zeroes for <API key>, // and the significant digits). // "-0.<API key>", "-0.0012345678901234567" // - the longest exponential representation. (A negative number with // <API key> significant digits). // "-1.7976931348623157e+308", "-1.<API key>" // In addition, the buffer must be able to hold the trailing '\0' character. bool ToShortest(double value, StringBuilder* result_builder) const { return <API key>(value, result_builder, SHORTEST); } // Same as ToShortest, but for single-precision floats. bool ToShortestSingle(float value, StringBuilder* result_builder) const { return <API key>(value, result_builder, SHORTEST_SINGLE); } // Computes a decimal representation with a fixed number of digits after the // decimal point. The last emitted digit is rounded. // Examples: // ToFixed(3.12, 1) -> "3.1" // ToFixed(3.1415, 3) -> "3.142" // ToFixed(1234.56789, 4) -> "1234.5679" // ToFixed(1.23, 5) -> "1.23000" // ToFixed(0.1, 4) -> "0.1000" // ToFixed(1e30, 2) -> "<API key>.00" // ToFixed(0.1, 30) -> "0.<API key>" // ToFixed(0.1, 17) -> "0.10000000000000001" // If requested_digits equals 0, then the tail of the result depends on // the <API key> and <API key>. // Examples, for requested_digits == 0, // let <API key> and <API key> be // - false and false: then 123.45 -> 123 // 0.678 -> 1 // - true and false: then 123.45 -> 123. // 0.678 -> 1. // - true and true: then 123.45 -> 123.0 // 0.678 -> 1.0 // Returns true if the conversion succeeds. The conversion always succeeds // except for the following cases: // - the input value is special and no infinity_symbol or nan_symbol has // been provided to the constructor, // - 'value' > 10^<API key>, or // - 'requested_digits' > <API key>. // The last two conditions imply that the result for non-special values never // contains more than // 1 + <API key> + 1 + <API key> characters // (one additional character for the sign, and one for the decimal point). // In addition, the buffer must be able to hold the trailing '\0' character. bool ToFixed(double value, int requested_digits, StringBuilder* result_builder) const; // Computes a representation in exponential format with requested_digits // after the decimal point. The last emitted digit is rounded. // If requested_digits equals -1, then the shortest exponential representation // is computed. // Examples with <API key> deactivated, and // exponent_character set to 'e'. // ToExponential(3.12, 1) -> "3.1e0" // ToExponential(5.0, 3) -> "5.000e0" // ToExponential(0.001, 2) -> "1.00e-3" // ToExponential(3.1415, -1) -> "3.1415e0" // ToExponential(3.1415, 4) -> "3.1415e0" // ToExponential(3.1415, 3) -> "3.142e0" // ToExponential(123456789000000, 3) -> "1.235e14" // ToExponential(<API key>.0, -1) -> "1e30" // ToExponential(<API key>.0, 32) -> // "1.<API key>" // ToExponential(1234, 0) -> "1e3" // Returns true if the conversion succeeds. The conversion always succeeds // except for the following cases: // - the input value is special and no infinity_symbol or nan_symbol has // been provided to the constructor, // - 'requested_digits' > <API key>. // The last condition implies that the result never contains more than // <API key> + 8 characters (the sign, the digit before the // decimal point, the decimal point, the exponent character, the // exponent's sign, and at most 3 exponent digits). // In addition, the buffer must be able to hold the trailing '\0' character. bool ToExponential(double value, int requested_digits, StringBuilder* result_builder) const; // Computes 'precision' leading digits of the given 'value' and returns them // either in exponential or decimal format, depending on // max_{leading|trailing}<API key> (given to the // constructor). // The last computed digit is rounded. // Example with <API key> = 6. // ToPrecision(0.0000012345, 2) -> "0.0000012" // ToPrecision(0.00000012345, 2) -> "1.2e-7" // Similarly the converter may add up to // <API key> in precision mode to avoid // returning an exponential representation. A zero added by the // <API key> flag is counted for this limit. // Examples for <API key> = 1: // ToPrecision(230.0, 2) -> "230" // ToPrecision(230.0, 2) -> "230." with <API key>. // ToPrecision(230.0, 2) -> "2.3e2" with <API key>. // Examples for <API key> = 3, and no // <API key>: // ToPrecision(123450.0, 6) -> "123450" // ToPrecision(123450.0, 5) -> "123450" // ToPrecision(123450.0, 4) -> "123500" // ToPrecision(123450.0, 3) -> "123000" // ToPrecision(123450.0, 2) -> "1.2e5" // Returns true if the conversion succeeds. The conversion always succeeds // except for the following cases: // - the input value is special and no infinity_symbol or nan_symbol has // been provided to the constructor, // - precision < <API key> // - precision > kMaxPrecisionDigits // The last condition implies that the result never contains more than // kMaxPrecisionDigits + 7 characters (the sign, the decimal point, the // exponent character, the exponent's sign, and at most 3 exponent digits). // In addition, the buffer must be able to hold the trailing '\0' character. bool ToPrecision(double value, int precision, StringBuilder* result_builder) const; enum DtoaMode { // Produce the shortest correct representation. // For example the output of 0.<API key> is (the less accurate // but correct) 0.3. SHORTEST, // Same as SHORTEST, but for single-precision floats. SHORTEST_SINGLE, // Produce a fixed number of digits after the decimal point. // For instance fixed(0.1, 4) becomes 0.1000 // If the input number is big, the output will be big. FIXED, // Fixed number of digits (independent of the decimal point). PRECISION }; // Converts the given double 'v' to digit characters. 'v' must not be NaN, // +Infinity, or -Infinity. In <API key> this restriction also // applies to 'v' after it has been casted to a single-precision float. That // is, in this mode static_cast<float>(v) must not be NaN, +Infinity or // -Infinity. // The result should be interpreted as buffer * 10^(point-length). // The digits are written to the buffer in the platform's charset, which is // often UTF-8 (with ASCII-range digits) but may be another charset, such // as EBCDIC. // The output depends on the given mode: // - SHORTEST: produce the least amount of digits for which the internal // identity requirement is still satisfied. If the digits are printed // (together with the correct exponent) then reading this number will give // 'v' again. The buffer will choose the representation that is closest to // 'v'. If there are two at the same distance, than the one farther away // from 0 is chosen (halfway cases - ending with 5 - are rounded up). // In this mode the 'requested_digits' parameter is ignored. // - SHORTEST_SINGLE: same as SHORTEST but with single-precision. // - FIXED: produces digits necessary to print a given number with // 'requested_digits' digits after the decimal point. The produced digits // might be too short in which case the caller has to fill the remainder // with '0's. // Example: toFixed(0.001, 5) is allowed to return buffer="1", point=-2. // Halfway cases are rounded towards +/-Infinity (away from 0). The call // toFixed(0.15, 2) thus returns buffer="2", point=0. // The returned buffer may contain digits that would be truncated from the // shortest representation of the input. // - PRECISION: produces 'requested_digits' where the first digit is not '0'. // Even though the length of produced digits usually equals // 'requested_digits', the function is allowed to return fewer digits, in // which case the caller has to fill the missing digits with '0's. // Halfway cases are again rounded away from 0. // DoubleToAscii expects the given buffer to be big enough to hold all // digits and a terminating null-character. In SHORTEST-mode it expects a // buffer of at least <API key> + 1. In all other modes the // requested_digits parameter and the padding-zeroes limit the size of the // output. Don't forget the decimal point, the exponent character and the // terminating null-character when computing the maximal output size. // The given length is only used in debug mode to ensure the buffer is big // enough. static void DoubleToAscii(double v, DtoaMode mode, int requested_digits, char* buffer, int buffer_length, bool* sign, int* length, int* point); private: // Implementation for ToShortest and ToShortestSingle. bool <API key>(double value, StringBuilder* result_builder, DtoaMode mode) const; // If the value is a special value (NaN or Infinity) constructs the // corresponding string using the configured infinity/nan-symbol. // If either of them is NULL or the value is not special then the // function returns false. bool HandleSpecialValues(double value, StringBuilder* result_builder) const; // Constructs an exponential representation (i.e. 1.234e56). // The given exponent assumes a decimal point after the first decimal digit. void <API key>(const char* decimal_digits, int length, int exponent, StringBuilder* result_builder) const; // Creates a decimal representation (i.e 1234.5678). void <API key>(const char* decimal_digits, int length, int decimal_point, int digits_after_point, StringBuilder* result_builder) const; const int flags_; const char* const infinity_symbol_; const char* const nan_symbol_; const char exponent_character_; const int <API key>; const int <API key>; const int <API key>; const int <API key>; const int min_exponent_width_; <API key>(<API key>); }; } // namespace double_conversion #endif // <API key>
#ifndef <API key> #define <API key> #include <string> #include <vector> #include "base/callback_forward.h" #include "base/files/file_path.h" #include "base/strings/string16.h" #include "base/time/time.h" #include "ui/app_list/app_list_export.h" namespace base { class FilePath; } namespace gfx { class ImageSkia; class Size; } #if defined(TOOLKIT_VIEWS) namespace views { class View; } #endif namespace app_list { class AppListModel; class <API key>; class SearchResult; class SpeechUIModel; class APP_LIST_EXPORT AppListViewDelegate { public: // A user of the app list. struct APP_LIST_EXPORT User { User(); User(const User& other); ~User(); // Whether or not this user is the current user of the app list. bool active; // The name of this user. base::string16 name; // The email address of this user. base::string16 email; // The path to this user's profile directory. base::FilePath profile_path; }; typedef std::vector<User> Users; virtual ~AppListViewDelegate() {} // Whether to force the use of a native desktop widget when the app list // window is first created. virtual bool ForceNativeDesktop() const = 0; // Sets the delegate to use the profile at |profile_path|. This is currently // only used by non-Ash Windows. virtual void SetProfileByPath(const base::FilePath& profile_path) = 0; // Gets the model associated with the view delegate. The model may be owned // by the delegate, or owned elsewhere (e.g. a profile keyed service). virtual AppListModel* GetModel() = 0; // Gets the SpeechUIModel for the app list. Owned by the AppListViewDelegate. virtual SpeechUIModel* GetSpeechUI() = 0; // Gets a path to a shortcut for the given app. Returns asynchronously as the // shortcut may not exist yet. virtual void <API key>( const std::string& app_id, const base::Callback<void(const base::FilePath&)>& callback) = 0; // Invoked to start a new search. Delegate collects query input from // SearchBoxModel and populates SearchResults. Both models are sub models // of AppListModel. virtual void StartSearch() = 0; // Invoked to stop the current search. virtual void StopSearch() = 0; // Invoked to open the search result. virtual void OpenSearchResult(SearchResult* result, bool auto_launch, int event_flags) = 0; // Called to invoke a custom action on |result|. |action_index| corresponds // to the index of an icon in |result.action_icons()|. virtual void <API key>(SearchResult* result, int action_index, int event_flags) = 0; // Gets the timeout for auto-launching the first search result, or 0 if the // auto-launch should not happen for the current search session. virtual base::TimeDelta <API key>() = 0; // Invoked when the auto-launch is canceled by the user action. virtual void AutoLaunchCanceled() = 0; // Invoked when the app list UI is created. virtual void ViewInitialized() = 0; // Invoked to dismiss app list. This may leave the view open but hidden from // the user. virtual void Dismiss() = 0; // Invoked when the app list is closing. virtual void ViewClosing() = 0; // Returns the icon to be displayed in the window and taskbar. virtual gfx::ImageSkia GetWindowIcon() = 0; // Open the settings UI. virtual void OpenSettings() = 0; // Open the help UI. virtual void OpenHelp() = 0; // Open the feedback UI. virtual void OpenFeedback() = 0; // Invoked to toggle the status of speech recognition. virtual void <API key>() = 0; virtual void <API key>() = 0; // Shows the app list for the profile specified by |profile_path|. virtual void <API key>(const base::FilePath& profile_path) = 0; #if defined(TOOLKIT_VIEWS) // Creates the web view for the start page. The caller takes the ownership of // the returned view. virtual views::View* <API key>(const gfx::Size& size) = 0; // Creates the web views for the user-specified custom pages. The caller takes // ownership of the returned views. virtual std::vector<views::View*> <API key>( const gfx::Size& size) = 0; // Invoked when the custom launcher page's animation changes. virtual void <API key>(double progress) = 0; // Invoked when the custom launcher page's subpage should be popped. virtual void <API key>() = 0; #endif // Returns true if the delegate supports speech recognition. virtual bool <API key>() = 0; // Returns the list of users (for AppListMenu). virtual const Users& GetUsers() const = 0; // Returns true if the app list should be centered and in landscape mode. virtual bool ShouldCenterWindow() const = 0; // Adds/removes an observer for profile changes. virtual void AddObserver(<API key>* observer) {} virtual void RemoveObserver(<API key>* observer) {} }; } // namespace app_list #endif // <API key>
// modification, are permitted provided that the following conditions // are met: // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #pragma once #include <dp/fx/ParameterGroupSpec.h> #include <memory> #include <string> namespace dp { namespace fx { class ParameterSpec; namespace glsl { std::string getGLSLTypename( const dp::fx::ParameterSpec& parameterSpec ); /** \brief generate glsl struct for given spec \param parameterGroupSpec spec to generate struct for \param generatedName output, gives back name of generated struct **/ std::string generateStruct( const dp::fx::<API key>& parameterGroupSpec, std::string& generatedName ); /** \brief foreach parametergroupspec::name print #define name uniformName ([arrayIndex]) accessor name **/ std::string <API key>( const dp::fx::<API key>& parameterGroupSpec, const std::string& uniformName, const std::string& arrayIndex, const std::string& accessor ); } // namespace glsl } // namespace fx } // namespace dp
#import <UIKit/UIKit.h> @interface RCTTextView : UIView @property (nonatomic, assign) UIEdgeInsets contentInset; @property (nonatomic, strong) NSTextStorage *textStorage; @property (nonatomic, assign) CGRect textFrame; @property (nonatomic, assign) BOOL selectable; @end
#!/usr/bin/make # FILE IDENTIFICATION # Name: Makefile # Purpose: Makefile for the CLSQL package # Programer: Kevin M. Rosenberg # Date Started: Mar 2002 # CLSQL users are granted the rights to distribute and use this software PKG := clsql DEBPKG := cl-sql SUBDIRS := sql tests uffi db-mysql db-aodbc db-odbc \ db-postgresql <API key> db-sqlite \ db-oracle DOCSUBDIRS:=doc include Makefile.common LIBSUBDIRS=db-mysql uffi .PHONY: subdirs $(LIBSUBDIRS) .PHONY: all all: $(LIBSUBDIRS) $(LIBSUBDIRS): $(MAKE) -C $@ SOURCE_FILES=interfaces sql cmucl-compat doc test-suite Makefile VERSION \ COPYING.CLSQL COPYING.MaiSQL README INSTALL ChangeLog NEWS TODO \ set-logical.cl clsql-uffi.system \ clsql.system clsql-aodbc.system clsql-mysql.system \ clsql-postgresql.system <API key>.system .PHONY: doc doc: $(MAKE) -C doc .PHONY:dist dist: clean @$(MAKE) -C doc $@
<?php /* * * MD5 * MD5 * 3.3 * 2012-07-19 * * , * */ /** * * @param $prestr * @param $key * return */ function md5Sign($prestr, $key) { $prestr = $prestr . $key; return md5($prestr); } /** * * @param $prestr * @param $sign * @param $key * return */ function md5Verify($prestr, $sign, $key) { $prestr = $prestr . $key; $mysgin = md5($prestr); if($mysgin == $sign) { return true; } else { return false; } } ?>
<html> <head></head> <body> Using the Console <script> var a = 1; var b = 5; var c = a + b; console.log(c); </script> </body> </html>
#include "net/quic/congestion_control/paced_sender.h" #include <algorithm> #include "net/quic/quic_protocol.h" using std::max; namespace net { // To prevent too aggressive pacing we allow the following packet burst size. const int64 kMinPacketBurstSize = 2; // Max estimated time between calls to TimeUntilSend and // <API key>. const int64 <API key> = 2000; PacedSender::PacedSender(QuicBandwidth estimate, QuicByteCount max_segment_size) : leaky_bucket_(estimate), pace_(estimate), max_segment_size_(<API key>) { } void PacedSender::<API key>(QuicTime now, QuicBandwidth estimate) { leaky_bucket_.SetDrainingRate(now, estimate); pace_ = estimate; } void PacedSender::OnPacketSent(QuicTime now, QuicByteCount bytes) { leaky_bucket_.Add(now, bytes); } QuicTime::Delta PacedSender::TimeUntilSend(QuicTime now, QuicTime::Delta time_until_send) { if (time_until_send.ToMicroseconds() >= <API key>) { return time_until_send; } // Pace the data. QuicByteCount pacing_window = pace_.ToBytesPerPeriod( QuicTime::Delta::FromMicroseconds(<API key>)); QuicByteCount min_window_size = kMinPacketBurstSize * max_segment_size_; pacing_window = max(pacing_window, min_window_size); if (pacing_window > leaky_bucket_.BytesPending(now)) { // We have not filled our pacing window yet. return time_until_send; } return leaky_bucket_.TimeRemaining(now); } } // namespace net
import unittest from tracing.metrics import discover class <API key>(unittest.TestCase): def <API key>(self): self.assertFalse(discover.DiscoverMetrics([])) def <API key>(self): self.assertEqual(['sampleMetric'], discover.DiscoverMetrics( ['/tracing/metrics/sample_metric.html'])) def <API key>(self): self.assertGreater( len(discover.DiscoverMetrics( ['/tracing/metrics/all_metrics.html'])), 1)
"""ProvidedInstance provider async mode tests.""" import asyncio from dependency_injector import containers, providers from pytest import mark, raises from .common import RESOURCE1, init_resource @mark.asyncio async def <API key>(): class TestClient: def __init__(self, resource): self.resource = resource class TestService: def __init__(self, resource): self.resource = resource class TestContainer(containers.<API key>): resource = providers.Resource(init_resource, providers.Object(RESOURCE1)) client = providers.Factory(TestClient, resource=resource) service = providers.Factory(TestService, resource=client.provided.resource) container = TestContainer() instance1, instance2 = await asyncio.gather( container.service(), container.service(), ) assert instance1.resource is RESOURCE1 assert instance2.resource is RESOURCE1 assert instance1.resource is instance2.resource @mark.asyncio async def <API key>(): async def raise_exception(): raise RuntimeError() class TestContainer(containers.<API key>): client = providers.Factory(raise_exception) container = TestContainer() with raises(RuntimeError): await container.client.provided.attr() @mark.asyncio async def <API key>(): class TestClient: def __init__(self, resource): self.resource = resource class TestContainer(containers.<API key>): resource = providers.Resource(init_resource, providers.Object(RESOURCE1)) client = providers.Factory(TestClient, resource=resource) container = TestContainer() with raises(AttributeError): await container.client.provided.attr() @mark.asyncio async def test_provided_item(): class TestClient: def __init__(self, resource): self.resource = resource def __getitem__(self, item): return getattr(self, item) class TestService: def __init__(self, resource): self.resource = resource class TestContainer(containers.<API key>): resource = providers.Resource(init_resource, providers.Object(RESOURCE1)) client = providers.Factory(TestClient, resource=resource) service = providers.Factory(TestService, resource=client.provided["resource"]) container = TestContainer() instance1, instance2 = await asyncio.gather( container.service(), container.service(), ) assert instance1.resource is RESOURCE1 assert instance2.resource is RESOURCE1 assert instance1.resource is instance2.resource @mark.asyncio async def <API key>(): async def raise_exception(): raise RuntimeError() class TestContainer(containers.<API key>): client = providers.Factory(raise_exception) container = TestContainer() with raises(RuntimeError): await container.client.provided["item"]() @mark.asyncio async def <API key>(): class TestContainer(containers.<API key>): resource = providers.Resource(init_resource, providers.Object(RESOURCE1)) client = providers.Factory(dict, resource=resource) container = TestContainer() with raises(KeyError): await container.client.provided["item"]() @mark.asyncio async def <API key>(): class TestClient: def __init__(self, resource): self.resource = resource def get_resource(self): return self.resource class TestService: def __init__(self, resource): self.resource = resource class TestContainer(containers.<API key>): resource = providers.Resource(init_resource, providers.Object(RESOURCE1)) client = providers.Factory(TestClient, resource=resource) service = providers.Factory(TestService, resource=client.provided.get_resource.call()) container = TestContainer() instance1, instance2 = await asyncio.gather( container.service(), container.service(), ) assert instance1.resource is RESOURCE1 assert instance2.resource is RESOURCE1 assert instance1.resource is instance2.resource @mark.asyncio async def <API key>(): async def raise_exception(): raise RuntimeError() class TestContainer(containers.<API key>): client = providers.Factory(raise_exception) container = TestContainer() with raises(RuntimeError): await container.client.provided.method.call()() @mark.asyncio async def <API key>(): class TestClient: def method(self): raise RuntimeError() class TestContainer(containers.<API key>): client = providers.Factory(TestClient) container = TestContainer() with raises(RuntimeError): await container.client.provided.method.call()()
package org.globus.util; import java.io.File; import java.io.IOException; public class ConfigUtil { public static final int UNDEFINED_OS = -1; public static final int WINDOWS_OS = 0; public static final int UNIX_OS = 1; public static final int MAC_OS = 2; public static final int OTHER_OS = 3; private static int osType = UNDEFINED_OS; private static final String PROXY_NAME = "x509up_u"; public static String globus_dir = null; private static String UID = null; static { UID = System.getProperty("user.name"); } static { globus_dir = System.getProperty("user.home") + File.separator + ".globus" + File.separator; } /** Returns default PKCS11 library name */ public static String <API key>() { return "dspkcs"; // use the ibutton library as the default for now } /** Returns default location of user cert file */ public static String <API key>() { String location = null; location = globus_dir + "usercert.pem"; return location; } /** Returns default location of user key file */ public static String <API key>() { String location = null; location = globus_dir + "userkey.pem"; return location; } /** * Tries to discover user proxy location. * If a UID system property is set, and running on a Unix machine it * returns /tmp/x509up_u${UID}. If any other machine then Unix, it returns * ${tempdir}/x509up_u${UID}, where tempdir is a platform-specific * temporary directory as indicated by the java.io.tmpdir system property. * If a UID system property is not set, the username will be used instead * of the UID. That is, it returns ${tempdir}/x509up_u_${username} */ public static String <API key>() { String dir = null; if (getOS() == UNIX_OS) { dir = "/tmp/"; } else { String tmpDir = System.getProperty("java.io.tmpdir"); dir = (tmpDir == null) ? globus_dir : tmpDir; } return getLocation(dir, PROXY_NAME + "_" + UID); } private static String getLocation(String dir, String file) { File f = new File(dir, file); return f.getAbsolutePath(); } /** * Returns the user id. The user id is obtained by executing 'id -u' * external program. * <B>No it isn't, that's stupid. Returns the value of System.getProperty("user.name");</B> * <BR><BR><B>Note: </B><I> * Under some circumstances, this function executes an external program; * thus, its behavior is influenced by environment variables such as the * caller's PATH and the environment variables that control dynamic * loading. Care should be used if calling this function from a program * that will be run as a Unix setuid program, or in any other manner in * which the owner of the Unix process does not completely control its * runtime environment. * </I> * * @throws IOException if unable to determine the user id. * @return the user id */ public static String getUID() throws IOException { return UID; } /** * Discovers location of CA certificates directory. * First the ${user.home}/.globus/certificates directory is checked. * If the directory does not exist, and on a Unix machine, the * /etc/grid-security/certificates directory is checked next. * If that directory does not exist and GLOBUS_LOCATION * system property is set then the ${GLOBUS_LOCATION}/share/certificates * directory is checked. Otherwise, null is returned. * This indicates that the certificates directory could * not be found. */ public static String <API key>() { String location = null; location = getDir(globus_dir + "certificates"); if (location != null) return location; if (getOS() == UNIX_OS) { location = getDir( "/etc/grid-security/certificates"); if (location != null) return location; } String suffix = File.separator + "share" + File.separator + "certificates"; location = getDir(System.getProperty("GLOBUS_LOCATION") + suffix); if (location != null) return location; return null; } public static int getOS() { if (osType != UNDEFINED_OS) { return osType; } String osname = System.getProperty("os.name"); if (osname != null) { osname = osname.toLowerCase(); if (osname.indexOf("windows") != -1) { osType = WINDOWS_OS; } else if ( (osname.indexOf("solaris") != -1) || (osname.indexOf("sunos") != -1) || (osname.indexOf("linux") != -1) || (osname.indexOf("aix") != -1) || (osname.indexOf("hp-ux") != -1) || (osname.indexOf("compaq's digital unix") != -1) || (osname.indexOf("osf1") != -1) || (osname.indexOf("mac os x") != -1) || (osname.indexOf("netbsd") != -1) || (osname.indexOf("irix") != -1) ) { osType = UNIX_OS; } else if (osname.indexOf("mac") != -1) { osType = MAC_OS; } else { osType = OTHER_OS; } } else { osType = OTHER_OS; } return osType; } private static String getDir(String directory) { if (directory == null) return null; File f = new File(directory); if (f.isDirectory() && f.canRead()) { return f.getAbsolutePath(); } else { return null; } } }
// Project: Greenhouse.File /*jslint evil: true*/ /*globals Greenhouse*/ sc_require('core'); /** @class file properties @property dir @property name @extends SC.ChildRecord @version 0.1 */ Greenhouse.File = SC.Record.extend( /** @scope Greenhouse.File.prototype */ { type: 'File', <API key>: Greenhouse, name: SC.Record.attr(String), dir: SC.Record.attr(String), body: SC.Record.attr(String), primaryKey: 'id', isFile: YES, path: function(){ return this.get('dir') + this.get('name'); }.property('name', 'dir').cacheable(), pageRegex: function(){ var b = this.get('body'), re =/(\w+)\.(\w+)\s*=\s*SC\.Page\.(design|create)/; return b ? b.match(re): b; }.property('body').cacheable(), isPage: function(){ return this.get('pageRegex') !== null; }.property('pageRegex').cacheable(), pageName: function(){ var r = this.get('pageRegex') || []; return "%@.%@".fmt(r[1],r[2]); }.property('pageRegex').cacheable() }) ; Greenhouse.FILES_QUERY = SC.Query.remote(Greenhouse.File); Greenhouse.File.mixin({ });
#include <stdint.h> #include <string.h> #include <openssl/opensslconf.h> #if !defined(OPENSSL_NO_CHACHA) && !defined(OPENSSL_NO_POLY1305) #include <openssl/chacha.h> #include <openssl/poly1305.h> #include <openssl/evp.h> #include <openssl/err.h> #include "evp_locl.h" #define POLY1305_TAG_LEN 16 #define CHACHA20_NONCE_LEN 8 struct <API key> { unsigned char key[32]; unsigned char tag_len; }; static int <API key>(EVP_AEAD_CTX *ctx, const unsigned char *key, size_t key_len, size_t tag_len) { struct <API key> *c20_ctx; if (tag_len == 0) tag_len = POLY1305_TAG_LEN; if (tag_len > POLY1305_TAG_LEN) { EVPerr(<API key>, EVP_R_TOO_LARGE); return 0; } if (key_len != sizeof(c20_ctx->key)) return 0; /* internal error - EVP_AEAD_CTX_init should catch this. */ c20_ctx = OPENSSL_malloc(sizeof(struct <API key>)); if (c20_ctx == NULL) return 0; memcpy(&c20_ctx->key[0], key, key_len); c20_ctx->tag_len = tag_len; ctx->aead_state = c20_ctx; return 1; } static void <API key>(EVP_AEAD_CTX *ctx) { struct <API key> *c20_ctx = ctx->aead_state; OPENSSL_cleanse(c20_ctx->key, sizeof(c20_ctx->key)); OPENSSL_free(c20_ctx); } static void <API key>(poly1305_state *poly1305, const unsigned char *data, size_t data_len) { size_t j = data_len; unsigned char length_bytes[8]; unsigned i; for (i = 0; i < sizeof(length_bytes); i++) { length_bytes[i] = j; j >>= 8; } <API key>(poly1305, data, data_len); <API key>(poly1305, length_bytes, sizeof(length_bytes)); } #if __arm__ #define ALIGNED __attribute__((aligned(16))) #else #define ALIGNED #endif static ssize_t <API key>(const EVP_AEAD_CTX *ctx, unsigned char *out, size_t max_out_len, const unsigned char *nonce, size_t nonce_len, const unsigned char *in, size_t in_len, const unsigned char *ad, size_t ad_len) { const struct <API key> *c20_ctx = ctx->aead_state; unsigned char poly1305_key[32] ALIGNED; poly1305_state poly1305; const uint64_t in_len_64 = in_len; /* The underlying ChaCha implementation may not overflow the block * counter into the second counter word. Therefore we disallow * individual operations that work on more than 2TB at a time. * |in_len_64| is needed because, on 32-bit platforms, size_t is only * 32-bits and this produces a warning because it's always false. * Casting to uint64_t inside the conditional is not sufficient to stop * the warning. */ if (in_len_64 >= (1ull << 32)*64-64) { EVPerr(<API key>, EVP_R_TOO_LARGE); return -1; } if (max_out_len < in_len + c20_ctx->tag_len) { EVPerr(<API key>, <API key>); return -1; } if (nonce_len != CHACHA20_NONCE_LEN) { EVPerr(<API key>, EVP_R_IV_TOO_LARGE); return -1; } memset(poly1305_key, 0, sizeof(poly1305_key)); CRYPTO_chacha_20(poly1305_key, poly1305_key, sizeof(poly1305_key), c20_ctx->key, nonce, 0); <API key>(&poly1305, poly1305_key); <API key>(&poly1305, ad, ad_len); CRYPTO_chacha_20(out, in, in_len, c20_ctx->key, nonce, 1); <API key>(&poly1305, out, in_len); if (c20_ctx->tag_len != POLY1305_TAG_LEN) { unsigned char tag[POLY1305_TAG_LEN]; <API key>(&poly1305, tag); memcpy(out + in_len, tag, c20_ctx->tag_len); return in_len + c20_ctx->tag_len; } <API key>(&poly1305, out + in_len); return in_len + POLY1305_TAG_LEN; } static ssize_t <API key>(const EVP_AEAD_CTX *ctx, unsigned char *out, size_t max_out_len, const unsigned char *nonce, size_t nonce_len, const unsigned char *in, size_t in_len, const unsigned char *ad, size_t ad_len) { const struct <API key> *c20_ctx = ctx->aead_state; unsigned char mac[POLY1305_TAG_LEN]; unsigned char poly1305_key[32] ALIGNED; size_t out_len; poly1305_state poly1305; const uint64_t in_len_64 = in_len; if (in_len < c20_ctx->tag_len) { EVPerr(<API key>, EVP_R_BAD_DECRYPT); return -1; } /* The underlying ChaCha implementation may not overflow the block * counter into the second counter word. Therefore we disallow * individual operations that work on more than 2TB at a time. * |in_len_64| is needed because, on 32-bit platforms, size_t is only * 32-bits and this produces a warning because it's always false. * Casting to uint64_t inside the conditional is not sufficient to stop * the warning. */ if (in_len_64 >= (1ull << 32)*64-64) { EVPerr(<API key>, EVP_R_TOO_LARGE); return -1; } if (nonce_len != CHACHA20_NONCE_LEN) { EVPerr(<API key>, EVP_R_IV_TOO_LARGE); return -1; } out_len = in_len - c20_ctx->tag_len; if (max_out_len < out_len) { EVPerr(<API key>, <API key>); return -1; } memset(poly1305_key, 0, sizeof(poly1305_key)); CRYPTO_chacha_20(poly1305_key, poly1305_key, sizeof(poly1305_key), c20_ctx->key, nonce, 0); <API key>(&poly1305, poly1305_key); <API key>(&poly1305, ad, ad_len); <API key>(&poly1305, in, out_len); <API key>(&poly1305, mac); if (CRYPTO_memcmp(mac, in + out_len, c20_ctx->tag_len) != 0) { EVPerr(<API key>, EVP_R_BAD_DECRYPT); return -1; } CRYPTO_chacha_20(out, in, out_len, c20_ctx->key, nonce, 1); return out_len; } static const EVP_AEAD <API key> = { 32, /* key len */ CHACHA20_NONCE_LEN, /* nonce len */ POLY1305_TAG_LEN, /* overhead */ POLY1305_TAG_LEN, /* max tag length */ <API key>, <API key>, <API key>, <API key>, }; const EVP_AEAD *<API key>() { return &<API key>; } #endif /* !OPENSSL_NO_CHACHA && !OPENSSL_NO_POLY1305 */
#ifndef <API key> #define <API key> #include "ash/keyboard/<API key>.h" #include "ash/system/tray/<API key>.h" #include "ash/system/user/login_status.h" #include "base/macros.h" #include "ui/views/controls/button/button.h" namespace views { class ImageButton; } namespace ash { class StatusAreaWidget; // TODO(sky): make this visible on non-chromeos platforms. class VirtualKeyboardTray : public TrayBackgroundView, public views::ButtonListener, public KeyboardUIObserver { public: explicit VirtualKeyboardTray(StatusAreaWidget* status_area_widget); ~VirtualKeyboardTray() override; // TrayBackgroundView: void SetShelfAlignment(wm::ShelfAlignment alignment) override; base::string16 <API key>() override; void HideBubbleWithView(const views::TrayBubbleView* bubble_view) override; void <API key>() override; bool PerformAction(const ui::Event& event) override; // views::ButtonListener: void ButtonPressed(views::Button* sender, const ui::Event& event) override; // KeyboardUIObserver: void <API key>(bool new_value) override; private: views::ImageButton* button_; // Not owned. <API key>(VirtualKeyboardTray); }; } // namespace ash #endif // <API key>
<?php class <API key> extends <API key> { /** * Returns the lines where errors should occur. * * The key of the array should represent the line number and the value * should represent the number of errors that should occur on that line. * * @return array<int, int> */ public function getErrorList() { $errors = array( 10 => 1, 11 => 1, 12 => 1, 13 => 1, 16 => 1, 17 => 1, 20 => 1, 21 => 1, 24 => 1, 25 => 1, 30 => 1, 31 => 1, 50 => 1, 52 => 1, 53 => 1, 57 => 1, 58 => 1, 59 => 1, 60 => 1, 61 => 1, 62 => 1, 63 => 1, 64 => 1, 65 => 1, 66 => 1, 67 => 1, 68 => 1, 69 => 1, 71 => 1, 72 => 1, 73 => 1, 74 => 1, 118 => 1, ); return $errors; }//end getErrorList() /** * Returns the lines where warnings should occur. * * The key of the array should represent the line number and the value * should represent the number of warnings that should occur on that line. * * @return array<int, int> */ public function getWarningList() { return array(); }//end getWarningList() }//end class ?>
var App = (function () { 'use strict'; App.charts = function( ){ function randValue() { return (Math.floor(Math.random() * (1 + 50 - 20))) + 10; } //Counter function counter(){ $('[data-toggle="counter"]').each(function(i, e){ var _el = $(this); var prefix = ''; var suffix = ''; var start = 0; var end = 0; var decimals = 0; var duration = 2.5; if( _el.data('prefix') ){ prefix = _el.data('prefix'); } if( _el.data('suffix') ){ suffix = _el.data('suffix'); } if( _el.data('start') ){ start = _el.data('start'); } if( _el.data('end') ){ end = _el.data('end'); } if( _el.data('decimals') ){ decimals = _el.data('decimals'); } if( _el.data('duration') ){ duration = _el.data('duration'); } var count = new CountUp(_el.get(0), start, end, decimals, duration, { suffix: suffix, prefix: prefix, }); count.start(); }); } //Line Chart 1 function widget_linechart1(){ var color1 = App.color.alt2; var plot_statistics = $.plot($("#line-chart1"), [{ data: [ [0, 20], [1, 30], [2, 25], [3, 39], [4, 35], [5, 40], [6, 30], [7, 45] ], label: "Page Views" } ], { series: { lines: { show: true, lineWidth: 2, fill: true, fillColor: { colors: [{ opacity: 0.2 }, { opacity: 0.2 } ] } }, points: { show: true }, shadowSize: 0 }, legend:{ show: false }, grid: { margin: { left: -8, right: -8, top: 0, bottom: 0 }, show: false, labelMargin: 15, axisMargin: 500, hoverable: true, clickable: true, tickColor: "rgba(0,0,0,0.15)", borderWidth: 0 }, colors: [color1], xaxis: { ticks: 11, tickDecimals: 0 }, yaxis: { autoscaleMargin: 0.5, ticks: 4, tickDecimals: 0 } }); } //Chart Pie 4 function widget_chartpie4(){ var data = [ { label: "Google", data: 45}, { label: "Dribbble", data: 25}, { label: "Twitter", data: 20}, { label: "Facebook", data: 10} ]; var color1 = tinycolor( App.color.primary ).brighten( 9 ).toString(); var color2 = tinycolor( App.color.primary ).lighten( 13 ).toString(); var color3 = tinycolor( App.color.primary ).lighten( 20 ).toString(); var color4 = tinycolor( App.color.primary ).lighten( 27 ).toString(); $.plot('#pie-chart4', data, { series: { pie: { show: true, innerRadius: 0.27, shadow:{ top: 5, left: 15, alpha:0.3 }, stroke:{ width:0 }, label: { show: true, formatter: function (label, series) { return '<div style="font-size:12px;text-align:center;padding:2px;color:#333;">' + label + '</div>'; } }, highlight:{ opacity: 0.08 } } }, grid: { hoverable: true, clickable: true }, colors: [color1, color2, color3, color4], legend: { show: false } }); } //Bar Chart 1 function widget_barchart1(){ var color1 = tinycolor( App.color.alt3 ).lighten( 15 ).toString(); var color2 = tinycolor( App.color.alt3 ).brighten( 3 ).toString(); var plot_statistics = $.plot($("#bar-chart1"), [ { data: [ [0, 15], [1, 15], [2, 19], [3, 28], [4, 30], [5, 37], [6, 35], [7, 38], [8, 48], [9, 43], [10, 38], [11, 32], [12, 38] ], label: "Page Views" }, { data: [ [0, 7], [1, 10], [2, 15], [3, 23], [4, 24], [5, 29], [6, 25], [7, 33], [8, 35], [9, 38], [10, 32], [11, 27], [12, 32] ], label: "Unique Visitor" } ], { series: { bars: { align: 'center', show: true, lineWidth: 1, barWidth: 0.6, fill: true, fillColor: { colors: [{ opacity: 1 }, { opacity: 1 } ] } }, shadowSize: 2 }, legend:{ show: false }, grid: { margin: 0, show: false, labelMargin: 10, axisMargin: 500, hoverable: true, clickable: true, tickColor: "rgba(0,0,0,0.15)", borderWidth: 0 }, colors: [color1, color2], xaxis: { ticks: 11, tickDecimals: 0 }, yaxis: { autoscaleMargin: 0.5, ticks: 4, tickDecimals: 0 } }); } //Top pie widget 1 function widget_top_1(){ var data = [ { label: "Premium Purchases", data: 15 }, { label: "Standard Plans", data: 25 }, { label: "Services", data: 60 } ]; var color1 = tinycolor( App.color.primary ).lighten( 5 ).toString(); var color2 = App.color.alt2; var color3 = App.color.alt1; var legendContainer = $("#widget-top-1").parent().next().find(".legend"); $.plot('#widget-top-1', data, { series: { pie: { show: true, highlight: { opacity: 0.1 } } }, grid:{ hoverable: true }, legend:{ container: legendContainer }, colors: [color1, color2, color3] }); } //Mini widget 1 function line_chart_mini(){ var color1 = tinycolor( App.color.alt1 ).lighten( 7 ).toString(); var color2 = App.color.alt1; var data = [ [1, 20], [2, 60], [3, 35], [4, 70], [5, 45] ]; var data2 = [ [1, 60], [2, 20], [3, 65], [4, 35], [5, 65] ]; var plot_statistics = $.plot("#linechart-mini1", [ { data: data, canvasRender: true }, { data: data2, canvasRender: true } ], { series: { lines: { show: true, lineWidth: 0, fill: true, fillColor: { colors: [{ opacity: 0.7 }, { opacity: 0.7}] } }, fillColor: "rgba(0, 0, 0, 1)", shadowSize: 0, curvedLines: { apply: true, active: true, monotonicFit: true } }, legend:{ show: false }, grid: { show:false, hoverable: true, clickable: true }, colors: [color1, color2], xaxis: { autoscaleMargin: 0, ticks: 11, tickDecimals: 0 }, yaxis: { autoscaleMargin: 0.5, ticks: 5, tickDecimals: 0 } }); } //Live data chart function line_live_data(){ var color1 = App.color.alt2; var data = [], totalPoints = 300; function getRandomData() { if (data.length > 0) data = data.slice(1); // Do a random walk while (data.length < totalPoints) { var prev = data.length > 0 ? data[data.length - 1] : 50, y = prev + Math.random() * 10 - 5; if (y < 0) { y = 0; } else if (y > 100) { y = 100; } data.push(y); } // Zip the generated y values with the x values var res = []; for (var i = 0; i < data.length; ++i) { res.push([i, data[i]]) } return res; } var updateInterval = 30; var plot = $.plot("#live-data", [ getRandomData() ], { series: { shadowSize: 0,// Drawing is faster without shadows lines: { show: true, lineWidth: 2, fill: true, fillColor: { colors: [{ opacity: 0.2 }, { opacity: 0.2 } ] } } }, grid: { show: true, margin: { top: 3, bottom: 0, left: 0, right: 0, }, labelMargin: 0, axisMargin: 0, hoverable: true, clickable: true, tickColor: "rgba(0,0,0,0)", borderWidth: 0, minBorderMargin: 0 }, colors:[ color1 ], yaxis: { show: false, autoscaleMargin: 0.2, ticks: 5, tickDecimals: 0 }, xaxis: { show: false, autoscaleMargin: 0 } }); function update() { plot.setData([getRandomData()]); // Since the axes don't change, we don't need to call plot.setupGrid() plot.draw(); setTimeout(update, updateInterval); } update(); } //Line Chart Live function <API key>(){ var color1 = tinycolor( App.color.primary ).lighten( 22 ); var color2 = App.color.primary; var data_com2 = [ [1, randValue()], [2, randValue()], [3, 2 + randValue()], [4, 3 + randValue()], [5, 5 + randValue()], [6, 10 + randValue()], [7, 15 + randValue()], [8, 20 + randValue()], [9, 25 + randValue()], [10, 30 + randValue()], [11, 35 + randValue()], [12, 25 + randValue()], [13, 15 + randValue()], [14, 20 + randValue()], [15, 45 + randValue()], [16, 50 + randValue()], [17, 65 + randValue()], [18, 70 + randValue()], [19, 85 + randValue()], [20, 80 + randValue()], [21, 75 + randValue()], [22, 80 + randValue()], [23, 75 + randValue()] ]; var data_com = [ [1, randValue()], [2, randValue()], [3, 10 + randValue()], [4, 15 + randValue()], [5, 20 + randValue()], [6, 25 + randValue()], [7, 30 + randValue()], [8, 35 + randValue()], [9, 40 + randValue()], [10, 45 + randValue()], [11, 50 + randValue()], [12, 55 + randValue()], [13, 60 + randValue()], [14, 70 + randValue()], [15, 75 + randValue()], [16, 80 + randValue()], [17, 85 + randValue()], [18, 90 + randValue()], [19, 95 + randValue()], [20, 100 + randValue()], [21, 110 + randValue()], [22, 120 + randValue()], [23, 130 + randValue()] ]; var plot_statistics = $.plot($("#line-chart-live"), [{ data: data_com, showLabels: true, label: "New Visitors", labelPlacement: "below", canvasRender: true, cColor: "#FFFFFF" },{ data: data_com2, showLabels: true, label: "Old Visitors", labelPlacement: "below", canvasRender: true, cColor: "#FFFFFF" } ], { series: { lines: { show: true, lineWidth: 1.5, fill: true, fillColor: { colors: [{ opacity: 0.5 }, { opacity: 0.5}] }, }, fillColor: "rgba(0, 0, 0, 1)", points: { show: false, fill: true }, shadowSize: 0 }, legend:{ show: false }, grid: { show: true, margin: { top: -20, bottom: 0, left: 0, right: 0, }, labelMargin: 0, axisMargin: 0, hoverable: true, clickable: true, tickColor: "rgba(0,0,0,0)", borderWidth: 0, minBorderMargin: 0 }, colors: [color1, color2], xaxis: { autoscaleMargin: 0, ticks: 11, tickDecimals: 0 }, yaxis: { autoscaleMargin: 0.2, ticks: 5, tickDecimals: 0 } }); } //Fullwidth line chart 1 function line_chart2(){ var color1 = App.color.alt3; var chartEl = $("#line-chart2"); var counterEl = chartEl.parent().find(".counter .value").get(0); var data = [ [1, 10], [2, 30], [3, 10 + 45], [4, 15 + 21], [5, 57], [6, 80], [7, 65], [8, 50], [9, 80], [10, 70], [11, 90], [12, 55 + 12], [12, 55 + 12] ]; var plot_statistics = $.plot("#line-chart2", [{ data: data, showLabels: true, label: "New Visitors", labelPlacement: "below", canvasRender: true, cColor: "#FFFFFF" } ], { series: { lines: { show: true, lineWidth: 2, fill: true, fillColor: { colors: [{ opacity: 0.6 }, { opacity: 0.6}] } }, fillColor: "rgba(0, 0, 0, 1)", points: { show: true, fill: true, fillColor: color1 }, shadowSize: 0 }, legend:{ show: false }, grid: { show:false, margin: { left: -8, right: -8, top: 0, botttom: 0 }, labelMargin: 0, axisMargin: 0, hoverable: true, clickable: true, tickColor: "rgba(0, 0, 0, 0)", borderWidth: 0 }, colors: [color1], xaxis: { autoscaleMargin: 0, ticks: 11, tickDecimals: 0 }, yaxis: { autoscaleMargin: 0.5, ticks: 5, tickDecimals: 0 } }); //Counter plugin init var counter = new CountUp(counterEl, 0, 80, 0, 2.5, { suffix: '%' }); counter.start(); } //Line Chart 2 function widget_linechart2(){ var color1 = tinycolor( App.color.primary ).lighten( 5 ).toString(); var plot_statistics = $.plot($("#line-chart3"), [{ data: [ [0, 20], [1, 30], [2, 25], [3, 39], [4, 35], [5, 40], [6, 30], [7, 45] ], label: "Page Views" } ], { series: { lines: { show: true, lineWidth: 2, fill: true, fillColor: { colors: [{ opacity: 0.1 }, { opacity: 0.1 } ] } }, points: { show: true }, shadowSize: 0 }, legend:{ show: false }, grid: { labelMargin: 15, axisMargin: 500, hoverable: true, clickable: true, tickColor: "rgba(0,0,0,0.15)", borderWidth: 0 }, colors: [color1], xaxis: { ticks: 11, tickDecimals: 0 }, yaxis: { ticks: 4, tickSize: 15, tickDecimals: 0 } }); } //Bar Chart 2 function widget_barchart2(){ var color1 = App.color.alt3; var color2 = tinycolor( App.color.alt3 ).lighten( 22 ).toString(); var plot_statistics = $.plot($("#bar-chart2"), [ { data: [ [0, 7], [1, 13], [2, 17], [3, 20], [4, 26], [5, 37], [6, 35], [7, 28], [8, 38], [9, 38], [10, 32] ], label: "Page Views" }, { data: [ [0, 15], [1, 10], [2, 15], [3, 25], [4, 30], [5, 29], [6, 25], [7, 33], [8, 45], [9, 43], [10, 38] ], label: "Unique Visitor" } ], { series: { bars: { order: 2, align: 'center', show: true, lineWidth: 1, barWidth: 0.35, fill: true, fillColor: { colors: [{ opacity: 1 }, { opacity: 1 } ] } }, shadowSize: 2 }, legend:{ show: false }, grid: { labelMargin: 10, axisMargin: 500, hoverable: true, clickable: true, tickColor: "rgba(0,0,0,0.15)", borderWidth: 0 }, colors: [color1, color2], xaxis: { ticks: 11, tickDecimals: 0 }, yaxis: { ticks: 4, tickDecimals: 0 } }); } //CountUp counter(); //row 1 widget_linechart1(); widget_chartpie4(); widget_barchart1(); //row 2 widget_top_1(); line_chart_mini(); line_live_data(); //row 3 <API key>(); line_chart2(); //Row 4 widget_linechart2(); widget_barchart2(); }; return App; })(App || {});
"""Tests that the IPython printing module is properly loaded. """ import warnings from sympy.core.compatibility import u from sympy.interactive.session import <API key> from sympy.external import import_module from sympy.utilities.pytest import raises # run_cell was added in IPython 0.11 ipython = import_module("IPython", min_module_version="0.11") # disable tests if ipython is not present if not ipython: disabled = True def <API key>(): # Initialize and setup IPython session app = <API key>() app.run_cell("ip = get_ipython()") app.run_cell("inst = ip.instance()") app.run_cell("format = inst.display_formatter.format") app.run_cell("from sympy import Symbol") # Printing without printing extension app.run_cell("a = format(Symbol('pi'))") app.run_cell("a2 = format(Symbol('pi')**2)") # Deal with API change starting at IPython 1.0 if int(ipython.__version__.split(".")[0]) < 1: assert app.user_ns['a']['text/plain'] == "pi" assert app.user_ns['a2']['text/plain'] == "pi**2" else: assert app.user_ns['a'][0]['text/plain'] == "pi" assert app.user_ns['a2'][0]['text/plain'] == "pi**2" # Load printing extension app.run_cell("from sympy import init_printing") app.run_cell("init_printing()") # Printing with printing extension app.run_cell("a = format(Symbol('pi'))") app.run_cell("a2 = format(Symbol('pi')**2)") # Deal with API change starting at IPython 1.0 if int(ipython.__version__.split(".")[0]) < 1: assert app.user_ns['a']['text/plain'] in (u('\N{GREEK SMALL LETTER PI}'), 'pi') assert app.user_ns['a2']['text/plain'] in (u(' 2\n\N{GREEK SMALL LETTER PI} '), ' 2\npi ') else: assert app.user_ns['a'][0]['text/plain'] in (u('\N{GREEK SMALL LETTER PI}'), 'pi') assert app.user_ns['a2'][0]['text/plain'] in (u(' 2\n\N{GREEK SMALL LETTER PI} '), ' 2\npi ') def <API key>(): # Initialize and setup IPython session app = <API key>() app.run_cell("ip = get_ipython()") app.run_cell("inst = ip.instance()") app.run_cell("format = inst.display_formatter.format") app.run_cell("from sympy import Symbol") app.run_cell("from sympy import init_printing") app.run_cell("a = format({Symbol('pi'): 3.14, Symbol('n_i'): 3})") # Deal with API change starting at IPython 1.0 if int(ipython.__version__.split(".")[0]) < 1: text = app.user_ns['a']['text/plain'] raises(KeyError, lambda: app.user_ns['a']['text/latex']) else: text = app.user_ns['a'][0]['text/plain'] raises(KeyError, lambda: app.user_ns['a'][0]['text/latex']) # Note : In Python 3 the text is unicode, but in 2 it is a string. # XXX: How can we make this ignore the terminal width? This test fails if # the terminal is too narrow. assert text in ("{pi: 3.14, n_i: 3}", u('{n\N{LATIN SUBSCRIPT SMALL LETTER I}: 3, \N{GREEK SMALL LETTER PI}: 3.14}'), "{n_i: 3, pi: 3.14}", u('{\N{GREEK SMALL LETTER PI}: 3.14, n\N{LATIN SUBSCRIPT SMALL LETTER I}: 3}')) # If we enable the default printing, then the dictionary's should render # as a LaTeX version of the whole dict: ${\pi: 3.14, n_i: 3}$ app.run_cell("inst.display_formatter.formatters['text/latex'].enabled = True") app.run_cell("init_printing(use_latex=True)") app.run_cell("a = format({Symbol('pi'): 3.14, Symbol('n_i'): 3})") # Deal with API change starting at IPython 1.0 if int(ipython.__version__.split(".")[0]) < 1: text = app.user_ns['a']['text/plain'] latex = app.user_ns['a']['text/latex'] else: text = app.user_ns['a'][0]['text/plain'] latex = app.user_ns['a'][0]['text/latex'] assert text in ("{pi: 3.14, n_i: 3}", u('{n\N{LATIN SUBSCRIPT SMALL LETTER I}: 3, \N{GREEK SMALL LETTER PI}: 3.14}'), "{n_i: 3, pi: 3.14}", u('{\N{GREEK SMALL LETTER PI}: 3.14, n\N{LATIN SUBSCRIPT SMALL LETTER I}: 3}')) assert latex == r'$$\left \{ n_{i} : 3, \quad \pi : 3.14\right \}$$' app.run_cell("inst.display_formatter.formatters['text/latex'].enabled = True") app.run_cell("init_printing(use_latex=True, print_builtin=False)") app.run_cell("a = format({Symbol('pi'): 3.14, Symbol('n_i'): 3})") # Deal with API change starting at IPython 1.0 if int(ipython.__version__.split(".")[0]) < 1: text = app.user_ns['a']['text/plain'] raises(KeyError, lambda: app.user_ns['a']['text/latex']) else: text = app.user_ns['a'][0]['text/plain'] raises(KeyError, lambda: app.user_ns['a'][0]['text/latex']) # Note : In Python 3 the text is unicode, but in 2 it is a string. # Python 3.3.3 + IPython 0.13.2 gives: '{n_i: 3, pi: 3.14}' # Python 3.3.3 + IPython 1.1.0 gives: '{n_i: 3, pi: 3.14}' # Python 2.7.5 + IPython 1.1.0 gives: '{pi: 3.14, n_i: 3}' assert text in ("{pi: 3.14, n_i: 3}", "{n_i: 3, pi: 3.14}") def <API key>(): # Initialize and setup IPython session app = <API key>() app.run_cell("import IPython") app.run_cell("ip = get_ipython()") app.run_cell("inst = ip.instance()") app.run_cell("format = inst.display_formatter.format") app.run_cell("from sympy import init_printing, Matrix") app.run_cell("init_printing(use_latex='matplotlib')") # The png formatter is not enabled by default in this context app.run_cell("inst.display_formatter.formatters['image/png'].enabled = True") # Make sure no warnings are raised by IPython app.run_cell("import warnings") app.run_cell("warnings.simplefilter('error', IPython.core.formatters.FormatterWarning)") # This should not raise an exception app.run_cell("a = format(Matrix([1, 2, 3]))")
namespace open3mod { partial class TipOfTheDayDialog { <summary> Required designer variable. </summary> private System.ComponentModel.IContainer components = null; <summary> Clean up any resources being used. </summary> <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code <summary> Required method for Designer support - do not modify the contents of this method with the code editor. </summary> private void InitializeComponent() { System.ComponentModel.<API key> resources = new System.ComponentModel.<API key>(typeof(TipOfTheDayDialog)); this.button1 = new System.Windows.Forms.Button(); this.button2 = new System.Windows.Forms.Button(); this.buttonOk = new System.Windows.Forms.Button(); this.<API key> = new System.Windows.Forms.CheckBox(); this.panel1 = new System.Windows.Forms.Panel(); this.labelTipText = new System.Windows.Forms.Label(); this.pictureBoxTipPic = new System.Windows.Forms.PictureBox(); this.panel1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBoxTipPic)).BeginInit(); this.SuspendLayout(); // button1 this.button1.Location = new System.Drawing.Point(104, 223); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(88, 23); this.button1.TabIndex = 0; this.button1.Text = "Next"; this.button1.<API key> = true; this.button1.Click += new System.EventHandler(this.OnNext); // button2 this.button2.Location = new System.Drawing.Point(12, 223); this.button2.Name = "button2"; this.button2.Size = new System.Drawing.Size(92, 23); this.button2.TabIndex = 1; this.button2.Text = "Previous"; this.button2.<API key> = true; this.button2.Click += new System.EventHandler(this.OnPrevious); // buttonOk this.buttonOk.DialogResult = System.Windows.Forms.DialogResult.OK; this.buttonOk.Location = new System.Drawing.Point(430, 223); this.buttonOk.Name = "buttonOk"; this.buttonOk.Size = new System.Drawing.Size(100, 23); this.buttonOk.TabIndex = 2; this.buttonOk.Text = "OK"; this.buttonOk.<API key> = true; // <API key> this.<API key>.AutoSize = true; this.<API key>.Checked = global::CoreSettings.CoreSettings.Default.ShowTipsOnStartup; this.<API key>.DataBindings.Add(new System.Windows.Forms.Binding("Checked", global::CoreSettings.CoreSettings.Default, "ShowTipsOnStartup", true, System.Windows.Forms.<API key>.OnPropertyChanged)); this.<API key>.Location = new System.Drawing.Point(321, 227); this.<API key>.Name = "<API key>"; this.<API key>.Size = new System.Drawing.Size(103, 17); this.<API key>.TabIndex = 3; this.<API key>.Text = "Show on startup"; this.<API key>.<API key> = true; this.<API key>.CheckedChanged += new System.EventHandler(this.OnChangeStartup); // panel1 this.panel1.BackColor = System.Drawing.Color.White; this.panel1.Controls.Add(this.labelTipText); this.panel1.Controls.Add(this.pictureBoxTipPic); this.panel1.Location = new System.Drawing.Point(-1, 0); this.panel1.Name = "panel1"; this.panel1.Size = new System.Drawing.Size(543, 207); this.panel1.TabIndex = 4; // labelTipText this.labelTipText.AutoSize = true; this.labelTipText.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.labelTipText.Location = new System.Drawing.Point(229, 25); this.labelTipText.Name = "labelTipText"; this.labelTipText.Size = new System.Drawing.Size(205, 96); this.labelTipText.TabIndex = 1; this.labelTipText.Text = "You can use the force to control \r\nalmost everything.\r\n\r\nJust make sure the force" + " is strong\r\nin you. Do not attempt to count\r\nMidi-Chlorians."; // pictureBoxTipPic this.pictureBoxTipPic.Image = ((System.Drawing.Image)(resources.GetObject("pictureBoxTipPic.Image"))); this.pictureBoxTipPic.Location = new System.Drawing.Point(13, 12); this.pictureBoxTipPic.Name = "pictureBoxTipPic"; this.pictureBoxTipPic.Size = new System.Drawing.Size(220, 179); this.pictureBoxTipPic.TabIndex = 0; this.pictureBoxTipPic.TabStop = false; // TipOfTheDayDialog this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(542, 258); this.Controls.Add(this.panel1); this.Controls.Add(this.<API key>); this.Controls.Add(this.buttonOk); this.Controls.Add(this.button2); this.Controls.Add(this.button1); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.Name = "TipOfTheDayDialog"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "Tip of the Day"; this.FormClosing += new System.Windows.Forms.<API key>(this.OnClose); this.panel1.ResumeLayout(false); this.panel1.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBoxTipPic)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Button button1; private System.Windows.Forms.Button button2; private System.Windows.Forms.Button buttonOk; private System.Windows.Forms.CheckBox <API key>; private System.Windows.Forms.Panel panel1; private System.Windows.Forms.PictureBox pictureBoxTipPic; private System.Windows.Forms.Label labelTipText; } }
module Compiler.Simplify where import Data.Generics.PlateData import Compiler.Type import Data.List import Data.Maybe simplify :: Program1 -> Program2 simplify = addDollar . reform . freezeRules -- change rule application rule(arg) to rule_arg and replace all bits freezeRules :: Program1 -> Program1 freezeRules xs = map useDyn $ staticRules ++ dynInvoke where (staticRules,dynRules) = partition (\(Stmt1 a b c) -> null b) xs dynNames = [(a, (b,c)) | Stmt1 a b c <- dynRules] dynInvoke = [gen name arg res |Call1 name (Just arg) bind <- nub $ universeBi staticRules ,Just res <- [lookup name dynNames]] gen name arg (var,bod) = Stmt1 (getName name arg) "" (transformBi f bod) where f (Call1 v Nothing Nothing) | v == var = arg f x = x useDyn = transformBi f where f (Call1 v (Just x) y) | v `elem` map fst dynNames = Call1 (getName v x) Nothing y f x = x getName name (Literal1 x) = name ++ "_" ++ fromMaybe x (lookup x reps) where reps = [("'","squot"),("\"","dquot")] reform :: Program1 -> Program2 reform = concatMap reformStmt reformStmt (Stmt1 a "" (Choice1 xs)) | fst (last xs) == Call1 "_" Nothing Nothing = Stmt2 a (Choice2 (zipWith f [1..] $ init xs) (g $ length xs)) : zipWith (\i (_,v) -> Stmt2 (g i) (reformSeq v)) [1..] xs where f i (Literal1 x,_) = (x, g i) g i = a ++ "_" ++ show i reformStmt (Stmt1 a "" x) = [Stmt2 a $ reformSeq x] reformSeq (Seq1 act xs) = Seq2 act (map reformItem xs) reformItem (Literal1 x) = Literal2 x reformItem (Call1 name (Just (Literal1 x)) y) | name `elem` prims = Prim2 name x y reformItem (Call1 name Nothing y) = Rule2 name y addDollar :: Program2 -> Program2 addDollar = transformBi f where f (Seq2 act xs) | all (isNothing . getBind) xs && length (filter (isJust . getBind) ys) == 1 = Seq2 act ys where ys = transformBi (const $ Just (1::Int)) xs f x = x
<! Copyright (c) 2013, S-Core. All rights reserved. Use is subject to license terms. This distribution may include materials developed by third parties. <html> <head> <script src="jquery.js"></script> </head> <body> <div id="test"></div> <script> var x = $("#test") var __result1; var __expect1 = 1; x.keypress(function() { __result1 = 1;}) </script> </body> </html>
// Use of this source code is governed by a BSD-style // Memory allocator, based on tcmalloc. // The main allocator works in runs of pages. // Small allocation sizes (up to and including 32 kB) are // rounded to one of about 100 size classes, each of which // has its own free list of objects of exactly that size. // Any free page of memory can be split into a set of objects // of one size class, which are then managed using free list // allocators. // The allocator's data structures are: // FixAlloc: a free-list allocator for fixed-size objects, // used to manage storage used by the allocator. // MHeap: the malloc heap, managed at page (4096-byte) granularity. // MSpan: a run of pages managed by the MHeap. // MHeapMap: a mapping from page IDs to MSpans. // MHeapMapCache: a small cache of MHeapMap mapping page IDs // to size classes for pages used for small objects. // MCentral: a shared free list for a given size class. // MCache: a per-thread (in Go, per-M) cache for small objects. // MStats: allocation statistics. // Allocating a small object proceeds up a hierarchy of caches: // 1. Round the size up to one of the small size classes // and look in the corresponding MCache free list. // If the list is not empty, allocate an object from it. // This can all be done without acquiring a lock. // 2. If the MCache free list is empty, replenish it by // taking a bunch of objects from the MCentral free list. // Moving a bunch amortizes the cost of acquiring the MCentral lock. // 3. If the MCentral free list is empty, replenish it by // allocating a run of pages from the MHeap and then // chopping that memory into a objects of the given size. // Allocating many objects amortizes the cost of locking // the heap. // 4. If the MHeap is empty or has no page runs large enough, // allocate a new group of pages (at least 1MB) from the // operating system. Allocating a large run of pages // amortizes the cost of talking to the operating system. // Freeing a small object proceeds up the same hierarchy: // 1. Look up the size class for the object and add it to // the MCache free list. // 2. If the MCache free list is too long or the MCache has // too much memory, return some to the MCentral free lists. // 3. If all the objects in a given span have returned to // the MCentral list, return that span to the page heap. // 4. If the heap has too much memory, return some to the // operating system. // TODO(rsc): Step 4 is not implemented. // Allocating and freeing a large object uses the page heap // directly, bypassing the MCache and MCentral free lists. // This C code was written with an eye toward translating to Go // in the future. Methods have the form Type_Method(Type *t, ...). typedef struct FixAlloc FixAlloc; typedef struct MCentral MCentral; typedef struct MHeap MHeap; typedef struct MHeapMap MHeapMap; typedef struct MHeapMapCache MHeapMapCache; typedef struct MSpan MSpan; typedef struct MStats MStats; typedef struct MLink MLink; enum { PageShift = 12, PageSize = 1<<PageShift, PageMask = PageSize - 1, }; typedef uintptr PageID; // address >> PageShift enum { // Tunable constants. NumSizeClasses = 67, // Number of size classes (must match msize.c) MaxSmallSize = 32<<10, FixAllocChunk = 128<<10, // Chunk size for FixAlloc MaxMCacheListLen = 256, // Maximum objects on MCacheList MaxMCacheSize = 2<<20, // Maximum bytes in one MCache MaxMHeapList = 1<<(20 - PageShift), // Maximum page length for fixed-size list in MHeap. HeapAllocChunk = 1<<20, // Chunk size for heap growth }; #ifdef _64BIT #include "mheapmap64.h" #else #include "mheapmap32.h" #endif // A generic linked list of blocks. (Typically the block is bigger than sizeof(MLink).) struct MLink { MLink *next; }; // SysAlloc obtains a large chunk of memory from the operating system, // typically on the order of a hundred kilobytes or a megabyte. // SysUnused notifies the operating system that the contents // of the memory region are no longer needed and can be reused // for other purposes. The program reserves the right to start // accessing those pages in the future. // SysFree returns it unconditionally; this is only used if // an out-of-memory error has been detected midway through // an allocation. It is okay if SysFree is a no-op. void* SysAlloc(uintptr nbytes); void SysFree(void *v, uintptr nbytes); void SysUnused(void *v, uintptr nbytes); // FixAlloc is a simple free-list allocator for fixed size objects. // Malloc uses a FixAlloc wrapped around SysAlloc to manages its // MCache and MSpan objects. // Memory returned by FixAlloc_Alloc is not zeroed. // The caller is responsible for locking around FixAlloc calls. // Callers can keep state in the object but the first word is // smashed by freeing and reallocating. struct FixAlloc { uintptr size; void *(*alloc)(uintptr); void (*first)(void *arg, byte *p); // called first time p is returned void *arg; MLink *list; byte *chunk; uint32 nchunk; }; void FixAlloc_Init(FixAlloc *f, uintptr size, void *(*alloc)(uintptr), void (*first)(void*, byte*), void *arg); void* FixAlloc_Alloc(FixAlloc *f); void FixAlloc_Free(FixAlloc *f, void *p); // Statistics. // Shared with Go: if you edit this structure, also edit ../malloc/malloc.go. struct MStats { uint64 alloc; uint64 sys; uint64 stacks; uint64 inuse_pages; // protected by mheap.Lock uint64 next_gc; // protected by mheap.Lock bool enablegc; }; extern MStats mstats; // Size classes. Computed and initialized by InitSizes. // SizeToClass(0 <= n <= MaxSmallSize) returns the size class, // 1 <= sizeclass < NumSizeClasses, for n. // Size class 0 is reserved to mean "not small". // class_to_size[i] = largest size in class i // <API key>[i] = number of pages to allocate when // making new objects in class i // <API key>[i] = number of objects to move when // taking a bunch of objects out of the central lists // and putting them in the thread free list. int32 SizeToClass(int32); extern int32 class_to_size[NumSizeClasses]; extern int32 <API key>[NumSizeClasses]; extern int32 <API key>[NumSizeClasses]; extern void InitSizes(void); // Per-thread (in Go, per-M) cache for small objects. // No locking needed because it is per-thread (per-M). typedef struct MCacheList MCacheList; struct MCacheList { MLink *list; uint32 nlist; uint32 nlistmin; }; struct MCache { MCacheList list[NumSizeClasses]; uint64 size; }; void* MCache_Alloc(MCache *c, int32 sizeclass, uintptr size); void MCache_Free(MCache *c, void *p, int32 sizeclass, uintptr size); // An MSpan is a run of pages. enum { MSpanInUse = 0, MSpanFree, MSpanListHead, MSpanDead, }; struct MSpan { MSpan *next; // in a span linked list MSpan *prev; // in a span linked list MSpan *allnext; // in the list of all spans PageID start; // starting page number uintptr npages; // number of pages in span MLink *freelist; // list of free objects uint32 ref; // number of allocated objects in this span uint32 sizeclass; // size class uint32 state; // MSpanInUse etc union { uint32 *gcref; // sizeclass > 0 uint32 gcref0; // sizeclass == 0 }; }; void MSpan_Init(MSpan *span, PageID start, uintptr npages); // Every MSpan is in one doubly-linked list, // either one of the MHeap's free lists or one of the // MCentral's span lists. We use empty MSpan structures as list heads. void MSpanList_Init(MSpan *list); bool MSpanList_IsEmpty(MSpan *list); void MSpanList_Insert(MSpan *list, MSpan *span); void MSpanList_Remove(MSpan *span); // from whatever list it is in // Central list of free objects of a given size. struct MCentral { Lock; int32 sizeclass; MSpan nonempty; MSpan empty; int32 nfree; }; void MCentral_Init(MCentral *c, int32 sizeclass); int32 MCentral_AllocList(MCentral *c, int32 n, MLink **first); void MCentral_FreeList(MCentral *c, int32 n, MLink *first); // Main malloc heap. // The heap itself is the "free[]" and "large" arrays, // but all the other global data is here too. struct MHeap { Lock; MSpan free[MaxMHeapList]; // free lists of given length MSpan large; // free lists length >= MaxMHeapList MSpan *allspans; // span lookup MHeapMap map; MHeapMapCache mapcache; // central free lists for small size classes. // the union makes sure that the MCentrals are // spaced 64 bytes apart, so that each MCentral.Lock // gets its own cache line. union { MCentral; byte pad[64]; } central[NumSizeClasses]; FixAlloc spanalloc; // allocator for Span* FixAlloc cachealloc; // allocator for MCache* }; extern MHeap mheap; void MHeap_Init(MHeap *h, void *(*allocator)(uintptr)); MSpan* MHeap_Alloc(MHeap *h, uintptr npage, int32 sizeclass); void MHeap_Free(MHeap *h, MSpan *s); MSpan* MHeap_Lookup(MHeap *h, PageID p); MSpan* MHeap_LookupMaybe(MHeap *h, PageID p); int32 mlookup(void *v, byte **base, uintptr *size, uint32 **ref); void gc(int32 force); enum { RefcountOverhead = 4, // one uint32 per object RefFree = 0, // must be zero RefManual, // manual allocation - don't free RefStack, // stack segment - don't free and don't scan for pointers RefNone, // no references RefSome, // some references };
package net.sourceforge.pmd.lang.java.rule.strings; import net.sourceforge.pmd.lang.java.ast.ASTName; import net.sourceforge.pmd.lang.java.ast.<API key>; import net.sourceforge.pmd.lang.java.ast.ASTPrimaryPrefix; import net.sourceforge.pmd.lang.java.ast.ASTPrimarySuffix; import net.sourceforge.pmd.lang.java.rule.AbstractJavaRule; import net.sourceforge.pmd.lang.ast.Node; public class <API key> extends AbstractJavaRule { public Object visit(<API key> exp, Object data) { int n = exp.jjtGetNumChildren(); if (n < 4) { return data; } int first = getBadPrefixOrNull(exp, n); if (first == -1) { return data; } String second = getBadSuffixOrNull(exp, first + 2); if (second == null) { return data; } if (!(exp.jjtGetChild(first + 1) instanceof ASTPrimarySuffix)) { return data; } ASTPrimarySuffix methodCall = (ASTPrimarySuffix)exp.jjtGetChild(first + 1); if (!methodCall.isArguments() || methodCall.getArgumentCount() > 0) { return data; } addViolation(data, exp); return data; } private int getBadPrefixOrNull(<API key> exp, int childrenCount) { // verify PrimaryPrefix/Name[ends-with(@Image, 'toUpperCase'] for(int i = 0; i < childrenCount - 3; i++) { Node child = exp.jjtGetChild(i); String image; if (child instanceof ASTPrimaryPrefix) { if (child.jjtGetNumChildren() != 1 || !(child.jjtGetChild(0) instanceof ASTName)) { continue; } ASTName name = (ASTName) child.jjtGetChild(0); image = name.getImage(); } else if (child instanceof ASTPrimarySuffix) { image = ((ASTPrimarySuffix) child).getImage(); } else { continue; } if (image == null || !(image.endsWith("toUpperCase") || image.endsWith("toLowerCase"))) { continue; } else { return i; } } return -1; } private String getBadSuffixOrNull(<API key> exp, int equalsPosition) { // verify PrimarySuffix[@Image='equals'] if (!(exp.jjtGetChild(equalsPosition) instanceof ASTPrimarySuffix)) { return null; } ASTPrimarySuffix suffix = (ASTPrimarySuffix) exp.jjtGetChild(equalsPosition); if (suffix.getImage() == null || !(suffix.hasImageEqualTo("equals") || suffix.hasImageEqualTo("equalsIgnoreCase"))) { return null; } return suffix.getImage(); } }
-- | Handle conversion of CmmData to LLVM code. module LlvmCodeGen.Data ( genLlvmData, resolveLlvmDatas, resolveLlvmData ) where #include "HsVersions.h" import Llvm import LlvmCodeGen.Base import BlockId import CLabel import OldCmm import FastString import qualified Outputable import Data.List (foldl') -- * Constants -- | The string appended to a variable name to create its structure type alias structStr :: LMString structStr = fsLit "_struct" -- * Top level -- | Pass a CmmStatic section to an equivalent Llvm code. Can't -- complete this completely though as we need to pass all CmmStatic -- sections before all references can be resolved. This last step is -- done by 'resolveLlvmData'. genLlvmData :: LlvmEnv -> (Section, CmmStatics) -> LlvmUnresData genLlvmData env (sec, Statics lbl xs) = let static = map genData xs label = strCLabel_llvm env lbl types = map getStatTypes static getStatTypes (Left x) = cmmToLlvmType $ cmmLitType x getStatTypes (Right x) = getStatType x strucTy = LMStruct types alias = LMAlias ((label `appendFS` structStr), strucTy) in (lbl, sec, alias, static) resolveLlvmDatas :: LlvmEnv -> [LlvmUnresData] -> (LlvmEnv, [LlvmData]) resolveLlvmDatas env ldata = foldl' res (env, []) ldata where res (e, xs) ll = let (e', nd) = resolveLlvmData e ll in (e', nd:xs) -- | Fix up CLabel references now that we should have passed all CmmData. resolveLlvmData :: LlvmEnv -> LlvmUnresData -> (LlvmEnv, LlvmData) resolveLlvmData env (lbl, sec, alias, unres) = let (env', static, refs) = resDatas env unres ([], []) struct = Just $ LMStaticStruc static alias label = strCLabel_llvm env lbl link = if (<API key> lbl) then ExternallyVisible else Internal const = isSecConstant sec glob = LMGlobalVar label alias link Nothing Nothing const in (env', ((glob,struct):refs, [alias])) -- | Should a data in this section be considered constant isSecConstant :: Section -> Bool isSecConstant Text = True isSecConstant ReadOnlyData = True isSecConstant <API key> = True isSecConstant ReadOnlyData16 = True isSecConstant Data = False isSecConstant UninitialisedData = False isSecConstant (OtherSection _) = False -- ** Resolve Data/CLabel references -- | Resolve data list resDatas :: LlvmEnv -> [UnresStatic] -> ([LlvmStatic], [LMGlobal]) -> (LlvmEnv, [LlvmStatic], [LMGlobal]) resDatas env [] (stats, glob) = (env, stats, glob) resDatas env (cmm:rest) (stats, globs) = let (env', nstat, nglob) = resData env cmm in resDatas env' rest (stats ++ [nstat], globs ++ nglob) -- | Resolve an individual static label if it needs to be. -- We check the 'LlvmEnv' to see if the reference has been defined in this -- module. If it has we can retrieve its type and make a pointer, otherwise -- we introduce a generic external definition for the referenced label and -- then make a pointer. resData :: LlvmEnv -> UnresStatic -> (LlvmEnv, LlvmStatic, [LMGlobal]) resData env (Right stat) = (env, stat, []) resData env (Left cmm@(CmmLabel l)) = let label = strCLabel_llvm env l ty = funLookup label env lmty = cmmToLlvmType $ cmmLitType cmm in case ty of -- Make generic external label defenition and then pointer to it Nothing -> let glob@(var, _) = genStringLabelRef label env' = funInsert label (pLower $ getVarType var) env ptr = LMStaticPointer var in (env', LMPtoI ptr lmty, [glob]) -- Referenced data exists in this module, retrieve type and make -- pointer to it. Just ty' -> let var = LMGlobalVar label (LMPointer ty') ExternallyVisible Nothing Nothing False ptr = LMStaticPointer var in (env, LMPtoI ptr lmty, []) resData env (Left (CmmLabelOff label off)) = let (env', var, glob) = resData env (Left (CmmLabel label)) offset = LMStaticLit $ LMIntLit (toInteger off) llvmWord in (env', LMAdd var offset, glob) resData env (Left (CmmLabelDiffOff l1 l2 off)) = let (env1, var1, glob1) = resData env (Left (CmmLabel l1)) (env2, var2, glob2) = resData env1 (Left (CmmLabel l2)) var = LMSub var1 var2 offset = LMStaticLit $ LMIntLit (toInteger off) llvmWord in (env2, LMAdd var offset, glob1 ++ glob2) resData _ _ = panic "resData: Non CLabel expr as left type!" -- * Generate static data -- | Handle static data genData :: CmmStatic -> UnresStatic genData (CmmString str) = let v = map (\x -> LMStaticLit $ LMIntLit (fromIntegral x) i8) str ve = v ++ [LMStaticLit $ LMIntLit 0 i8] in Right $ LMStaticArray ve (LMArray (length ve) i8) genData (CmmUninitialised bytes) = Right $ LMUninitType (LMArray bytes i8) genData (CmmStaticLit lit) = genStaticLit lit -- | Generate Llvm code for a static literal. -- Will either generate the code or leave it unresolved if it is a 'CLabel' -- which isn't yet known. genStaticLit :: CmmLit -> UnresStatic genStaticLit (CmmInt i w) = Right $ LMStaticLit (LMIntLit i (LMInt $ widthInBits w)) genStaticLit (CmmFloat r w) = Right $ LMStaticLit (LMFloatLit (fromRational r) (widthToLlvmFloat w)) -- Leave unresolved, will fix later genStaticLit c@(CmmLabel _ ) = Left $ c genStaticLit c@(CmmLabelOff _ _) = Left $ c genStaticLit c@(CmmLabelDiffOff _ _ _) = Left $ c genStaticLit (CmmBlock b) = Left $ CmmLabel $ infoTblLbl b genStaticLit (CmmHighStackMark) = panic "genStaticLit: CmmHighStackMark unsupported!" -- * Misc -- | Error Function panic :: String -> a panic s = Outputable.panic $ "LlvmCodeGen.Data." ++ s
#ifndef <API key> #define <API key> #include <map> #include <utility> #include "base/gtest_prod_util.h" #include "base/memory/linked_ptr.h" #include "base/strings/string_piece.h" #include "content/common/content_export.h" #include "webkit/common/resource_type.h" class GURL; namespace webkit_glue { struct <API key>; } namespace content { // SiteIsolationPolicy implements the cross-site document blocking policy (XSDP) // for Site Isolation. XSDP will monitor network responses to a renderer and // information from other sites. For now SiteIsolationPolicy monitors responses // to gather various UMA stats to see the compatibility impact of actual // deployment of the policy. The UMA stat categories SiteIsolationPolicy gathers // are as follows: // SiteIsolation.AllResponses : # of all network responses. // SiteIsolation.XSD.DataLength : the length of the first packet of a response. // SiteIsolation.XSD.MimeType (enum): // # of responses from other sites, tagged with a document mime type. // 0:HTML, 1:XML, 2:JSON, 3:Plain, 4:Others // SiteIsolation.XSD.[%MIMETYPE].Blocked : // blocked # of cross-site document responses grouped by sniffed MIME type. // SiteIsolation.XSD.[%MIMETYPE].Blocked.<API key> : // # of responses with renderable status code, // out of SiteIsolation.XSD.[%MIMETYPE].Blocked. // SiteIsolation.XSD.[%MIMETYPE].Blocked.<API key> : // # of responses with non-renderable status code, // out of SiteIsolation.XSD.[%MIMETYPE].Blocked. // SiteIsolation.XSD.[%MIMETYPE].NoSniffBlocked.<API key> : // # of responses failed to be sniffed for its MIME type, but blocked by // "<API key>: nosniff" header, and with renderable status code // out of SiteIsolation.XSD.[%MIMETYPE].Blocked. // SiteIsolation.XSD.[%MIMETYPE].NoSniffBlocked.<API key> : // # of responses failed to be sniffed for its MIME type, but blocked by // "<API key>: nosniff" header, and with non-renderable status // code out of SiteIsolation.XSD.[%MIMETYPE].Blocked. // SiteIsolation.XSD.[%MIMETYPE].NotBlocked : // # of responses, but not blocked due to failure of mime sniffing. // SiteIsolation.XSD.[%MIMETYPE].NotBlocked.MaybeJS : // # of responses that are plausibly sniffed to be JavaScript. struct <API key> { enum CanonicalMimeType { HTML = 0, XML = 1, JSON = 2, Plain = 3, Others = 4, <API key>, }; <API key>(); std::string frame_origin; GURL response_url; ResourceType::Type resource_type; CanonicalMimeType canonical_mime_type; int http_status_code; bool no_sniff; }; class CONTENT_EXPORT SiteIsolationPolicy { public: // Set activation flag for the UMA data collection for this renderer process. static void SetPolicyEnabled(bool enabled); // Returns any bookkeeping data about the HTTP header information for the // request identified by |request_id|. Any data returned should then be // passed to ShouldBlockResponse with the first packet. static linked_ptr<<API key>> OnReceivedResponse( const GURL& frame_origin, const GURL& response_url, ResourceType::Type resource_type, int origin_pid, const webkit_glue::<API key>& info); // Examines the first network packet in case response_url is registered as a // cross-site document by DidReceiveResponse(). In case that this response is // blocked, it returns an alternative data to be sent to the renderer in // |alternative_data|. This records various kinds of UMA data stats. This // function is called only if the length of received data is non-zero. static bool ShouldBlockResponse( linked_ptr<<API key>>& resp_data, const char* payload, int length, std::string* alternative_data); private: <API key>(<API key>, IsBlockableScheme); <API key>(<API key>, IsSameSite); <API key>(<API key>, <API key>); <API key>(<API key>, SniffForHTML); <API key>(<API key>, SniffForXML); <API key>(<API key>, SniffForJSON); <API key>(<API key>, SniffForJS); // Returns the representative mime type enum value of the mime type of // response. For example, this returns the same value for all text/xml mime // type families such as application/xml, application/rss+xml. static <API key>::CanonicalMimeType <API key>( const std::string& mime_type); // Returns whether this scheme is a target of cross-site document
#!/bin/sh # This script need openssl 0.9.8a or newer, so it can parse the # otherName section for pkinit certificates. openssl=openssl gen_cert() { keytype=${6:-rsa:1024} ${openssl} req \ -new \ -subj "$1" \ -config openssl.cnf \ -newkey $keytype \ -sha1 \ -nodes \ -keyout out.key \ -out cert.req > /dev/null 2>/dev/null if [ "$3" = "ca" ] ; then ${openssl} x509 \ -req \ -days 3650 \ -in cert.req \ -extfile openssl.cnf \ -extensions $4 \ -signkey out.key \ -out cert.crt ln -s ca.crt `${openssl} x509 -hash -noout -in cert.crt`.0 name=$3 elif [ "$3" = "proxy" ] ; then ${openssl} x509 \ -req \ -in cert.req \ -days 3650 \ -out cert.crt \ -CA $2.crt \ -CAkey $2.key \ -CAcreateserial \ -extfile openssl.cnf \ -extensions $4 name=$5 else ${openssl} ca \ -name $4 \ -days 3650 \ -cert $2.crt \ -keyfile $2.key \ -in cert.req \ -out cert.crt \ -outdir . \ -batch \ -config openssl.cnf name=$3 fi mv cert.crt $name.crt mv out.key $name.key } echo "01" > serial > index.txt rm -f *.0 gen_cert "/CN=hx509 Test Root CA/C=SE" "root" "ca" "v3_ca" gen_cert "/CN=OCSP responder/C=SE" "ca" "ocsp-responder" "ocsp" gen_cert "/CN=Test cert/C=SE" "ca" "test" "usr" gen_cert "/CN=Revoke cert/C=SE" "ca" "revoke" "usr" gen_cert "/CN=Test cert KeyEncipherment/C=SE" "ca" "test-ke-only" "usr_ke" gen_cert "/CN=Test cert DigitalSignature/C=SE" "ca" "test-ds-only" "usr_ds" gen_cert "/CN=pkinit/C=SE" "ca" "pkinit" "pkinit_client" $openssl ecparam -name secp256r1 -out eccurve.pem gen_cert "/CN=pkinit-ec/C=SE" "ca" "pkinit-ec" "pkinit_client" "XXX" ec:eccurve.pem gen_cert "/C=SE/CN=pkinit/CN=pkinit-proxy" "pkinit" "proxy" "proxy_cert" pkinit-proxy gen_cert "/CN=kdc/C=SE" "ca" "kdc" "pkinit_kdc" gen_cert "/CN=www.test.h5l.se/C=SE" "ca" "https" "https" gen_cert "/CN=Sub CA/C=SE" "ca" "sub-ca" "subca" gen_cert "/CN=Test sub cert/C=SE" "sub-ca" "sub-cert" "usr" gen_cert "/C=SE/CN=Test cert/CN=proxy" "test" "proxy" "proxy_cert" proxy-test gen_cert "/C=SE/CN=Test cert/CN=proxy/CN=child" "proxy-test" "proxy" "proxy_cert" proxy-level-test gen_cert "/C=SE/CN=Test cert/CN=no-proxy" "test" "proxy" "usr_cert" no-proxy-test gen_cert "/C=SE/CN=Test cert/CN=proxy10" "test" "proxy" "proxy10_cert" proxy10-test gen_cert "/C=SE/CN=Test cert/CN=proxy10/CN=child" "proxy10-test" "proxy" "proxy10_cert" proxy10-child-test gen_cert "/C=SE/CN=Test cert/CN=proxy10/CN=child/CN=child" "proxy10-child-test" "proxy" "proxy10_cert" <API key> # combine cat sub-ca.crt ca.crt > sub-ca-combined.crt cat test.crt test.key > test.combined.crt cat pkinit-proxy.crt pkinit.crt > pkinit-proxy-chain.crt # password protected key ${openssl} rsa -in test.key -aes256 -passout pass:foobar -out test-pw.key ${openssl} rsa -in pkinit.key -aes256 -passout pass:foo -out pkinit-pw.key ${openssl} ca \ -name usr \ -cert ca.crt \ -keyfile ca.key \ -revoke revoke.crt \ -config openssl.cnf ${openssl} pkcs12 \ -export \ -in test.crt \ -inkey test.key \ -passout pass:foobar \ -out test.p12 \ -name "friendlyname-test" \ -certfile ca.crt \ -caname ca ${openssl} pkcs12 \ -export \ -in sub-cert.crt \ -inkey sub-cert.key \ -passout pass:foobar \ -out sub-cert.p12 \ -name "<API key>" \ -certfile sub-ca-combined.crt \ -caname sub-ca \ -caname ca ${openssl} pkcs12 \ -keypbe NONE \ -certpbe NONE \ -export \ -in test.crt \ -inkey test.key \ -passout pass:foobar \ -out test-nopw.p12 \ -name "friendlyname-cert" \ -certfile ca.crt \ -caname ca ${openssl} smime \ -sign \ -nodetach \ -binary \ -in static-file \ -signer test.crt \ -inkey test.key \ -outform DER \ -out test-signed-data ${openssl} smime \ -sign \ -nodetach \ -binary \ -in static-file \ -signer test.crt \ -inkey test.key \ -noattr \ -outform DER \ -out <API key> ${openssl} smime \ -sign \ -nodetach \ -binary \ -in static-file \ -signer test.crt \ -inkey test.key \ -noattr \ -nocerts \ -outform DER \ -out <API key> ${openssl} smime \ -sign \ -md sha1 \ -nodetach \ -binary \ -in static-file \ -signer test.crt \ -inkey test.key \ -outform DER \ -out test-signed-sha-1 ${openssl} smime \ -sign \ -md sha256 \ -nodetach \ -binary \ -in static-file \ -signer test.crt \ -inkey test.key \ -outform DER \ -out test-signed-sha-256 ${openssl} smime \ -sign \ -md sha512 \ -nodetach \ -binary \ -in static-file \ -signer test.crt \ -inkey test.key \ -outform DER \ -out test-signed-sha-512 ${openssl} smime \ -encrypt \ -nodetach \ -binary \ -in static-file \ -outform DER \ -out <API key> \ -rc2-40 \ test.crt ${openssl} smime \ -encrypt \ -nodetach \ -binary \ -in static-file \ -outform DER \ -out <API key> \ -rc2-64 \ test.crt ${openssl} smime \ -encrypt \ -nodetach \ -binary \ -in static-file \ -outform DER \ -out <API key> \ -rc2-128 \ test.crt ${openssl} smime \ -encrypt \ -nodetach \ -binary \ -in static-file \ -outform DER \ -out test-enveloped-des \ -des \ test.crt ${openssl} smime \ -encrypt \ -nodetach \ -binary \ -in static-file \ -outform DER \ -out <API key> \ -des3 \ test.crt ${openssl} smime \ -encrypt \ -nodetach \ -binary \ -in static-file \ -outform DER \ -out <API key> \ -aes128 \ test.crt ${openssl} smime \ -encrypt \ -nodetach \ -binary \ -in static-file \ -outform DER \ -out <API key> \ -aes256 \ test.crt echo ocsp requests ${openssl} ocsp \ -issuer ca.crt \ -cert test.crt \ -reqout ocsp-req1.der ${openssl} ocsp \ -index index.txt \ -rsigner ocsp-responder.crt \ -rkey ocsp-responder.key \ -CA ca.crt \ -reqin ocsp-req1.der \ -noverify \ -respout ocsp-resp1-ocsp.der ${openssl} ocsp \ -index index.txt \ -rsigner ca.crt \ -rkey ca.key \ -CA ca.crt \ -reqin ocsp-req1.der \ -noverify \ -respout ocsp-resp1-ca.der ${openssl} ocsp \ -index index.txt \ -rsigner ocsp-responder.crt \ -rkey ocsp-responder.key \ -CA ca.crt \ -resp_no_certs \ -reqin ocsp-req1.der \ -noverify \ -respout <API key>.der ${openssl} ocsp \ -index index.txt \ -rsigner ocsp-responder.crt \ -rkey ocsp-responder.key \ -CA ca.crt \ -reqin ocsp-req1.der \ -resp_key_id \ -noverify \ -respout ocsp-resp1-keyhash.der ${openssl} ocsp \ -issuer ca.crt \ -cert revoke.crt \ -reqout ocsp-req2.der ${openssl} ocsp \ -index index.txt \ -rsigner ocsp-responder.crt \ -rkey ocsp-responder.key \ -CA ca.crt \ -reqin ocsp-req2.der \ -noverify \ -respout ocsp-resp2.der ${openssl} ca \ -gencrl \ -name usr \ -crldays 3600 \ -keyfile ca.key \ -cert ca.crt \ -crl_reason superseded \ -out crl1.crl \ -config openssl.cnf ${openssl} crl -in crl1.crl -outform der -out crl1.der
<?php /** * @namespace */ namespace ZendTest\Feed\Reader\Entry; use Zend\Feed\Reader; use Zend\Date; class <API key> extends \<API key> { protected $_feedSamplePath = null; protected $_expectedCats = array(); protected $_expectedCatsDc = array(); public function setup() { Reader\Reader::reset(); if (\Zend\Registry::isRegistered('Zend_Locale')) { $registry = \Zend\Registry::getInstance(); unset($registry['Zend_Locale']); } $this->_feedSamplePath = dirname(__FILE__) . '/_files/AtomStandaloneEntry'; $this->_options = Date\Date::setOptions(); foreach($this->_options as $k=>$v) { if (is_null($v)) { unset($this->_options[$k]); } } Date\Date::setOptions(array('format_type'=>'iso')); $this->_expectedCats = array( array( 'term' => 'topic1', 'scheme' => 'http://example.com/schema1', 'label' => 'topic1' ), array( 'term' => 'topic1', 'scheme' => 'http://example.com/schema2', 'label' => 'topic1' ), array( 'term' => 'cat_dog', 'scheme' => 'http://example.com/schema1', 'label' => 'Cat & Dog' ) ); $this->_expectedCatsDc = array( array( 'term' => 'topic1', 'scheme' => null, 'label' => 'topic1' ), array( 'term' => 'topic2', 'scheme' => null, 'label' => 'topic2' ) ); } public function teardown() { Date\Date::setOptions($this->_options); } public function <API key>() { $object = Reader\Reader::importString( file_get_contents($this->_feedSamplePath . '/id/atom10.xml') ); $this->assertTrue($object instanceof Reader\Entry\Atom); } /** * Get Id (Unencoded Text) * @group ZFR002 */ public function <API key>() { $entry = Reader\Reader::importString( file_get_contents($this->_feedSamplePath . '/id/atom10.xml') ); $this->assertEquals('1', $entry->getId()); } /** * Get creation date (Unencoded Text) * @group ZFR002 */ public function <API key>() { $entry = Reader\Reader::importString( file_get_contents($this->_feedSamplePath . '/datecreated/atom10.xml') ); $edate = new Date\Date; $edate->set('2009-03-07T08:03:50Z', Date\Date::ISO_8601); $this->assertTrue($edate->equals($entry->getDateCreated())); } /** * Get modification date (Unencoded Text) * @group ZFR002 */ public function <API key>() { $entry = Reader\Reader::importString( file_get_contents($this->_feedSamplePath . '/datemodified/atom10.xml') ); $edate = new Date\Date; $edate->set('2009-03-07T08:03:50Z', Date\Date::ISO_8601); $this->assertTrue($edate->equals($entry->getDateModified())); } /** * Get Title (Unencoded Text) * @group ZFR002 */ public function <API key>() { $entry = Reader\Reader::importString( file_get_contents($this->_feedSamplePath . '/title/atom10.xml') ); $this->assertEquals('Entry Title', $entry->getTitle()); } /** * Get Authors (Unencoded Text) * @group ZFR002 */ public function <API key>() { $entry = Reader\Reader::importString( file_get_contents($this->_feedSamplePath . '/author/atom10.xml') ); $authors = array( array('email'=>'joe@example.com','name'=>'Joe Bloggs','uri'=>'http: array('name'=>'Joe Bloggs','uri'=>'http: array('name'=>'Joe Bloggs'), array('email'=>'joe@example.com','uri'=>'http: array('uri'=>'http: array('email'=>'joe@example.com') ); $this->assertEquals($authors, (array) $entry->getAuthors()); } /** * Get Author (Unencoded Text) * @group ZFR002 */ public function <API key>() { $entry = Reader\Reader::importString( file_get_contents($this->_feedSamplePath . '/author/atom10.xml') ); $this->assertEquals(array('name'=>'Joe Bloggs','email'=>'joe@example.com','uri'=>'http: } /** * Get Description (Unencoded Text) * @group ZFR002 */ public function <API key>() { $entry = Reader\Reader::importString( file_get_contents($this->_feedSamplePath . '/description/atom10.xml') ); $this->assertEquals('Entry Description', $entry->getDescription()); } /** * Get enclosure * @group ZFR002 */ public function <API key>() { $entry = Reader\Reader::importString( file_get_contents($this->_feedSamplePath.'/enclosure/atom10.xml') ); $expected = new \stdClass(); $expected->url = 'http: $expected->length = '1234'; $expected->type = 'audio/mpeg'; $this->assertEquals($expected, $entry->getEnclosure()); } /** * TEXT * @group ZFRATOMCONTENT */ public function <API key>() { $entry = Reader\Reader::importString( file_get_contents($this->_feedSamplePath . '/content/atom10.xml') ); $this->assertEquals('Entry Content &amp;', $entry->getContent()); } /** * HTML Escaped * @group ZFRATOMCONTENT */ public function <API key>() { $entry = Reader\Reader::importString( file_get_contents($this->_feedSamplePath . '/content/atom10_Html.xml') ); $this->assertEquals('<p>Entry Content &amp;</p>', $entry->getContent()); } /** * HTML CDATA Escaped * @group ZFRATOMCONTENT */ public function <API key>() { $entry = Reader\Reader::importString( file_get_contents($this->_feedSamplePath . '/content/atom10_HtmlCdata.xml') ); $this->assertEquals('<p>Entry Content &amp;</p>', $entry->getContent()); } /** * XHTML * @group ZFRATOMCONTENT */ public function <API key>() { $entry = Reader\Reader::importString( file_get_contents($this->_feedSamplePath . '/content/atom10_Xhtml.xml') ); $this->assertEquals('<p class="x:"><em>Entry Content &amp;x:</em></p>', $entry->getContent()); } /** * Get Link (Unencoded Text) * @group ZFR002 */ public function <API key>() { $entry = Reader\Reader::importString( file_get_contents($this->_feedSamplePath . '/link/atom10.xml') ); $this->assertEquals('http: } /** * Get Comment HTML Link * @group ZFR002 */ public function <API key>() { $entry = Reader\Reader::importString( file_get_contents($this->_feedSamplePath . '/commentlink/atom10.xml') ); $this->assertEquals('http: } /** * Get category data * @group ZFR002 */ public function <API key>() { $entry = Reader\Reader::importString( file_get_contents($this->_feedSamplePath.'/category/atom10.xml') ); $this->assertEquals($this->_expectedCats, (array) $entry->getCategories()); $this->assertEquals(array('topic1','Cat & Dog'), array_values($entry->getCategories()->getValues())); } }
#include "ui/android/window_android.h" #include "base/android/jni_android.h" #include "base/android/jni_array.h" #include "base/android/jni_string.h" #include "base/android/jni_weak_ref.h" #include "base/android/scoped_java_ref.h" #include "jni/WindowAndroid_jni.h" #include "ui/android/<API key>.h" #include "ui/android/<API key>.h" namespace ui { using base::android::AttachCurrentThread; using base::android::ScopedJavaLocalRef; WindowAndroid::WindowAndroid(JNIEnv* env, jobject obj) : compositor_(NULL) { java_window_.Reset(env, obj); } void WindowAndroid::Destroy(JNIEnv* env, jobject obj) { delete this; } ScopedJavaLocalRef<jobject> WindowAndroid::GetJavaObject() { return base::android::ScopedJavaLocalRef<jobject>(java_window_); } bool WindowAndroid::<API key>(JNIEnv* env) { return RegisterNativesImpl(env); } WindowAndroid::~WindowAndroid() { DCHECK(!compositor_); } void WindowAndroid::<API key>() { FOR_EACH_OBSERVER(<API key>, observer_list_, <API key>()); } void WindowAndroid::AddObserver(<API key>* observer) { if (!observer_list_.HasObserver(observer)) observer_list_.AddObserver(observer); } void WindowAndroid::RemoveObserver(<API key>* observer) { observer_list_.RemoveObserver(observer); } void WindowAndroid::AttachCompositor(<API key>* compositor) { if (compositor_ && compositor != compositor_) DetachCompositor(); compositor_ = compositor; FOR_EACH_OBSERVER(<API key>, observer_list_, OnAttachCompositor()); } void WindowAndroid::DetachCompositor() { compositor_ = NULL; FOR_EACH_OBSERVER(<API key>, observer_list_, OnDetachCompositor()); observer_list_.Clear(); } void WindowAndroid::RequestVSyncUpdate() { JNIEnv* env = AttachCurrentThread(); <API key>(env, GetJavaObject().obj()); } void WindowAndroid::SetNeedsAnimate() { if (compositor_) compositor_->SetNeedsAnimate(); } void WindowAndroid::Animate(base::TimeTicks begin_frame_time) { FOR_EACH_OBSERVER( <API key>, observer_list_, OnAnimate(begin_frame_time)); } void WindowAndroid::OnVSync(JNIEnv* env, jobject obj, jlong time_micros, jlong period_micros) { base::TimeTicks frame_time(base::TimeTicks::FromInternalValue(time_micros)); base::TimeDelta vsync_period( base::TimeDelta::FromMicroseconds(period_micros)); FOR_EACH_OBSERVER( <API key>, observer_list_, OnVSync(frame_time, vsync_period)); if (compositor_) compositor_->OnVSync(frame_time, vsync_period); } void WindowAndroid::OnVisibilityChanged(JNIEnv* env, jobject obj, bool visible) { FOR_EACH_OBSERVER(<API key>, observer_list_, <API key>(visible)); } void WindowAndroid::OnActivityStopped(JNIEnv* env, jobject obj) { FOR_EACH_OBSERVER(<API key>, observer_list_, OnActivityStopped()); } void WindowAndroid::OnActivityStarted(JNIEnv* env, jobject obj) { FOR_EACH_OBSERVER(<API key>, observer_list_, OnActivityStarted()); } bool WindowAndroid::HasPermission(const std::string& permission) { JNIEnv* env = AttachCurrentThread(); return <API key>( env, GetJavaObject().obj(), base::android::<API key>(env, permission).obj()); } bool WindowAndroid::<API key>(const std::string& permission) { JNIEnv* env = AttachCurrentThread(); return <API key>( env, GetJavaObject().obj(), base::android::<API key>(env, permission).obj()); } // Native JNI methods jlong Init(JNIEnv* env, const JavaParamRef<jobject>& obj) { WindowAndroid* window = new WindowAndroid(env, obj); return reinterpret_cast<intptr_t>(window); } } // namespace ui
"""Test that anonymous structs/unions are transparent to member access""" import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil class AnonymousTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @skipIf( compiler="icc", bugnumber="llvm.org/pr15036: LLDB generates an incorrect AST layout for an anonymous struct when DWARF is generated by ICC") def test_expr_nest(self): self.build() self.common_setup(self.line0) # These should display correctly. self.expect("expression n->foo.d", <API key>, substrs=["= 4"]) self.expect("expression n->b", <API key>, substrs=["= 2"]) def test_expr_child(self): self.build() self.common_setup(self.line1) # These should display correctly. self.expect("expression c->foo.d", <API key>, substrs=["= 4"]) self.expect( "expression c->grandchild.b", <API key>, substrs=["= 2"]) @skipIf( compiler="icc", bugnumber="llvm.org/pr15036: This particular regression was introduced by r181498") def <API key>(self): self.build() self.common_setup(self.line2) # These should display correctly. self.expect("expression g.child.foo.d", <API key>, substrs=["= 4"]) self.expect("expression g.child.b", <API key>, substrs=["= 2"]) def test_expr_parent(self): self.build() if "clang" in self.getCompiler() and "3.4" in self.getCompilerVersion(): self.skipTest( "llvm.org/pr16214 -- clang emits partial DWARF for structures referenced via typedef") self.common_setup(self.line2) # These should display correctly. self.expect("expression pz", <API key>, substrs=["(type_z *) $", " = 0x0000"]) self.expect("expression z.y", <API key>, substrs=["(type_y) $", "dummy = 2"]) def test_expr_null(self): self.build() self.common_setup(self.line2) # This should fail because pz is 0, but it succeeds on OS/X. # This fails on Linux with an upstream error "Couldn't dematerialize struct", as does "p *n" with "int *n = 0". # Note that this can also trigger llvm.org/pr15036 when run # interactively at the lldb command prompt. self.expect("expression *(type_z *)pz", error=True) def test_child_by_name(self): self.build() # Set debugger into synchronous mode self.dbg.SetAsync(False) # Create a target exe = self.getBuildArtifact("a.out") target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) break_in_main = target.<API key>( '// Set breakpoint 2 here.', lldb.SBFileSpec(self.source)) self.assertTrue(break_in_main, VALID_BREAKPOINT) process = target.LaunchSimple( None, None, self.<API key>()) self.assertTrue(process, PROCESS_IS_VALID) threads = lldbutil.<API key>( process, break_in_main) if len(threads) != 1: self.fail("Failed to stop at breakpoint in main.") thread = threads[0] frame = thread.frames[0] if not frame.IsValid(): self.fail("Failed to get frame 0.") var_n = frame.FindVariable("n") if not var_n.IsValid(): self.fail("Failed to get the variable 'n'") elem_a = var_n.<API key>("a") if not elem_a.IsValid(): self.fail("Failed to get the element a in n") error = lldb.SBError() value = elem_a.GetValueAsSigned(error, 1000) if not error.Success() or value != 0: self.fail("failed to get the correct value for element a in n") def test_nest_flat(self): self.build() self.common_setup(self.line2) # These should display correctly. self.expect('frame variable n --flat', substrs=['n.a = 0', 'n.b = 2', 'n.foo.c = 0', 'n.foo.d = 4']) def setUp(self): # Call super's setUp(). TestBase.setUp(self) # Find the line numbers to break in main.c. self.source = 'main.c' self.line0 = line_number(self.source, '// Set breakpoint 0 here.') self.line1 = line_number(self.source, '// Set breakpoint 1 here.') self.line2 = line_number(self.source, '// Set breakpoint 2 here.') def common_setup(self, line): # Set debugger into synchronous mode self.dbg.SetAsync(False) # Create a target exe = self.getBuildArtifact("a.out") target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) # Set breakpoints inside and outside methods that take pointers to the # containing struct. lldbutil.<API key>( self, self.source, line, <API key>=1, loc_exact=True) # Now launch the process, and do not stop at entry point. process = target.LaunchSimple( None, None, self.<API key>()) self.assertTrue(process, PROCESS_IS_VALID) # The stop reason of the thread should be breakpoint. self.expect("thread list", <API key>, substrs=['stopped', 'stop reason = breakpoint']) # The breakpoint should have a hit count of 1. self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE, substrs=[' resolved, hit count = 1'])
<!DOCTYPE html PUBLIC "- <html xmlns="http: <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>FusionCharts XT - Using Initialize Event Demos</title> <link href="../../../assets/ui/css/style.css" rel="stylesheet" type="text/css" /> <script type="text/javascript" src="../../../../Charts/FusionCharts.js"></script> <script type="text/javascript" language="Javascript" src="../../../assets/ui/js/jquery.min.js"></script> <script type="text/javascript" language="Javascript" src="../../../assets/ui/js/lib.js"></script> <!--[if IE 6]> <script src="../../../assets/ui/js/DD_belatedPNG_0.0.8a-min.js"></script> <script> /* select the element name, css selector, background etc */ DD_belatedPNG.fix('img'); /* string argument can be any CSS selector */ </script> <![endif] <style type="text/css"> h2.headline { font: normal 110%/137.5% "Trebuchet MS", Arial, Helvetica, sans-serif; padding: 0; margin: 25px 0 25px 0; color: #7d7c8b; text-align: center; } p.small { font: normal 68.75%/150% Verdana, Geneva, sans-serif; color: #919191; padding: 0; margin: 0 auto; width: 664px; text-align: center; } </style> </head> <body> <!-- wrapper --> <div id="wrapper"> <!-- header --> <div id="header"> <div class="logo"> <a class="imagelink" href="http: <img src="../../../assets/ui/images/fusionchartsv3.2-logo.png" width="131" height="75" alt="FusionCharts XT logo" /> </a> </div><h1 class="brand-name">FusionCharts XT</h1> <h1 class="logo-text">Using Initialize Event</h1> </div> <!-- content area --> <div class="content-area"> <div id="<API key>"> <p class="text" align="center">Using Initialize Event</p> <div id="messageBox" style="margin-left:100px; margin-right:100px; display:none;"></div> <p>&nbsp;</p> <div class="clear"></div> <div class="gen-chart-render"> <div id="chartContainer">FusionCharts will load here!</div> <script type="text/javascript"><! FusionCharts.addEventListener ( 'Initialized', function (identifier, parameter) { alert(identifier.sender.id + " has initialized."); }); var myChart = new FusionCharts( "../../../../Charts/Column3D.swf", "myChartId", "400", "300", "0", "1" ); myChart.setXMLData('<chart caption="Weekly Sales Summary" xAxisName="Week" yAxisName="Sales" numberPrefix="$"><set label="Week 1" value="14400" /><set label="Week 2" value="19600" /><set label="Week 3" value="24000" /><set label="Week 4" value="15700" /></chart>'); myChart.render("chartContainer"); </script> </div> <br/> <div class="clear"></div> <p class="small">&nbsp;</p> <p>&nbsp;</p> <div class="underline-dull"></div> <div> <p class="highlightBlock">The above sample showcases how to listen to Initialize event using JavaScript. Click <a href="../../../../Contents/index.html?JavaScript/API/Events.html#initialize" target="_blank">here</a> to know more on how the code of this example works.</p> </div> </div> </div> <!-- footer --> <div id="footer"> <ul> <li><a href="../../index.html"><span>&laquo; Back to list of examples</span></a></li> <li class="pipe">|</li> <li><a href="../../../NoChart.html"><span>Unable to see the chart above?</span></a></li> </ul> </div> </div> <script type="text/javascript"><!-- $(document).ready ( function() { <API key>( "Your browser does not seem to have Flash Player support. JavaScript chart is rendered instead", isJSRenderer(myChart) ); }); </script> </body> </html>
#include <ctype.h> #include <stdlib.h> #include <string.h> #include "base.h" #include "log.h" #include "buffer.h" #include "plugin.h" #ifdef USE_OPENSSL # include <openssl/md5.h> #else # include "md5.h" #endif /* plugin config for all request/connections */ typedef struct { buffer *cookie_name; buffer *cookie_domain; unsigned short cookie_max_age; } plugin_config; typedef struct { PLUGIN_DATA; plugin_config **config_storage; plugin_config conf; } plugin_data; /* init the plugin data */ INIT_FUNC(mod_usertrack_init) { plugin_data *p; p = calloc(1, sizeof(*p)); return p; } /* detroy the plugin data */ FREE_FUNC(mod_usertrack_free) { plugin_data *p = p_d; UNUSED(srv); if (!p) return HANDLER_GO_ON; if (p->config_storage) { size_t i; for (i = 0; i < srv->config_context->used; i++) { plugin_config *s = p->config_storage[i]; buffer_free(s->cookie_name); buffer_free(s->cookie_domain); free(s); } free(p->config_storage); } free(p); return HANDLER_GO_ON; } /* handle plugin config and check values */ SETDEFAULTS_FUNC(<API key>) { plugin_data *p = p_d; size_t i = 0; config_values_t cv[] = { { "usertrack.cookie-name", NULL, T_CONFIG_STRING, <API key> }, { "usertrack.cookie-max-age", NULL, T_CONFIG_SHORT, <API key> }, { "usertrack.cookie-domain", NULL, T_CONFIG_STRING, <API key> }, { "usertrack.cookiename", NULL, T_CONFIG_DEPRECATED, <API key> }, { NULL, NULL, T_CONFIG_UNSET, <API key> } }; if (!p) return HANDLER_ERROR; p->config_storage = calloc(1, srv->config_context->used * sizeof(specific_config *)); for (i = 0; i < srv->config_context->used; i++) { plugin_config *s; s = calloc(1, sizeof(plugin_config)); s->cookie_name = buffer_init(); s->cookie_domain = buffer_init(); s->cookie_max_age = 0; cv[0].destination = s->cookie_name; cv[1].destination = &(s->cookie_max_age); cv[2].destination = s->cookie_domain; p->config_storage[i] = s; if (0 != <API key>(srv, ((data_config *)srv->config_context->data[i])->value, cv)) { return HANDLER_ERROR; } if (buffer_is_empty(s->cookie_name)) { buffer_copy_string(s->cookie_name, "TRACKID"); } else { size_t j; for (j = 0; j < s->cookie_name->used - 1; j++) { char c = s->cookie_name->ptr[j] | 32; if (c < 'a' || c > 'z') { log_error_write(srv, __FILE__, __LINE__, "sb", "invalid character in usertrack.cookie-name:", s->cookie_name); return HANDLER_ERROR; } } } if (!buffer_is_empty(s->cookie_domain)) { size_t j; for (j = 0; j < s->cookie_domain->used - 1; j++) { char c = s->cookie_domain->ptr[j]; if (c <= 32 || c >= 127 || c == '"' || c == '\\') { log_error_write(srv, __FILE__, __LINE__, "sb", "invalid character in usertrack.cookie-domain:", s->cookie_domain); return HANDLER_ERROR; } } } } return HANDLER_GO_ON; } #define PATCH(x) \ p->conf.x = s->x; static int <API key>(server *srv, connection *con, plugin_data *p) { size_t i, j; plugin_config *s = p->config_storage[0]; PATCH(cookie_name); PATCH(cookie_domain); PATCH(cookie_max_age); /* skip the first, the global context */ for (i = 1; i < srv->config_context->used; i++) { data_config *dc = (data_config *)srv->config_context->data[i]; s = p->config_storage[i]; /* condition didn't match */ if (!config_check_cond(srv, con, dc)) continue; /* merge config */ for (j = 0; j < dc->value->used; j++) { data_unset *du = dc->value->data[j]; if (<API key>(du->key, CONST_STR_LEN("usertrack.cookie-name"))) { PATCH(cookie_name); } else if (<API key>(du->key, CONST_STR_LEN("usertrack.cookie-max-age"))) { PATCH(cookie_max_age); } else if (<API key>(du->key, CONST_STR_LEN("usertrack.cookie-domain"))) { PATCH(cookie_domain); } } } return 0; } #undef PATCH URIHANDLER_FUNC(<API key>) { plugin_data *p = p_d; data_string *ds; unsigned char h[16]; MD5_CTX Md5Ctx; char hh[32]; if (con->uri.path->used == 0) return HANDLER_GO_ON; <API key>(srv, con, p); if (NULL != (ds = (data_string *)array_get_element(con->request.headers, "Cookie"))) { char *g; /* we have a cookie, does it contain a valid name ? */ /* parse the cookie * * check for cookiename + (WS | '=') * */ if (NULL != (g = strstr(ds->value->ptr, p->conf.cookie_name->ptr))) { char *nc; /* skip WS */ for (nc = g + p->conf.cookie_name->used-1; *nc == ' ' || *nc == '\t'; nc++); if (*nc == '=') { /* ok, found the key of our own cookie */ if (strlen(nc) > 32) { /* i'm lazy */ return HANDLER_GO_ON; } } } } /* set a cookie */ if (NULL == (ds = (data_string *)<API key>(con->response.headers, TYPE_STRING))) { ds = data_response_init(); } buffer_copy_string(ds->key, "Set-Cookie"); <API key>(ds->value, p->conf.cookie_name); <API key>(ds->value, "="); /* taken from mod_auth.c */ /* generate shared-secret */ MD5_Init(&Md5Ctx); MD5_Update(&Md5Ctx, (unsigned char *)con->uri.path->ptr, con->uri.path->used - 1); MD5_Update(&Md5Ctx, (unsigned char *)"+", 1); /* we assume sizeof(time_t) == 4 here, but if not it ain't a problem at all */ LI_ltostr(hh, srv->cur_ts); MD5_Update(&Md5Ctx, (unsigned char *)hh, strlen(hh)); LI_ltostr(hh, rand()); MD5_Update(&Md5Ctx, (unsigned char *)hh, strlen(hh)); MD5_Final(h, &Md5Ctx); <API key>(ds->value, (char *)h, 16, ENCODING_HEX); <API key>(ds->value, "; Path=/"); <API key>(ds->value, "; Version=1"); if (!buffer_is_empty(p->conf.cookie_domain)) { <API key>(ds->value, "; Domain="); <API key>(ds->value, CONST_BUF_LEN(p->conf.cookie_domain), ENCODING_REL_URI); } if (p->conf.cookie_max_age) { <API key>(ds->value, "; max-age="); buffer_append_long(ds->value, p->conf.cookie_max_age); } array_insert_unique(con->response.headers, (data_unset *)ds); return HANDLER_GO_ON; } /* this function is called at dlopen() time and inits the callbacks */ int <API key>(plugin *p) { p->version = LIGHTTPD_VERSION_ID; p->name = buffer_init_string("usertrack"); p->init = mod_usertrack_init; p->handle_uri_clean = <API key>; p->set_defaults = <API key>; p->cleanup = mod_usertrack_free; p->data = NULL; return 0; }
#!/bin/sh # This is an example of a script to run a DOS attack # in a "secure" environment on a server with # self-load-balancing option if [ -d examples ] ; then cd examples fi export LD_LIBRARY_PATH=${LD_LIBRARY_PATH}:/usr/local/lib/ while [ 0 ] ; do PATH=examples/bin/:../bin/:./bin/:${PATH} turnutils_uclient -O -n 10 -m 10 -l 170 -g -u ninefingers -w <API key> -y $@ ::1 & PATH=examples/bin/:../bin/:./bin/:${PATH} turnutils_uclient -O -n 10 -m 10 -l 170 -e 127.0.0.1 -g -u ninefingers -w <API key> $@ ::1 & PATH=examples/bin/:../bin:./bin/:${PATH} turnutils_uclient -O -S -i turn_client_cert.pem -k turn_client_pkey.pem -n 10 -m 10 -l 170 -e ::1 -g -u ninefingers -w <API key> -s $@ 127.0.0.1 & PATH=examples/bin/:../bin/:./bin/:${PATH} turnutils_uclient -O -t -n 30 -m 10 -l 170 -e 127.0.0.1 -g -u gorst -w hero $@ ::1 & PATH=examples/bin/:../bin/:./bin/:${PATH} turnutils_uclient -O -T -n 10 -m 10 -l 170 -y -g -u gorst -w hero $@ ::1 & PATH=examples/bin/:../bin:./bin/:${PATH} turnutils_uclient -O -T -S -i turn_client_cert.pem -k turn_client_pkey.pem -n 10 -m 10 -l 170 -y -g -u gorst -w hero $@ ::1 & PATH=examples/bin/:../bin:./bin/:${PATH} turnutils_uclient -O -t -S -i turn_client_cert.pem -k turn_client_pkey.pem -n 10 -m 10 -l 170 -e 127.0.0.1 -g -u gorst -w hero $@ ::1 & sleep 1 PATH=examples/bin/:../bin/:./bin/:${PATH} turnutils_uclient -O -n 10 -m 10 -l 170 -g -u ninefingers -w <API key> -y -p 12345 $@ ::1 & PATH=examples/bin/:../bin/:./bin/:${PATH} turnutils_uclient -O -n 10 -m 10 -l 170 -e 127.0.0.1 -g -u ninefingers -w <API key> -p 12345 $@ ::1 & PATH=examples/bin/:../bin:./bin/:${PATH} turnutils_uclient -O -S -i turn_client_cert.pem -k turn_client_pkey.pem -n 10 -m 10 -l 170 -e ::1 -g -u ninefingers -w <API key> -s -p 12345 $@ 127.0.0.1 & PATH=examples/bin/:../bin/:./bin/:${PATH} turnutils_uclient -O -t -n 30 -m 10 -l 170 -e 127.0.0.1 -g -u gorst -w hero -p 12345 $@ ::1 & PATH=examples/bin/:../bin/:./bin/:${PATH} turnutils_uclient -O -T -n 10 -m 10 -l 170 -y -g -u gorst -w hero -p 12345 $@ ::1 & PATH=examples/bin/:../bin:./bin/:${PATH} turnutils_uclient -O -T -S -i turn_client_cert.pem -k turn_client_pkey.pem -n 10 -m 10 -l 170 -y -g -u gorst -w hero -p 12345 $@ ::1 & PATH=examples/bin/:../bin:./bin/:${PATH} turnutils_uclient -O -t -S -i turn_client_cert.pem -k turn_client_pkey.pem -n 10 -m 10 -l 170 -e 127.0.0.1 -g -u gorst -w hero -p 12345 $@ ::1 & sleep 1 PATH=examples/bin/:../bin/:./bin/:${PATH} turnutils_uclient -O -n 10 -m 10 -l 170 -g -u ninefingers -w <API key> -y -p 12346 $@ ::1 & PATH=examples/bin/:../bin/:./bin/:${PATH} turnutils_uclient -O -n 10 -m 10 -l 170 -e 127.0.0.1 -g -u ninefingers -w <API key> -p 12346 $@ ::1 & PATH=examples/bin/:../bin:./bin/:${PATH} turnutils_uclient -O -S -i turn_client_cert.pem -k turn_client_pkey.pem -n 10 -m 10 -l 170 -e ::1 -g -u ninefingers -w <API key> -s -p 12346 $@ 127.0.0.1 & PATH=examples/bin/:../bin/:./bin/:${PATH} turnutils_uclient -O -t -n 30 -m 10 -l 170 -e 127.0.0.1 -g -u gorst -w hero -p 12346 $@ ::1 & PATH=examples/bin/:../bin/:./bin/:${PATH} turnutils_uclient -O -T -n 10 -m 10 -l 170 -y -g -u gorst -w hero -p 12346 $@ ::1 & PATH=examples/bin/:../bin:./bin/:${PATH} turnutils_uclient -O -T -S -i turn_client_cert.pem -k turn_client_pkey.pem -n 10 -m 10 -l 170 -y -g -u gorst -w hero -p 12346 $@ ::1 & PATH=examples/bin/:../bin:./bin/:${PATH} turnutils_uclient -O -t -S -i turn_client_cert.pem -k turn_client_pkey.pem -n 10 -m 10 -l 170 -e 127.0.0.1 -g -u gorst -w hero -p 12346 $@ ::1 & sleep 1 type killall >>/dev/null 2>>/dev/null ER=$? if [ ${ER} -eq 0 ] ; then killall turnutils_uclient >>/dev/null 2>>/dev/null else type pkill >>/dev/null 2>>/dev/null ER=$? if [ ${ER} -eq 0 ] ; then pkill turnutils_u >>/dev/null 2>>/dev/null else sleep 10 fi fi done
// Authors: Alessandro Tasora, Radu Serban #include "chrono/physics/ChLinkBrake.h" namespace chrono { // Register into the object factory, to enable run-time dynamic creation and persistence CH_FACTORY_REGISTER(ChLinkBrake) ChLinkBrake::ChLinkBrake() : brake_torque(0), stick_ratio(1.1), brake_mode(BRAKE_ROTATION), last_dir(0), must_stick(false) { // Mask: initialize our LinkMaskLF (lock formulation mask) mask.SetLockMask(false, false, false, false, false, false, false); BuildLink(); } ChLinkBrake::ChLinkBrake(const ChLinkBrake& other) : ChLinkLock(other) { brake_torque = other.brake_torque; stick_ratio = other.stick_ratio; brake_mode = other.brake_mode; last_dir = other.last_dir; must_stick = other.must_stick; } void ChLinkBrake::Set_brake_mode(int mmode) { if (mmode != brake_mode) { brake_mode = mmode; // reset mask for default free brake mask.Constr_E3().SetMode(CONSTRAINT_FREE); mask.Constr_X().SetMode(CONSTRAINT_FREE); BuildLink(); } } void ChLinkBrake::SetDisabled(bool mdis) { ChLinkLock::SetDisabled(mdis); mask.Constr_E3().SetMode(CONSTRAINT_FREE); mask.Constr_X().SetMode(CONSTRAINT_FREE); BuildLink(); } // Update time: just change internal time! void ChLinkBrake::UpdateTime(double time) { ChTime = time; } // Update forces: if not sticked, apply torque void ChLinkBrake::UpdateForces(double mytime) { // First, inherit to parent class ChLinkLock::UpdateForces(mytime); if (this->IsDisabled()) return; // then, if not sticking, if (this->brake_torque) { if (brake_mode == BRAKE_ROTATION) { if (mask.Constr_E3().IsActive() == false) { int mdir; Vector mv_torque = Vmul(VECT_Z, this->brake_torque); mdir = 0; // clockwise torque if (Vdot(this->relWvel, mv_torque) > 0.0) { mv_torque = Vmul(mv_torque, -1.0); // keep torque always opposed to ang speed. mdir = 1; // counterclockwise torque } if (mdir != this->last_dir) this->must_stick = true; this->last_dir = mdir; // +++ADD TO LINK TORQUE VECTOR C_torque = Vadd(C_torque, mv_torque); } } if (brake_mode == BRAKE_TRANSLATEX) { if (mask.Constr_X().IsActive() == false) { int mdir; Vector mv_force = Vmul(VECT_X, this->brake_torque); mdir = 0; // F--> rear motion: frontfacing break force if (this->relM_dt.pos.x() > 0.0) { mv_force = Vmul(mv_force, -1.0); // break force always opposed to speed mdir = 1; // F<-- backfacing breakforce for front motion } if (mdir != this->last_dir) this->must_stick = true; this->last_dir = mdir; // +++ADD TO LINK TORQUE VECTOR C_force = Vadd(C_force, mv_force); } } } // turn off sticking feature if stick ration not > 1.0 if (this->stick_ratio <= 1.0) must_stick = false; } void ChLinkBrake::ArchiveOUT(ChArchiveOut& marchive) { // version number marchive.VersionWrite<ChLinkBrake>(); // serialize parent class ChLinkLock::ArchiveOUT(marchive); // serialize all member data: marchive << CHNVP(brake_torque); marchive << CHNVP(stick_ratio); marchive << CHNVP(brake_mode); } Method to allow de serialization of transient data from archives. void ChLinkBrake::ArchiveIN(ChArchiveIn& marchive) { // version number /*int version =*/ marchive.VersionRead<ChLinkBrake>(); // deserialize parent class ChLinkLock::ArchiveIN(marchive); // deserialize all member data: marchive >> CHNVP(brake_torque); marchive >> CHNVP(stick_ratio); marchive >> CHNVP(brake_mode); } } // end namespace chrono
goog.provide('goog.math.Rect'); goog.require('goog.math.Box'); goog.require('goog.math.Size'); goog.math.Rect = function(x, y, w, h) { this.left = x; this.top = y; this.width = w; this.height = h; }; goog.math.Rect.prototype.clone = function() { return new goog.math.Rect(this.left, this.top, this.width, this.height); }; goog.math.Rect.prototype.toBox = function() { var right = this.left + this.width; var bottom = this.top + this.height; return new goog.math.Box(this.top, right, bottom, this.left); }; goog.math.Rect.createFromBox = function(box) { return new goog.math.Rect(box.left, box.top, box.right - box.left, box.bottom - box.top); }; if(goog.DEBUG) { goog.math.Rect.prototype.toString = function() { return '(' + this.left + ', ' + this.top + ' - ' + this.width + 'w x ' + this.height + 'h)'; }; } goog.math.Rect.equals = function(a, b) { if(a == b) { return true; } if(! a || ! b) { return false; } return a.left == b.left && a.width == b.width && a.top == b.top && a.height == b.height; }; goog.math.Rect.prototype.intersection = function(rect) { var x0 = Math.max(this.left, rect.left); var x1 = Math.min(this.left + this.width, rect.left + rect.width); if(x0 <= x1) { var y0 = Math.max(this.top, rect.top); var y1 = Math.min(this.top + this.height, rect.top + rect.height); if(y0 <= y1) { this.left = x0; this.top = y0; this.width = x1 - x0; this.height = y1 - y0; return true; } } return false; }; goog.math.Rect.intersection = function(a, b) { var x0 = Math.max(a.left, b.left); var x1 = Math.min(a.left + a.width, b.left + b.width); if(x0 <= x1) { var y0 = Math.max(a.top, b.top); var y1 = Math.min(a.top + a.height, b.top + b.height); if(y0 <= y1) { return new goog.math.Rect(x0, y0, x1 - x0, y1 - y0); } } return null; }; goog.math.Rect.intersects = function(a, b) { return(a.left <= b.left + b.width && b.left <= a.left + a.width && a.top <= b.top + b.height && b.top <= a.top + a.height); }; goog.math.Rect.prototype.intersects = function(rect) { return goog.math.Rect.intersects(this, rect); }; goog.math.Rect.difference = function(a, b) { var intersection = goog.math.Rect.intersection(a, b); if(! intersection || ! intersection.height || ! intersection.width) { return[a.clone()]; } var result =[]; var top = a.top; var height = a.height; var ar = a.left + a.width; var ab = a.top + a.height; var br = b.left + b.width; var bb = b.top + b.height; if(b.top > a.top) { result.push(new goog.math.Rect(a.left, a.top, a.width, b.top - a.top)); top = b.top; height -= b.top - a.top; } if(bb < ab) { result.push(new goog.math.Rect(a.left, bb, a.width, ab - bb)); height = bb - top; } if(b.left > a.left) { result.push(new goog.math.Rect(a.left, top, b.left - a.left, height)); } if(br < ar) { result.push(new goog.math.Rect(br, top, ar - br, height)); } return result; }; goog.math.Rect.prototype.difference = function(rect) { return goog.math.Rect.difference(this, rect); }; goog.math.Rect.prototype.boundingRect = function(rect) { var right = Math.max(this.left + this.width, rect.left + rect.width); var bottom = Math.max(this.top + this.height, rect.top + rect.height); this.left = Math.min(this.left, rect.left); this.top = Math.min(this.top, rect.top); this.width = right - this.left; this.height = bottom - this.top; }; goog.math.Rect.boundingRect = function(a, b) { if(! a || ! b) { return null; } var clone = a.clone(); clone.boundingRect(b); return clone; }; goog.math.Rect.prototype.contains = function(another) { if(another instanceof goog.math.Rect) { return this.left <= another.left && this.left + this.width >= another.left + another.width && this.top <= another.top && this.top + this.height >= another.top + another.height; } else { return another.x >= this.left && another.x <= this.left + this.width && another.y >= this.top && another.y <= this.top + this.height; } }; goog.math.Rect.prototype.getSize = function() { return new goog.math.Size(this.width, this.height); };
import nibabel as nib import numpy as np from scipy import stats def <API key>(func_timeseries, mask): for i in range(0, len(func_timeseries)): for j in range(0, len(func_timeseries[0])): for k in range(0, len(func_timeseries[0][0])): var = func_timeseries[i][j][k].var() if int(var) == 0: mask[i][j][k] = mask[i][j][k] * 0 return mask def load(func_file, mask_file, check4d=True): func_img = nib.load(func_file) mask_img = nib.load(mask_file) mask = mask_img.get_data() func = func_img.get_data().astype(np.float) if check4d and len(func.shape) != 4: raise Exception("Input functional %s should be 4-dimensional" % func_file) mask_var_filtered = <API key>(func, mask) func = func[mask_var_filtered.nonzero()].T # will have ntpts x nvoxs return func def robust_stdev(func, interp="fraction"): """ Compute robust estimation of standard deviation """ lower_qs = np.percentile(func, 25, axis=0) upper_qs = np.percentile(func, 75, axis=0) # note: won't work on roxy with scipy == 0.9 #lower_qs = stats.scoreatpercentile(func, 25, <API key>=interp, axis=0) #upper_qs = stats.scoreatpercentile(func, 75, <API key>=interp, axis=0) stdev = (upper_qs - lower_qs)/1.349 return stdev def ar_nitime(x, order=1, center=False): """ Borrowed from nipy.algorithms.AR_est_YW. aka from nitime import algorithms as alg. We could speed this up by having the autocorr only compute lag1. """ from nitime.lazy import scipy_linalg as linalg import nitime.utils as utils if center: x = x.copy() x = x - x.mean() r_m = utils.autocorr(x)[:order + 1] Tm = linalg.toeplitz(r_m[:order]) y = r_m[1:] ak = linalg.solve(Tm, y) return ak[0] def ar_statsmodels(x, order=(1,0), trend='nc'): import statsmodels.api as sm arma_mod = sm.tsa.ARMA(x) arma_res = arma_mod.fit(order=order, trend=trend, disp=False) return arma_res.arparams[0] def ar1(func, method=ar_nitime): func_centered = func - func.mean(0) #import code #code.interact(local=locals()) ar_vals = np.apply_along_axis(method, 0, func_centered) return ar_vals def calc_dvars(func, output_all=False, interp="fraction"): # Robust standard deviation func_sd = robust_stdev(func, interp) # AR1 func_ar1 = ar1(func) # Predicted standard deviation of temporal derivative func_sd_pd = np.sqrt(2 * (1 - func_ar1)) * func_sd diff_sd_mean= func_sd_pd.mean() # Compute temporal difference time series func_deriv = np.diff(func, axis=0) # DVARS ## (no standardization) dvars_plain = func_deriv.std(1, ddof=1) # TODO: Why are we not ^2 this & getting the sqrt? ## standardization dvars_stdz = dvars_plain/diff_sd_mean ## voxelwise standardization diff_vx_stdz= func_deriv/func_sd_pd dvars_vx_stdz = diff_vx_stdz.std(1, ddof=1) if output_all: out = np.vstack((dvars_stdz, dvars_plain, dvars_vx_stdz)) else: out = dvars_stdz.reshape(len(dvars_stdz), 1) return out def calc_mean_dvars(dvars): mean_dvars = dvars.mean(0) return mean_dvars def mean_dvars_wrapper(func_file, mask_file, dvars_out_file=None): func = load(func_file, mask_file) dvars = calc_dvars(func) if dvars_out_file: np.savetxt(dvars_out_file, dvars, fmt='%.12f') mean_d = calc_mean_dvars(dvars) return mean_d[0] def test(): func = load("sample_func.nii.gz", "sample_func_mask.nii.gz") dvars = calc_dvars(func) mean_d = calc_mean_dvars(dvars) ref_dvars = np.loadtxt("sample_dvars.txt") ref_dvars = ref_dvars[:,[1,0,2]] def specific_tests(): import numpy.testing ffile = "sample_func.nii.gz" mfile = "sample_func_mask.nii.gz" func = load(ffile, mfile) # Robust Standard Deviation ## Differences in the two approaches exist because python will handle ## ties via averaging func_sd = robust_stdev(func) ref_sd = load("ref_dvars/DVARS-1033--SD.nii.gz", mfile, False) print np.abs(func_sd - ref_sd).mean() ## so we can fix this issue by changing the interpolation/ties approach ## note however that normally we will use interp="fraction" func_sd = robust_stdev(func, interp="higher") ## test assert_allclose(func_sd, ref_sd) print np.abs(func_sd - ref_sd).mean() # AR1 func_ar1 = ar1(func) ref_ar1 = load("ref_dvars/DVARS-1033--AR1.nii.gz", mfile, False) ## test assert_allclose(func_ar1, ref_ar1, 1e-6, 1e-6) print np.abs(func_ar1 - ref_ar1).mean() # Predicted standard deviation of temporal derivative func_sd_pd = np.sqrt(2 * (1 - func_ar1)) * func_sd diff_sd_mean= func_sd_pd.mean() ref_sd_pd = load("ref_dvars/<API key>.nii.gz", mfile, False) ## test assert_allclose(func_sd_pd, ref_sd_pd, 1e-5, 1e-5) print np.abs(func_sd_pd - ref_sd_pd).mean() # Compute temporal difference time series func_deriv = np.diff(func, axis=0) ref_deriv = load("ref_dvars/DVARS-1033--Diff.nii.gz", mfile) ## test (these should be flipped in sign) assert_equal(func_deriv, -1*ref_deriv) print np.abs(func_deriv - (-1*ref_deriv)).mean() # DVARS (no standardization) dvars_plain = func_deriv.std(1, ddof=1) ref_plain = np.loadtxt("ref_dvars/DVARS-1033--DiffSD.dat") print np.abs(dvars_plain - ref_plain).mean() print np.vstack((dvars_plain[:10], ref_plain[:10])).T print np.vstack((func_deriv.std(1, ddof=1)[:10], ref_plain[:10])).T ## it seems like the differences above stem from an incorrect averaging by my modication of DVARS func_img = nib.load("ref_dvars/DVARS-1033--Diff.nii.gz") func_all = func_img.get_data().astype(np.float) func_all = func_all.reshape(np.prod(func_all.shape[:3]), func_all.shape[-1]) func_all = func_all.T print func_all[0,func_all[0,:].nonzero()].std(ddof=1) - ref_plain[0] # DVARS ## (no standardization) dvars_plain = func_deriv.std(1, ddof=1) # TODO: Why are we not ^2 this & getting the sqrt? ## standardization dvars_stdz = dvars_plain/diff_sd_mean ## voxelwise standardization diff_vx_stdz= func_deriv/func_sd_pd dvars_vx_stdz = diff_vx_stdz.std(1, ddof=1) ## reference ref_dvars = np.loadtxt("sample_dvars.txt") ref_dvars = ref_dvars[:,[1,0,2]] ## test print np.abs(dvars_plain - ref_dvars[:,0]).mean() ## Below tests show that ar_nitime is much faster ## so we will use that # %timeit ar_nitime(func_centered[:,0]) # %timeit ar_statsmodels(func_centered[:,0])
#!/usr/bin/env python # Hack to prevent stupid "TypeError: 'NoneType' object is not callable" error # in multiprocessing/util.py _exit_function when running `python # setup.py test` (see for m in ('multiprocessing', 'billiard'): try: __import__(m) except ImportError: pass from setuptools import setup, find_packages from setuptools.command.test import test as TestCommand import sys setup_requires = [ 'pytest', ] dev_requires = [ 'flake8>=2.0,<2.1', ] unittest2_requires = ['unittest2'] flask_requires = [ 'Flask>=0.8', 'blinker>=1.1', ] <API key> = [ 'Flask-Login>=0.2.0', ] <API key> = [ 'paste', 'web.py', ] # If it's python3, remove unittest2 & web.py if sys.version_info[0] == 3: unittest2_requires = [] <API key> = [] tests_require = [ 'bottle', 'celery>=2.5', 'Django>=1.4', 'django-celery>=2.5', 'exam>=0.5.2', 'logbook', 'mock', 'nose', 'pep8', 'pytz', 'pytest>=2.7.0,<2.8.0', 'pytest-cov>=1.4', 'pytest-django>=2.8.0,<2.7.0', 'pytest-timeout==0.4', 'requests', 'tornado', 'webob', 'webtest', 'anyjson', ] + (flask_requires + <API key> + unittest2_requires + <API key>) class PyTest(TestCommand): def initialize_options(self): TestCommand.initialize_options(self) self.pytest_args = [] def finalize_options(self): TestCommand.finalize_options(self) self.test_args = [] self.test_suite = True def run_tests(self): # import here, cause outside the eggs aren't loaded import pytest errno = pytest.main(self.pytest_args) sys.exit(errno) setup( name='raven', version='5.7.0.dev0', author='David Cramer', author_email='dcramer@gmail.com', url='https://github.com/getsentry/raven-python', description='Raven is a client for Sentry (https: long_description=__doc__, packages=find_packages(exclude=("tests", "tests.*",)), zip_safe=False, extras_require={ 'flask': flask_requires, 'tests': tests_require, 'dev': dev_requires, }, license='BSD', tests_require=tests_require, cmdclass={'test': PyTest}, <API key>=True, entry_points={ 'console_scripts': [ 'raven = raven.scripts.runner:main', ], 'paste.filter_app_factory': [ 'raven = raven.contrib.paste:<API key>', ], }, classifiers=[ 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python', 'Topic :: Software Development', ], )
{-# LANGUAGE DataKinds, PolyKinds, TypeOperators, TypeFamilies , TypeApplications, TypeInType module DumpParsedAst where import Data.Kind data Peano = Zero | Succ Peano type family Length (as :: [k]) :: Peano where Length (a : as) = Succ (Length as) Length '[] = Zero -- vis kind app data T f (a :: k) = MkT (f a) type family F1 (a :: k) (f :: k -> Type) :: Type where F1 @Peano a f = T @Peano f a main = putStrLn "hello"
layout: data_model title: <API key> this_version: 1.2 <div class="row"> <div class="col-md-10"> <h1><API key><span class="subdued">CybOX Common Schema</span></h1> <p class="<API key>">The <a href='/data-model/1.2/cyboxCommon/<API key>'><API key></a> is a type (extended from <API key>) representing the specification of a single Object property whose core value is of type base64Binary. This type will be assigned to any property of a CybOX object that should contain content of type Base64Binary and enables the use of relevant metadata for the property.</p><p class="<API key>">Properties that use this type can express multiple values by providing them using a delimiter-separated list. The default delimiter is '##comma##' (no quotes) but can be overridden through use of the delimiter field. Note that whitespace is preserved and so, when specifying a list of values, do not include a space following the delimiter in a list unless the first character of the next list item should, in fact, be a space.</p> </div> <div id="nav-area" class="col-md-2"> <p> <form id="nav-version"> <select> <option value="1.2" selected="selected">STIX 1.2</option> <option value="1.1.1" >STIX 1.1.1</option> <option value="1.1" >STIX 1.1</option> <option value="1.0.1" >STIX 1.0.1</option> <option value="1.0" >STIX 1.0</option> </select> </form> </p> </div> </div> <hr /> <h2>Fields</h2> <table class="table table-striped table-hover"> <thead> <tr> <th>Field Name</th> <th>Type</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td>@id<span class="occurrence">optional</span></td> <td> QName </td> <td> <p>The id field specifies a unique ID for this Object Property.</p> </td> </tr> <tr> <td>@idref<span class="occurrence">optional</span></td> <td> QName </td> <td> <p>The idref field specifies a unique ID reference for this Object Property.</p> <p>When idref is specified, the id attribute must not be specified, and any instance of this property should not hold content unless an extension of the property allows it.</p> </td> </tr> <tr> <td>@datatype<span class="occurrence">optional</span></td> <td> DatatypeEnum </td> <td> <p>This attribute is optional and specifies the expected type for the value of the specified property.</p> </td> </tr> <tr> <td>@appears_random<span class="occurrence">optional</span></td> <td> boolean </td> <td> <p>This field is optional and conveys whether the associated object property value appears to somewhat random in nature. An object property with this field set to TRUE need not provide any further information including a value. If more is known about the particular variation of randomness, a regex value could be provided to outline what is known of the structure.</p> </td> </tr> <tr> <td>@is_obfuscated<span class="occurrence">optional</span></td> <td> boolean </td> <td> <p>This field is optional and conveys whether the associated Object property has been obfuscated.</p> </td> </tr> <tr> <td>@<API key><span class="occurrence">optional</span></td> <td> anyURI </td> <td> <p>This field is optional and conveys a reference to a description of the algorithm used to obfuscate this Object property.</p> </td> </tr> <tr> <td>@is_defanged<span class="occurrence">optional</span></td> <td> boolean </td> <td> <p>This field is optional and conveys whether the associated Object property has been defanged (representation changed to prevent malicious effects of handling/processing).</p> </td> </tr> <tr> <td>@<API key><span class="occurrence">optional</span></td> <td> anyURI </td> <td> <p>This field is optional and conveys a reference to a description of the algorithm used to defang (representation changed to prevent malicious effects of handling/processing) this Object property.</p> </td> </tr> <tr> <td>@<API key><span class="occurrence">optional</span></td> <td> string </td> <td> <p>This field is optional and specifies the type (e.g. RegEx) of refanging transform specified in the optional accompanying refangingTransform property.</p> </td> </tr> <tr> <td>@refanging_transform<span class="occurrence">optional</span></td> <td> string </td> <td> <p>This field is optional and specifies an automated transform that can be applied to the Object property content in order to refang it to its original format.</p> </td> </tr> <tr> <td>@observed_encoding<span class="occurrence">optional</span></td> <td> string </td> <td> <p>This field is optional and specifies the encoding of the string when it is/was observed. This may be different from the encoding used to represent the string within this element.</p> <p>It is strongly recommended that character set names should be taken from the IANA character set registry (https: <p>This field is intended to be applicable only to fields which contain string values.</p> </td> </tr> <tr> <td>@condition<span class="occurrence">optional</span></td> <td> ConditionTypeEnum </td> <td> <p>This field is optional and defines the relevant condition to apply to the value.</p> </td> </tr> <tr> <td>@is_case_sensitive<span class="occurrence">optional</span></td> <td> boolean </td> <td> <p>The is_case_sensitive field is optional and should be used when specifying the case-sensitivity of a pattern which uses an Equals, DoesNotEqual, Contains, DoesNotContain, StartsWith, EndsWith, or FitsPattern condition. The default value for this field is "true" which indicates that pattern evaluations are to be considered case-sensitive.</p> </td> </tr> <tr> <td>@apply_condition<span class="occurrence">optional</span></td> <td> <API key> </td> <td> <p>This field indicates how a condition should be applied when the field body contains a list of values. (Its value is moot if the field value contains only a single value - both possible values for this field would have the same behavior.) If this field is set to ANY, then a pattern is considered to be matched if the provided condition successfully evaluates for any of the values in the field body. If the field is set to ALL, then the patern only matches if the provided condition successfully evaluates for every value in the field body.</p> </td> </tr> <tr> <td>@delimiter<span class="occurrence">optional</span></td> <td> string </td> <td> <p>The delimiter field specifies the delimiter used when defining lists of values. The default value is "##comma##".</p> </td> </tr> <tr> <td>@bit_mask<span class="occurrence">optional</span></td> <td> hexBinary </td> <td> <p>Used to specify a bit_mask in conjunction with one of the defined binary conditions (bitwiseAnd, bitwiseOr, and bitwiseXor). This bitmask is then uses as one operand in the indicated bitwise computation.</p> </td> </tr> <tr> <td>@pattern_type<span class="occurrence">optional</span></td> <td> PatternTypeEnum </td> <td> <p>This field is optional and defines the type of pattern used if one is specified for the field value. This is applicable only if the Condition field is set to 'FitsPattern'.</p> </td> </tr> <tr> <td>@regex_syntax<span class="occurrence">optional</span></td> <td> string </td> <td> <p>This field is optional and defines the syntax format used for a regular expression, if one is specified for the field value. This is applicable only if the Condition field is set to 'FitsPattern'.</p> <p>Setting this attribute with an empty value (e.g., "") or omitting it entirely notifies CybOX consumers and pattern evaluators that the corresponding regular expression utilizes capabilities, character classes, escapes, and other lexical tokens defined by the CybOX Language Specification.</p> <p>Setting this attribute with a non-empty value notifies CybOX consumers and pattern evaluators that the corresponding regular expression utilizes capabilities not defined by the CybOX Language Specification. The regular expression must be evaluated through a compatible regular expression engine in this case.</p> </td> </tr> <tr> <td>@has_changed<span class="occurrence">optional</span></td> <td> boolean </td> <td> <p>This field is optional and conveys a targeted observation pattern of whether the associated field value has changed. This field would be leveraged within a pattern observable triggering on whether the value of a single field value has changed.</p> </td> </tr> <tr> <td>@trend<span class="occurrence">optional</span></td> <td> boolean </td> <td> <p>This field is optional and conveys a targeted observation pattern of the nature of any trend in the associated field value. This field would be leveraged within a pattern observable triggering on the matching of a specified trend in the value of a single specified field.</p> </td> </tr> </tbody> </table>
#include "xfa/fxfa/parser/cxfa_margin.h" #include "xfa/fxfa/parser/xfa_object.h" CXFA_Margin::CXFA_Margin(CXFA_Node* pNode) : CXFA_Data(pNode) {} bool CXFA_Margin::GetLeftInset(FX_FLOAT& fInset, FX_FLOAT fDefInset) const { fInset = fDefInset; return TryMeasure(<API key>, fInset); } bool CXFA_Margin::GetTopInset(FX_FLOAT& fInset, FX_FLOAT fDefInset) const { fInset = fDefInset; return TryMeasure(<API key>, fInset); } bool CXFA_Margin::GetRightInset(FX_FLOAT& fInset, FX_FLOAT fDefInset) const { fInset = fDefInset; return TryMeasure(<API key>, fInset); } bool CXFA_Margin::GetBottomInset(FX_FLOAT& fInset, FX_FLOAT fDefInset) const { fInset = fDefInset; return TryMeasure(<API key>, fInset); }
$(function () { var svc = new as.Service("admin/<API key>"); function <API key>(list) { this.administrators = ko.mapping.fromJS(list); this.nameToAdd = ko.observable(""); as.util.addRequired(this, "nameToAdd", "Name To Add"); as.util.addAnyErrors(this); } <API key>.prototype.addAdmin = function(){ var vm = this; svc.post(vm.nameToAdd()).then(function (data) { vm.nameToAdd(""); vm.administrators.push(ko.mapping.fromJS(data)); }); } <API key>.prototype.deleteAdmin = function(item){ var vm = this; svc.delete(item.id()).then(function () { vm.administrators.remove(item); }); } svc.get().then(function (data) { var vm = new <API key>(data); ko.applyBindings(vm); }); });
#!/usr/bin/env python # This is generated, do not edit. Update <API key>.groovy and # 3ppFetch.template instead. from __future__ import print_function import argparse import json import os _FILE_URL = 'https://repo.maven.apache.org/maven2/org/apache/maven/wagon/wagon-http-shared/1.0-beta-6/wagon-http-shared-1.0-beta-6.jar' _FILE_NAME = 'wagon-http-shared-1.0-beta-6.jar' _FILE_VERSION = '1.0-beta-6' def do_latest(): print(_FILE_VERSION) def get_download_url(version): if _FILE_URL.endswith('.jar'): ext = '.jar' elif _FILE_URL.endswith('.aar'): ext = '.aar' else: raise Exception('Unsupported extension for %s' % _FILE_URL) partial_manifest = { 'url': [_FILE_URL], 'name': [_FILE_NAME], 'ext': ext, } print(json.dumps(partial_manifest)) def main(): ap = argparse.ArgumentParser() sub = ap.add_subparsers() latest = sub.add_parser("latest") latest.set_defaults(func=lambda _opts: do_latest()) download = sub.add_parser("get_url") download.set_defaults( func=lambda _opts: get_download_url(os.environ['_3PP_VERSION'])) opts = ap.parse_args() opts.func(opts) if __name__ == '__main__': main()
module HLint.Generalise where import Data.Monoid import Control.Monad warn = concatMap ==> (=<<) warn = liftM ==> fmap warn = map ==> fmap warn = a ++ b ==> a `Data.Monoid.mappend` b
<link rel="import" href="<API key>.html"> <link rel="import" href="chromedash-metadata.html"> <link rel="import" href="chromedash-legend.html"> <link rel="import" href="../bower_components/paper-button/paper-button.html">
package sbt package inc import java.io.File import scala.math.abs import sbt.inc.TestCaseGenerators._ import org.scalacheck._ import Gen._ import Prop._ object AnalysisTest extends Properties("Analysis") { // Merge and split a hard-coded trivial example. property("Simple Merge and Split") = { def f(s: String) = new File(s) val aScala = f("A.scala") val bScala = f("B.scala") val aSource = genSource("A" :: "A$" :: Nil).sample.get val bSource = genSource("B" :: "B$" :: Nil).sample.get val cSource = genSource("C" :: Nil).sample.get val exists = new Exists(true) val sourceInfos = SourceInfos.makeInfo(Nil, Nil) var a = Analysis.Empty a = a.addProduct(aScala, f("A.class"), exists, "A") a = a.addProduct(aScala, f("A$.class"), exists, "A$") a = a.addSource(aScala, aSource, exists, Nil, Nil, sourceInfos) a = a.addBinaryDep(aScala, f("x.jar"), "x", exists) a = a.addExternalDep(aScala, "C", cSource, inherited=false) var b = Analysis.Empty b = b.addProduct(bScala, f("B.class"), exists, "B") b = b.addProduct(bScala, f("B$.class"), exists, "B$") b = b.addSource(bScala, bSource, exists, Nil, Nil, sourceInfos) b = b.addBinaryDep(bScala, f("x.jar"), "x", exists) b = b.addBinaryDep(bScala, f("y.jar"), "y", exists) b = b.addExternalDep(bScala, "A", aSource, inherited=true) var ab = Analysis.Empty ab = ab.addProduct(aScala, f("A.class"), exists, "A") ab = ab.addProduct(aScala, f("A$.class"), exists, "A$") ab = ab.addProduct(bScala, f("B.class"), exists, "B") ab = ab.addProduct(bScala, f("B$.class"), exists, "B$") ab = ab.addSource(aScala, aSource, exists, Nil, Nil, sourceInfos) ab = ab.addSource(bScala, bSource, exists, aScala :: Nil, aScala :: Nil, sourceInfos) ab = ab.addBinaryDep(aScala, f("x.jar"), "x", exists) ab = ab.addBinaryDep(bScala, f("x.jar"), "x", exists) ab = ab.addBinaryDep(bScala, f("y.jar"), "y", exists) ab = ab.addExternalDep(aScala, "C", cSource, inherited=false) val split: Map[String, Analysis] = ab.groupBy({ f: File => f.getName.substring(0, 1) }) val aSplit = split.getOrElse("A", Analysis.Empty) val bSplit = split.getOrElse("B", Analysis.Empty) val merged = Analysis.merge(a :: b :: Nil) ("split(AB)(A) == A" |: compare(a, aSplit)) && ("split(AB)(B) == B" |: compare(b, bSplit)) && ("merge(A, B) == AB" |: compare(merged, ab)) } // Merge and split large, generated examples. // Mustn't shrink, as the default Shrink[Int] doesn't respect the lower bound of choose(), which will cause // a divide-by-zero error masking the original error. property("Complex Merge and Split") = forAllNoShrink(genAnalysis, choose(1, 10)) { (analysis: Analysis, numSplits: Int) => val grouped: Map[Int, Analysis] = analysis.groupBy({ f: File => abs(f.hashCode()) % numSplits}) def getGroup(i: Int): Analysis = grouped.getOrElse(i, Analysis.Empty) val splits = (Range(0, numSplits) map getGroup).toList val merged: Analysis = Analysis.merge(splits) "Merge all" |: compare(analysis, merged) } // Compare two analyses with useful labelling when they aren't equal. private[this] def compare(left: Analysis, right: Analysis): Prop = s" LEFT: $left" |: s"RIGHT: $right" |: s"STAMPS EQUAL: ${left.stamps == right.stamps}" |: s"APIS EQUAL: ${left.apis == right.apis}" |: s"RELATIONS EQUAL: ${left.relations == right.relations}" |: "UNEQUAL" |: (left == right) }
/* $NoKeywords: $ */ // Definition of surface proxy object #if !defined(<API key>) #define <API key> class ON_Curve; class ON_NurbsSurface; class ON_CLASS ON_SurfaceProxy : public ON_Surface { public: // virtual ON_Object::DestroyRuntimeCache override void DestroyRuntimeCache( bool bDelete = true ); public: ON_SurfaceProxy(); ON_SurfaceProxy(const ON_Surface*); ON_SurfaceProxy(const ON_SurfaceProxy&); ON_SurfaceProxy& operator=(const ON_SurfaceProxy&); virtual ~ON_SurfaceProxy(); void SetProxySurface( const ON_Surface* proxy_surface ); const ON_Surface* ProxySurface() const; bool <API key>() const; private: const ON_Surface* m_surface; bool m_bTransposed; // proxy surface parameterization is transpose of m_surface public: /* Description: Get a duplicate of the surface. Returns: A duplicate of the surface. Remarks: The caller must delete the returned surface. For non-ON_SurfaceProxy objects, this simply duplicates the surface using ON_Object::Duplicate. For ON_SurfaceProxy objects, this duplicates the actual proxy surface geometry and, if necessary, transposes the result to that the returned surfaces's parameterization and locus match the proxy surface's. */ virtual ON_Surface* DuplicateSurface() const; // ON_Object overrides // virtual ON_Object::SizeOf override unsigned int SizeOf() const; // virtual ON_Object::DataCRC override ON__UINT32 DataCRC(ON__UINT32 current_remainder) const; /* Description: Tests an object to see if its data members are correctly initialized. Parameters: text_log - [in] if the object is not valid and text_log is not NULL, then a brief englis description of the reason the object is not valid is appened to the log. The information appended to text_log is suitable for low-level debugging purposes by programmers and is not intended to be useful as a high level user interface tool. Returns: @untitled table true object is valid false object is invalid, uninitialized, etc. Remarks: Overrides virtual ON_Object::IsValid */ ON_BOOL32 IsValid( ON_TextLog* text_log = NULL ) const; void Dump( ON_TextLog& ) const; // for debugging ON_BOOL32 Write( ON_BinaryArchive& // open binary file ) const; ON_BOOL32 Read( ON_BinaryArchive& // open binary file ); // ON_Geometry overrides int Dimension() const; ON_BOOL32 GetBBox( // returns true if successful double*, // minimum double*, // maximum ON_BOOL32 = false // true means grow box ) const; ON_BOOL32 Transform( const ON_Xform& ); ON_Interval Domain( int // 0 gets first parameter's domain, 1 gets second parameter's domain ) const; int SpanCount( int // 0 gets first parameter's domain, 1 gets second parameter's domain ) const; // number of smooth spans in curve ON_BOOL32 GetSpanVector( // span "knots" int, // 0 gets first parameter's domain, 1 gets second parameter's domain double* // array of length SpanCount() + 1 ) const; int Degree( // returns maximum algebraic degree of any span // ( or a good estimate if curve spans are not algebraic ) int // 0 gets first parameter's domain, 1 gets second parameter's domain ) const; ON_BOOL32 <API key>( // returns tminus < tplus: parameters tminus <= s <= tplus int, // 0 gets first parameter, 1 gets second parameter double, // t = parameter in domain double*, // tminus double* // tplus ) const; // override virtual ON_Surface::IsIsoparametric ISO IsIsoparametric( const ON_Curve& curve, const ON_Interval* curve_domain = NULL ) const; // override virtual ON_Surface::IsIsoparametric ISO IsIsoparametric( const ON_BoundingBox& bbox ) const; /* Description: Test a surface to see if it is planar. Parameters: plane - [out] if not NULL and true is returned, the plane parameters are filled in. tolerance - [in] tolerance to use when checking Returns: true if there is a plane such that the maximum distance from the surface to the plane is <= tolerance. Remarks: Overrides virtual ON_Surface::IsPlanar. */ ON_BOOL32 IsPlanar( ON_Plane* plane = NULL, double tolerance = ON_ZERO_TOLERANCE ) const; ON_BOOL32 IsClosed( // true if surface is closed in direction int // dir 0 = "s", 1 = "t" ) const; ON_BOOL32 IsPeriodic( // true if surface is periodic in direction int // dir 0 = "s", 1 = "t" ) const; ON_BOOL32 IsSingular( // true if surface side is collapsed to a point int // side of parameter space to test // 0 = south, 1 = east, 2 = north, 3 = west ) const; /* Description: Search for a derivatitive, tangent, or curvature discontinuity. Parameters: dir - [in] If 0, then "u" parameter is checked. If 1, then the "v" parameter is checked. c - [in] type of continity to test for. t0 - [in] Search begins at t0. If there is a discontinuity at t0, it will be ignored. This makes it possible to repeatedly call <API key> and step through the discontinuities. t1 - [in] (t0 != t1) If there is a discontinuity at t1 is will be ingored unless c is a locus discontinuity type and t1 is at the start or end of the curve. t - [out] if a discontinuity is found, then *t reports the parameter at the discontinuity. hint - [in/out] if <API key> will be called repeatedly, passing a "hint" with initial value *hint=0 will increase the speed of the search. dtype - [out] if not NULL, *dtype reports the kind of discontinuity found at *t. A value of 1 means the first derivative or unit tangent was discontinuous. A value of 2 means the second derivative or curvature was discontinuous. A value of 0 means teh curve is not closed, a locus discontinuity test was applied, and t1 is at the start of end of the curve. cos_angle_tolerance - [in] default = cos(1 degree) Used only when c is ON::G1_continuous or ON::G2_continuous. If the cosine of the angle between two tangent vectors is <= cos_angle_tolerance, then a G1 discontinuity is reported. curvature_tolerance - [in] (default = ON_SQRT_EPSILON) Used only when c is ON::G2_continuous. If K0 and K1 are curvatures evaluated from above and below and |K0 - K1| > curvature_tolerance, then a curvature discontinuity is reported. Returns: Parametric continuity tests c = (C0_continuous, ..., G2_continuous): true if a parametric discontinuity was found strictly between t0 and t1. Note well that all curves are parametrically continuous at the ends of their domains. Locus continuity tests c = (C0_locus_continuous, ...,G2_locus_continuous): true if a locus discontinuity was found strictly between t0 and t1 or at t1 is the at the end of a curve. Note well that all open curves (IsClosed()=false) are locus discontinuous at the ends of their domains. All closed curves (IsClosed()=true) are at least C0_locus_continuous at the ends of their domains. */ bool <API key>( int dir, ON::continuity c, double t0, double t1, double* t, int* hint=NULL, int* dtype=NULL, double cos_angle_tolerance=<API key>, double curvature_tolerance=ON_SQRT_EPSILON ) const; /* Description: Test continuity at a surface parameter value. Parameters: c - [in] continuity to test for s - [in] surface parameter to test t - [in] surface parameter to test hint - [in] evaluation hint point_tolerance - [in] if the distance between two points is greater than point_tolerance, then the surface is not C0. d1_tolerance - [in] if the difference between two first derivatives is greater than d1_tolerance, then the surface is not C1. d2_tolerance - [in] if the difference between two second derivatives is greater than d2_tolerance, then the surface is not C2. cos_angle_tolerance - [in] default = cos(1 degree) Used only when c is ON::G1_continuous or ON::G2_continuous. If the cosine of the angle between two normal vectors is <= cos_angle_tolerance, then a G1 discontinuity is reported. curvature_tolerance - [in] (default = ON_SQRT_EPSILON) Used only when c is ON::G2_continuous. If K0 and K1 are curvatures evaluated from above and below and |K0 - K1| > curvature_tolerance, then a curvature discontinuity is reported. Returns: true if the surface has at least the c type continuity at the parameter t. Remarks: Overrides virtual ON_Surface::IsContinuous */ bool IsContinuous( ON::continuity c, double s, double t, int* hint = NULL, double point_tolerance=ON_ZERO_TOLERANCE, double d1_tolerance=ON_ZERO_TOLERANCE, double d2_tolerance=ON_ZERO_TOLERANCE, double cos_angle_tolerance=<API key>, double curvature_tolerance=ON_SQRT_EPSILON ) const; ON_BOOL32 Reverse( // reverse parameterizatrion, Domain changes from [a,b] to [-b,-a] int // dir 0 = "s", 1 = "t" ); ON_BOOL32 Transpose(); // transpose surface parameterization (swap "s" and "t") // work horse evaluator ON_BOOL32 Evaluate( // returns false if unable to evaluate double, double, // evaluation parameters int, // number of derivatives (>=0) int, // array stride (>=Dimension()) double*, // array of length stride*(ndir+1)*(ndir+2)/2 int = 0, // optional - determines which quadrant to evaluate from // 0 = default // 1 from NE quadrant // 2 from NW quadrant // 3 from SW quadrant // 4 from SE quadrant int* = 0 // optional - evaluation hint (int[2]) used to speed // repeated evaluations ) const; ON_Curve* IsoCurve( int dir, double c ) const; int GetNurbForm( // returns 0: unable to create NURBS representation // with desired accuracy. // 1: success - returned NURBS parameterization // matches the surface's to wthe desired accuracy // 2: success - returned NURBS point locus matches // the surfaces's to the desired accuracy but, on // the interior of the surface's domain, the // surface's parameterization and the NURBS // parameterization may not match to the // desired accuracy. ON_NurbsSurface&, double = 0.0 ) const; int HasNurbForm( // returns 0: unable to create NURBS representation // with desired accuracy. // 1: success - returned NURBS parameterization // matches the surface's to wthe desired accuracy // 2: success - returned NURBS point locus matches // the surfaces's to the desired accuracy but, on // the interior of the surface's domain, the // surface's parameterization and the NURBS // parameterization may not match to the // desired accuracy. ) const; bool <API key>( double nurbs_s, double nurbs_t, double* surface_s, double* surface_t ) const; bool <API key>( double surface_s, double surface_t, double* nurbs_s, double* nurbs_t ) const; private: ON_OBJECT_DECLARE(ON_SurfaceProxy); }; #endif
from __future__ import absolute_import import unittest from telemetry import decorators from telemetry.testing import tab_test_case from telemetry.timeline import model as timeline_model from telemetry.timeline import tracing_config from tracing.trace_data import trace_data class <API key>(unittest.TestCase): def testEmptyImport(self): timeline_model.TimelineModel(trace_data.<API key>([])) def testBrowserProcess(self): trace = trace_data.<API key>([ { "name": "process_name", "args": {"name": "Browser"}, "pid": 5, "ph": "M" }, { "name": "thread_name", "args": {"name": "CrBrowserMain"}, "pid": 5, "tid": 32578, "ph": "M" }]) model = timeline_model.TimelineModel(trace) self.assertEqual(5, model.browser_process.pid) class <API key>(tab_test_case.TabTestCase): def setUp(self): super(<API key>, self).setUp() self.tracing_controller = self._browser.platform.tracing_controller self.config = tracing_config.TracingConfig() self.config.chrome_trace_config.<API key>() self.config.enable_chrome_trace = True def testGetTrace(self): self.tracing_controller.StartTracing(self.config) self.tabs[0].AddTimelineMarker('trace-event') trace = self.tracing_controller.StopTracing() model = timeline_model.TimelineModel(trace) markers = model.FindTimelineMarkers('trace-event') self.assertEqual(len(markers), 1) def <API key>(self): self.assertEqual(len(self.tabs), 1) # We have a single tab/page. self.tracing_controller.StartTracing(self.config) self.tabs[0].AddTimelineMarker('single-tab-marker') trace = self.tracing_controller.StopTracing() model = timeline_model.TimelineModel(trace) # Check that we can find the marker injected into the trace. renderer_thread = model.<API key>(self.tabs[0].id) markers = list(renderer_thread.IterTimelineMarkers('single-tab-marker')) self.assertEqual(len(markers), 1) @decorators.Enabled('has tabs') def <API key>(self): # Make sure a couple of tabs exist. first_tab = self.tabs[0] second_tab = self.tabs.New() second_tab.Navigate('about:blank') second_tab.<API key>() self.tracing_controller.StartTracing(self.config) first_tab.AddTimelineMarker('background-tab') second_tab.AddTimelineMarker('foreground-tab') trace = self.tracing_controller.StopTracing() model = timeline_model.TimelineModel(trace) # Check that we can find the marker injected into the foreground tab. renderer_thread = model.<API key>(second_tab.id) markers = list(renderer_thread.IterTimelineMarkers([ 'foreground-tab', 'background-tab'])) self.assertEqual(len(markers), 1) self.assertEqual(markers[0].name, 'foreground-tab') # Check that trying to find the background tab rases an error. with self.assertRaises(AssertionError): model.<API key>(first_tab.id)
'use strict'; const ChildProcess = require('child_process'); const Fs = require('fs'); const internals = { linter: __dirname + '/../linter/index.js' }; exports.lint = function (settings) { return new Promise((resolve, reject) => { const linterPath = (settings.linter && settings.linter !== 'eslint') ? settings.linter : internals.linter; let linterOptions; try { linterOptions = JSON.parse(settings['lint-options'] || '{}'); } catch (err) { return reject(new Error('lint-options could not be parsed')); } linterOptions.fix = settings['lint-fix']; const child = ChildProcess.fork(linterPath, [JSON.stringify(linterOptions)], { cwd: settings.lintingPath }); child.once('message', (message) => { child.kill(); const result = { lint: message, totalErrors: 0, totalWarnings: 0 }; result.lint.forEach((lint) => { let errors = 0; let warnings = 0; lint.errors.forEach((err) => { if (err.severity === 'ERROR') { errors++; } else { warnings++; } }); lint.totalErrors = errors; lint.totalWarnings = warnings; result.totalErrors += errors; result.totalWarnings += warnings; if (lint.fix) { Fs.writeFileSync(lint.filename, lint.fix.output); } }); result.total = result.totalErrors + result.totalWarnings; return resolve(result); }); }); };
#include <tests_internal.h> #define NAME_SIZE 250 static void test_ksResize (void) { int i; KeySet * ks = 0; KeySet * copy = ksNew (0, KS_END); char name[NAME_SIZE]; ks = ksNew (20, keyNew ("user:/test01", KEY_END), keyNew ("user:/test02", KEY_END), keyNew ("user:/test03", KEY_END), keyNew ("user:/test04", KEY_END), keyNew ("user:/test05", KEY_END), keyNew ("user:/test11", KEY_END), keyNew ("user:/test12", KEY_END), keyNew ("user:/test13", KEY_END), keyNew ("user:/test14", KEY_END), keyNew ("user:/test15", KEY_END), keyNew ("user:/test21", KEY_END), keyNew ("user:/test22", KEY_END), keyNew ("user:/test23", KEY_END), keyNew ("user:/test24", KEY_END), keyNew ("user:/test25", KEY_END), keyNew ("user:/test31", KEY_END), keyNew ("user:/test32", KEY_END), keyNew ("user:/test33", KEY_END), keyNew ("user:/test34", KEY_END), keyNew ("user:/test35", KEY_END), KS_END); succeed_if (ksGetAlloc (ks) == 20, "20 keys with alloc 20 should work"); ksDel (ks); printf ("Test resize of keyset\n"); exit_if_fail ((ks = ksNew (0, KS_END)) != 0, "could not create new keyset"); for (i = 0; i < 100; i++) { snprintf (name, NAME_SIZE, "user:/test%d", i); ksAppendKey (ks, keyNew (name, KEY_END)); if (i >= 63) { succeed_if (ksGetAlloc (ks) == 127, "allocation size wrong"); } else if (i >= 31) { succeed_if (ksGetAlloc (ks) == 63, "allocation size wrong"); } else if (i >= 15) { succeed_if (ksGetAlloc (ks) == 31, "allocation size wrong"); } else if (i >= 0) { succeed_if (ksGetAlloc (ks) == 15, "allocation size wrong"); } } succeed_if (ksGetSize (ks) == 100, "could not append 100 keys"); succeed_if (ksGetAlloc (ks) == 127, "allocation size wrong"); for (i = 100; i >= 0; i { keyDel (ksPop (ks)); if (i >= 64) { succeed_if (ksGetAlloc (ks) == 127, "allocation size wrong"); } else if (i >= 32) { succeed_if (ksGetAlloc (ks) == 63, "allocation size wrong"); } else if (i >= 16) { succeed_if (ksGetAlloc (ks) == 31, "allocation size wrong"); } else if (i >= 0) { succeed_if (ksGetAlloc (ks) == 15, "allocation size wrong"); } } succeed_if (ksGetSize (ks) == 0, "could not pop 100 keys"); succeed_if (ksGetAlloc (ks) == 15, "allocation size wrong"); ksDel (ks); exit_if_fail ((ks = ksNew (0, KS_END)) != 0, "could not create new keyset"); ksResize (ks, 100); succeed_if (ksGetAlloc (ks) == 100, "allocation size wrong"); for (i = 0; i < 100; i++) { snprintf (name, NAME_SIZE, "user:/test%d", i); ksAppendKey (ks, keyNew (name, KEY_END)); succeed_if (ksGetAlloc (ks) == 100, "allocation size wrong"); } succeed_if (ksGetSize (ks) == 100, "could not append 100 keys"); succeed_if (ksGetAlloc (ks) == 100, "allocation size wrong"); ksDel (ks); ks = #include "data_keyset.c" succeed_if (ksGetSize (ks) == 102, "Problem loading keyset with 102 keys"); succeed_if (ksGetAlloc (ks) == 102, "alloc size wrong"); ksCopy (copy, ks); succeed_if (ksGetSize (copy) == 102, "Problem copy keyset with 102 keys"); succeed_if (ksGetAlloc (copy) == 127, "alloc of copy size wrong"); compare_keyset (copy, ks); ksClear (copy); // useless, just test for double free ksCopy (copy, ks); succeed_if (ksGetSize (copy) == 102, "Problem copy keyset with 102 keys"); succeed_if (ksGetAlloc (copy) == 127, "alloc of copy size wrong"); compare_keyset (copy, ks); ksDel (copy); ksDel (ks); } int main (int argc, char ** argv) { printf ("KEYSET SIZE TESTS\n"); printf ("==================\n\n"); init (argc, argv); test_ksResize (); printf ("\ntest_size RESULTS: %d test(s) done. %d error(s).\n", nbTest, nbError); return nbError; }
# Use of this source code is governed by a BSD-style all: index.html CLEANFILES=get.bin final-test.bin a.out clean: rm -f $(CLEANFILES)
#ifndef <API key> #define <API key> #include "<API key>.h" #include <QmitkAbstractView.h> #include "mitkColorProperty.h" #include "mitkTubeGraph.h" #include "<API key>.h" #include "<API key>.h" #include <QCheckBox> #include <QSignalMapper> /*! * * \brief <API key> * */ class QmitkTubeGraphView: public QmitkAbstractView { // this is needed for all Qt objects that should have a MOC object (everything that derives from QObject) Q_OBJECT typedef mitk::TubeGraphProperty::LabelGroup LabelGroupType; typedef LabelGroupType::Label LabelType; public: static const std::string VIEW_ID; /** * @brief Constructor. **/ QmitkTubeGraphView(); /** * @brief Destructor. */ virtual ~QmitkTubeGraphView(); virtual void CreateQtPartControl(QWidget *parent) override; /** \brief Method to create the connections for the component. This Method is obligatory even if no connections is needed*/ virtual void CreateConnections(); protected slots: //active tube graph void <API key>(int); //activation mode void <API key>(); void OnDeselectAllTubes(); void OnSetRootToggled(bool); void OnTabSwitched(int); //attributation tab void OnAddingLabelGroup(); void OnRemoveLabelGroup(); //annotation tab void OnAddingAnnotation(); void OnRemoveAnnotation(); //edit tab void <API key>(); void OnSeperateSelection(); void OnDeleteSelection(); //label group void <API key>(bool, QString labelName, QString labelGroupName); void OnLabelChanged(QString labelName, QString labelGroupName); void OnLabelColorChanged(mitk::Color color, QString labelName, QString labelGroupName); protected: mitk::<API key>::ActivationMode GetActivationMode(); virtual void SetFocus() override; virtual void NodeRemoved(const mitk::DataNode* node) override; \brief called by QmitkAbstractView when DataManager's selection has changed virtual void OnSelectionChanged( berry::IWorkbenchPart::Pointer source,const QList<mitk::DataNode::Pointer>& nodes ) override; Ui::<API key> m_Controls; // the Qt parent of our GUI (NOT of this object) QWidget* m_Parent; private: void <API key>(); void <API key>(LabelGroupType* labelGroup); void <API key>(); void SetTabsEnable(bool enable); void UpdateLabelGroups(); void UpdateAnnotation(); void <API key>(); void <API key>(); mitk::TubeGraph::Pointer m_ActiveTubeGraph; mitk::TubeGraphProperty::Pointer m_ActiveProperty; mitk::<API key>::Pointer m_ActiveInteractor; mitk::<API key>::ActivationMode m_ActivationMode; /* std::vector<QString> m_LabelGroupName; std::vector<QString> m_LabelName;*/ unsigned int <API key>; }; #endif//<API key>
#include <stdio.h> #include <boost/filesystem/operations.hpp> #include <boost/filesystem/path.hpp> #include <gtest/gtest.h> #include <osquery/events.h> #include <osquery/filesystem.h> #include <osquery/tables.h> #include "osquery/events/linux/inotify.h" #include "osquery/tests/test_util.h" namespace fs = boost::filesystem; namespace osquery { const int kMaxEventLatency = 3000; class INotifyTests : public testing::Test { protected: void SetUp() override { // INotify will use data from the config and config parsers. Registry::registry("config_parser")->setUp(); // Create a basic path trigger, this is a file path. real_test_path = <API key> + "inotify-trigger" + std::to_string(rand() % 10000 + 10000); // Create a similar directory for embedded paths and directories. real_test_dir = <API key> + "inotify-triggers" + std::to_string(rand() % 10000 + 10000); // Create the embedded paths. real_test_dir_path = real_test_dir + "/1"; real_test_sub_dir = real_test_dir + "/2"; <API key> = real_test_sub_dir + "/1"; } void TearDown() override { // End the event loops, and join on the threads. remove(real_test_path); fs::remove_all(real_test_dir); } void StartEventLoop() { event_pub_ = std::make_shared<<API key>>(); auto status = EventFactory::<API key>(event_pub_); FILE* fd = fopen(real_test_path.c_str(), "w"); fclose(fd); temp_thread_ = std::thread(EventFactory::run, "inotify"); } void StopEventLoop() { while (!event_pub_->hasStarted()) { ::usleep(20); } EventFactory::end(true); temp_thread_.join(); } void SubscriptionAction(const std::string& path, uint32_t mask = IN_ALL_EVENTS, EventCallback ec = nullptr) { auto sc = std::make_shared<<API key>>(); sc->path = path; sc->mask = mask; EventFactory::addSubscription("inotify", "TestSubscriber", sc, ec); event_pub_->configure(); } bool WaitForEvents(size_t max, size_t num_events = 0) { size_t delay = 0; while (delay <= max * 1000) { if (num_events > 0 && event_pub_->numEvents() >= num_events) { return true; } else if (num_events == 0 && event_pub_->numEvents() > 0) { return true; } delay += 50; ::usleep(50); } return false; } void TriggerEvent(const std::string& path) { FILE* fd = fopen(path.c_str(), "w"); fputs("inotify", fd); fclose(fd); } void RemoveAll(std::shared_ptr<<API key>>& pub) { pub->subscriptions_.clear(); // Reset monitors. std::vector<std::string> monitors; for (const auto& path : pub->path_descriptors_) { monitors.push_back(path.first); } for (const auto& path : monitors) { pub->removeMonitor(path, true); } } protected: Internal state managers: publisher reference. std::shared_ptr<<API key>> event_pub_{nullptr}; Internal state managers: event publisher thread. std::thread temp_thread_; Transient paths ./inotify-trigger. std::string real_test_path; Transient paths ./inotify-triggers/. std::string real_test_dir; Transient paths ./inotify-triggers/1. std::string real_test_dir_path; Transient paths ./inotify-triggers/2/. std::string real_test_sub_dir; Transient paths ./inotify-triggers/2/1. std::string <API key>; }; TEST_F(INotifyTests, <API key>) { auto pub = std::make_shared<<API key>>(); auto status = EventFactory::<API key>(pub); EXPECT_TRUE(status.ok()); // Make sure only one event type exists EXPECT_EQ(EventFactory::numEventPublishers(), 1U); // And deregister status = EventFactory::<API key>("inotify"); EXPECT_TRUE(status.ok()); } TEST_F(INotifyTests, test_inotify_init) { // Handle should not be initialized during ctor. auto event_pub = std::make_shared<<API key>>(); EXPECT_FALSE(event_pub->isHandleOpen()); // Registering the event type initializes inotify. auto status = EventFactory::<API key>(event_pub); EXPECT_TRUE(status.ok()); EXPECT_TRUE(event_pub->isHandleOpen()); // Similarly deregistering closes the handle. EventFactory::<API key>("inotify"); EXPECT_FALSE(event_pub->isHandleOpen()); } TEST_F(INotifyTests, <API key>) { auto pub = std::make_shared<<API key>>(); EventFactory::<API key>(pub); // This subscription path is fake, and will succeed. auto mc = std::make_shared<<API key>>(); mc->path = "/this/path/is/fake"; auto subscription = Subscription::create("TestSubscriber", mc); auto status = EventFactory::addSubscription("inotify", subscription); EXPECT_TRUE(status.ok()); EventFactory::<API key>("inotify"); } TEST_F(INotifyTests, <API key>) { auto pub = std::make_shared<<API key>>(); EventFactory::<API key>(pub); // This subscription path *should* be real. auto mc = std::make_shared<<API key>>(); mc->path = "/"; mc->mask = IN_ALL_EVENTS; auto subscription = Subscription::create("TestSubscriber", mc); auto status = EventFactory::addSubscription("inotify", subscription); EXPECT_TRUE(status.ok()); EventFactory::<API key>("inotify"); } TEST_F(INotifyTests, <API key>) { auto pub = std::make_shared<<API key>>(); pub->addMonitor("/etc", IN_ALL_EVENTS, false, false); EXPECT_EQ(pub->path_descriptors_.count("/etc"), 1U); // This will fail because there is no trailing "/" at the end. // The configure component should take care of these paths. EXPECT_FALSE(pub->isPathMonitored("/etc/passwd")); pub->path_descriptors_.clear(); // Calling addMonitor the correct way. pub->addMonitor("/etc/", IN_ALL_EVENTS, false, false); EXPECT_TRUE(pub->isPathMonitored("/etc/passwd")); pub->path_descriptors_.clear(); // Test the matching capability. { auto sc = pub-><API key>(); sc->path = "/etc"; pub->monitorSubscription(sc, false); EXPECT_EQ(sc->path, "/etc/"); EXPECT_TRUE(pub->isPathMonitored("/etc/")); EXPECT_TRUE(pub->isPathMonitored("/etc/passwd")); } mc->path = real_test_dir + "/*/1";
#include "std.h" #include "mordor/exception.h" namespace Mordor { StdStream::StdStream(IOManager *ioManager, Scheduler *scheduler, int stream) { #ifdef WINDOWS HANDLE hFile = GetStdHandle(stream); if (hFile == <API key>) <API key>("GetStdHandle"); if (hFile == NULL) <API key>(<API key>, "GetStdHandle"); init(hFile, ioManager, scheduler, false); #else init(stream, ioManager, scheduler, stream); #endif } }
// Use of this source code is governed by a BSD-style // Annotate Ref in Prog with C types by parsing gcc debug output. // Conversion of debug output to Go types. package main import ( "bytes" "debug/dwarf" "debug/elf" "debug/macho" "debug/pe" "encoding/binary" "errors" "flag" "fmt" "go/ast" "go/parser" "go/token" "os" "strconv" "strings" "unicode" "unicode/utf8" ) var debugDefine = flag.Bool("debug-define", false, "print relevant #defines") var debugGcc = flag.Bool("debug-gcc", false, "print gcc invocations") var nameToC = map[string]string{ "schar": "signed char", "uchar": "unsigned char", "ushort": "unsigned short", "uint": "unsigned int", "ulong": "unsigned long", "longlong": "long long", "ulonglong": "unsigned long long", "complexfloat": "float complex", "complexdouble": "double complex", } // cname returns the C name to use for C.s. // The expansions are listed in nameToC and also // struct_foo becomes "struct foo", and similarly for // union and enum. func cname(s string) string { if t, ok := nameToC[s]; ok { return t } if strings.HasPrefix(s, "struct_") { return "struct " + s[len("struct_"):] } if strings.HasPrefix(s, "union_") { return "union " + s[len("union_"):] } if strings.HasPrefix(s, "enum_") { return "enum " + s[len("enum_"):] } if strings.HasPrefix(s, "sizeof_") { return "sizeof(" + cname(s[len("sizeof_"):]) + ")" } return s } // <API key> processes the import C preamble, and discards // all #cgo CFLAGS and LDFLAGS directives, so they don't make their // way into _cgo_export.h. func (f *File) <API key>() { linesIn := strings.Split(f.Preamble, "\n") linesOut := make([]string, 0, len(linesIn)) for _, line := range linesIn { l := strings.TrimSpace(line) if len(l) < 5 || l[:4] != "#cgo" || !unicode.IsSpace(rune(l[4])) { linesOut = append(linesOut, line) } } f.Preamble = strings.Join(linesOut, "\n") } // addToFlag appends args to flag. All flags are later written out onto the // _cgo_flags file for the build system to use. func (p *Package) addToFlag(flag string, args []string) { p.CgoFlags[flag] = append(p.CgoFlags[flag], args...) if flag == "CFLAGS" { // We'll also need these when preprocessing for dwarf information. p.GccOptions = append(p.GccOptions, args...) } } // splitQuoted splits the string s around each instance of one or more consecutive // white space characters while taking into account quotes and escaping, and // returns an array of substrings of s or an empty list if s contains only white space. // Single quotes and double quotes are recognized to prevent splitting within the // quoted region, and are removed from the resulting substrings. If a quote in s // isn't closed err will be set and r will have the unclosed argument as the // last element. The backslash is used for escaping. // For example, the following string: // `a b:"c d" 'e''f' "g\""` // Would be parsed as: // []string{"a", "b:c d", "ef", `g"`} func splitQuoted(s string) (r []string, err error) { var args []string arg := make([]rune, len(s)) escaped := false quoted := false quote := '\x00' i := 0 for _, r := range s { switch { case escaped: escaped = false case r == '\\': escaped = true continue case quote != 0: if r == quote { quote = 0 continue } case r == '"' || r == '\'': quoted = true quote = r continue case unicode.IsSpace(r): if quoted || i > 0 { quoted = false args = append(args, string(arg[:i])) i = 0 } continue } arg[i] = r i++ } if quoted || i > 0 { args = append(args, string(arg[:i])) } if quote != 0 { err = errors.New("unclosed quote") } else if escaped { err = errors.New("unfinished escaping") } return args, err } var safeBytes = []byte(`+-.,/0123456789:=<API key>\<API key>`) func safeName(s string) bool { if s == "" { return false } for i := 0; i < len(s); i++ { if c := s[i]; c < 0x80 && bytes.IndexByte(safeBytes, c) < 0 { return false } } return true } // Translate rewrites f.AST, the original Go input, to remove // references to the imported package C, replacing them with // references to the equivalent Go types, functions, and variables. func (p *Package) Translate(f *File) { for _, cref := range f.Ref { // Convert C.ulong to C.unsigned long, etc. cref.Name.C = cname(cref.Name.Go) } p.loadDefines(f) needType := p.guessKinds(f) if len(needType) > 0 { p.loadDWARF(f, needType) } p.rewriteRef(f) } // loadDefines coerces gcc into spitting out the #defines in use // in the file f and saves relevant renamings in f.Name[name].Define. func (p *Package) loadDefines(f *File) { var b bytes.Buffer b.WriteString(builtinProlog) b.WriteString(f.Preamble) stdout := p.gccDefines(b.Bytes()) for _, line := range strings.Split(stdout, "\n") { if len(line) < 9 || line[0:7] != "#define" { continue } line = strings.TrimSpace(line[8:]) var key, val string spaceIndex := strings.Index(line, " ") tabIndex := strings.Index(line, "\t") if spaceIndex == -1 && tabIndex == -1 { continue } else if tabIndex == -1 || (spaceIndex != -1 && spaceIndex < tabIndex) { key = line[0:spaceIndex] val = strings.TrimSpace(line[spaceIndex:]) } else { key = line[0:tabIndex] val = strings.TrimSpace(line[tabIndex:]) } if n := f.Name[key]; n != nil { if *debugDefine { fmt.Fprintf(os.Stderr, "#define %s %s\n", key, val) } n.Define = val } } } // guessKinds tricks gcc into revealing the kind of each // name xxx for the references C.xxx in the Go input. // The kind is either a constant, type, or variable. func (p *Package) guessKinds(f *File) []*Name { // Coerce gcc into telling us whether each name is // a type, a value, or undeclared. We compile a function // containing the line: // name; // If name is a type, gcc will print: // cgo-test:2: warning: useless type name in empty declaration // If name is a value, gcc will print // cgo-test:2: warning: statement with no effect // If name is undeclared, gcc will print // cgo-test:2: error: 'name' undeclared (first use in this function) // A line number directive causes the line number to // correspond to the index in the names array. // The line also has an enum declaration: // name; enum { _cgo_enum_1 = name }; // If name is not a constant, gcc will print: // cgo-test:4: error: enumerator value for '_cgo_enum_4' is not an integer constant // we assume lines without that error are constants. // Make list of names that need sniffing, type lookup. toSniff := make([]*Name, 0, len(f.Name)) needType := make([]*Name, 0, len(f.Name)) for _, n := range f.Name { // If we've already found this name as a #define // and we can translate it as a constant value, do so. if n.Define != "" { ok := false if _, err := strconv.Atoi(n.Define); err == nil { ok = true } else if n.Define[0] == '"' || n.Define[0] == '\'' { if _, err := parser.ParseExpr(n.Define); err == nil { ok = true } } if ok { n.Kind = "const" // Turn decimal into hex, just for consistency // with enum-derived constants. Otherwise // in the cgo -godefs output half the constants // are in hex and half are in whatever the #define used. i, err := strconv.ParseInt(n.Define, 0, 64) if err == nil { n.Const = fmt.Sprintf("%#x", i) } else { n.Const = n.Define } continue } if isName(n.Define) { n.C = n.Define } } // If this is a struct, union, or enum type name, // record the kind but also that we need type information. if strings.HasPrefix(n.C, "struct ") || strings.HasPrefix(n.C, "union ") || strings.HasPrefix(n.C, "enum ") { n.Kind = "type" i := len(needType) needType = needType[0 : i+1] needType[i] = n continue } i := len(toSniff) toSniff = toSniff[0 : i+1] toSniff[i] = n } if len(toSniff) == 0 { return needType } var b bytes.Buffer b.WriteString(builtinProlog) b.WriteString(f.Preamble) b.WriteString("void __cgo__f__(void) {\n") b.WriteString("#line 1 \"cgo-test\"\n") for i, n := range toSniff { fmt.Fprintf(&b, "%s; \nenum { _cgo_enum_%d = %s }; \n", n.C, i, i, n.C, i) } b.WriteString("}\n") stderr := p.gccErrors(b.Bytes()) if stderr == "" { fatalf("gcc produced no output\non input:\n%s", b.Bytes()) } names := make([]*Name, len(toSniff)) copy(names, toSniff) isConst := make([]bool, len(toSniff)) for i := range isConst { isConst[i] = true // until proven otherwise } for _, line := range strings.Split(stderr, "\n") { if len(line) < 9 || line[0:9] != "cgo-test:" { // the user will see any compiler errors when the code is compiled later. continue } line = line[9:] colon := strings.Index(line, ":") if colon < 0 { continue } i, err := strconv.Atoi(line[0:colon]) if err != nil { continue } i = (i - 1) / 2 what := "" switch { default: continue case strings.Contains(line, ": useless type name in empty declaration"), strings.Contains(line, ": declaration does not declare anything"), strings.Contains(line, ": unexpected type name"): what = "type" isConst[i] = false case strings.Contains(line, ": statement with no effect"), strings.Contains(line, ": expression result unused"): what = "not-type" // const or func or var case strings.Contains(line, "undeclared"): error_(token.NoPos, "%s", strings.TrimSpace(line[colon+1:])) case strings.Contains(line, "is not an integer constant"): isConst[i] = false continue } n := toSniff[i] if n == nil { continue } toSniff[i] = nil n.Kind = what j := len(needType) needType = needType[0 : j+1] needType[j] = n } for i, b := range isConst { if b { names[i].Kind = "const" if toSniff[i] != nil && names[i].Const == "" { j := len(needType) needType = needType[0 : j+1] needType[j] = names[i] } } } for _, n := range toSniff { if n == nil { continue } if n.Kind != "" { continue } error_(token.NoPos, "could not determine kind of name for C.%s", n.Go) } if nerrors > 0 { fatalf("unresolved names") } return needType } // loadDWARF parses the DWARF debug information generated // by gcc to learn the details of the constants, variables, and types // being referred to as C.xxx. func (p *Package) loadDWARF(f *File, names []*Name) { // Extract the types from the DWARF section of an object // from a well-formed C program. Gcc only generates DWARF info // for symbols in the object file, so it is not enough to print the // preamble and hope the symbols we care about will be there. // Instead, emit // typeof(names[i]) *__cgo__i; // for each entry in names and then dereference the type we // learn for __cgo__i. var b bytes.Buffer b.WriteString(builtinProlog) b.WriteString(f.Preamble) for i, n := range names { fmt.Fprintf(&b, "typeof(%s) *__cgo__%d;\n", n.C, i) if n.Kind == "const" { fmt.Fprintf(&b, "enum { __cgo_enum__%d = %s };\n", i, n.C) } } // Apple's LLVM-based gcc does not include the enumeration // names and values in its DWARF debug output. In case we're // using such a gcc, create a data block initialized with the values. // We can read them out of the object file. fmt.Fprintf(&b, "long long __cgodebug_data[] = {\n") for _, n := range names { if n.Kind == "const" { fmt.Fprintf(&b, "\t%s,\n", n.C) } else { fmt.Fprintf(&b, "\t0,\n") } } // for the last entry, we can not use 0, otherwise // in case all __cgodebug_data is zero initialized, // LLVM-based gcc will place the it in the __DATA.__common // zero-filled section (our debug/macho doesn't support // this) fmt.Fprintf(&b, "\t1\n") fmt.Fprintf(&b, "};\n") d, bo, debugData := p.gccDebug(b.Bytes()) enumVal := make([]int64, len(debugData)/8) for i := range enumVal { enumVal[i] = int64(bo.Uint64(debugData[i*8:])) } // Scan DWARF info for top-level TagVariable entries with AttrName __cgo__i. types := make([]dwarf.Type, len(names)) enums := make([]dwarf.Offset, len(names)) nameToIndex := make(map[*Name]int) for i, n := range names { nameToIndex[n] = i } nameToRef := make(map[*Name]*Ref) for _, ref := range f.Ref { nameToRef[ref.Name] = ref } r := d.Reader() for { e, err := r.Next() if err != nil { fatalf("reading DWARF entry: %s", err) } if e == nil { break } switch e.Tag { case dwarf.TagEnumerationType: offset := e.Offset for { e, err := r.Next() if err != nil { fatalf("reading DWARF entry: %s", err) } if e.Tag == 0 { break } if e.Tag == dwarf.TagEnumerator { entryName := e.Val(dwarf.AttrName).(string) if strings.HasPrefix(entryName, "__cgo_enum__") { n, _ := strconv.Atoi(entryName[len("__cgo_enum__"):]) if 0 <= n && n < len(names) { enums[n] = offset } } } } case dwarf.TagVariable: name, _ := e.Val(dwarf.AttrName).(string) typOff, _ := e.Val(dwarf.AttrType).(dwarf.Offset) if name == "" || typOff == 0 { fatalf("malformed DWARF TagVariable entry") } if !strings.HasPrefix(name, "__cgo__") { break } typ, err := d.Type(typOff) if err != nil { fatalf("loading DWARF type: %s", err) } t, ok := typ.(*dwarf.PtrType) if !ok || t == nil { fatalf("internal error: %s has non-pointer type", name) } i, err := strconv.Atoi(name[7:]) if err != nil { fatalf("malformed __cgo__ name: %s", name) } if enums[i] != 0 { t, err := d.Type(enums[i]) if err != nil { fatalf("loading DWARF type: %s", err) } types[i] = t } else { types[i] = t.Type } } if e.Tag != dwarf.TagCompileUnit { r.SkipChildren() } } // Record types and typedef information. var conv typeConv conv.Init(p.PtrSize, p.IntSize) for i, n := range names { if types[i] == nil { continue } pos := token.NoPos if ref, ok := nameToRef[n]; ok { pos = ref.Pos() } f, fok := types[i].(*dwarf.FuncType) if n.Kind != "type" && fok { n.Kind = "func" n.FuncType = conv.FuncType(f, pos) } else { n.Type = conv.Type(types[i], pos) if enums[i] != 0 && n.Type.EnumValues != nil { k := fmt.Sprintf("__cgo_enum__%d", i) n.Kind = "const" n.Const = fmt.Sprintf("%#x", n.Type.EnumValues[k]) // Remove injected enum to ensure the value will deep-compare // equally in future loads of the same constant. delete(n.Type.EnumValues, k) } // Prefer debug data over DWARF debug output, if we have it. if n.Kind == "const" && i < len(enumVal) { n.Const = fmt.Sprintf("%#x", enumVal[i]) } } } } // rewriteRef rewrites all the C.xxx references in f.AST to refer to the // Go equivalents, now that we have figured out the meaning of all // the xxx. In *godefs or *cdefs mode, rewriteRef replaces the names // with full definitions instead of mangled names. func (p *Package) rewriteRef(f *File) { // Assign mangled names. for _, n := range f.Name { if n.Kind == "not-type" { n.Kind = "var" } if n.Mangle == "" { // When using gccgo variables have to be // exported so that they become global symbols // that the C code can refer to. prefix := "_C" if *gccgo && n.Kind == "var" { prefix = "C" } n.Mangle = prefix + n.Kind + "_" + n.Go } } // Now that we have all the name types filled in, // scan through the Refs to identify the ones that // are trying to do a ,err call. Also check that // functions are only used in calls. for _, r := range f.Ref { if r.Name.Kind == "const" && r.Name.Const == "" { error_(r.Pos(), "unable to find value of constant C.%s", r.Name.Go) } var expr ast.Expr = ast.NewIdent(r.Name.Mangle) // default switch r.Context { case "call", "call2": if r.Name.Kind != "func" { if r.Name.Kind == "type" { r.Context = "type" expr = r.Name.Type.Go break } error_(r.Pos(), "call of non-function C.%s", r.Name.Go) break } if r.Context == "call2" { // Invent new Name for the two-result function. n := f.Name["2"+r.Name.Go] if n == nil { n = new(Name) *n = *r.Name n.AddError = true n.Mangle = "_C2func_" + n.Go f.Name["2"+r.Name.Go] = n } expr = ast.NewIdent(n.Mangle) r.Name = n break } case "expr": if r.Name.Kind == "func" { error_(r.Pos(), "must call C.%s", r.Name.Go) } if r.Name.Kind == "type" { // Okay - might be new(T) expr = r.Name.Type.Go } if r.Name.Kind == "var" { expr = &ast.StarExpr{X: expr} } case "type": if r.Name.Kind != "type" { error_(r.Pos(), "expression C.%s used as type", r.Name.Go) } else if r.Name.Type == nil { // Use of C.enum_x, C.struct_x or C.union_x without C definition. // GCC won't raise an error when using pointers to such unknown types. error_(r.Pos(), "type C.%s: undefined C type '%s'", r.Name.Go, r.Name.C) } else { expr = r.Name.Type.Go } default: if r.Name.Kind == "func" { error_(r.Pos(), "must call C.%s", r.Name.Go) } } if *godefs || *cdefs { // Substitute definition for mangled type name. if id, ok := expr.(*ast.Ident); ok { if t := typedef[id.Name]; t != nil { expr = t.Go } if id.Name == r.Name.Mangle && r.Name.Const != "" { expr = ast.NewIdent(r.Name.Const) } } } *r.Expr = expr } } // gccName returns the name of the compiler to run. Use $CC if set in // the environment, otherwise just "gcc". func (p *Package) gccName() string { // Use $CC if set, since that's what the build uses. if ret := os.Getenv("CC"); ret != "" { return ret } // Fall back to $GCC if set, since that's what we used to use. if ret := os.Getenv("GCC"); ret != "" { return ret } return "gcc" } // gccMachine returns the gcc -m flag to use, either "-m32", "-m64" or "-marm". func (p *Package) gccMachine() []string { switch goarch { case "amd64": return []string{"-m64"} case "386": return []string{"-m32"} case "arm": return []string{"-marm"} // not thumb } return nil } func gccTmp() string { return *objDir + "_cgo_.o" } // gccCmd returns the gcc command line to use for compiling // the input. func (p *Package) gccCmd() []string { c := []string{ p.gccName(), "-Wall", // many warnings "-Werror", // warnings are errors "-o" + gccTmp(), // write object to tmp "-gdwarf-2", // generate DWARF v2 debugging symbols "-<API key>", // gets rid of e.g. untyped enum otherwise "-c", // do not link "-xc", // input language is C } if strings.Contains(p.gccName(), "clang") { c = append(c, "-ferror-limit=0", // Apple clang version 1.7 (tags/Apple/clang-77) (based on LLVM 2.9svn) // doesn't have -<API key>, so we need yet another // flag to disable the warning. Yes, really good diagnostics, clang. "-<API key>", "-<API key>", "-Wno-unused-function", "-Qunused-arguments", ) } c = append(c, p.GccOptions...) c = append(c, p.gccMachine()...) c = append(c, "-") //read input from standard input return c } // gccDebug runs gcc -gdwarf-2 over the C program stdin and // returns the corresponding DWARF data and, if present, debug data block. func (p *Package) gccDebug(stdin []byte) (*dwarf.Data, binary.ByteOrder, []byte) { runGcc(stdin, p.gccCmd()) if f, err := macho.Open(gccTmp()); err == nil { d, err := f.DWARF() if err != nil { fatalf("cannot load DWARF output from %s: %v", gccTmp(), err) } var data []byte if f.Symtab != nil { for i := range f.Symtab.Syms { s := &f.Symtab.Syms[i] // Mach-O still uses a leading _ to denote non-assembly symbols. if s.Name == "_"+"__cgodebug_data" { // Found it. Now find data section. if i := int(s.Sect) - 1; 0 <= i && i < len(f.Sections) { sect := f.Sections[i] if sect.Addr <= s.Value && s.Value < sect.Addr+sect.Size { if sdat, err := sect.Data(); err == nil { data = sdat[s.Value-sect.Addr:] } } } } } } return d, f.ByteOrder, data } if f, err := elf.Open(gccTmp()); err == nil { d, err := f.DWARF() if err != nil { fatalf("cannot load DWARF output from %s: %v", gccTmp(), err) } var data []byte symtab, err := f.Symbols() if err == nil { for i := range symtab { s := &symtab[i] if s.Name == "__cgodebug_data" { // Found it. Now find data section. if i := int(s.Section); 0 <= i && i < len(f.Sections) { sect := f.Sections[i] if sect.Addr <= s.Value && s.Value < sect.Addr+sect.Size { if sdat, err := sect.Data(); err == nil { data = sdat[s.Value-sect.Addr:] } } } } } } return d, f.ByteOrder, data } if f, err := pe.Open(gccTmp()); err == nil { d, err := f.DWARF() if err != nil { fatalf("cannot load DWARF output from %s: %v", gccTmp(), err) } var data []byte for _, s := range f.Symbols { if s.Name == "_"+"__cgodebug_data" { if i := int(s.SectionNumber) - 1; 0 <= i && i < len(f.Sections) { sect := f.Sections[i] if s.Value < sect.Size { if sdat, err := sect.Data(); err == nil { data = sdat[s.Value:] } } } } } return d, binary.LittleEndian, data } fatalf("cannot parse gcc output %s as ELF, Mach-O, PE object", gccTmp()) panic("not reached") } // gccDefines runs gcc -E -dM -xc - over the C program stdin // and returns the corresponding standard output, which is the // #defines that gcc encountered while processing the input // and its included files. func (p *Package) gccDefines(stdin []byte) string { base := []string{p.gccName(), "-E", "-dM", "-xc"} base = append(base, p.gccMachine()...) stdout, _ := runGcc(stdin, append(append(base, p.GccOptions...), "-")) return stdout } // gccErrors runs gcc over the C program stdin and returns // the errors that gcc prints. That is, this function expects // gcc to fail. func (p *Package) gccErrors(stdin []byte) string { // TODO(rsc): require failure args := p.gccCmd() // GCC 4.8.0 has a bug: it sometimes does not apply // -Wunused-value to values that are macros defined in system // headers. See issue 5118. Adding -Wsystem-headers avoids // that problem. This will produce additional errors, but it // doesn't matter because we will ignore all errors that are // not marked for the cgo-test file. args = append(args, "-Wsystem-headers") if *debugGcc { fmt.Fprintf(os.Stderr, "$ %s <<EOF\n", strings.Join(args, " ")) os.Stderr.Write(stdin) fmt.Fprint(os.Stderr, "EOF\n") } stdout, stderr, _ := run(stdin, args) if *debugGcc { os.Stderr.Write(stdout) os.Stderr.Write(stderr) } return string(stderr) } // runGcc runs the gcc command line args with stdin on standard input. // If the command exits with a non-zero exit status, runGcc prints // details about what was run and exits. // Otherwise runGcc returns the data written to standard output and standard error. // Note that for some of the uses we expect useful data back // on standard error, but for those uses gcc must still exit 0. func runGcc(stdin []byte, args []string) (string, string) { if *debugGcc { fmt.Fprintf(os.Stderr, "$ %s <<EOF\n", strings.Join(args, " ")) os.Stderr.Write(stdin) fmt.Fprint(os.Stderr, "EOF\n") } stdout, stderr, ok := run(stdin, args) if *debugGcc { os.Stderr.Write(stdout) os.Stderr.Write(stderr) } if !ok { os.Stderr.Write(stderr) os.Exit(2) } return string(stdout), string(stderr) } // A typeConv is a translator from dwarf types to Go types // with equivalent memory layout. type typeConv struct { // Cache of already-translated or in-progress types. m map[dwarf.Type]*Type typedef map[string]ast.Expr // Predeclared types. bool ast.Expr byte ast.Expr // denotes padding int8, int16, int32, int64 ast.Expr uint8, uint16, uint32, uint64, uintptr ast.Expr float32, float64 ast.Expr complex64, complex128 ast.Expr void ast.Expr unsafePointer ast.Expr string ast.Expr goVoid ast.Expr // _Ctype_void, denotes C's void ptrSize int64 intSize int64 } var tagGen int var typedef = make(map[string]*Type) var goIdent = make(map[string]*ast.Ident) func (c *typeConv) Init(ptrSize, intSize int64) { c.ptrSize = ptrSize c.intSize = intSize c.m = make(map[dwarf.Type]*Type) c.bool = c.Ident("bool") c.byte = c.Ident("byte") c.int8 = c.Ident("int8") c.int16 = c.Ident("int16") c.int32 = c.Ident("int32") c.int64 = c.Ident("int64") c.uint8 = c.Ident("uint8") c.uint16 = c.Ident("uint16") c.uint32 = c.Ident("uint32") c.uint64 = c.Ident("uint64") c.uintptr = c.Ident("uintptr") c.float32 = c.Ident("float32") c.float64 = c.Ident("float64") c.complex64 = c.Ident("complex64") c.complex128 = c.Ident("complex128") c.unsafePointer = c.Ident("unsafe.Pointer") c.void = c.Ident("void") c.string = c.Ident("string") c.goVoid = c.Ident("_Ctype_void") } // base strips away qualifiers and typedefs to get the underlying type func base(dt dwarf.Type) dwarf.Type { for { if d, ok := dt.(*dwarf.QualType); ok { dt = d.Type continue } if d, ok := dt.(*dwarf.TypedefType); ok { dt = d.Type continue } break } return dt } // Map from dwarf text names to aliases we use in package "C". var dwarfToName = map[string]string{ "long int": "long", "long unsigned int": "ulong", "unsigned int": "uint", "short unsigned int": "ushort", "short int": "short", "long long int": "longlong", "long long unsigned int": "ulonglong", "signed char": "schar", "float complex": "complexfloat", "double complex": "complexdouble", } const signedDelta = 64 // String returns the current type representation. Format arguments // are assembled within this method so that any changes in mutable // values are taken into account. func (tr *TypeRepr) String() string { if len(tr.Repr) == 0 { return "" } if len(tr.FormatArgs) == 0 { return tr.Repr } return fmt.Sprintf(tr.Repr, tr.FormatArgs...) } // Empty returns true if the result of String would be "". func (tr *TypeRepr) Empty() bool { return len(tr.Repr) == 0 } // Set modifies the type representation. // If fargs are provided, repr is used as a format for fmt.Sprintf. // Otherwise, repr is used unprocessed as the type representation. func (tr *TypeRepr) Set(repr string, fargs ...interface{}) { tr.Repr = repr tr.FormatArgs = fargs } // Type returns a *Type with the same memory layout as // dtype when used as the type of a variable or a struct field. func (c *typeConv) Type(dtype dwarf.Type, pos token.Pos) *Type { if t, ok := c.m[dtype]; ok { if t.Go == nil { fatalf("%s: type conversion loop at %s", lineno(pos), dtype) } return t } // clang won't generate DW_AT_byte_size for pointer types, // so we have to fix it here. if dt, ok := base(dtype).(*dwarf.PtrType); ok && dt.ByteSize == -1 { dt.ByteSize = c.ptrSize } t := new(Type) t.Size = dtype.Size() t.Align = -1 t.C = &TypeRepr{Repr: dtype.Common().Name} c.m[dtype] = t if t.Size < 0 { // Unsized types are [0]byte t.Size = 0 t.Go = c.Opaque(0) if t.C.Empty() { t.C.Set("void") } return t } switch dt := dtype.(type) { default: fatalf("%s: unexpected type: %s", lineno(pos), dtype) case *dwarf.AddrType: if t.Size != c.ptrSize { fatalf("%s: unexpected: %d-byte address type - %s", lineno(pos), t.Size, dtype) } t.Go = c.uintptr t.Align = t.Size case *dwarf.ArrayType: if dt.StrideBitSize > 0 { // Cannot represent bit-sized elements in Go. t.Go = c.Opaque(t.Size) break } gt := &ast.ArrayType{ Len: c.intExpr(dt.Count), } t.Go = gt // publish before recursive call sub := c.Type(dt.Type, pos) t.Align = sub.Align gt.Elt = sub.Go t.C.Set("typeof(%s[%d])", sub.C, dt.Count) case *dwarf.BoolType: t.Go = c.bool t.Align = 1 case *dwarf.CharType: if t.Size != 1 { fatalf("%s: unexpected: %d-byte char type - %s", lineno(pos), t.Size, dtype) } t.Go = c.int8 t.Align = 1 case *dwarf.EnumType: if t.Align = t.Size; t.Align >= c.ptrSize { t.Align = c.ptrSize } t.C.Set("enum " + dt.EnumName) signed := 0 t.EnumValues = make(map[string]int64) for _, ev := range dt.Val { t.EnumValues[ev.Name] = ev.Val if ev.Val < 0 { signed = signedDelta } } switch t.Size + int64(signed) { default: fatalf("%s: unexpected: %d-byte enum type - %s", lineno(pos), t.Size, dtype) case 1: t.Go = c.uint8 case 2: t.Go = c.uint16 case 4: t.Go = c.uint32 case 8: t.Go = c.uint64 case 1 + signedDelta: t.Go = c.int8 case 2 + signedDelta: t.Go = c.int16 case 4 + signedDelta: t.Go = c.int32 case 8 + signedDelta: t.Go = c.int64 } case *dwarf.FloatType: switch t.Size { default: fatalf("%s: unexpected: %d-byte float type - %s", lineno(pos), t.Size, dtype) case 4: t.Go = c.float32 case 8: t.Go = c.float64 } if t.Align = t.Size; t.Align >= c.ptrSize { t.Align = c.ptrSize } case *dwarf.ComplexType: switch t.Size { default: fatalf("%s: unexpected: %d-byte complex type - %s", lineno(pos), t.Size, dtype) case 8: t.Go = c.complex64 case 16: t.Go = c.complex128 } if t.Align = t.Size; t.Align >= c.ptrSize { t.Align = c.ptrSize } case *dwarf.FuncType: // No attempt at translation: would enable calls // directly between worlds, but we need to moderate those. t.Go = c.uintptr t.Align = c.ptrSize case *dwarf.IntType: if dt.BitSize > 0 { fatalf("%s: unexpected: %d-bit int type - %s", lineno(pos), dt.BitSize, dtype) } switch t.Size { default: fatalf("%s: unexpected: %d-byte int type - %s", lineno(pos), t.Size, dtype) case 1: t.Go = c.int8 case 2: t.Go = c.int16 case 4: t.Go = c.int32 case 8: t.Go = c.int64 } if t.Align = t.Size; t.Align >= c.ptrSize { t.Align = c.ptrSize } case *dwarf.PtrType: t.Align = c.ptrSize // Translate void* as unsafe.Pointer if _, ok := base(dt.Type).(*dwarf.VoidType); ok { t.Go = c.unsafePointer t.C.Set("void*") break } gt := &ast.StarExpr{} t.Go = gt // publish before recursive call sub := c.Type(dt.Type, pos) gt.X = sub.Go t.C.Set("%s*", sub.C) case *dwarf.QualType: // Ignore qualifier. t = c.Type(dt.Type, pos) c.m[dtype] = t return t case *dwarf.StructType: // Convert to Go struct, being careful about alignment. // Have to give it a name to simulate C "struct foo" references. tag := dt.StructName if tag == "" { tag = "__" + strconv.Itoa(tagGen) tagGen++ } else if t.C.Empty() { t.C.Set(dt.Kind + " " + tag) } name := c.Ident("_Ctype_" + dt.Kind + "_" + tag) t.Go = name // publish before recursive calls goIdent[name.Name] = name switch dt.Kind { case "class", "union": t.Go = c.Opaque(t.Size) if t.C.Empty() { t.C.Set("typeof(unsigned char[%d])", t.Size) } t.Align = 1 // TODO: should probably base this on field alignment. typedef[name.Name] = t case "struct": g, csyntax, align := c.Struct(dt, pos) if t.C.Empty() { t.C.Set(csyntax) } t.Align = align tt := *t if tag != "" { tt.C = &TypeRepr{"struct %s", []interface{}{tag}} } tt.Go = g typedef[name.Name] = &tt } case *dwarf.TypedefType: // Record typedef for printing. if dt.Name == "_GoString_" { // Special C name for Go string type. // Knows string layout used by compilers: pointer plus length, // which rounds up to 2 pointers after alignment. t.Go = c.string t.Size = c.ptrSize * 2 t.Align = c.ptrSize break } if dt.Name == "_GoBytes_" { // Special C name for Go []byte type. // Knows slice layout used by compilers: pointer, length, cap. t.Go = c.Ident("[]byte") t.Size = c.ptrSize + 4 + 4 t.Align = c.ptrSize break } name := c.Ident("_Ctype_" + dt.Name) goIdent[name.Name] = name t.Go = name // publish before recursive call sub := c.Type(dt.Type, pos) t.Size = sub.Size t.Align = sub.Align if _, ok := typedef[name.Name]; !ok { tt := *t tt.Go = sub.Go typedef[name.Name] = &tt } if *godefs || *cdefs { t.Go = sub.Go } case *dwarf.UcharType: if t.Size != 1 { fatalf("%s: unexpected: %d-byte uchar type - %s", lineno(pos), t.Size, dtype) } t.Go = c.uint8 t.Align = 1 case *dwarf.UintType: if dt.BitSize > 0 { fatalf("%s: unexpected: %d-bit uint type - %s", lineno(pos), dt.BitSize, dtype) } switch t.Size { default: fatalf("%s: unexpected: %d-byte uint type - %s", lineno(pos), t.Size, dtype) case 1: t.Go = c.uint8 case 2: t.Go = c.uint16 case 4: t.Go = c.uint32 case 8: t.Go = c.uint64 } if t.Align = t.Size; t.Align >= c.ptrSize { t.Align = c.ptrSize } case *dwarf.VoidType: t.Go = c.goVoid t.C.Set("void") t.Align = 1 } switch dtype.(type) { case *dwarf.AddrType, *dwarf.BoolType, *dwarf.CharType, *dwarf.IntType, *dwarf.FloatType, *dwarf.UcharType, *dwarf.UintType: s := dtype.Common().Name if s != "" { if ss, ok := dwarfToName[s]; ok { s = ss } s = strings.Join(strings.Split(s, " "), "") // strip spaces name := c.Ident("_Ctype_" + s) tt := *t typedef[name.Name] = &tt if !*godefs && !*cdefs { t.Go = name } } } if t.C.Empty() { fatalf("%s: internal error: did not create C name for %s", lineno(pos), dtype) } return t } // FuncArg returns a Go type with the same memory layout as // dtype when used as the type of a C function argument. func (c *typeConv) FuncArg(dtype dwarf.Type, pos token.Pos) *Type { t := c.Type(dtype, pos) switch dt := dtype.(type) { case *dwarf.ArrayType: // Arrays are passed implicitly as pointers in C. // In Go, we must be explicit. tr := &TypeRepr{} tr.Set("%s*", t.C) return &Type{ Size: c.ptrSize, Align: c.ptrSize, Go: &ast.StarExpr{X: t.Go}, C: tr, } case *dwarf.TypedefType: // C has much more relaxed rules than Go for // implicit type conversions. When the parameter // is type T defined as *X, simulate a little of the // laxness of C by making the argument *X instead of T. if ptr, ok := base(dt.Type).(*dwarf.PtrType); ok { // Unless the typedef happens to point to void* since // Go has special rules around using unsafe.Pointer. if _, void := base(ptr.Type).(*dwarf.VoidType); void { break } t = c.Type(ptr, pos) if t == nil { return nil } // Remember the C spelling, in case the struct // has __attribute__((unavailable)) on it. See issue 2888. t.Typedef = dt.Name } } return t } // FuncType returns the Go type analogous to dtype. // There is no guarantee about matching memory layout. func (c *typeConv) FuncType(dtype *dwarf.FuncType, pos token.Pos) *FuncType { p := make([]*Type, len(dtype.ParamType)) gp := make([]*ast.Field, len(dtype.ParamType)) for i, f := range dtype.ParamType { // gcc's DWARF generator outputs a single DotDotDotType parameter for // function pointers that specify no parameters (e.g. void // (*__cgo_0)()). Treat this special case as void. This case is // invalid according to ISO C anyway (i.e. void (*__cgo_1)(...) is not if _, ok := f.(*dwarf.DotDotDotType); ok && i == 0 { p, gp = nil, nil break } p[i] = c.FuncArg(f, pos) gp[i] = &ast.Field{Type: p[i].Go} } var r *Type var gr []*ast.Field if _, ok := dtype.ReturnType.(*dwarf.VoidType); ok { gr = []*ast.Field{{Type: c.goVoid}} } else if dtype.ReturnType != nil { r = c.Type(dtype.ReturnType, pos) gr = []*ast.Field{{Type: r.Go}} } return &FuncType{ Params: p, Result: r, Go: &ast.FuncType{ Params: &ast.FieldList{List: gp}, Results: &ast.FieldList{List: gr}, }, } } // Identifier func (c *typeConv) Ident(s string) *ast.Ident { return ast.NewIdent(s) } // Opaque type of n bytes. func (c *typeConv) Opaque(n int64) ast.Expr { return &ast.ArrayType{ Len: c.intExpr(n), Elt: c.byte, } } // Expr for integer n. func (c *typeConv) intExpr(n int64) ast.Expr { return &ast.BasicLit{ Kind: token.INT, Value: strconv.FormatInt(n, 10), } } // Add padding of given size to fld. func (c *typeConv) pad(fld []*ast.Field, size int64) []*ast.Field { n := len(fld) fld = fld[0 : n+1] fld[n] = &ast.Field{Names: []*ast.Ident{c.Ident("_")}, Type: c.Opaque(size)} return fld } func (c *typeConv) Struct(dt *dwarf.StructType, pos token.Pos) (expr *ast.StructType, csyntax string, align int64) { var buf bytes.Buffer buf.WriteString("struct {") fld := make([]*ast.Field, 0, 2*len(dt.Field)+1) // enough for padding around every field off := int64(0) // Rename struct fields that happen to be named Go keywords into // _{keyword}. Create a map from C ident -> Go ident. The Go ident will // be mangled. Any existing identifier that already has the same name on // the C-side will cause the Go-mangled version to be prefixed with _. // (e.g. in a struct with fields '_type' and 'type', the latter would be // rendered as '__type' in Go). ident := make(map[string]string) used := make(map[string]bool) for _, f := range dt.Field { ident[f.Name] = f.Name used[f.Name] = true } if !*godefs && !*cdefs { for cid, goid := range ident { if token.Lookup(goid).IsKeyword() { // Avoid keyword goid = "_" + goid // Also avoid existing fields for _, exist := used[goid]; exist; _, exist = used[goid] { goid = "_" + goid } used[goid] = true ident[cid] = goid } } } anon := 0 for _, f := range dt.Field { if f.ByteOffset > off { fld = c.pad(fld, f.ByteOffset-off) off = f.ByteOffset } t := c.Type(f.Type, pos) tgo := t.Go size := t.Size if f.BitSize > 0 { if f.BitSize%8 != 0 { continue } size = f.BitSize / 8 name := tgo.(*ast.Ident).String() if strings.HasPrefix(name, "int") { name = "int" } else { name = "uint" } tgo = ast.NewIdent(name + fmt.Sprint(f.BitSize)) } n := len(fld) fld = fld[0 : n+1] name := f.Name if name == "" { name = fmt.Sprintf("anon%d", anon) anon++ ident[name] = name } fld[n] = &ast.Field{Names: []*ast.Ident{c.Ident(ident[name])}, Type: tgo} off += size buf.WriteString(t.C.String()) buf.WriteString(" ") buf.WriteString(name) buf.WriteString("; ") if t.Align > align { align = t.Align } } if off < dt.ByteSize { fld = c.pad(fld, dt.ByteSize-off) off = dt.ByteSize } if off != dt.ByteSize { fatalf("%s: struct size calculation error off=%d bytesize=%d", lineno(pos), off, dt.ByteSize) } buf.WriteString("}") csyntax = buf.String() if *godefs || *cdefs { godefsFields(fld) } expr = &ast.StructType{Fields: &ast.FieldList{List: fld}} return } func upper(s string) string { if s == "" { return "" } r, size := utf8.DecodeRuneInString(s) if r == '_' { return "X" + s } return string(unicode.ToUpper(r)) + s[size:] } // godefsFields rewrites field names for use in Go or C definitions. // It strips leading common prefixes (like tv_ in tv_sec, tv_usec) // converts names to upper case, and rewrites _ into Pad_godefs_n, // so that all fields are exported. func godefsFields(fld []*ast.Field) { prefix := fieldPrefix(fld) npad := 0 for _, f := range fld { for _, n := range f.Names { if n.Name != prefix { n.Name = strings.TrimPrefix(n.Name, prefix) } if n.Name == "_" { // Use exported name instead. n.Name = "Pad_cgo_" + strconv.Itoa(npad) npad++ } if !*cdefs { n.Name = upper(n.Name) } } p := &f.Type t := *p if star, ok := t.(*ast.StarExpr); ok { star = &ast.StarExpr{X: star.X} *p = star p = &star.X t = *p } if id, ok := t.(*ast.Ident); ok { if id.Name == "unsafe.Pointer" { *p = ast.NewIdent("*byte") } } } } // fieldPrefix returns the prefix that should be removed from all the // field names when generating the C or Go code. For generated // C, we leave the names as is (tv_sec, tv_usec), since that's what // people are used to seeing in C. For generated Go code, such as // package syscall's data structures, we drop a common prefix // (so sec, usec, which will get turned into Sec, Usec for exporting). func fieldPrefix(fld []*ast.Field) string { if *cdefs { return "" } prefix := "" for _, f := range fld { for _, n := range f.Names { // Ignore field names that don't have the prefix we're // looking for. It is common in C headers to have fields // named, say, _pad in an otherwise prefixed header. // If the struct has 3 fields tv_sec, tv_usec, _pad1, then we // still want to remove the tv_ prefix. // The check for "orig_" here handles orig_eax in the // x86 ptrace register sets, which otherwise have all fields // with reg_ prefixes. if strings.HasPrefix(n.Name, "orig_") || strings.HasPrefix(n.Name, "_") { continue } i := strings.Index(n.Name, "_") if i < 0 { continue } if prefix == "" { prefix = n.Name[:i+1] } else if prefix != n.Name[:i+1] { return "" } } } return prefix }
// The LLVM Compiler Infrastructure // <regex> // template <class <API key>, class Allocator, class charT, class traits> // bool // regex_search(<API key> first, <API key> last, // match_results<<API key>, Allocator>& m, // const basic_regex<charT, traits>& e, // regex_constants::match_flag_type flags = regex_constants::match_default); #include <regex> #include <cassert> // PR34310 int main() { assert(std::regex_search("HelloWorld", std::regex("[^\\W]"))); assert(std::regex_search("_", std::regex("[^\\W]"))); return 0; }
#include "content/renderer/media/crypto/ppapi_decryptor.h" #include <string> #include "base/bind.h" #include "base/logging.h" #include "base/message_loop/message_loop.h" #include "base/message_loop/message_loop_proxy.h" #include "content/renderer/pepper/<API key>.h" #include "content/renderer/pepper/<API key>.h" #include "media/base/<API key>.h" #include "media/base/cdm_key_information.h" #include "media/base/data_buffer.h" #include "media/base/decoder_buffer.h" #include "media/base/key_systems.h" #include "media/base/<API key>.h" #include "media/base/video_frame.h" namespace content { scoped_ptr<PpapiDecryptor> PpapiDecryptor::Create( const std::string& key_system, bool <API key>, bool <API key>, const GURL& security_origin, const CreatePepperCdmCB& <API key>, const media::SessionMessageCB& session_message_cb, const media::SessionClosedCB& session_closed_cb, const media::<API key>& <API key>, const media::SessionKeysChangeCB& <API key>, const media::<API key>& <API key>) { std::string plugin_type = media::GetPepperType(key_system); DCHECK(!plugin_type.empty()); scoped_ptr<PepperCdmWrapper> pepper_cdm_wrapper = <API key>.Run(plugin_type, security_origin); if (!pepper_cdm_wrapper) { DLOG(ERROR) << "Plugin instance creation failed."; return scoped_ptr<PpapiDecryptor>(); } return scoped_ptr<PpapiDecryptor>(new PpapiDecryptor( key_system, <API key>, <API key>, pepper_cdm_wrapper.Pass(), session_message_cb, session_closed_cb, <API key>, <API key>, <API key>)); } PpapiDecryptor::PpapiDecryptor( const std::string& key_system, bool <API key>, bool <API key>, scoped_ptr<PepperCdmWrapper> pepper_cdm_wrapper, const media::SessionMessageCB& session_message_cb, const media::SessionClosedCB& session_closed_cb, const media::<API key>& <API key>, const media::SessionKeysChangeCB& <API key>, const media::<API key>& <API key>) : pepper_cdm_wrapper_(pepper_cdm_wrapper.Pass()), session_message_cb_(session_message_cb), session_closed_cb_(session_closed_cb), <API key>(<API key>), <API key>(<API key>), <API key>(<API key>), render_loop_proxy_(base::MessageLoopProxy::current()), weak_ptr_factory_(this) { DCHECK(pepper_cdm_wrapper_.get()); DCHECK(!session_message_cb_.is_null()); DCHECK(!session_closed_cb_.is_null()); DCHECK(!<API key>.is_null()); DCHECK(!<API key>.is_null()); DCHECK(!<API key>.is_null()); base::WeakPtr<PpapiDecryptor> weak_this = weak_ptr_factory_.GetWeakPtr(); CdmDelegate()->Initialize( key_system, <API key>, <API key>, base::Bind(&PpapiDecryptor::OnSessionMessage, weak_this), base::Bind(&PpapiDecryptor::OnSessionClosed, weak_this), base::Bind(&PpapiDecryptor::<API key>, weak_this), base::Bind(&PpapiDecryptor::OnSessionKeysChange, weak_this), base::Bind(&PpapiDecryptor::<API key>, weak_this), base::Bind(&PpapiDecryptor::OnFatalPluginError, weak_this)); } PpapiDecryptor::~PpapiDecryptor() { pepper_cdm_wrapper_.reset(); } void PpapiDecryptor::<API key>( const uint8* certificate_data, int <API key>, scoped_ptr<media::SimpleCdmPromise> promise) { DVLOG(2) << __FUNCTION__; DCHECK(render_loop_proxy_-><API key>()); if (!CdmDelegate()) { promise->reject(INVALID_STATE_ERROR, 0, "CdmDelegate() does not exist."); return; } CdmDelegate()-><API key>( certificate_data, <API key>, promise.Pass()); } void PpapiDecryptor::<API key>( SessionType session_type, media::EmeInitDataType init_data_type, const uint8* init_data, int init_data_length, scoped_ptr<media::<API key>> promise) { DVLOG(2) << __FUNCTION__; DCHECK(render_loop_proxy_-><API key>()); if (!CdmDelegate()) { promise->reject(INVALID_STATE_ERROR, 0, "CdmDelegate() does not exist."); return; } CdmDelegate()-><API key>(session_type, init_data_type, init_data, init_data_length, promise.Pass()); } void PpapiDecryptor::LoadSession( SessionType session_type, const std::string& session_id, scoped_ptr<media::<API key>> promise) { DVLOG(2) << __FUNCTION__; DCHECK(render_loop_proxy_-><API key>()); if (!CdmDelegate()) { promise->reject(INVALID_STATE_ERROR, 0, "CdmDelegate() does not exist."); return; } CdmDelegate()->LoadSession(session_type, session_id, promise.Pass()); } void PpapiDecryptor::UpdateSession( const std::string& session_id, const uint8* response, int response_length, scoped_ptr<media::SimpleCdmPromise> promise) { DCHECK(render_loop_proxy_-><API key>()); if (!CdmDelegate()) { promise->reject(INVALID_STATE_ERROR, 0, "CdmDelegate() does not exist."); return; } CdmDelegate()->UpdateSession(session_id, response, response_length, promise.Pass()); } void PpapiDecryptor::CloseSession(const std::string& session_id, scoped_ptr<media::SimpleCdmPromise> promise) { DCHECK(render_loop_proxy_-><API key>()); if (!CdmDelegate()) { promise->reject(INVALID_STATE_ERROR, 0, "CdmDelegate() does not exist."); return; } CdmDelegate()->CloseSession(session_id, promise.Pass()); } void PpapiDecryptor::RemoveSession( const std::string& session_id, scoped_ptr<media::SimpleCdmPromise> promise) { DCHECK(render_loop_proxy_-><API key>()); if (!CdmDelegate()) { promise->reject(INVALID_STATE_ERROR, 0, "CdmDelegate() does not exist."); return; } CdmDelegate()->RemoveSession(session_id, promise.Pass()); } media::CdmContext* PpapiDecryptor::GetCdmContext() { return this; } media::Decryptor* PpapiDecryptor::GetDecryptor() { return this; } int PpapiDecryptor::GetCdmId() const { return kInvalidCdmId; } void PpapiDecryptor::RegisterNewKeyCB(StreamType stream_type, const NewKeyCB& new_key_cb) { if (!render_loop_proxy_-><API key>()) { render_loop_proxy_->PostTask(FROM_HERE, base::Bind(&PpapiDecryptor::RegisterNewKeyCB, weak_ptr_factory_.GetWeakPtr(), stream_type, new_key_cb)); return; } DVLOG(3) << __FUNCTION__ << " - stream_type: " << stream_type; switch (stream_type) { case kAudio: new_audio_key_cb_ = new_key_cb; break; case kVideo: new_video_key_cb_ = new_key_cb; break; default: NOTREACHED(); } } void PpapiDecryptor::Decrypt( StreamType stream_type, const scoped_refptr<media::DecoderBuffer>& encrypted, const DecryptCB& decrypt_cb) { if (!render_loop_proxy_-><API key>()) { render_loop_proxy_->PostTask(FROM_HERE, base::Bind(&PpapiDecryptor::Decrypt, weak_ptr_factory_.GetWeakPtr(), stream_type, encrypted, decrypt_cb)); return; } DVLOG(3) << __FUNCTION__ << " - stream_type: " << stream_type; if (!CdmDelegate() || !CdmDelegate()->Decrypt(stream_type, encrypted, decrypt_cb)) { decrypt_cb.Run(kError, NULL); } } void PpapiDecryptor::CancelDecrypt(StreamType stream_type) { if (!render_loop_proxy_-><API key>()) { render_loop_proxy_->PostTask(FROM_HERE, base::Bind(&PpapiDecryptor::CancelDecrypt, weak_ptr_factory_.GetWeakPtr(), stream_type)); return; } DVLOG(1) << __FUNCTION__ << " - stream_type: " << stream_type; if (CdmDelegate()) CdmDelegate()->CancelDecrypt(stream_type); } void PpapiDecryptor::<API key>( const media::AudioDecoderConfig& config, const DecoderInitCB& init_cb) { if (!render_loop_proxy_-><API key>()) { render_loop_proxy_->PostTask( FROM_HERE, base::Bind(&PpapiDecryptor::<API key>, weak_ptr_factory_.GetWeakPtr(), config, init_cb)); return; } DVLOG(2) << __FUNCTION__; DCHECK(config.is_encrypted()); DCHECK(config.IsValidConfig()); <API key> = init_cb; if (!CdmDelegate() || !CdmDelegate()-><API key>( config, base::Bind(&PpapiDecryptor::<API key>, weak_ptr_factory_.GetWeakPtr(), kAudio))) { base::ResetAndReturn(&<API key>).Run(false); return; } } void PpapiDecryptor::<API key>( const media::VideoDecoderConfig& config, const DecoderInitCB& init_cb) { if (!render_loop_proxy_-><API key>()) { render_loop_proxy_->PostTask( FROM_HERE, base::Bind(&PpapiDecryptor::<API key>, weak_ptr_factory_.GetWeakPtr(), config, init_cb)); return; } DVLOG(2) << __FUNCTION__; DCHECK(config.is_encrypted()); DCHECK(config.IsValidConfig()); <API key> = init_cb; if (!CdmDelegate() || !CdmDelegate()-><API key>( config, base::Bind(&PpapiDecryptor::<API key>, weak_ptr_factory_.GetWeakPtr(), kVideo))) { base::ResetAndReturn(&<API key>).Run(false); return; } } void PpapiDecryptor::<API key>( const scoped_refptr<media::DecoderBuffer>& encrypted, const AudioDecodeCB& audio_decode_cb) { if (!render_loop_proxy_-><API key>()) { render_loop_proxy_->PostTask( FROM_HERE, base::Bind(&PpapiDecryptor::<API key>, weak_ptr_factory_.GetWeakPtr(), encrypted, audio_decode_cb)); return; } DVLOG(3) << __FUNCTION__; if (!CdmDelegate() || !CdmDelegate()-><API key>(encrypted, audio_decode_cb)) { audio_decode_cb.Run(kError, AudioFrames()); } } void PpapiDecryptor::<API key>( const scoped_refptr<media::DecoderBuffer>& encrypted, const VideoDecodeCB& video_decode_cb) { if (!render_loop_proxy_-><API key>()) { render_loop_proxy_->PostTask( FROM_HERE, base::Bind(&PpapiDecryptor::<API key>, weak_ptr_factory_.GetWeakPtr(), encrypted, video_decode_cb)); return; } DVLOG(3) << __FUNCTION__; if (!CdmDelegate() || !CdmDelegate()-><API key>(encrypted, video_decode_cb)) { video_decode_cb.Run(kError, NULL); } } void PpapiDecryptor::ResetDecoder(StreamType stream_type) { if (!render_loop_proxy_-><API key>()) { render_loop_proxy_->PostTask(FROM_HERE, base::Bind(&PpapiDecryptor::ResetDecoder, weak_ptr_factory_.GetWeakPtr(), stream_type)); return; } DVLOG(2) << __FUNCTION__ << " - stream_type: " << stream_type; if (CdmDelegate()) CdmDelegate()->ResetDecoder(stream_type); } void PpapiDecryptor::DeinitializeDecoder(StreamType stream_type) { if (!render_loop_proxy_-><API key>()) { render_loop_proxy_->PostTask( FROM_HERE, base::Bind(&PpapiDecryptor::DeinitializeDecoder, weak_ptr_factory_.GetWeakPtr(), stream_type)); return; } DVLOG(2) << __FUNCTION__ << " - stream_type: " << stream_type; if (CdmDelegate()) CdmDelegate()->DeinitializeDecoder(stream_type); } void PpapiDecryptor::<API key>(StreamType stream_type, bool success) { DCHECK(render_loop_proxy_-><API key>()); switch (stream_type) { case kAudio: DCHECK(!<API key>.is_null()); base::ResetAndReturn(&<API key>).Run(success); break; case kVideo: DCHECK(!<API key>.is_null()); base::ResetAndReturn(&<API key>).Run(success); break; default: NOTREACHED(); } } void PpapiDecryptor::OnSessionMessage(const std::string& session_id, MessageType message_type, const std::vector<uint8>& message, const GURL& <API key>) { DCHECK(render_loop_proxy_-><API key>()); session_message_cb_.Run(session_id, message_type, message, <API key>); } void PpapiDecryptor::OnSessionKeysChange(const std::string& session_id, bool <API key>, media::CdmKeysInfo keys_info) { DCHECK(render_loop_proxy_-><API key>()); // TODO(jrummell): Handling resume playback should be done in the media if (<API key>) <API key>(); <API key>.Run(session_id, <API key>, keys_info.Pass()); } void PpapiDecryptor::<API key>( const std::string& session_id, const base::Time& new_expiry_time) { DCHECK(render_loop_proxy_-><API key>()); <API key>.Run(session_id, new_expiry_time); } void PpapiDecryptor::OnSessionClosed(const std::string& session_id) { DCHECK(render_loop_proxy_-><API key>()); session_closed_cb_.Run(session_id); } void PpapiDecryptor::<API key>( const std::string& session_id, MediaKeys::Exception exception_code, uint32 system_code, const std::string& error_description) { DCHECK(render_loop_proxy_-><API key>()); <API key>.Run(session_id, exception_code, system_code, error_description); } void PpapiDecryptor::<API key>() { if (!new_audio_key_cb_.is_null()) new_audio_key_cb_.Run(); if (!new_video_key_cb_.is_null()) new_video_key_cb_.Run(); } void PpapiDecryptor::OnFatalPluginError() { DCHECK(render_loop_proxy_-><API key>()); pepper_cdm_wrapper_.reset(); } <API key>* PpapiDecryptor::CdmDelegate() { DCHECK(render_loop_proxy_-><API key>()); return (pepper_cdm_wrapper_) ? pepper_cdm_wrapper_->GetCdmDelegate() : NULL; } } // namespace content
#include "core/editing/EphemeralRange.h" #include "core/dom/Document.h" #include "core/dom/Element.h" #include "core/dom/Range.h" #include "core/dom/Text.h" namespace blink { template <typename Strategy> <API key><Strategy>::<API key>(const PositionTemplate<Strategy>& start, const PositionTemplate<Strategy>& end) : m_startPosition(start) , m_endPosition(end) #if ENABLE(ASSERT) , m_domTreeVersion(start.isNull() ? 0 : start.document()->domTreeVersion()) #endif { if (m_startPosition.isNull()) { ASSERT(m_endPosition.isNull()); return; } ASSERT(m_endPosition.isNotNull()); ASSERT(m_startPosition.document() == m_endPosition.document()); ASSERT(m_startPosition.inDocument()); ASSERT(m_endPosition.inDocument()); } template <typename Strategy> <API key><Strategy>::<API key>(const <API key><Strategy>& other) : <API key>(other.m_startPosition, other.m_endPosition) { ASSERT(other.isValid()); } template <typename Strategy> <API key><Strategy>::<API key>(const PositionTemplate<Strategy>& position) : <API key>(position, position) { } template <typename Strategy> <API key><Strategy>::<API key>(const Range* range) { if (!range) return; ASSERT(range->inDocument()); m_startPosition = <API key><Strategy>(range->startPosition()); m_endPosition = <API key><Strategy>(range->endPosition()); #if ENABLE(ASSERT) m_domTreeVersion = range->ownerDocument().domTreeVersion(); #endif } template <typename Strategy> <API key><Strategy>::<API key>() { } template <typename Strategy> <API key><Strategy>::~<API key>() { } template <typename Strategy> <API key><Strategy>& <API key><Strategy>::operator=(const <API key><Strategy>& other) { ASSERT(other.isValid()); m_startPosition = other.m_startPosition; m_endPosition = other.m_endPosition; #if ENABLE(ASSERT) m_domTreeVersion = other.m_domTreeVersion; #endif return *this; } template <typename Strategy> bool <API key><Strategy>::operator==(const <API key><Strategy>& other) const { return startPosition() == other.startPosition() && endPosition() == other.endPosition(); } template <typename Strategy> bool <API key><Strategy>::operator!=(const <API key><Strategy>& other) const { return !operator==(other); } template <typename Strategy> Document& <API key><Strategy>::document() const { ASSERT(isNotNull()); return *m_startPosition.document(); } template <typename Strategy> PositionTemplate<Strategy> <API key><Strategy>::startPosition() const { ASSERT(isValid()); return m_startPosition; } template <typename Strategy> PositionTemplate<Strategy> <API key><Strategy>::endPosition() const { ASSERT(isValid()); return m_endPosition; } template <typename Strategy> bool <API key><Strategy>::isCollapsed() const { ASSERT(isValid()); return m_startPosition == m_endPosition; } template <typename Strategy> <API key><Strategy> <API key><Strategy>::rangeOfContents(const Node& node) { return <API key><Strategy>(PositionTemplate<Strategy>::firstPositionInNode(&const_cast<Node&>(node)), PositionTemplate<Strategy>::lastPositionInNode(&const_cast<Node&>(node))); } #if ENABLE(ASSERT) template <typename Strategy> bool <API key><Strategy>::isValid() const { return m_startPosition.isNull() || m_domTreeVersion == m_startPosition.document()->domTreeVersion(); } #else template <typename Strategy> bool <API key><Strategy>::isValid() const { return true; } #endif <API key><Range> createRange(const EphemeralRange& range) { if (range.isNull()) return nullptr; return Range::create(range.document(), range.startPosition(), range.endPosition()); } template class <API key> <API key><EditingStrategy>; template class <API key> <API key><<API key>>; } // namespace blink
#include "chrome/browser/ash/login/screens/<API key>.h" #include "chrome/browser/ash/login/screens/<API key>.h" #include "chrome/browser/ash/login/ui/login_display_host.h" #include "chrome/browser/ash/login/ui/signin_ui.h" #include "chrome/browser/ash/login/wizard_controller.h" #include "chrome/browser/ui/webui/chromeos/login/<API key>.h" #include "chrome/browser/ui/webui/chromeos/login/<API key>.h" #include "chrome/browser/ui/webui/chromeos/login/<API key>.h" #include "chrome/grit/generated_resources.h" #include "chromeos/login/auth/<API key>.h" #include "chromeos/login/auth/key.h" #include "chromeos/network/network_state.h" #include "chromeos/network/<API key>.h" #include "components/user_manager/known_user.h" #include "ui/base/l10n/l10n_util.h" namespace ash { namespace { constexpr char kUserActionCancel[] = "cancel"; SigninError GetSigninError(authpolicy::ErrorType error) { switch (error) { case authpolicy::<API key>: return SigninError::<API key>; case authpolicy::<API key>: return SigninError::<API key>; default: DLOG(WARNING) << "Unhandled error code: " << error; return SigninError::<API key>; } } } // namespace <API key>::<API key>( <API key>* view, ErrorScreen* error_screen, const base::RepeatingClosure& exit_callback) : BaseScreen(<API key>::kScreenId, OobeScreenPriority::DEFAULT), <API key>(std::make_unique<AuthPolicyHelper>()), view_(view), error_screen_(error_screen), exit_callback_(exit_callback) { <API key> = base::MakeRefCounted<<API key>>(); <API key>->Init(); if (view_) view_->Bind(this); } <API key>::~<API key>() { if (view_) view_->Unbind(); } void <API key>::OnViewDestroyed( <API key>* view) { if (view_ == view) view_ = nullptr; } void <API key>::ShowImpl() { if (!view_) return; scoped_observation_.Observe(<API key>.get()); UpdateState(NetworkError::ERROR_REASON_UPDATE); if (!<API key>) view_->Show(); } void <API key>::HideImpl() { scoped_observation_.Reset(); view_->Reset(); <API key>><API key>(); <API key> = false; error_screen_->SetParentScreen(OobeScreen::SCREEN_UNKNOWN); error_screen_->Hide(); } void <API key>::OnUserAction(const std::string& action_id) { if (action_id == kUserActionCancel) { HandleCancel(); return; } BaseScreen::OnUserAction(action_id); } bool <API key>::HandleAccelerator( <API key> action) { if (action == <API key>::kCancelScreenAction) { HandleCancel(); return true; } return false; } void <API key>::HandleCancel() { view_->Reset(); <API key>><API key>(); if (LoginDisplayHost::default_host()->HasUserPods()) { exit_callback_.Run(); } } void <API key>::HandleCompleteAuth( const std::string& username, const std::string& password) { if (LoginDisplayHost::default_host()) LoginDisplayHost::default_host()->SetDisplayEmail(username); DCHECK(<API key>); Key key(password); key.SetLabel(<API key>); <API key>>AuthenticateUser( username, std::string() /* object_guid */, password, base::BindOnce(&<API key>::OnAdAuthResult, weak_factory_.GetWeakPtr(), username, key)); } void <API key>::OnAdAuthResult( const std::string& username, const Key& key, authpolicy::ErrorType error, const authpolicy::<API key>& account_info) { if (error != authpolicy::ERROR_NONE) <API key>><API key>(); switch (error) { case authpolicy::ERROR_NONE: { DCHECK(account_info.has_account_id() && !account_info.account_id().empty() && LoginDisplayHost::default_host()); const AccountId account_id(user_manager::known_user::GetAccountId( username, account_info.account_id(), AccountType::ACTIVE_DIRECTORY)); LoginDisplayHost::default_host()-><API key>( account_info.display_name(), account_info.given_name()); UserContext user_context( user_manager::UserType::<API key>, account_id); user_context.SetKey(key); user_context.SetAuthFlow(UserContext::<API key>); user_context.SetIsUsingOAuth(false); LoginDisplayHost::default_host()->CompleteLogin(user_context); break; } case authpolicy::<API key>: LoginDisplayHost::default_host() ->GetWizardController() -><API key>(username); break; case authpolicy::<API key>: case authpolicy::ERROR_BAD_USER_NAME: view_->SetErrorState( username, static_cast<int>(<API key>::BAD_USERNAME)); break; case authpolicy::ERROR_BAD_PASSWORD: view_->SetErrorState( username, static_cast<int>(<API key>::BAD_AUTH_PASSWORD)); break; default: view_->SetErrorState(username, static_cast<int>(<API key>::NONE)); LoginDisplayHost::default_host()->GetSigninUI()->ShowSigninError( GetSigninError(error), /*details=*/std::string()); } } void <API key>::UpdateState(NetworkError::ErrorReason reason) { <API key>::State state = <API key>->state(); const bool is_online = <API key>::IsOnline(state, reason); if (!is_online) { <API key> = true; error_screen_->SetParentScreen(<API key>::kScreenId); error_screen_-><API key>(state, reason); } else { error_screen_->HideCaptivePortal(); if (<API key> && error_screen_->GetParentScreen() == <API key>::kScreenId) { <API key> = false; error_screen_->SetParentScreen(OobeScreen::SCREEN_UNKNOWN); error_screen_->Hide(); view_->Show(); } } } } // namespace ash
"""`Resource` - Flask request scope example.""" from dependency_injector import containers, providers from dependency_injector.wiring import Closing, Provide, inject from flask import Flask, current_app class Service: def init_service() -> Service: print("Init service") yield Service() print("Shutdown service") class Container(containers.<API key>): service = providers.Resource(init_service) @inject def index_view(service: Service = Closing[Provide[Container.service]]): assert service is current_app.container.service() return "Hello World!" container = Container() container.wire(modules=[__name__]) app = Flask(__name__) app.container = container app.add_url_rule("/", "index", view_func=index_view) if __name__ == "__main__": app.run()
#include "content/renderer/usb/type_converters.h" #include <stddef.h> #include "base/logging.h" namespace mojo { // static blink::WebUSBDevice::TransferDirection TypeConverter<blink::WebUSBDevice::TransferDirection, device::usb::TransferDirection>:: Convert(const device::usb::TransferDirection& direction) { switch (direction) { case device::usb::TransferDirection::INBOUND: return blink::WebUSBDevice::TransferDirection::In; case device::usb::TransferDirection::OUTBOUND: return blink::WebUSBDevice::TransferDirection::Out; default: NOTREACHED(); return blink::WebUSBDevice::TransferDirection::In; } } // static device::usb::TransferDirection TypeConverter<device::usb::TransferDirection, blink::WebUSBDevice::TransferDirection>:: Convert(const blink::WebUSBDevice::TransferDirection& direction) { switch (direction) { case blink::WebUSBDevice::TransferDirection::In: return device::usb::TransferDirection::INBOUND; case blink::WebUSBDevice::TransferDirection::Out: return device::usb::TransferDirection::OUTBOUND; default: NOTREACHED(); return device::usb::TransferDirection::INBOUND; } } // static device::usb::ControlTransferType TypeConverter<device::usb::ControlTransferType, blink::WebUSBDevice::RequestType>:: Convert(const blink::WebUSBDevice::RequestType& direction) { switch (direction) { case blink::WebUSBDevice::RequestType::Standard: return device::usb::ControlTransferType::STANDARD; case blink::WebUSBDevice::RequestType::Class: return device::usb::ControlTransferType::CLASS; case blink::WebUSBDevice::RequestType::Vendor: return device::usb::ControlTransferType::VENDOR; default: NOTREACHED(); return device::usb::ControlTransferType::STANDARD; } } // static device::usb::<API key> TypeConverter<device::usb::<API key>, blink::WebUSBDevice::RequestRecipient>:: Convert(const blink::WebUSBDevice::RequestRecipient& direction) { switch (direction) { case blink::WebUSBDevice::RequestRecipient::Device: return device::usb::<API key>::DEVICE; case blink::WebUSBDevice::RequestRecipient::Interface: return device::usb::<API key>::INTERFACE; case blink::WebUSBDevice::RequestRecipient::Endpoint: return device::usb::<API key>::ENDPOINT; case blink::WebUSBDevice::RequestRecipient::Other: return device::usb::<API key>::OTHER; default: NOTREACHED(); return device::usb::<API key>::DEVICE; } } // static device::usb::<API key> TypeConverter<device::usb::<API key>, blink::WebUSBDevice::<API key>>:: Convert(const blink::WebUSBDevice::<API key>& parameters) { device::usb::<API key> params = device::usb::<API key>::New(); params->type = mojo::ConvertTo<device::usb::ControlTransferType>(parameters.type); params->recipient = mojo::ConvertTo<device::usb::<API key>>( parameters.recipient); params->request = parameters.request; params->value = parameters.value; params->index = parameters.index; return params; } // static blink::WebUSBDeviceInfo::Endpoint::Type TypeConverter< blink::WebUSBDeviceInfo::Endpoint::Type, device::usb::EndpointType>::Convert(const device::usb::EndpointType& endpoint_type) { switch (endpoint_type) { case device::usb::EndpointType::BULK: return blink::WebUSBDeviceInfo::Endpoint::Type::Bulk; case device::usb::EndpointType::INTERRUPT: return blink::WebUSBDeviceInfo::Endpoint::Type::Interrupt; case device::usb::EndpointType::ISOCHRONOUS: return blink::WebUSBDeviceInfo::Endpoint::Type::Isochronous; default: NOTREACHED(); return blink::WebUSBDeviceInfo::Endpoint::Type::Bulk; } } // static blink::WebUSBDeviceInfo::Endpoint TypeConverter<blink::WebUSBDeviceInfo::Endpoint, device::usb::EndpointInfoPtr>:: Convert(const device::usb::EndpointInfoPtr& info) { blink::WebUSBDeviceInfo::Endpoint endpoint; endpoint.endpointNumber = info->endpoint_number; endpoint.direction = mojo::ConvertTo<blink::WebUSBDevice::TransferDirection>(info->direction); endpoint.type = mojo::ConvertTo<blink::WebUSBDeviceInfo::Endpoint::Type>(info->type); endpoint.packetSize = info->packet_size; return endpoint; } // static blink::WebUSBDeviceInfo::AlternateInterface TypeConverter<blink::WebUSBDeviceInfo::AlternateInterface, device::usb::<API key>>:: Convert(const device::usb::<API key>& info) { blink::WebUSBDeviceInfo::AlternateInterface alternate; alternate.alternateSetting = info->alternate_setting; alternate.classCode = info->class_code; alternate.subclassCode = info->subclass_code; alternate.protocolCode = info->protocol_code; if (!info->interface_name.is_null()) alternate.interfaceName = blink::WebString::fromUTF8(info->interface_name); alternate.endpoints = blink::WebVector<blink::WebUSBDeviceInfo::Endpoint>( info->endpoints.size()); for (size_t i = 0; i < info->endpoints.size(); ++i) { alternate.endpoints[i] = mojo::ConvertTo<blink::WebUSBDeviceInfo::Endpoint>(info->endpoints[i]); } return alternate; } // static blink::WebUSBDeviceInfo::Interface TypeConverter< blink::WebUSBDeviceInfo::Interface, device::usb::InterfaceInfoPtr>::Convert(const device::usb::InterfaceInfoPtr& info) { blink::WebUSBDeviceInfo::Interface interface; interface.interfaceNumber = info->interface_number; interface.alternates = blink::WebVector<blink::WebUSBDeviceInfo::AlternateInterface>( info->alternates.size()); for (size_t i = 0; i < info->alternates.size(); ++i) { interface.alternates[i] = mojo::ConvertTo<blink::WebUSBDeviceInfo::AlternateInterface>( info->alternates[i]); } return interface; } // static blink::WebUSBDeviceInfo::Configuration TypeConverter<blink::WebUSBDeviceInfo::Configuration, device::usb::<API key>>:: Convert(const device::usb::<API key>& info) { blink::WebUSBDeviceInfo::Configuration config; config.configurationValue = info->configuration_value; if (!info->configuration_name.is_null()) { config.configurationName = blink::WebString::fromUTF8(info->configuration_name); } config.interfaces = blink::WebVector<blink::WebUSBDeviceInfo::Interface>( info->interfaces.size()); for (size_t i = 0; i < info->interfaces.size(); ++i) { config.interfaces[i] = mojo::ConvertTo<blink::WebUSBDeviceInfo::Interface>( info->interfaces[i]); } return config; } // static blink::WebUSBDeviceInfo TypeConverter<blink::WebUSBDeviceInfo, device::usb::DeviceInfoPtr>::Convert( const device::usb::DeviceInfoPtr& info) { blink::WebUSBDeviceInfo device; device.guid = blink::WebString::fromUTF8(info->guid); device.usbVersionMajor = info->usb_version_major; device.usbVersionMinor = info->usb_version_minor; device.usbVersionSubminor = info-><API key>; device.deviceClass = info->class_code; device.deviceSubclass = info->subclass_code; device.deviceProtocol = info->protocol_code; device.vendorID = info->vendor_id; device.productID = info->product_id; device.deviceVersionMajor = info-><API key>; device.deviceVersionMinor = info-><API key>; device.<API key> = info-><API key>; if (!info->manufacturer_name.is_null()) { device.manufacturerName = blink::WebString::fromUTF8(info->manufacturer_name); } if (!info->product_name.is_null()) device.productName = blink::WebString::fromUTF8(info->product_name); if (!info->serial_number.is_null()) device.serialNumber = blink::WebString::fromUTF8(info->serial_number); device.configurations = blink::WebVector<blink::WebUSBDeviceInfo::Configuration>( info->configurations.size()); for (size_t i = 0; i < info->configurations.size(); ++i) { device.configurations[i] = mojo::ConvertTo<blink::WebUSBDeviceInfo::Configuration>( info->configurations[i]); } return device; } // static device::usb::DeviceFilterPtr TypeConverter<device::usb::DeviceFilterPtr, blink::WebUSBDeviceFilter>::Convert( const blink::WebUSBDeviceFilter& web_filter) { device::usb::DeviceFilterPtr filter = device::usb::DeviceFilter::New(); filter->has_vendor_id = web_filter.hasVendorID; filter->vendor_id = web_filter.vendorID; filter->has_product_id = web_filter.hasProductID; filter->product_id = web_filter.productID; filter->has_class_code = web_filter.hasClassCode; filter->class_code = web_filter.classCode; filter->has_subclass_code = web_filter.hasSubclassCode; filter->subclass_code = web_filter.subclassCode; filter->has_protocol_code = web_filter.hasProtocolCode; filter->protocol_code = web_filter.protocolCode; return filter; } // static device::usb::<API key> TypeConverter<device::usb::<API key>, blink::<API key>>:: Convert(const blink::<API key>& web_options) { device::usb::<API key> options = device::usb::EnumerationOptions::New(); options->filters = mojo::Array<device::usb::DeviceFilterPtr>::New( web_options.filters.size()); for (size_t i = 0; i < web_options.filters.size(); ++i) { options->filters[i] = device::usb::DeviceFilter::From(web_options.filters[i]); } return options; } } // namespace mojo
from __future__ import unicode_literals from __future__ import print_function from __future__ import division from __future__ import absolute_import from future import standard_library standard_library.install_aliases() from builtins import * __author__ = 'Yin' from pymongo import MongoClient from get_database import get_user_db OldUsers=MongoClient('localhost').Test_database.moves_user_access Users=get_user_db() for olduser in OldUsers.find(): Users.insert(olduser)
#include "chrome/browser/ui/webui/bookmarks_ui.h" #include "base/memory/ref_counted_memory.h" #include "base/memory/singleton.h" #include "base/message_loop.h" #include "base/<API key>.h" #include "base/stringprintf.h" #include "chrome/browser/bookmarks/bookmark_editor.h" #include "chrome/browser/bookmarks/bookmark_model.h" #include "chrome/browser/bookmarks/bookmark_utils.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_list.h" #include "chrome/browser/ui/webui/<API key>.h" #include "chrome/common/url_constants.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_ui.h" #include "googleurl/src/gurl.h" #include "grit/theme_resources.h" #include "ui/base/resource/resource_bundle.h" using content::WebContents; // <API key> <API key>::<API key>() : DataSource(chrome::<API key>, MessageLoop::current()) { } void <API key>::StartDataRequest(const std::string& path, bool is_incognito, int request_id) { NOTREACHED() << "We should never get here since the extension should have" << "been triggered"; SendResponse(request_id, NULL); } std::string <API key>::GetMimeType(const std::string& path) const { NOTREACHED() << "We should never get here since the extension should have" << "been triggered"; return "text/html"; } <API key>::~<API key>() {} // BookmarksUI BookmarksUI::BookmarksUI(content::WebUI* web_ui) : WebUIController(web_ui) { <API key>* html_source = new <API key>(); // Set up the chrome://bookmarks/ source. Profile* profile = Profile::FromWebUI(web_ui); <API key>::AddDataSource(profile, html_source); } // static base::RefCountedMemory* BookmarksUI::<API key>( ui::ScaleFactor scale_factor) { return ResourceBundle::GetSharedInstance(). <API key>(<API key>, scale_factor); }
#ifndef ANKI_MATH_MAT4_H #define ANKI_MATH_MAT4_H #include "anki/math/CommonIncludes.h" namespace anki { @addtogroup math @{ Template struct that gives the type of the TVec4 SIMD template<typename T> class TMat4Simd { public: using Type = Array<T, 16>; }; #if ANKI_SIMD == ANKI_SIMD_SSE // Specialize for F32 template<> class TMat4Simd<F32> { public: using Type = Array<__m128, 4>; }; #endif 4x4 Matrix. Used mainly for transformations but not necessarily. Its row major. SSE optimized @note TMat4*TMat4: 64 muls 48 adds template<typename T> class alignas(16) TMat4: public TMat<T, 4, 4, typename TMat4Simd<T>::Type, TMat4<T>, TVec4<T>, TVec4<T>> { @name Friends @{ template<typename Y> friend TMat4<Y> operator+(const Y f, const TMat4<Y>& m4); template<typename Y> friend TMat4<Y> operator-(const Y f, const TMat4<Y>& m4); template<typename Y> friend TMat4<Y> operator*(const Y f, const TMat4<Y>& m4); template<typename Y> friend TMat4<Y> operator/(const Y f, const TMat4<Y>& m4); @} public: using Base = TMat<T, 4, 4, typename TMat4Simd<T>::Type, TMat4<T>, TVec4<T>, TVec4<T>>; using Base::getTranslationPart; using Base::setTranslationPart; using Base::getRotationPart; using Base::setRotationPart; @name Constructors @{ explicit TMat4() : Base() {} TMat4(const TMat4& b) : Base(b) {} explicit TMat4(T m00, T m01, T m02, T m03, T m10, T m11, T m12, T m13, T m20, T m21, T m22, T m23, T m30, T m31, T m32, T m33) { TMat4& m = *this; m(0, 0) = m00; m(0, 1) = m01; m(0, 2) = m02; m(0, 3) = m03; m(1, 0) = m10; m(1, 1) = m11; m(1, 2) = m12; m(1, 3) = m13; m(2, 0) = m20; m(2, 1) = m21; m(2, 2) = m22; m(2, 3) = m23; m(3, 0) = m30; m(3, 1) = m31; m(3, 2) = m32; m(3, 3) = m33; } explicit TMat4(const T f) : Base(f) {} explicit TMat4(const TMat3<T>& m3) { TMat4& m = *this; m(0, 0) = m3(0, 0); m(0, 1) = m3(0, 1); m(0, 2) = m3(0, 2); m(0, 3) = 0.0; m(1, 0) = m3(1, 0); m(1, 1) = m3(1, 1); m(1, 2) = m3(1, 2); m(1, 3) = 0.0; m(2, 0) = m3(2, 0); m(2, 1) = m3(2, 1); m(2, 2) = m3(2, 2); m(2, 3) = 0.0; m(3, 0) = 0.0; m(3, 1) = 0.0; m(3, 2) = 0.0; m(3, 3) = 1.0; } explicit TMat4(const TVec3<T>& v) { TMat4& m = *this; m(0, 0) = 1.0; m(0, 1) = 0.0; m(0, 2) = 0.0; m(0, 3) = v.x(); m(1, 0) = 0.0; m(1, 1) = 1.0; m(1, 2) = 0.0; m(1, 3) = v.y(); m(2, 0) = 0.0; m(2, 1) = 0.0; m(2, 2) = 1.0; m(2, 3) = v.z(); m(3, 0) = 0.0; m(3, 1) = 0.0; m(3, 2) = 0.0; m(3, 3) = 1.0; } explicit TMat4(const TVec4<T>& v) { TMat4& m = *this; m(0, 0) = 1.0; m(0, 1) = 0.0; m(0, 2) = 0.0; m(0, 3) = v.x(); m(1, 0) = 0.0; m(1, 1) = 1.0; m(1, 2) = 0.0; m(1, 3) = v.y(); m(2, 0) = 0.0; m(2, 1) = 0.0; m(2, 2) = 1.0; m(2, 3) = v.z(); m(3, 0) = 0.0; m(3, 1) = 0.0; m(3, 2) = 0.0; m(3, 3) = v.w(); } explicit TMat4(const TVec4<T>& transl, const TMat3<T>& rot) { setRotationPart(rot); setTranslationPart(transl); TMat4& m = *this; m(3, 0) = m(3, 1) = m(3, 2) = 0.0; } explicit TMat4(const TVec4<T>& transl, const TMat3<T>& rot, const T scale) { if(isZero<T>(scale - 1.0)) { setRotationPart(rot); } else { setRotationPart(rot * scale); } setTranslationPart(transl); TMat4& m = *this; m(3, 0) = m(3, 1) = m(3, 2) = 0.0; } explicit TMat4(const TTransform<T>& t) : TMat4(TVec4<T>(t.getOrigin().xyz(), 1.0), t.getRotation().getRotationPart(), t.getScale()) {} @} @name Other @{ T getDet() const { const TMat4& t = *this; return t(0, 3) * t(1, 2) * t(2, 1) * t(3, 0) - t(0, 2) * t(1, 3) * t(2, 1) * t(3, 0) - t(0, 3) * t(1, 1) * t(2, 2) * t(3, 0) + t(0, 1) * t(1, 3) * t(2, 2) * t(3, 0) + t(0, 2) * t(1, 1) * t(2, 3) * t(3, 0) - t(0, 1) * t(1, 2) * t(2, 3) * t(3, 0) - t(0, 3) * t(1, 2) * t(2, 0) * t(3, 1) + t(0, 2) * t(1, 3) * t(2, 0) * t(3, 1) + t(0, 3) * t(1, 0) * t(2, 2) * t(3, 1) - t(0, 0) * t(1, 3) * t(2, 2) * t(3, 1) - t(0, 2) * t(1, 0) * t(2, 3) * t(3, 1) + t(0, 0) * t(1, 2) * t(2, 3) * t(3, 1) + t(0, 3) * t(1, 1) * t(2, 0) * t(3, 2) - t(0, 1) * t(1, 3) * t(2, 0) * t(3, 2) - t(0, 3) * t(1, 0) * t(2, 1) * t(3, 2) + t(0, 0) * t(1, 3) * t(2, 1) * t(3, 2) + t(0, 1) * t(1, 0) * t(2, 3) * t(3, 2) - t(0, 0) * t(1, 1) * t(2, 3) * t(3, 2) - t(0, 2) * t(1, 1) * t(2, 0) * t(3, 3) + t(0, 1) * t(1, 2) * t(2, 0) * t(3, 3) + t(0, 2) * t(1, 0) * t(2, 1) * t(3, 3) - t(0, 0) * t(1, 2) * t(2, 1) * t(3, 3) - t(0, 1) * t(1, 0) * t(2, 2) * t(3, 3) + t(0, 0) * t(1, 1) * t(2, 2) * t(3, 3); } Invert using Cramer's rule TMat4 getInverse() const { Array<T, 12> tmp; const TMat4& in = (*this); TMat4 m4; tmp[0] = in(2, 2) * in(3, 3); tmp[1] = in(3, 2) * in(2, 3); tmp[2] = in(1, 2) * in(3, 3); tmp[3] = in(3, 2) * in(1, 3); tmp[4] = in(1, 2) * in(2, 3); tmp[5] = in(2, 2) * in(1, 3); tmp[6] = in(0, 2) * in(3, 3); tmp[7] = in(3, 2) * in(0, 3); tmp[8] = in(0, 2) * in(2, 3); tmp[9] = in(2, 2) * in(0, 3); tmp[10] = in(0, 2) * in(1, 3); tmp[11] = in(1, 2) * in(0, 3); m4(0, 0) = tmp[0] * in(1, 1) + tmp[3] * in(2, 1) + tmp[4] * in(3, 1); m4(0, 0) -= tmp[1] * in(1, 1) + tmp[2] * in(2, 1) + tmp[5] * in(3, 1); m4(0, 1) = tmp[1] * in(0, 1) + tmp[6] * in(2, 1) + tmp[9] * in(3, 1); m4(0, 1) -= tmp[0] * in(0, 1) + tmp[7] * in(2, 1) + tmp[8] * in(3, 1); m4(0, 2) = tmp[2] * in(0, 1) + tmp[7] * in(1, 1) + tmp[10] * in(3, 1); m4(0, 2) -= tmp[3] * in(0, 1) + tmp[6] * in(1, 1) + tmp[11] * in(3, 1); m4(0, 3) = tmp[5] * in(0, 1) + tmp[8] * in(1, 1) + tmp[11] * in(2, 1); m4(0, 3) -= tmp[4] * in(0, 1) + tmp[9] * in(1, 1) + tmp[10] * in(2, 1); m4(1, 0) = tmp[1] * in(1, 0) + tmp[2] * in(2, 0) + tmp[5] * in(3, 0); m4(1, 0) -= tmp[0] * in(1, 0) + tmp[3] * in(2, 0) + tmp[4] * in(3, 0); m4(1, 1) = tmp[0] * in(0, 0) + tmp[7] * in(2, 0) + tmp[8] * in(3, 0); m4(1, 1) -= tmp[1] * in(0, 0) + tmp[6] * in(2, 0) + tmp[9] * in(3, 0); m4(1, 2) = tmp[3] * in(0, 0) + tmp[6] * in(1, 0) + tmp[11] * in(3, 0); m4(1, 2) -= tmp[2] * in(0, 0) + tmp[7] * in(1, 0) + tmp[10] * in(3, 0); m4(1, 3) = tmp[4] * in(0, 0) + tmp[9] * in(1, 0) + tmp[10] * in(2, 0); m4(1, 3) -= tmp[5] * in(0, 0) + tmp[8] * in(1, 0) + tmp[11] * in(2, 0); tmp[0] = in(2, 0) * in(3, 1); tmp[1] = in(3, 0) * in(2, 1); tmp[2] = in(1, 0) * in(3, 1); tmp[3] = in(3, 0) * in(1, 1); tmp[4] = in(1, 0) * in(2, 1); tmp[5] = in(2, 0) * in(1, 1); tmp[6] = in(0, 0) * in(3, 1); tmp[7] = in(3, 0) * in(0, 1); tmp[8] = in(0, 0) * in(2, 1); tmp[9] = in(2, 0) * in(0, 1); tmp[10] = in(0, 0) * in(1, 1); tmp[11] = in(1, 0) * in(0, 1); m4(2, 0) = tmp[0] * in(1, 3) + tmp[3] * in(2, 3) + tmp[4] * in(3, 3); m4(2, 0) -= tmp[1] * in(1, 3) + tmp[2] * in(2, 3) + tmp[5] * in(3, 3); m4(2, 1) = tmp[1] * in(0, 3) + tmp[6] * in(2, 3) + tmp[9] * in(3, 3); m4(2, 1) -= tmp[0] * in(0, 3) + tmp[7] * in(2, 3) + tmp[8] * in(3, 3); m4(2, 2) = tmp[2] * in(0, 3) + tmp[7] * in(1, 3) + tmp[10] * in(3, 3); m4(2, 2) -= tmp[3] * in(0, 3) + tmp[6] * in(1, 3) + tmp[11] * in(3, 3); m4(2, 3) = tmp[5] * in(0, 3) + tmp[8] * in(1, 3) + tmp[11] * in(2, 3); m4(2, 3) -= tmp[4] * in(0, 3) + tmp[9] * in(1, 3) + tmp[10] * in(2, 3); m4(3, 0) = tmp[2] * in(2, 2) + tmp[5] * in(3, 2) + tmp[1] * in(1, 2); m4(3, 0) -= tmp[4] * in(3, 2) + tmp[0] * in(1, 2) + tmp[3] * in(2, 2); m4(3, 1) = tmp[8] * in(3, 2) + tmp[0] * in(0, 2) + tmp[7] * in(2, 2); m4(3, 1) -= tmp[6] * in(2, 2) + tmp[9] * in(3, 2) + tmp[1] * in(0, 2); m4(3, 2) = tmp[6] * in(1, 2) + tmp[11] * in(3, 2) + tmp[3] * in(0, 2); m4(3, 2) -= tmp[10] * in(3, 2) + tmp[2] * in(0, 2) + tmp[7] * in(1, 2); m4(3, 3) = tmp[10] * in(2, 2) + tmp[4] * in(0, 2) + tmp[9] * in(1, 2); m4(3, 3) -= tmp[8] * in(1, 2) + tmp[11] * in(2, 2) + tmp[5] * in(0, 2); T det = in(0, 0) * m4(0, 0) + in(1, 0) * m4(0, 1) + in(2, 0) * m4(0, 2) + in(3, 0) * m4(0, 3); ANKI_ASSERT(!isZero<T>(det)); // Cannot invert, det == 0 det = 1.0 / det; m4 *= det; return m4; } See getInverse void invert() { (*this) = getInverse(); } If we suppose this matrix represents a transformation, return the inverted transformation TMat4 <API key>() const { TMat3<T> invertedRot = getRotationPart().getTransposed(); TVec3<T> invertedTsl = getTranslationPart(); invertedTsl = -(invertedRot * invertedTsl); return TMat4(invertedTsl, invertedRot); } void setIdentity() { (*this) = getIdentity(); } static const TMat4& getIdentity() { static const TMat4 ident( 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0); return ident; } 12 muls, 27 adds. Something like m4 = m0 * m1 but without touching the 4rth row and allot faster static TMat4 <API key>(const TMat4& m0, const TMat4& m1) { // See the clean code in < r664 // one of the 2 mat4 doesnt represent transformation ANKI_ASSERT(isZero<T>(m0(3, 0) + m0(3, 1) + m0(3, 2) + m0(3, 3) - 1.0) && isZero<T>(m1(3, 0) + m1(3, 1) + m1(3, 2) + m1(3, 3) - 1.0)); TMat4 m4; m4(0, 0) = m0(0, 0) * m1(0, 0) + m0(0, 1) * m1(1, 0) + m0(0, 2) * m1(2, 0); m4(0, 1) = m0(0, 0) * m1(0, 1) + m0(0, 1) * m1(1, 1) + m0(0, 2) * m1(2, 1); m4(0, 2) = m0(0, 0) * m1(0, 2) + m0(0, 1) * m1(1, 2) + m0(0, 2) * m1(2, 2); m4(1, 0) = m0(1, 0) * m1(0, 0) + m0(1, 1) * m1(1, 0) + m0(1, 2) * m1(2, 0); m4(1, 1) = m0(1, 0) * m1(0, 1) + m0(1, 1) * m1(1, 1) + m0(1, 2) * m1(2, 1); m4(1, 2) = m0(1, 0) * m1(0, 2) + m0(1, 1) * m1(1, 2) + m0(1, 2) * m1(2, 2); m4(2, 0) = m0(2, 0) * m1(0, 0) + m0(2, 1) * m1(1, 0) + m0(2, 2) * m1(2, 0); m4(2, 1) = m0(2, 0) * m1(0, 1) + m0(2, 1) * m1(1, 1) + m0(2, 2) * m1(2, 1); m4(2, 2) = m0(2, 0) * m1(0, 2) + m0(2, 1) * m1(1, 2) + m0(2, 2) * m1(2, 2); m4(0, 3) = m0(0, 0) * m1(0, 3) + m0(0, 1) * m1(1, 3) + m0(0, 2) * m1(2, 3) + m0(0, 3); m4(1, 3) = m0(1, 0) * m1(0, 3) + m0(1, 1) * m1(1, 3) + m0(1, 2) * m1(2, 3) + m0(1, 3); m4(2, 3) = m0(2, 0) * m1(0, 3) + m0(2, 1) * m1(1, 3) + m0(2, 2) * m1(2, 3) + m0(2, 3); m4(3, 0) = m4(3, 1) = m4(3, 2) = 0.0; m4(3, 3) = 1.0; return m4; } @note 9 muls, 9 adds TVec3<T> transform(const TVec3<T>& v) const { const TMat4& m = *this; return TVec3<T>( m(0, 0) * v.x() + m(0, 1) * v.y() + m(0, 2) * v.z() + m(0, 3), m(1, 0) * v.x() + m(1, 1) * v.y() + m(1, 2) * v.z() + m(1, 3), m(2, 0) * v.x() + m(2, 1) * v.y() + m(2, 2) * v.z() + m(2, 3)); } @} }; #if ANKI_SIMD == ANKI_SIMD_SSE // Forward declare specializations template<> TMat4<F32>::Base::TMat(const TMat4<F32>::Base& b); template<> TMat4<F32>::Base::TMat(const F32 f); template<> TMat4<F32>& TMat4<F32>::Base::operator=(const TMat4<F32>& b); template<> TMat4<F32> TMat4<F32>::Base::operator+(const TMat4<F32>& b) const; template<> TMat4<F32>& TMat4<F32>::Base::operator+=(const TMat4<F32>& b); template<> TMat4<F32> TMat4<F32>::Base::operator-(const TMat4<F32>& b) const; template<> TMat4<F32>& TMat4<F32>::Base::operator-=(const TMat4<F32>& b); template<> TMat4<F32> TMat4<F32>::Base::operator*(const TMat4<F32>& b) const; template<> TVec4<F32> TMat4<F32>::Base::operator*(const TVec4<F32>& b) const; template<> void TMat4<F32>::Base::setRows(const TVec4<F32>& a, const TVec4<F32>& b, const TVec4<F32>& c, const TVec4<F32>& d); template<> void TMat4<F32>::Base::setRow(const U i, const TVec4<F32>& v); template<> void TMat4<F32>::Base::transpose(); #elif ANKI_SIMD == ANKI_SIMD_NEON # error "TODO" #endif F32 4x4 matrix typedef TMat4<F32> Mat4; static_assert(sizeof(Mat4) == sizeof(F32) * 4 * 4, "Incorrect size"); @} } // end namespace anki #include "anki/math/Mat4.inl.h" #endif
// The LLVM Compiler Infrastructure // This file is distributed under the University of Illinois Open Source \file This file moves ARGUMENT instructions after ScheduleDAG scheduling. Arguments are really live-in registers, however, since we use virtual registers and LLVM doesn't support live-in virtual registers, we're currently making do with ARGUMENT instructions which are placed at the top of the entry block. The trick is to get them to *stay* at the top of the entry block. The ARGUMENTS physical register keeps these instructions pinned in place during liveness-aware CodeGen passes, however one thing which does not respect this is the ScheduleDAG scheduler. This pass is therefore run immediately after that. This is all hopefully a temporary solution until we find a better solution for describing the live-in nature of arguments. #include "MCTargetDesc/<API key>.h" #include "WebAssembly.h" #include "<API key>.h" #include "<API key>.h" #include "<API key>.h" #include "llvm/CodeGen/<API key>.h" #include "llvm/CodeGen/MachineRegisterInfo.h" #include "llvm/CodeGen/Passes.h" #include "llvm/Support/Debug.h" #include "llvm/Support/raw_ostream.h" using namespace llvm; #define DEBUG_TYPE "wasm-argument-move" namespace { class <API key> final : public MachineFunctionPass { public: static char ID; // Pass identification, replacement for typeid <API key>() : MachineFunctionPass(ID) {} StringRef getPassName() const override { return "WebAssembly Argument Move"; } void getAnalysisUsage(AnalysisUsage &AU) const override { AU.setPreservesCFG(); AU.addPreserved<<API key>>(); AU.addPreservedID(MachineDominatorsID); MachineFunctionPass::getAnalysisUsage(AU); } bool <API key>(MachineFunction &MF) override; }; } // end anonymous namespace char <API key>::ID = 0; INITIALIZE_PASS(<API key>, DEBUG_TYPE, "Move ARGUMENT instructions for WebAssembly", false, false) FunctionPass *llvm::<API key>() { return new <API key>(); } bool <API key>::<API key>(MachineFunction &MF) { LLVM_DEBUG({ dbgs() << "********** Argument Move **********\n" << "********** Function: " << MF.getName() << '\n'; }); bool Changed = false; MachineBasicBlock &EntryMBB = MF.front(); MachineBasicBlock::iterator InsertPt = EntryMBB.end(); // Look for the first NonArg instruction. for (MachineInstr &MI : EntryMBB) { if (!WebAssembly::isArgument(MI)) { InsertPt = MI; break; } } // Now move any argument instructions later in the block // to before our first NonArg instruction. for (MachineInstr &MI : llvm::make_range(InsertPt, EntryMBB.end())) { if (WebAssembly::isArgument(MI)) { EntryMBB.insert(InsertPt, MI.removeFromParent()); Changed = true; } } return Changed; }
// This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // You should have received a copy of the GNU Lesser General Public // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. package gnu.trove.map.hash; // THIS IS A GENERATED CLASS. DO NOT HAND EDIT! // import gnu.trove.map.TShortByteMap; import gnu.trove.function.TByteFunction; import gnu.trove.procedure.*; import gnu.trove.set.*; import gnu.trove.iterator.*; import gnu.trove.iterator.hash.*; import gnu.trove.impl.hash.*; import gnu.trove.impl.HashFunctions; import gnu.trove.*; import java.io.*; import java.util.*; /** * An open addressed Map implementation for short keys and byte values. * * @author Eric D. Friedman * @author Rob Eden * @author Jeff Randall * @version $Id: _K__V_HashMap.template,v 1.1.2.16 2010/03/02 04:09:50 robeden Exp $ */ public class TShortByteHashMap extends TShortByteHash implements TShortByteMap, Externalizable { static final long serialVersionUID = 1L; /** the values of the map */ protected transient byte[] _values; /** * Creates a new <code>TShortByteHashMap</code> instance with the default * capacity and load factor. */ public TShortByteHashMap() { super(); } /** * Creates a new <code>TShortByteHashMap</code> instance with a prime * capacity equal to or greater than <tt>initialCapacity</tt> and * with the default load factor. * * @param initialCapacity an <code>int</code> value */ public TShortByteHashMap( int initialCapacity ) { super( initialCapacity ); } /** * Creates a new <code>TShortByteHashMap</code> instance with a prime * capacity equal to or greater than <tt>initialCapacity</tt> and * with the specified load factor. * * @param initialCapacity an <code>int</code> value * @param loadFactor a <code>float</code> value */ public TShortByteHashMap( int initialCapacity, float loadFactor ) { super( initialCapacity, loadFactor ); } /** * Creates a new <code>TShortByteHashMap</code> instance with a prime * capacity equal to or greater than <tt>initialCapacity</tt> and * with the specified load factor. * * @param initialCapacity an <code>int</code> value * @param loadFactor a <code>float</code> value * @param noEntryKey a <code>short</code> value that represents * <tt>null</tt> for the Key set. * @param noEntryValue a <code>byte</code> value that represents * <tt>null</tt> for the Value set. */ public TShortByteHashMap( int initialCapacity, float loadFactor, short noEntryKey, byte noEntryValue ) { super( initialCapacity, loadFactor, noEntryKey, noEntryValue ); } /** * Creates a new <code>TShortByteHashMap</code> instance containing * all of the entries in the map passed in. * * @param keys a <tt>short</tt> array containing the keys for the matching values. * @param values a <tt>byte</tt> array containing the values. */ public TShortByteHashMap( short[] keys, byte[] values ) { super( Math.max( keys.length, values.length ) ); int size = Math.min( keys.length, values.length ); for ( int i = 0; i < size; i++ ) { this.put( keys[i], values[i] ); } } /** * Creates a new <code>TShortByteHashMap</code> instance containing * all of the entries in the map passed in. * * @param map a <tt>TShortByteMap</tt> that will be duplicated. */ public TShortByteHashMap( TShortByteMap map ) { super( map.size() ); if ( map instanceof TShortByteHashMap ) { TShortByteHashMap hashmap = ( TShortByteHashMap ) map; this._loadFactor = hashmap._loadFactor; this.no_entry_key = hashmap.no_entry_key; this.no_entry_value = hashmap.no_entry_value; //noinspection RedundantCast if ( this.no_entry_key != ( short ) 0 ) { Arrays.fill( _set, this.no_entry_key ); } //noinspection RedundantCast if ( this.no_entry_value != ( byte ) 0 ) { Arrays.fill( _values, this.no_entry_value ); } setUp( (int) Math.ceil( DEFAULT_CAPACITY / _loadFactor ) ); } putAll( map ); } /** * initializes the hashtable to a prime capacity which is at least * <tt>initialCapacity + 1</tt>. * * @param initialCapacity an <code>int</code> value * @return the actual capacity chosen */ protected int setUp( int initialCapacity ) { int capacity; capacity = super.setUp( initialCapacity ); _values = new byte[capacity]; return capacity; } /** * rehashes the map to the new capacity. * * @param newCapacity an <code>int</code> value */ /** {@inheritDoc} */ protected void rehash( int newCapacity ) { int oldCapacity = _set.length; short oldKeys[] = _set; byte oldVals[] = _values; byte oldStates[] = _states; _set = new short[newCapacity]; _values = new byte[newCapacity]; _states = new byte[newCapacity]; for ( int i = oldCapacity; i if( oldStates[i] == FULL ) { short o = oldKeys[i]; int index = insertKey( o ); _values[index] = oldVals[i]; } } } /** {@inheritDoc} */ public byte put( short key, byte value ) { int index = insertKey( key ); return doPut( key, value, index ); } /** {@inheritDoc} */ public byte putIfAbsent( short key, byte value ) { int index = insertKey( key ); if (index < 0) return _values[-index - 1]; return doPut( key, value, index ); } private byte doPut( short key, byte value, int index ) { byte previous = no_entry_value; boolean isNewMapping = true; if ( index < 0 ) { index = -index -1; previous = _values[index]; isNewMapping = false; } _values[index] = value; if (isNewMapping) { postInsertHook( consumeFreeSlot ); } return previous; } /** {@inheritDoc} */ public void putAll( Map<? extends Short, ? extends Byte> map ) { ensureCapacity( map.size() ); // could optimize this for cases when map instanceof THashMap for ( Map.Entry<? extends Short, ? extends Byte> entry : map.entrySet() ) { this.put( entry.getKey().shortValue(), entry.getValue().byteValue() ); } } /** {@inheritDoc} */ public void putAll( TShortByteMap map ) { ensureCapacity( map.size() ); TShortByteIterator iter = map.iterator(); while ( iter.hasNext() ) { iter.advance(); this.put( iter.key(), iter.value() ); } } /** {@inheritDoc} */ public byte get( short key ) { int index = index( key ); return index < 0 ? no_entry_value : _values[index]; } /** {@inheritDoc} */ public void clear() { super.clear(); Arrays.fill( _set, 0, _set.length, no_entry_key ); Arrays.fill( _values, 0, _values.length, no_entry_value ); Arrays.fill( _states, 0, _states.length, FREE ); } /** {@inheritDoc} */ public boolean isEmpty() { return 0 == _size; } /** {@inheritDoc} */ public byte remove( short key ) { byte prev = no_entry_value; int index = index( key ); if ( index >= 0 ) { prev = _values[index]; removeAt( index ); // clear key,state; adjust size } return prev; } /** {@inheritDoc} */ protected void removeAt( int index ) { _values[index] = no_entry_value; super.removeAt( index ); // clear key, state; adjust size } /** {@inheritDoc} */ public TShortSet keySet() { return new TKeyView(); } /** {@inheritDoc} */ public short[] keys() { short[] keys = new short[size()]; short[] k = _set; byte[] states = _states; for ( int i = k.length, j = 0; i if ( states[i] == FULL ) { keys[j++] = k[i]; } } return keys; } /** {@inheritDoc} */ public short[] keys( short[] array ) { int size = size(); if ( array.length < size ) { array = new short[size]; } short[] keys = _set; byte[] states = _states; for ( int i = keys.length, j = 0; i if ( states[i] == FULL ) { array[j++] = keys[i]; } } return array; } /** {@inheritDoc} */ public TByteCollection valueCollection() { return new TValueView(); } /** {@inheritDoc} */ public byte[] values() { byte[] vals = new byte[size()]; byte[] v = _values; byte[] states = _states; for ( int i = v.length, j = 0; i if ( states[i] == FULL ) { vals[j++] = v[i]; } } return vals; } /** {@inheritDoc} */ public byte[] values( byte[] array ) { int size = size(); if ( array.length < size ) { array = new byte[size]; } byte[] v = _values; byte[] states = _states; for ( int i = v.length, j = 0; i if ( states[i] == FULL ) { array[j++] = v[i]; } } return array; } /** {@inheritDoc} */ public boolean containsValue( byte val ) { byte[] states = _states; byte[] vals = _values; for ( int i = vals.length; i if ( states[i] == FULL && val == vals[i] ) { return true; } } return false; } /** {@inheritDoc} */ public boolean containsKey( short key ) { return contains( key ); } /** {@inheritDoc} */ public TShortByteIterator iterator() { return new <API key>( this ); } /** {@inheritDoc} */ public boolean forEachKey( TShortProcedure procedure ) { return forEach( procedure ); } /** {@inheritDoc} */ public boolean forEachValue( TByteProcedure procedure ) { byte[] states = _states; byte[] values = _values; for ( int i = values.length; i if ( states[i] == FULL && ! procedure.execute( values[i] ) ) { return false; } } return true; } /** {@inheritDoc} */ public boolean forEachEntry( TShortByteProcedure procedure ) { byte[] states = _states; short[] keys = _set; byte[] values = _values; for ( int i = keys.length; i if ( states[i] == FULL && ! procedure.execute( keys[i], values[i] ) ) { return false; } } return true; } /** {@inheritDoc} */ public void transformValues( TByteFunction function ) { byte[] states = _states; byte[] values = _values; for ( int i = values.length; i if ( states[i] == FULL ) { values[i] = function.execute( values[i] ); } } } /** {@inheritDoc} */ public boolean retainEntries( TShortByteProcedure procedure ) { boolean modified = false; byte[] states = _states; short[] keys = _set; byte[] values = _values; // Temporarily disable compaction. This is a fix for bug #1738760 <API key>(); try { for ( int i = keys.length; i if ( states[i] == FULL && ! procedure.execute( keys[i], values[i] ) ) { removeAt( i ); modified = true; } } } finally { <API key>( true ); } return modified; } /** {@inheritDoc} */ public boolean increment( short key ) { return adjustValue( key, ( byte ) 1 ); } /** {@inheritDoc} */ public boolean adjustValue( short key, byte amount ) { int index = index( key ); if (index < 0) { return false; } else { _values[index] += amount; return true; } } /** {@inheritDoc} */ public byte adjustOrPutValue( short key, byte adjust_amount, byte put_amount ) { int index = insertKey( key ); final boolean isNewMapping; final byte newValue; if ( index < 0 ) { index = -index -1; newValue = ( _values[index] += adjust_amount ); isNewMapping = false; } else { newValue = ( _values[index] = put_amount ); isNewMapping = true; } byte previousState = _states[index]; if ( isNewMapping ) { postInsertHook(consumeFreeSlot); } return newValue; } /** a view onto the keys of the map. */ protected class TKeyView implements TShortSet { /** {@inheritDoc} */ public TShortIterator iterator() { return new <API key>( TShortByteHashMap.this ); } /** {@inheritDoc} */ public short getNoEntryValue() { return no_entry_key; } /** {@inheritDoc} */ public int size() { return _size; } /** {@inheritDoc} */ public boolean isEmpty() { return 0 == _size; } /** {@inheritDoc} */ public boolean contains( short entry ) { return TShortByteHashMap.this.contains( entry ); } /** {@inheritDoc} */ public short[] toArray() { return TShortByteHashMap.this.keys(); } /** {@inheritDoc} */ public short[] toArray( short[] dest ) { return TShortByteHashMap.this.keys( dest ); } /** * Unsupported when operating upon a Key Set view of a TShortByteMap * <p/> * {@inheritDoc} */ public boolean add( short entry ) { throw new <API key>(); } /** {@inheritDoc} */ public boolean remove( short entry ) { return no_entry_value != TShortByteHashMap.this.remove( entry ); } /** {@inheritDoc} */ public boolean containsAll( Collection<?> collection ) { for ( Object element : collection ) { if ( element instanceof Short ) { short ele = ( ( Short ) element ).shortValue(); if ( ! TShortByteHashMap.this.containsKey( ele ) ) { return false; } } else { return false; } } return true; } /** {@inheritDoc} */ public boolean containsAll( TShortCollection collection ) { TShortIterator iter = collection.iterator(); while ( iter.hasNext() ) { if ( ! TShortByteHashMap.this.containsKey( iter.next() ) ) { return false; } } return true; } /** {@inheritDoc} */ public boolean containsAll( short[] array ) { for ( short element : array ) { if ( ! TShortByteHashMap.this.contains( element ) ) { return false; } } return true; } /** * Unsupported when operating upon a Key Set view of a TShortByteMap * <p/> * {@inheritDoc} */ public boolean addAll( Collection<? extends Short> collection ) { throw new <API key>(); } /** * Unsupported when operating upon a Key Set view of a TShortByteMap * <p/> * {@inheritDoc} */ public boolean addAll( TShortCollection collection ) { throw new <API key>(); } /** * Unsupported when operating upon a Key Set view of a TShortByteMap * <p/> * {@inheritDoc} */ public boolean addAll( short[] array ) { throw new <API key>(); } /** {@inheritDoc} */ @SuppressWarnings({"<API key>"}) public boolean retainAll( Collection<?> collection ) { boolean modified = false; TShortIterator iter = iterator(); while ( iter.hasNext() ) { if ( ! collection.contains( Short.valueOf ( iter.next() ) ) ) { iter.remove(); modified = true; } } return modified; } /** {@inheritDoc} */ public boolean retainAll( TShortCollection collection ) { if ( this == collection ) { return false; } boolean modified = false; TShortIterator iter = iterator(); while ( iter.hasNext() ) { if ( ! collection.contains( iter.next() ) ) { iter.remove(); modified = true; } } return modified; } /** {@inheritDoc} */ public boolean retainAll( short[] array ) { boolean changed = false; Arrays.sort( array ); short[] set = _set; byte[] states = _states; for ( int i = set.length; i if ( states[i] == FULL && ( Arrays.binarySearch( array, set[i] ) < 0) ) { removeAt( i ); changed = true; } } return changed; } /** {@inheritDoc} */ public boolean removeAll( Collection<?> collection ) { boolean changed = false; for ( Object element : collection ) { if ( element instanceof Short ) { short c = ( ( Short ) element ).shortValue(); if ( remove( c ) ) { changed = true; } } } return changed; } /** {@inheritDoc} */ public boolean removeAll( TShortCollection collection ) { if ( this == collection ) { clear(); return true; } boolean changed = false; TShortIterator iter = collection.iterator(); while ( iter.hasNext() ) { short element = iter.next(); if ( remove( element ) ) { changed = true; } } return changed; } /** {@inheritDoc} */ public boolean removeAll( short[] array ) { boolean changed = false; for ( int i = array.length; i if ( remove( array[i] ) ) { changed = true; } } return changed; } /** {@inheritDoc} */ public void clear() { TShortByteHashMap.this.clear(); } /** {@inheritDoc} */ public boolean forEach( TShortProcedure procedure ) { return TShortByteHashMap.this.forEachKey( procedure ); } @Override public boolean equals( Object other ) { if (! (other instanceof TShortSet)) { return false; } final TShortSet that = ( TShortSet ) other; if ( that.size() != this.size() ) { return false; } for ( int i = _states.length; i if ( _states[i] == FULL ) { if ( ! that.contains( _set[i] ) ) { return false; } } } return true; } @Override public int hashCode() { int hashcode = 0; for ( int i = _states.length; i if ( _states[i] == FULL ) { hashcode += HashFunctions.hash( _set[i] ); } } return hashcode; } @Override public String toString() { final StringBuilder buf = new StringBuilder( "{" ); forEachKey( new TShortProcedure() { private boolean first = true; public boolean execute( short key ) { if ( first ) { first = false; } else { buf.append( ", " ); } buf.append( key ); return true; } } ); buf.append( "}" ); return buf.toString(); } } /** a view onto the values of the map. */ protected class TValueView implements TByteCollection { /** {@inheritDoc} */ public TByteIterator iterator() { return new <API key>( TShortByteHashMap.this ); } /** {@inheritDoc} */ public byte getNoEntryValue() { return no_entry_value; } /** {@inheritDoc} */ public int size() { return _size; } /** {@inheritDoc} */ public boolean isEmpty() { return 0 == _size; } /** {@inheritDoc} */ public boolean contains( byte entry ) { return TShortByteHashMap.this.containsValue( entry ); } /** {@inheritDoc} */ public byte[] toArray() { return TShortByteHashMap.this.values(); } /** {@inheritDoc} */ public byte[] toArray( byte[] dest ) { return TShortByteHashMap.this.values( dest ); } public boolean add( byte entry ) { throw new <API key>(); } /** {@inheritDoc} */ public boolean remove( byte entry ) { byte[] values = _values; short[] set = _set; for ( int i = values.length; i if ( ( set[i] != FREE && set[i] != REMOVED ) && entry == values[i] ) { removeAt( i ); return true; } } return false; } /** {@inheritDoc} */ public boolean containsAll( Collection<?> collection ) { for ( Object element : collection ) { if ( element instanceof Byte ) { byte ele = ( ( Byte ) element ).byteValue(); if ( ! TShortByteHashMap.this.containsValue( ele ) ) { return false; } } else { return false; } } return true; } /** {@inheritDoc} */ public boolean containsAll( TByteCollection collection ) { TByteIterator iter = collection.iterator(); while ( iter.hasNext() ) { if ( ! TShortByteHashMap.this.containsValue( iter.next() ) ) { return false; } } return true; } /** {@inheritDoc} */ public boolean containsAll( byte[] array ) { for ( byte element : array ) { if ( ! TShortByteHashMap.this.containsValue( element ) ) { return false; } } return true; } /** {@inheritDoc} */ public boolean addAll( Collection<? extends Byte> collection ) { throw new <API key>(); } /** {@inheritDoc} */ public boolean addAll( TByteCollection collection ) { throw new <API key>(); } /** {@inheritDoc} */ public boolean addAll( byte[] array ) { throw new <API key>(); } /** {@inheritDoc} */ @SuppressWarnings({"<API key>"}) public boolean retainAll( Collection<?> collection ) { boolean modified = false; TByteIterator iter = iterator(); while ( iter.hasNext() ) { if ( ! collection.contains( Byte.valueOf ( iter.next() ) ) ) { iter.remove(); modified = true; } } return modified; } /** {@inheritDoc} */ public boolean retainAll( TByteCollection collection ) { if ( this == collection ) { return false; } boolean modified = false; TByteIterator iter = iterator(); while ( iter.hasNext() ) { if ( ! collection.contains( iter.next() ) ) { iter.remove(); modified = true; } } return modified; } /** {@inheritDoc} */ public boolean retainAll( byte[] array ) { boolean changed = false; Arrays.sort( array ); byte[] values = _values; byte[] states = _states; for ( int i = values.length; i if ( states[i] == FULL && ( Arrays.binarySearch( array, values[i] ) < 0) ) { removeAt( i ); changed = true; } } return changed; } /** {@inheritDoc} */ public boolean removeAll( Collection<?> collection ) { boolean changed = false; for ( Object element : collection ) { if ( element instanceof Byte ) { byte c = ( ( Byte ) element ).byteValue(); if ( remove( c ) ) { changed = true; } } } return changed; } /** {@inheritDoc} */ public boolean removeAll( TByteCollection collection ) { if ( this == collection ) { clear(); return true; } boolean changed = false; TByteIterator iter = collection.iterator(); while ( iter.hasNext() ) { byte element = iter.next(); if ( remove( element ) ) { changed = true; } } return changed; } /** {@inheritDoc} */ public boolean removeAll( byte[] array ) { boolean changed = false; for ( int i = array.length; i if ( remove( array[i] ) ) { changed = true; } } return changed; } /** {@inheritDoc} */ public void clear() { TShortByteHashMap.this.clear(); } /** {@inheritDoc} */ public boolean forEach( TByteProcedure procedure ) { return TShortByteHashMap.this.forEachValue( procedure ); } /** {@inheritDoc} */ @Override public String toString() { final StringBuilder buf = new StringBuilder( "{" ); forEachValue( new TByteProcedure() { private boolean first = true; public boolean execute( byte value ) { if ( first ) { first = false; } else { buf.append( ", " ); } buf.append( value ); return true; } } ); buf.append( "}" ); return buf.toString(); } } class <API key> extends <API key> implements TShortIterator { /** * Creates an iterator over the specified map * * @param hash the <tt>TPrimitiveHash</tt> we will be iterating over. */ <API key>( TPrimitiveHash hash ) { super( hash ); } /** {@inheritDoc} */ public short next() { moveToNextIndex(); return _set[_index]; } /** @{inheritDoc} */ public void remove() { if ( _expectedSize != _hash.size() ) { throw new <API key>(); } // Disable auto compaction during the remove. This is a workaround for bug 1642768. try { _hash.<API key>(); TShortByteHashMap.this.removeAt( _index ); } finally { _hash.<API key>( false ); } _expectedSize } } class <API key> extends <API key> implements TByteIterator { /** * Creates an iterator over the specified map * * @param hash the <tt>TPrimitiveHash</tt> we will be iterating over. */ <API key>( TPrimitiveHash hash ) { super( hash ); } /** {@inheritDoc} */ public byte next() { moveToNextIndex(); return _values[_index]; } /** @{inheritDoc} */ public void remove() { if ( _expectedSize != _hash.size() ) { throw new <API key>(); } // Disable auto compaction during the remove. This is a workaround for bug 1642768. try { _hash.<API key>(); TShortByteHashMap.this.removeAt( _index ); } finally { _hash.<API key>( false ); } _expectedSize } } class <API key> extends <API key> implements TShortByteIterator { /** * Creates an iterator over the specified map * * @param map the <tt>TShortByteHashMap</tt> we will be iterating over. */ <API key>( TShortByteHashMap map ) { super( map ); } /** {@inheritDoc} */ public void advance() { moveToNextIndex(); } /** {@inheritDoc} */ public short key() { return _set[_index]; } /** {@inheritDoc} */ public byte value() { return _values[_index]; } /** {@inheritDoc} */ public byte setValue( byte val ) { byte old = value(); _values[_index] = val; return old; } /** @{inheritDoc} */ public void remove() { if ( _expectedSize != _hash.size() ) { throw new <API key>(); } // Disable auto compaction during the remove. This is a workaround for bug 1642768. try { _hash.<API key>(); TShortByteHashMap.this.removeAt( _index ); } finally { _hash.<API key>( false ); } _expectedSize } } /** {@inheritDoc} */ @Override public boolean equals( Object other ) { if ( ! ( other instanceof TShortByteMap ) ) { return false; } TShortByteMap that = ( TShortByteMap ) other; if ( that.size() != this.size() ) { return false; } byte[] values = _values; byte[] states = _states; byte this_no_entry_value = getNoEntryValue(); byte that_no_entry_value = that.getNoEntryValue(); for ( int i = values.length; i if ( states[i] == FULL ) { short key = _set[i]; byte that_value = that.get( key ); byte this_value = values[i]; if ( ( this_value != that_value ) && ( this_value != this_no_entry_value ) && ( that_value != that_no_entry_value ) ) { return false; } } } return true; } /** {@inheritDoc} */ @Override public int hashCode() { int hashcode = 0; byte[] states = _states; for ( int i = _values.length; i if ( states[i] == FULL ) { hashcode += HashFunctions.hash( _set[i] ) ^ HashFunctions.hash( _values[i] ); } } return hashcode; } /** {@inheritDoc} */ @Override public String toString() { final StringBuilder buf = new StringBuilder( "{" ); forEachEntry( new TShortByteProcedure() { private boolean first = true; public boolean execute( short key, byte value ) { if ( first ) first = false; else buf.append( ", " ); buf.append(key); buf.append("="); buf.append(value); return true; } }); buf.append( "}" ); return buf.toString(); } /** {@inheritDoc} */ public void writeExternal(ObjectOutput out) throws IOException { // VERSION out.writeByte( 0 ); // SUPER super.writeExternal( out ); // NUMBER OF ENTRIES out.writeInt( _size ); // ENTRIES for ( int i = _states.length; i if ( _states[i] == FULL ) { out.writeShort( _set[i] ); out.writeByte( _values[i] ); } } } /** {@inheritDoc} */ public void readExternal(ObjectInput in) throws IOException, <API key> { // VERSION in.readByte(); // SUPER super.readExternal( in ); // NUMBER OF ENTRIES int size = in.readInt(); setUp( size ); // ENTRIES while (size short key = in.readShort(); byte val = in.readByte(); put(key, val); } } } // TShortByteHashMap
#ifndef <API key> #define <API key> #include "core/dom/MutationObserver.h" #include "platform/heap/Handle.h" #include "wtf/HashSet.h" #include "wtf/text/AtomicString.h" #include "wtf/text/AtomicStringHash.h" namespace blink { class QualifiedName; class <API key> final : public <API key><<API key>> { public: static <API key>* create(MutationObserver&, Node*, <API key>, const HashSet<AtomicString>& attributeFilter); ~<API key>(); void resetObservation(<API key>, const HashSet<AtomicString>& attributeFilter); void <API key>(Node&); void <API key>(); bool <API key>() const { return <API key> && !<API key>->isEmpty(); } void unregister(); bool <API key>(Node&, MutationObserver::MutationType, const QualifiedName* attributeName) const; bool isSubtree() const { return m_options & MutationObserver::Subtree; } MutationObserver& observer() const { return *m_observer; } <API key> deliveryOptions() const { return m_options & (MutationObserver::AttributeOldValue | MutationObserver::<API key>); } <API key> mutationTypes() const { return m_options & MutationObserver::AllMutationTypes; } void <API key>(HeapHashSet<Member<Node>>&) const; DECLARE_TRACE(); void dispose(); private: <API key>(MutationObserver&, Node*, <API key>, const HashSet<AtomicString>& attributeFilter); Member<MutationObserver> m_observer; WeakMember<Node> m_registrationNode; Member<Node> <API key>; typedef HeapHashSet<Member<Node>> NodeHashSet; Member<NodeHashSet> <API key>; <API key> m_options; HashSet<AtomicString> m_attributeFilter; }; } // namespace blink #endif // <API key>
package org.chromium.chrome.browser.signin; import android.accounts.Account; import androidx.annotation.Nullable; import androidx.annotation.VisibleForTesting; import org.chromium.base.ApplicationState; import org.chromium.base.ApplicationStatus; import org.chromium.base.Log; import org.chromium.base.TraceEvent; import org.chromium.base.metrics.RecordUserAction; import org.chromium.chrome.browser.<API key>; import org.chromium.chrome.browser.signin.services.SigninManager; import org.chromium.chrome.browser.signin.services.SigninManager.SignInCallback; import org.chromium.chrome.browser.sync.SyncService; import org.chromium.chrome.browser.sync.SyncUserDataWiper; import org.chromium.components.signin.<API key>; import org.chromium.components.signin.<API key>; import org.chromium.components.signin.<API key>; import org.chromium.components.signin.AccountUtils; import org.chromium.components.signin.ChildAccountStatus; import org.chromium.components.signin.ChildAccountStatus.Status; import org.chromium.components.signin.base.CoreAccountInfo; import org.chromium.components.signin.identitymanager.<API key>; import org.chromium.components.signin.identitymanager.ConsentLevel; import org.chromium.components.signin.metrics.SigninAccessPoint; import org.chromium.components.signin.metrics.SignoutReason; import java.util.List; /** * This class regroups sign-in checks when chrome starts up and when accounts change on device */ public class SigninChecker implements ApplicationStatus.<API key>, <API key>.Observer { private static final String TAG = "SigninChecker"; private final SigninManager mSigninManager; private final <API key> <API key>; private final <API key> <API key>; // Counter to record the number of child account checks done for tests. private int <API key>; /** * Please use <API key> to get {@link SigninChecker} instance instead of creating it * manually. */ public SigninChecker(SigninManager signinManager, <API key> <API key>) { mSigninManager = signinManager; <API key> = <API key>; <API key> = <API key>.getInstance(); <API key> = 0; ApplicationStatus.<API key>(this); <API key>.addObserver(this); } private void <API key>() { <API key>.getAccounts().then(accounts -> { <API key>.<API key>(() -> { mSigninManager.<API key>(() -> { <API key>(accounts, /*accountsChanged=*/false); checkChildAccount(accounts); }); }); }); } /** * This method is invoked every time the accounts on device are seeded. */ @Override public void onAccountsSeeded(List<CoreAccountInfo> accountInfos, boolean accountsChanged) { final List<Account> accounts = AccountUtils.toAndroidAccounts(accountInfos); mSigninManager.<API key>(() -> { <API key>(accounts, accountsChanged); checkChildAccount(accounts); }); } @VisibleForTesting public int <API key>() { return <API key>; } /** * Validates that the primary account exists on device. */ private void <API key>(List<Account> accounts, boolean accountsChanged) { final CoreAccountInfo oldAccount = mSigninManager.getIdentityManager().<API key>(ConsentLevel.SIGNIN); boolean oldSyncConsent = mSigninManager.getIdentityManager().<API key>(ConsentLevel.SYNC) != null; if (oldAccount == null) { // Do nothing if user is not signed in return; } if (AccountUtils.findAccountByName(accounts, oldAccount.getEmail()) != null) { // Reload the accounts if the primary account is still on device and this is triggered // by an accounts change event. if (accountsChanged) { mSigninManager.<API key>(oldAccount.getId()); } return; } // Check whether the primary account is renamed to another account when it is not on device <API key>.get() .<API key>(oldAccount.getEmail(), accounts) .then(newAccountName -> { if (newAccountName != null) { // Sign in to the new account if the current primary account is renamed to // a new account. <API key>(newAccountName, oldSyncConsent); } else { // Sign out if the current primary account is not renamed mSigninManager.signOut(SignoutReason.<API key>); } }); } private void <API key>(String newAccountName, boolean shouldEnableSync) { mSigninManager.signOut(SignoutReason.<API key>, () -> { if (shouldEnableSync) { mSigninManager.signinAndEnableSync(SigninAccessPoint.ACCOUNT_RENAMED, AccountUtils.<API key>(newAccountName), new SignInCallback() { @Override public void onSignInComplete() { SyncService.get().<API key>( <API key>.BASIC_FLOW); } @Override public void onSignInAborted() {} }); } else { mSigninManager.signin(AccountUtils.<API key>(newAccountName), null); } }, false); } private void checkChildAccount(List<Account> accounts) { AccountUtils.<API key>( <API key>, accounts, this::<API key>); } private void <API key>(@Status int status, @Nullable Account childAccount) { if (ChildAccountStatus.isChild(status)) { assert childAccount != null; mSigninManager.onFirstRunCheckDone(); if (mSigninManager.isSignInAllowed()) { Log.d(TAG, "The child account sign-in starts."); final SignInCallback signInCallback = new SignInCallback() { @Override public void onSignInComplete() { final SyncService syncService = SyncService.get(); if (syncService != null) { syncService.<API key>( <API key>.BASIC_FLOW); } ++<API key>; } @Override public void onSignInAborted() {} }; SyncUserDataWiper.wipeSyncUserData().then((Void v) -> { RecordUserAction.record("<API key>"); mSigninManager.signinAndEnableSync( SigninAccessPoint.FORCED_SIGNIN, childAccount, signInCallback); }); return; } } ++<API key>; } /** * Called once during initialization and then again for every start (warm-start). * Responsible for checking if configuration has changed since Chrome was last launched * and updates state accordingly. */ public void onMainActivityStart() { try (TraceEvent ignored = TraceEvent.scoped("SigninHelper.onMainActivityStart")) { <API key>(); } } @Override public void <API key>(int newState) { if (newState == ApplicationState.<API key>) { onMainActivityStart(); } } }
// .NAME <API key> - OpenGL rendering window // .SECTION Description // <API key> is a concrete implementation of the abstract // class vtkRenderWindow. <API key> interfaces to the standard // OpenGL graphics library in the Windows/NT environment.. #ifndef <API key> #define <API key> #include "<API key>.h" // For export macro #include "<API key>.h" class vtkIdList; class <API key> <API key> : public <API key> { public: static <API key> *New(); vtkTypeMacro(<API key>,<API key>); void PrintSelf(ostream& os, vtkIndent indent); // Description: // Begin the rendering process. virtual void Start(void); // Description: // End the rendering process and display the image. void Frame(void); // Description: // Create the window virtual void WindowInitialize(void); // Description: // Initialize the rendering window. This will setup all system-specific // resources. This method and Finalize() must be symmetric and it // should be possible to call them multiple times, even changing WindowId // in-between. This is what WindowRemap does. virtual void Initialize(void); // Description: // Finalize the rendering window. This will shutdown all system-specific // resources. After having called this, it should be possible to destroy // a window that was used for a SetWindowId() call without any ill effects. virtual void Finalize(void); // Description: // Change the window to fill the entire screen. virtual void SetFullScreen(int); // Description: // Remap the window. virtual void WindowRemap(void); // Description: // Set the preferred window size to full screen. virtual void PrefFullScreen(void); // Description: // Set the size of the window in pixels. virtual void SetSize(int,int); virtual void SetSize(int a[2]) {<API key>::SetSize(a);}; // Description: // Get the current size of the window in pixels. virtual int *GetSize(); // Description: // Set the position of the window. virtual void SetPosition(int,int); virtual void SetPosition(int a[2]) {<API key>::SetPosition(a);}; // Description: // Get the current size of the screen in pixels. virtual int *GetScreenSize(); // Description: // Get the position in screen coordinates of the window. virtual int *GetPosition(); // Description: // Set the name of the window. This appears at the top of the window // normally. virtual void SetWindowName(const char *); // Description: // Set this RenderWindow's window id to a pre-existing window. void SetWindowInfo(char *); // Description: // Sets the WindowInfo that will be used after a WindowRemap. void SetNextWindowInfo(char *); // Description: // Sets the HWND id of the window that WILL BE created. void SetParentInfo(char *); //BTX virtual void *GetGenericDisplayId() {return (void *)this->ContextId;}; virtual void *GetGenericWindowId() {return (void *)this->WindowId;}; virtual void *GetGenericParentId() {return (void *)this->ParentId;}; virtual void *GetGenericContext() {return (void *)this->DeviceContext;}; virtual void *GetGenericDrawable() {return (void *)this->WindowId;}; virtual void SetDisplayId(void *); // Description: // Get the window id. virtual HWND GetWindowId(); // Description: // Set the window id to a pre-existing window. virtual void SetWindowId(HWND); void SetWindowId(void *foo) {this->SetWindowId((HWND)foo);}; // Description: // Initialize the render window from the information associated // with the currently activated OpenGL context. virtual bool <API key>(); // Description: // Set the window's parent id to a pre-existing window. virtual void SetParentId(HWND); void SetParentId(void *foo) {this->SetParentId((HWND)foo);}; void SetContextId(HGLRC); // hsr void SetDeviceContext(HDC); // hsr // Description: // Set the window id of the new window once a WindowRemap is done. virtual void SetNextWindowId(HWND); // Description: // Set the window id of the new window once a WindowRemap is done. // This is the generic prototype as required by the vtkRenderWindow // parent. virtual void SetNextWindowId(void *arg); //ETX // Description: // Prescribe that the window be created in a stereo-capable mode. This // method must be called before the window is realized. This method // overrides the superclass method since this class can actually check // whether the window has been realized yet. virtual void <API key>(int capable); // Description: // Make this windows OpenGL context the current context. void MakeCurrent(); // Description: // Tells if this window is the current OpenGL context for the calling thread. virtual bool IsCurrent(); // Description: // Get report of capabilities for the render window const char *ReportCapabilities(); // Description: // Does this render window support OpenGL? 0-false, 1-true int SupportsOpenGL(); // Description: // Is this render window using hardware acceleration? 0-false, 1-true int IsDirect(); // Description: // Check to see if a mouse button has been pressed. // All other events are ignored by this method. // This is a useful check to abort a long render. virtual int GetEventPending(); // Description: // These methods can be used by MFC applications // to support print preview and printing, or more // general rendering into memory. void <API key>(int x, int y, HDC prn); void <API key>(HBITMAP hbmp); void <API key>(void); HDC GetMemoryDC(); unsigned char *GetMemoryData(){return this->MemoryData;}; // Description: // Initialize OpenGL for this window. virtual void SetupPalette(HDC hDC); virtual void SetupPixelFormat(HDC hDC, DWORD dwFlags, int debug, int bpp=16, int zbpp=16); // Description: // Clean up device contexts, rendering contexts, etc. void Clean(); // Description: // Hide or Show the mouse cursor, it is nice to be able to hide the // default cursor if you want VTK to display a 3D cursor instead. // Set cursor position in window (note that (0,0) is the lower left // corner). void HideCursor(); void ShowCursor(); void SetCursorPosition(int x, int y); // Description: // Change the shape of the cursor virtual void SetCurrentCursor(int); // Description: // Override the default implementation so that we can actively switch between // on and off screen rendering. virtual void <API key>(int offscreen); protected: <API key>(); ~<API key>(); HINSTANCE ApplicationInstance; HPALETTE Palette; HPALETTE OldPalette; HGLRC ContextId; HDC DeviceContext; BOOL MFChandledWindow; HWND WindowId; HWND ParentId; HWND NextWindowId; int OwnWindow; int ScreenSize[2]; // the following is used to support rendering into memory BITMAPINFO MemoryDataHeader; HBITMAP MemoryBuffer; unsigned char *MemoryData; // the data in the DIBSection HDC MemoryHdc; int ScreenMapped; int ScreenWindowSize[2]; HDC ScreenDeviceContext; int ScreenDoubleBuffer; HGLRC ScreenContextId; int <API key>; // to avoid recursion (and memory leaks...) //BTX // message handler virtual LRESULT MessageProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam); static LRESULT APIENTRY WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam); //ETX int CursorHidden; int ForceMakeCurrent; char *Capabilities; int <API key>; void <API key>(int xsize, int ysize); virtual void CreateAWindow(); virtual void DestroyWindow(); void <API key>(); void <API key>(void); void CreateOffScreenDC(int xsize, int ysize, HDC aHdc); void CreateOffScreenDC(HBITMAP hbmp, HDC aHdc); void <API key>(int width,int height); void SaveScreenRendering(); void CleanUpRenderers(); private: <API key>(const <API key>&); // Not implemented. void operator=(const <API key>&); // Not implemented. }; #endif
package de.unifreiburg.cs.proglang.jgs.signatures import de.unifreiburg.cs.proglang.jgs.constraints.TypeViews.TypeView /** * JGS Symbols that occur in method signatures. * They correspond to Jimple's Parameters, @return, or literal security levels */ sealed trait Symbol[Level] sealed case class Param[Level] (position : Int) extends Symbol[Level] { if (position < 0) { throw new <API key>(s"Negative position for parameter: ${position}") } override def toString: String = s"@param${position}" } sealed case class Return[Level] () extends Symbol[Level] { override def toString : String = "@return" } sealed case class Literal[Level] (level : TypeView[Level]) extends Symbol[Level] { override def toString : String = level.toString } object Symbol { def param[Level](pos : Int) : Param[Level] = { Param(pos) } def ret[Level]() : Return[Level] = Return() def literal[Level](t : TypeView[Level]) = Literal(t) }
# support only a few flags that might be passed through: # BUILD_PREFIX, BUILD_TYPE, CMAKE_FLAGS* CMAKE_FLAGS+=$(strip $(CMAKE_FLAGS1) $(CMAKE_FLAGS2) $(CMAKE_FLAGS3) $(CMAKE_FLAGS4) $(CMAKE_FLAGS5) $(CMAKE_FLAGS6) $(CMAKE_FLAGS7) $(CMAKE_FLAGS8) $(CMAKE_FLAGS9) $(CMAKE_FLAGS10) $(CMAKE_FLAGS11) $(CMAKE_FLAGS12) $(CMAKE_FLAGS13) $(CMAKE_FLAGS14) $(CMAKE_FLAGS15) $(CMAKE_FLAGS16) $(CMAKE_FLAGS17) $(CMAKE_FLAGS18) $(CMAKE_FLAGS19) $(CMAKE_FLAGS20)) ifneq "$(BUILD_PREFIX)" "" CMAKE_FLAGS+=-<API key>="$(BUILD_PREFIX)" endif ifeq "$(BUILD_TYPE)" "" BUILD_TYPE="Release" endif CMAKE_FLAGS+=-DCMAKE_BUILD_TYPE=$(BUILD_TYPE) CMAKE_CONFIG=--config $(BUILD_TYPE) .PHONY: all all: configure ifeq ($(OS),Windows_NT) cmake --build pod-build $(CMAKE_CONFIG) --target install else $(MAKE) -C pod-build all install endif pod-build: cmake -E make_directory pod-build .PHONY: configure configure: pod-build @echo Configuring with CMAKE_FLAGS: $(CMAKE_FLAGS) @cd pod-build && cmake $(CMAKE_FLAGS) .. .PHONY: options options: configure ifeq ($(OS),Windows_NT) cmake-gui pod-build else ccmake pod-build endif .PHONY: clean clean: cmake --build pod-build --target clean cmake -E remove_directory pod-build cmake -E remove_directory build # other (custom) targets are passed through to the cmake-generated Makefile %:: cmake --build pod-build $(CMAKE_CONFIG) --target $@ # Default to a less-verbose build. If you want all the gory compiler output, # run "make VERBOSE=1" $(VERBOSE).SILENT: rules specific to this project (everything above is the generic pods makefile wrapper of a cmake project) .PHONY: mlint mlint : matlab -nodisplay -r "addpath(fullfile(pwd,'thirdParty','runmlint')); runmlint('.mlintopts'); exit" .PHONY: test test : configure -@cd pod-build && ctest -M Experimental -C $(BUILD_TYPE) --output-on-failure --timeout 300 release_filelist: configure echo ".UNITTEST" echo ".mlintopts" find * -type f | grep -v "pod-build" | grep -v "\.valgrind" | grep -v "\.viewer-prefs" | grep -v "\.out" | grep -v "\.autosave" | grep -v "\.git" | grep -v "\.tmp" | grep -v "drake_config\.mat" | grep -v "DoxygenMatlab" | grep -v "\.aux" | grep -v "\.d" | grep -v "\.log" | grep -v "\.bib" find pod-build/lib -type f -find pod-build/bin -type f 2> /dev/null
# OpenThread on CC2538 Example This directory contains example platform drivers for the [Texas Instruments CC2538][cc2538]. [cc2538]: http: The example platform drivers are intended to present the minimal code necessary to support OpenThread. As a result, the example platform drivers do not necessarily highlight the platform's full capabilities. ## Toolchain Download and install the [GNU toolchain for ARM Cortex-M][gnu-toolchain]. [gnu-toolchain]: https://launchpad.net/gcc-arm-embedded ## Build Examples bash $ cd <path-to-openthread> $ ./bootstrap $ make -f examples/Makefile-cc2538 After a successful build, the `elf` files are found in `<path-to-openthread>/output/bin`. You can convert them to `bin` files using `<API key>`: bash $ <API key> -O binary <API key> <API key>.bin ## Flash Binaries Compiled binaries may be flashed onto the CC2538 using the [Serial Bootloader Interface][cc2538-bsl] or [JTAG interface][jtag]. The [cc2538-bsl.py script][cc2538-bsl-tool] provides a convenient method for flashing a CC2538 via the UART. [cc2538-bsl]: http: [cc2538-bsl-tool]: https://github.com/JelmerT/cc2538-bsl [jtag]: https://en.wikipedia.org/wiki/JTAG ## Interact 1. Open terminal to `/dev/ttyUSB1` (serial port settings: 115200 8-N-1). 2. Type `help` for list of commands. bash > help help channel childtimeout contextreusedelay extaddr extpanid ipaddr keysequence leaderweight masterkey mode netdataregister networkidtimeout networkname panid ping prefix releaserouterid rloc16 route <API key> scan start state stop whitelist
#ifndef __eglext_h_ #define __eglext_h_ #ifdef __cplusplus extern "C" { #endif #include <EGL/eglplatform.h> /* Header file version number */ #define EGL_EGLEXT_VERSION 10 #ifndef <API key> #define <API key> 1 #define EGL_CONFORMANT_KHR 0x3042 /* EGLConfig attribute */ #define <API key> 0x0020 /* EGL_SURFACE_TYPE bitfield */ #define <API key> 0x0040 /* EGL_SURFACE_TYPE bitfield */ #endif #ifndef <API key> #define <API key> 1 #define <API key> 0x0001 /* <API key> bitfield */ #define <API key> 0x0002 /* <API key> bitfield */ #define <API key> 0x0080 /* EGL_SURFACE_TYPE bitfield */ #define <API key> 0x0100 /* EGL_SURFACE_TYPE bitfield */ #define <API key> 0x3043 /* EGLConfig attribute */ #define <API key> 0x30C0 /* <API key> value */ #define <API key> 0x30C1 /* <API key> value */ #define <API key> 0x30C2 /* <API key> value */ #define <API key> 0x30C3 /* <API key> value */ #define <API key> 0x30C4 /* eglLockSurfaceKHR attribute */ #define <API key> 0x30C5 /* eglLockSurfaceKHR attribute */ #define <API key> 0x30C6 /* eglQuerySurface attribute */ #define <API key> 0x30C7 /* eglQuerySurface attribute */ #define <API key> 0x30C8 /* eglQuerySurface attribute */ #define <API key> 0x30C9 /* eglQuerySurface attribute */ #define <API key> 0x30CA /* eglQuerySurface attribute */ #define <API key> 0x30CB /* eglQuerySurface attribute */ #define <API key> 0x30CC /* eglQuerySurface attribute */ #define <API key> 0x30CD /* eglQuerySurface attribute */ #define EGL_LOWER_LEFT_KHR 0x30CE /* <API key> value */ #define EGL_UPPER_LEFT_KHR 0x30CF /* <API key> value */ #ifdef <API key> EGLAPI EGLBoolean EGLAPIENTRY eglLockSurfaceKHR (EGLDisplay display, EGLSurface surface, const EGLint *attrib_list); EGLAPI EGLBoolean EGLAPIENTRY eglUnlockSurfaceKHR (EGLDisplay display, EGLSurface surface); #endif /* <API key> */ typedef EGLBoolean (EGLAPIENTRYP <API key>) (EGLDisplay display, EGLSurface surface, const EGLint *attrib_list); typedef EGLBoolean (EGLAPIENTRYP <API key>) (EGLDisplay display, EGLSurface surface); #endif #ifndef EGL_KHR_image #define EGL_KHR_image 1 #define <API key> 0x30B0 /* eglCreateImageKHR target */ typedef void *EGLImageKHR; #define EGL_NO_IMAGE_KHR ((EGLImageKHR)0) #ifdef <API key> EGLAPI EGLImageKHR EGLAPIENTRY eglCreateImageKHR (EGLDisplay dpy, EGLContext ctx, EGLenum target, EGLClientBuffer buffer, const EGLint *attrib_list); EGLAPI EGLBoolean EGLAPIENTRY eglDestroyImageKHR (EGLDisplay dpy, EGLImageKHR image); #endif /* <API key> */ typedef EGLImageKHR (EGLAPIENTRYP <API key>) (EGLDisplay dpy, EGLContext ctx, EGLenum target, EGLClientBuffer buffer, const EGLint *attrib_list); typedef EGLBoolean (EGLAPIENTRYP <API key>) (EGLDisplay dpy, EGLImageKHR image); #endif #ifndef <API key> #define <API key> 1 #define <API key> 0x30BA /* eglCreateImageKHR target */ #endif #ifndef <API key> #define <API key> 1 #define <API key> 0x30B1 /* eglCreateImageKHR target */ #define <API key> 0x30BC /* eglCreateImageKHR attribute */ #endif #ifndef <API key> #define <API key> 1 #define <API key> 0x30B3 /* eglCreateImageKHR target */ #define <API key> 0x30B4 /* eglCreateImageKHR target */ #define <API key> 0x30B5 /* eglCreateImageKHR target */ #define <API key> 0x30B6 /* eglCreateImageKHR target */ #define <API key> 0x30B7 /* eglCreateImageKHR target */ #define <API key> 0x30B8 /* eglCreateImageKHR target */ #endif #ifndef <API key> #define <API key> 1 #define <API key> 0x30B2 /* eglCreateImageKHR target */ #define <API key> 0x30BD /* eglCreateImageKHR attribute */ #endif #ifndef <API key> #define <API key> 1 #define <API key> 0x30B9 /* eglCreateImageKHR target */ #endif #if <API key> /* EGLTimeKHR requires 64-bit uint support */ #ifndef <API key> #define <API key> 1 typedef void* EGLSyncKHR; typedef <API key> EGLTimeKHR; #define EGL_SYNC_STATUS_KHR 0x30F1 #define EGL_SIGNALED_KHR 0x30F2 #define EGL_UNSIGNALED_KHR 0x30F3 #define <API key> 0x30F5 #define <API key> 0x30F6 #define EGL_SYNC_TYPE_KHR 0x30F7 #define <API key> 0x30FA #define <API key> 0x0001 /* <API key> <flags> bitfield */ #define EGL_FOREVER_KHR <API key> #define EGL_NO_SYNC_KHR ((EGLSyncKHR)0) #ifdef <API key> EGLAPI EGLSyncKHR EGLAPIENTRY eglCreateSyncKHR(EGLDisplay dpy, EGLenum type, const EGLint *attrib_list); EGLAPI EGLBoolean EGLAPIENTRY eglDestroySyncKHR(EGLDisplay dpy, EGLSyncKHR sync); EGLAPI EGLint EGLAPIENTRY <API key>(EGLDisplay dpy, EGLSyncKHR sync, EGLint flags, EGLTimeKHR timeout); EGLAPI EGLBoolean EGLAPIENTRY eglSignalSyncKHR(EGLDisplay dpy, EGLSyncKHR sync, EGLenum mode); EGLAPI EGLBoolean EGLAPIENTRY eglGetSyncAttribKHR(EGLDisplay dpy, EGLSyncKHR sync, EGLint attribute, EGLint *value); #endif /* <API key> */ typedef EGLSyncKHR (EGLAPIENTRYP <API key>) (EGLDisplay dpy, EGLenum type, const EGLint *attrib_list); typedef EGLBoolean (EGLAPIENTRYP <API key>) (EGLDisplay dpy, EGLSyncKHR sync); typedef EGLint (EGLAPIENTRYP <API key>) (EGLDisplay dpy, EGLSyncKHR sync, EGLint flags, EGLTimeKHR timeout); typedef EGLBoolean (EGLAPIENTRYP <API key>) (EGLDisplay dpy, EGLSyncKHR sync, EGLenum mode); typedef EGLBoolean (EGLAPIENTRYP <API key>) (EGLDisplay dpy, EGLSyncKHR sync, EGLint attribute, EGLint *value); #endif #endif #ifndef EGL_KHR_image_base #define EGL_KHR_image_base 1 /* Most interfaces defined by <API key> above */ #define <API key> 0x30D2 /* eglCreateImageKHR attribute */ #endif #ifndef <API key> #define <API key> 1 /* Interfaces defined by EGL_KHR_image above */ #endif #ifndef <API key> #define <API key> 1 #define <API key> 0x3100 #define <API key> 0x3101 #define <API key> 0x3102 #define <API key> 0x3103 #endif #ifndef <API key> #define <API key> 1 #define <API key> 0x3110 #endif #ifndef <API key> #define <API key> 1 #define <API key> 0x30E0 #define <API key> 0x30E1 #endif #ifndef <API key> #define <API key> 1 #define <API key> 0x30E2 #define <API key> 0 #define <API key> 0x30E3 #endif #if <API key> /* EGLTimeNV requires 64-bit uint support */ #ifndef EGL_NV_sync #define EGL_NV_sync 1 #define <API key> 0x30E6 #define EGL_SYNC_STATUS_NV 0x30E7 #define EGL_SIGNALED_NV 0x30E8 #define EGL_UNSIGNALED_NV 0x30E9 #define <API key> 0x0001 #define EGL_FOREVER_NV <API key> #define <API key> 0x30EA #define <API key> 0x30EB #define <API key> 0x30EC #define EGL_SYNC_TYPE_NV 0x30ED #define <API key> 0x30EE #define EGL_SYNC_FENCE_NV 0x30EF #define EGL_NO_SYNC_NV ((EGLSyncNV)0) typedef void* EGLSyncNV; typedef <API key> EGLTimeNV; #ifdef <API key> EGLSyncNV <API key> (EGLDisplay dpy, EGLenum condition, const EGLint *attrib_list); EGLBoolean eglDestroySyncNV (EGLSyncNV sync); EGLBoolean eglFenceNV (EGLSyncNV sync); EGLint eglClientWaitSyncNV (EGLSyncNV sync, EGLint flags, EGLTimeNV timeout); EGLBoolean eglSignalSyncNV (EGLSyncNV sync, EGLenum mode); EGLBoolean eglGetSyncAttribNV (EGLSyncNV sync, EGLint attribute, EGLint *value); #endif /* <API key> */ typedef EGLSyncNV (EGLAPIENTRYP <API key>) (EGLDisplay dpy, EGLenum condition, const EGLint *attrib_list); typedef EGLBoolean (EGLAPIENTRYP <API key>) (EGLSyncNV sync); typedef EGLBoolean (EGLAPIENTRYP PFNEGLFENCENVPROC) (EGLSyncNV sync); typedef EGLint (EGLAPIENTRYP <API key>) (EGLSyncNV sync, EGLint flags, EGLTimeNV timeout); typedef EGLBoolean (EGLAPIENTRYP <API key>) (EGLSyncNV sync, EGLenum mode); typedef EGLBoolean (EGLAPIENTRYP <API key>) (EGLSyncNV sync, EGLint attribute, EGLint *value); #endif #endif #if <API key> /* Dependent on <API key> which requires 64-bit uint support */ #ifndef EGL_KHR_fence_sync #define EGL_KHR_fence_sync 1 /* Reuses most tokens and entry points from <API key> */ #define <API key> 0x30F0 #define <API key> 0x30F8 #define EGL_SYNC_FENCE_KHR 0x30F9 #endif #endif #ifndef EGL_HI_clientpixmap #define EGL_HI_clientpixmap 1 /* Surface Attribute */ #define <API key> 0x8F74 /* * Structure representing a client pixmap * (pixmap's data is in client-space memory). */ struct EGLClientPixmapHI { void* pData; EGLint iWidth; EGLint iHeight; EGLint iStride; }; #ifdef <API key> EGLAPI EGLSurface EGLAPIENTRY <API key>(EGLDisplay dpy, EGLConfig config, struct EGLClientPixmapHI* pixmap); #endif /* <API key> */ typedef EGLSurface (EGLAPIENTRYP <API key>) (EGLDisplay dpy, EGLConfig config, struct EGLClientPixmapHI* pixmap); #endif /* EGL_HI_clientpixmap */ #ifndef EGL_HI_colorformats #define EGL_HI_colorformats 1 /* Config Attribute */ #define EGL_COLOR_FORMAT_HI 0x8F70 /* Color Formats */ #define EGL_COLOR_RGB_HI 0x8F71 #define EGL_COLOR_RGBA_HI 0x8F72 #define EGL_COLOR_ARGB_HI 0x8F73 #endif /* EGL_HI_colorformats */ #ifndef EGL_MESA_drm_image #define EGL_MESA_drm_image 1 #define <API key> 0x31D0 /* CreateDRMImageMESA attribute */ #define <API key> 0x31D1 /* CreateDRMImageMESA attribute */ #define <API key> 0x31D2 /* <API key> attribute value */ #define EGL_DRM_BUFFER_MESA 0x31D3 /* eglCreateImageKHR target */ #define <API key> 0x31D4 #define <API key> 0x00000001 /* <API key> bits */ #define <API key> 0x00000002 /* <API key> bits */ #ifdef <API key> EGLAPI EGLImageKHR EGLAPIENTRY <API key> (EGLDisplay dpy, const EGLint *attrib_list); EGLAPI EGLBoolean EGLAPIENTRY <API key> (EGLDisplay dpy, EGLImageKHR image, EGLint *name, EGLint *handle, EGLint *stride); #endif /* <API key> */ typedef EGLImageKHR (EGLAPIENTRYP <API key>) (EGLDisplay dpy, const EGLint *attrib_list); typedef EGLBoolean (EGLAPIENTRYP <API key>) (EGLDisplay dpy, EGLImageKHR image, EGLint *name, EGLint *handle, EGLint *stride); #endif #ifndef <API key> #define <API key> 1 #define <API key> 0x30BE #ifdef <API key> EGLAPI EGLBoolean EGLAPIENTRY eglPostSubBufferNV (EGLDisplay dpy, EGLSurface surface, EGLint x, EGLint y, EGLint width, EGLint height); #endif /* <API key> */ typedef EGLBoolean (EGLAPIENTRYP <API key>) (EGLDisplay dpy, EGLSurface surface, EGLint x, EGLint y, EGLint width, EGLint height); #endif #ifndef <API key> #define <API key> 1 #ifdef <API key> EGLAPI EGLBoolean <API key>(EGLDisplay dpy, EGLSurface surface, EGLint attribute, void **value); #endif typedef EGLBoolean (EGLAPIENTRYP <API key>) (EGLDisplay dpy, EGLSurface surface, EGLint attribute, void **value); #endif #ifndef <API key> #define <API key> 1 #define <API key> 0x3200 #endif #ifndef <API key> #define <API key> 1 #define <API key> 0x3131 #define <API key> 0x3132 #define <API key> 0x3133 #endif #if <API key> /* EGLTimeKHR requires 64-bit uint support */ #ifndef EGL_NV_system_time #define EGL_NV_system_time 1 typedef <API key> EGLuint64NV; #ifdef <API key> EGLAPI EGLuint64NV EGLAPIENTRY <API key>(void); EGLAPI EGLuint64NV EGLAPIENTRY eglGetSystemTimeNV(void); #endif /* <API key> */ typedef EGLuint64NV (EGLAPIENTRYP <API key>) (void); typedef EGLuint64NV (EGLAPIENTRYP <API key>) (void); #endif #endif #ifndef <API key> #define <API key> 1 #define <API key> 0x30BF #define <API key> 0x3138 #define <API key> 0x31BE #define <API key> 0x31BF #endif #ifdef __cplusplus } #endif #endif
# -*- coding: utf-8 -*- # Generated by Django 1.9.7 on 2017-06-06 17:16 from __future__ import unicode_literals from django.db import migrations import kolibri.core.fields class Migration(migrations.Migration): dependencies = [("content", "0001_initial")] operations = [ migrations.AddField( model_name="<API key>", name="last_updated", field=kolibri.core.fields.DateTimeTzField(null=True), ) ]
#include <boost/variant2/variant.hpp> using namespace boost::variant2; struct X { int v; X() = default; constexpr X( int v ): v( v ) {} constexpr operator int() const { return v; } }; struct Y { int v; constexpr Y(): v() {} constexpr Y( int v ): v( v ) {} constexpr operator int() const { return v; } }; enum E { v }; #define STATIC_ASSERT(...) static_assert(__VA_ARGS__, #__VA_ARGS__) template<class V, class T, class A> constexpr T test( A const& a ) { V v; v = a; return get<T>(v); } int main() { { constexpr variant<int> v( 1 ); constexpr auto w = test<variant<int>, int>( v ); STATIC_ASSERT( w == 1 ); } { constexpr variant<X> v( 1 ); constexpr auto w = test<variant<X>, X>( v ); STATIC_ASSERT( w == 1 ); } #if defined( <API key> ) && <API key> < 50000 #else { constexpr variant<Y> v( 1 ); constexpr auto w = test<variant<Y>, Y>( v ); STATIC_ASSERT( w == 1 ); } #endif { constexpr variant<int, float> v( 1 ); constexpr auto w = test<variant<int, float>, int>( v ); STATIC_ASSERT( w == 1 ); } { constexpr variant<int, float> v( 3.0f ); constexpr auto w = test<variant<int, float>, float>( v ); STATIC_ASSERT( w == 3.0f ); } { constexpr variant<int, int, float> v( 3.0f ); constexpr auto w = test<variant<int, int, float>, float>( v ); STATIC_ASSERT( w == 3.0f ); } { constexpr variant<E, E, X> v( 1 ); constexpr auto w = test<variant<E, E, X>, X>( v ); STATIC_ASSERT( w == 1 ); } { constexpr variant<int, int, float, float, X> v( X(1) ); constexpr auto w = test<variant<int, int, float, float, X>, X>( v ); STATIC_ASSERT( w == 1 ); } #if defined( <API key> ) && <API key> < 50000 #else { constexpr variant<E, E, Y> v( 1 ); constexpr auto w = test<variant<E, E, Y>, Y>( v ); STATIC_ASSERT( w == 1 ); } { constexpr variant<int, int, float, float, Y> v( Y(1) ); constexpr auto w = test<variant<int, int, float, float, Y>, Y>( v ); STATIC_ASSERT( w == 1 ); } #endif }
void __cdecl _splitpath ( register const char *path, char *drive, char *dir, char *fname, char *ext );