answer
stringlengths
15
1.25M
<!doctype html> <html xmlns="http: <head> <meta http-equiv="X-UA-Compatible" content="IE=Edge" /> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Select, add, or change Earth EC servers &#8212; Google Earth Enterprise 5.3.4 documentation</title> <link rel="stylesheet" href="../../static/bizstyle.css" type="text/css" /> <link rel="stylesheet" href="../../static/pygments.css" type="text/css" /> <script type="text/javascript" id="<API key>" data-url_root="../../" src="../../static/<API key>.js"></script> <script type="text/javascript" src="../../static/jquery.js"></script> <script type="text/javascript" src="../../static/underscore.js"></script> <script type="text/javascript" src="../../static/doctools.js"></script> <script type="text/javascript" src="../../static/bizstyle.js"></script> <link rel="index" title="Index" href="../../genindex.html" /> <link rel="search" title="Search" href="../../search.html" /> <link rel="next" title="Fix Earth EC issues" href="fixEarthECIssues.html" /> <link rel="prev" title="EC bandwidth requirements" href="<API key>.html" /> <meta name="viewport" content="width=device-width,initial-scale=1.0"> <!--[if lt IE 9]> <script type="text/javascript" src="static/css3-mediaqueries.js"></script> <![endif] </head><body> <div class="related" role="navigation" aria-label="related navigation"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../../genindex.html" title="General Index" accesskey="I">index</a></li> <li class="right" > <a href="fixEarthECIssues.html" title="Fix Earth EC issues" accesskey="N">next</a> |</li> <li class="right" > <a href="<API key>.html" title="EC bandwidth requirements" accesskey="P">previous</a> |</li> <li class="nav-item nav-item-0"><a href="../../index.html">Google Earth Enterprise 5.3.4 documentation</a> &#187;</li> <li class="nav-item nav-item-1"><a href="../<API key>.html" accesskey="U">Google Earth Enterprise client</a> &#187;</li> </ul> </div> <div class="sphinxsidebar" role="navigation" aria-label="main navigation"> <div class="<API key>"> <h4>Previous topic</h4> <p class="topless"><a href="<API key>.html" title="previous chapter">EC bandwidth requirements</a></p> <h4>Next topic</h4> <p class="topless"><a href="fixEarthECIssues.html" title="next chapter">Fix Earth EC issues</a></p> <div id="searchbox" style="display: none" role="search"> <h3>Quick search</h3> <div class="searchformwrapper"> <form class="search" action="../../search.html" method="get"> <input type="text" name="q" /> <input type="submit" value="Go" /> <input type="hidden" name="check_keywords" value="yes" /> <input type="hidden" name="area" value="default" /> </form> </div> </div> <script type="text/javascript">$('#searchbox').show(0);</script> </div> </div> <div class="document"> <div class="documentwrapper"> <div class="bodywrapper"> <div class="body" role="main"> <p><a class="reference internal" href="../../images/<API key>.png"><img alt="Google logo" src="../../images/<API key>.png" style="width: 130px; height: 44px;" /></a></p> <div class="section" id="<API key>"> <h1>Select, add, or change Earth EC servers<a class="headerlink" href=" <div class="docutils container"> <div class="content docutils container"> <p>You can use Google Earth EC to view globes and maps from your own database servers.</p> <p>Earth EC lets you do any of the following:</p> <ul class="simple"> <li>Add as many database servers as you want.</li> <li>Set a default server that is automatically signed in to whenever you start Earth EC.</li> <li>Connect to as many as eight servers at the same time.</li> <li>Change servers, or sign in and out of servers.</li> <li>Remove servers that you no longer use.</li> </ul> <p class="rubric" id="<API key>">Sign in to an Earth EC server</p> <p class="rubric" id="<API key>">To sign in to a server:</p> <ol class="arabic"> <li><p class="first">From Google Earth EC, select <strong>File</strong> &gt; <strong>Server Sign In</strong>.</p> <p>The <strong>Select Server</strong> window appears. When you start Google Earth EC the first time, <strong>Select Server</strong> appears automatically.</p> </li> <li><p class="first">Enter your server settings as shown in the table below.</p> </li> </ol> <p class="rubric" id="<API key>">Select Server options</p> <table border="1" class="colwidths-given docutils"> <colgroup> <col width="41%" /> <col width="59%" /> </colgroup> <thead valign="bottom"> <tr class="row-odd"><th class="head">Setting</th> <th class="head">Description</th> </tr> </thead> <tbody valign="top"> <tr class="row-even"><td>Server</td> <td>Select or enter the address for the database server that hosts the globes or maps you want to view. If you do not know the server address, ask your administrator.</td> </tr> <tr class="row-odd"><td>Port</td> <td>Select or enter the port for the server. If you don’t know the port number, ask your administrator.</td> </tr> <tr class="row-even"><td>Always sign in to this server</td> <td>Select to skip the Select Server window and automatically sign in to this server whenever you start Earth EC. To display Select Server again, select <strong>File &gt; Disable Automatic Sign In</strong>.</td> </tr> <tr class="row-odd"><td>Disable caching</td> <td>Select this if you want to make sure that you are viewing the latest content from the server or if your cached files become corrupted. <strong>Note:</strong> Disabling the cache slows down performance.</td> </tr> </tbody> </table> <p class="rubric" id="<API key>">Sign out of an Earth EC server</p> <p>To sign out of a server database, go to <strong>File</strong> &gt; <strong>Server Sign Out</strong>.</p> <p class="rubric" id="<API key>">Add servers to Earth EC</p> <p>To add a server database, go to <strong>File</strong> &gt; <strong>Add Database</strong>.</p> <p>The <strong>Select Server</strong> window appears so that you can enter your server settings.</p> <p class="rubric" id="<API key>">Connect to multiple Earth EC servers at the same time</p> <p>Whenever you add another server database, Earth EC signs into the new database and stays connected to your current database. You can view data from up to eight server databases at the same time.</p> <p class="rubric" id="<API key>">Change your Earth EC server</p> <p class="rubric" id="<API key>">To change your Earth EC server:</p> <ol class="arabic simple"> <li>Select <strong>File</strong> &gt; <strong>Server Sign Out</strong>. Earth EC signs out of your current server.</li> <li>Select <strong>File</strong> &gt; <strong>Server Sign In</strong>.</li> <li>Select a server from the list that appears.</li> </ol> <p class="rubric">Useful resources</p> <ul class="simple"> <li><a class="reference internal" href="whatisEC.html"><span class="doc">What is Google Earth EC?</span></a></li> <li><a class="reference internal" href="fixEarthECIssues.html"><span class="doc">Fix Earth EC issues</span></a></li> </ul> </div> </div> </div> </div> </div> </div> <div class="clearer"></div> </div> <div class="related" role="navigation" aria-label="related navigation"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../../genindex.html" title="General Index" >index</a></li> <li class="right" > <a href="fixEarthECIssues.html" title="Fix Earth EC issues" >next</a> |</li> <li class="right" > <a href="<API key>.html" title="EC bandwidth requirements" >previous</a> |</li> <li class="nav-item nav-item-0"><a href="../../index.html">Google Earth Enterprise 5.3.4 documentation</a> &#187;</li> <li class="nav-item nav-item-1"><a href="../<API key>.html" >Google Earth Enterprise client</a> &#187;</li> </ul> </div> <div class="footer" role="contentinfo"> & Created using <a href="http://sphinx-doc.org/">Sphinx</a> 1.7.5. </div> </body> </html>
#ifndef _PCH_PEI_INIT_H_ #define _PCH_PEI_INIT_H_ // Define the PCH PEI Init PPI GUID #define <API key> \ { \ 0xACB93B08, 0x5CDC, 0x4A8F, 0x93, 0xD4, 0x6, 0xE3, 0x42, 0xDF, 0x18, 0x2E \ } // Extern the GUID for PPI users. extern EFI_GUID gPchPeiInitPpiGuid; #endif
"""HTTP Support for Hass.io.""" import asyncio import logging import os import re from typing import Dict, Union import aiohttp from aiohttp import web from aiohttp.hdrs import CONTENT_LENGTH, CONTENT_TYPE from aiohttp.web_exceptions import HTTPBadGateway import async_timeout from homeassistant.components.http import KEY_AUTHENTICATED, HomeAssistantView from homeassistant.components.onboarding import async_is_onboarded from homeassistant.const import HTTP_UNAUTHORIZED from .const import X_HASS_IS_ADMIN, X_HASS_USER_ID, X_HASSIO _LOGGER = logging.getLogger(__name__) MAX_UPLOAD_SIZE = 1024 * 1024 * 1024 NO_TIMEOUT = re.compile( r"^(?:" r"|homeassistant/update" r"|hassos/update" r"|hassos/update/cli" r"|supervisor/update" r"|addons/[^/]+/(?:update|install|rebuild)" r"|snapshots/.+/full" r"|snapshots/.+/partial" r"|snapshots/[^/]+/(?:upload|download)" r")$" ) NO_AUTH_ONBOARDING = re.compile( r"^(?:" r"|supervisor/logs" r"|snapshots/[^/]+/.+" r")$" ) NO_AUTH = re.compile( r"^(?:" r"|app/.*" r"|addons/[^/]+/logo" r"|addons/[^/]+/icon" r")$" ) class HassIOView(HomeAssistantView): """Hass.io view to handle base part.""" name = "api:hassio" url = "/api/hassio/{path:.+}" requires_auth = False def __init__(self, host: str, websession: aiohttp.ClientSession): """Initialize a Hass.io base view.""" self._host = host self._websession = websession async def _handle( self, request: web.Request, path: str ) -> Union[web.Response, web.StreamResponse]: """Route data to Hass.io.""" hass = request.app["hass"] if _need_auth(hass, path) and not request[KEY_AUTHENTICATED]: return web.Response(status=HTTP_UNAUTHORIZED) return await self._command_proxy(path, request) delete = _handle get = _handle post = _handle async def _command_proxy( self, path: str, request: web.Request ) -> Union[web.Response, web.StreamResponse]: """Return a client request with proxy origin for Hass.io supervisor. This method is a coroutine. """ read_timeout = _get_timeout(path) client_timeout = 10 data = None headers = _init_header(request) if path == "snapshots/new/upload": # We need to reuse the full content type that includes the boundary headers[ "Content-Type" ] = request.<API key> # pylint: disable=protected-access # Snapshots are big, so we need to adjust the allowed size request._client_max_size = ( # pylint: disable=protected-access MAX_UPLOAD_SIZE ) client_timeout = 300 try: with async_timeout.timeout(client_timeout): data = await request.read() method = getattr(self._websession, request.method.lower()) client = await method( f"http://{self._host}/{path}", data=data, headers=headers, timeout=read_timeout, ) # Simple request if int(client.headers.get(CONTENT_LENGTH, 0)) < 4194000: # Return Response body = await client.read() return web.Response( content_type=client.content_type, status=client.status, body=body ) # Stream response response = web.StreamResponse(status=client.status, headers=client.headers) response.content_type = client.content_type await response.prepare(request) async for data in client.content.iter_chunked(4096): await response.write(data) return response except aiohttp.ClientError as err: _LOGGER.error("Client error on api %s request %s", path, err) except asyncio.TimeoutError: _LOGGER.error("Client timeout error on API request %s", path) raise HTTPBadGateway() def _init_header(request: web.Request) -> Dict[str, str]: """Create initial header.""" headers = { X_HASSIO: os.environ.get("HASSIO_TOKEN", ""), CONTENT_TYPE: request.content_type, } # Add user data user = request.get("hass_user") if user is not None: headers[X_HASS_USER_ID] = request["hass_user"].id headers[X_HASS_IS_ADMIN] = str(int(request["hass_user"].is_admin)) return headers def _get_timeout(path: str) -> int: """Return timeout for a URL path.""" if NO_TIMEOUT.match(path): return 0 return 300 def _need_auth(hass, path: str) -> bool: """Return if a path need authentication.""" if not async_is_onboarded(hass) and NO_AUTH_ONBOARDING.match(path): return False if NO_AUTH.match(path): return False return True
package com.mendix.core; import java.io.InputStream; import java.io.IOException; import java.util.Collection; import java.util.Date; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.concurrent.Future; import java.util.concurrent.<API key>; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import com.mendix.core.actionmanagement.ActionListener; import com.mendix.core.actionmanagement.CoreAction; import com.mendix.core.component.LocalComponent; import com.mendix.core.component.InternalCore; import com.mendix.core.conf.Configuration; import com.mendix.externalinterface.connector.RequestHandler; import com.mendix.integration.Integration; import com.mendix.integration.WebserviceException; import com.mendix.logging.ILogNode; import com.mendix.logging.LogSubscriber; import com.mendix.m2ee.api.IMxRuntimeRequest; import com.mendix.<API key>.MendixException; import com.mendix.<API key>.IWebserviceResponse; import com.mendix.<API key>.connectionbus.data.IDataTable; import com.mendix.<API key>.connectionbus.requests.<API key>; import com.mendix.<API key>.connectionbus.requests.IRetrievalSchema; import com.mendix.<API key>.connectionbus.requests.types.IGetRequest; import com.mendix.<API key>.connectionbus.requests.types.IOQLTextGetRequest; import com.mendix.<API key>.connectionbus.requests.types.<API key>; import com.mendix.<API key>.core.IContext; import com.mendix.<API key>.core.IDataType; import com.mendix.<API key>.core.ILanguage; import com.mendix.<API key>.core.IMendixIdentifier; import com.mendix.<API key>.core.IMendixObject; import com.mendix.<API key>.core.IProfiler; import com.mendix.<API key>.core.ISession; import com.mendix.<API key>.core.IUser; import com.mendix.<API key>.core.UserAction; import com.mendix.<API key>.core.meta.IMetaAssociation; import com.mendix.<API key>.core.meta.IMetaObject; import com.mendix.<API key>.core.meta.IMetaPrimitive; public final class Core { public Core() {} private static LocalComponent component; private static Integration integration; public static void initialize(LocalComponent localComponent, Integration i) { component = localComponent; integration = i; } public static LocalComponent getComponent() { return component; } /** * Returns the mode in which the Mendix Business Server has been started. * @return the mode the Mendix Business Server is running in. */ @Deprecated public static com.mendix.core.component.InternalCore.Mode getMode() { return InternalCore.getMode(); } public static boolean isInDevelopment() { return component.configuration().isInDevelopment(); } /** * Returns the id of this server instance. * @return the server id in UUID format. */ public static String getXASId() { return component.core().getXASId(); } /** * Returns the names of all modeled microflows. * @return all microflow names (format "ModuleName.MicroflowName"). */ public static Set<String> getMicroflowNames() { return component.core().getMicroflowNames(); } /** * Returns all input parameter data types the specified action by name. * @param actionName the name of a microflow or java action (format "ModuleName.ActionName"). * @return data types by input parameter name. */ public static Map<String, IDataType> getInputParameters(String actionName) { return component.core().getInputParameters(actionName); } /** * Returns the return type of the specified action. * @param actionName the name of a microflow or java action (format "ModuleName.ActionName"). * @return the return data type of the specified action. */ public static IDataType getReturnType(String actionName) { return component.core().getReturnType(actionName); } /** * Evaluate the given (microflow)expression. * @param context the context * @param variables name of variables referenced in the expression (without '$') and their values. * @param expression the expression * @return the evaluated value of the expression. */ public static Object evaluateExpression(IContext context, Map<String,Object> variables, String expression) { return component.core().evaluateExpression(context, variables, expression); } /** * Execute an action asynchronously, result is given and/or exceptions are raised when calling Future.get(). * When calling Future.get() the result of the action will return immediately if the execution is done, * otherwise the call is blocking. Exceptions raised while executing the action will not be thrown until * Future.get() is called. * @param <T> action type, subclass of CoreAction. * @param <R> result type of the action, can be any object. * @param action the action to execute. * @return the Future object. * */ public static <T extends CoreAction<R>,R> Future<R> execute(T action) { return component.core().execute(action); } /** * Execute an action synchronously. * @param <T> action type, subclass of CoreAction. * @param <R> result type of action, can be any object. * @param action the action to execute. * @return return value of the specified action. */ public static <T extends CoreAction<R>,R> R executeSync(T action) throws CoreException { return component.core().executeSync(action); } /** * Execute the specified action (synchronously). * @param context the context for this action. * @param actionName the name of a microflow or java action (format "ModuleName.ActionName"). * @param params for microflows: add IMendixObject, IMendixIdentifier or primitive parameters. * for Java actions: add any object parameters. * @return return value of the specified action. */ public static <R> R execute(IContext context, String actionName, Object ... params) throws CoreException { return (R)component.core().execute(context, actionName, params); } /** * Execute the specified action (asynchronously) * Result is given and/or exceptions are raised when calling Future.get(). * When calling Future.get() the result of the action will return immediately if the execution is done, * otherwise the call is blocking. Exceptions raised while executing the action will not be thrown until * Future.get() is called. * @param context the context for this action. * @param actionName the name of a microflow or java action (format "ModuleName.ActionName"). * @param params for microflows: add IMendixObject, IMendixIdentifier or primitive parameters. * for Java actions: add any object parameters. * @return the Future object. */ public static <R> Future<R> executeAsync(IContext context, String actionName, Object ... params) throws CoreException { return component.core().executeAsync(context, actionName, params); } /** * Execute the specified action (synchronously). * @param context the context for this action. * @param actionName the name of a microflow or java action (format "ModuleName.ActionName"). * @param params action parameters by name. * @return return value of the specified action. */ public static <R> R execute(IContext context, String actionName, Map<String,Object> params) throws CoreException { return (R)component.core().execute(context, actionName, params); } /** * Execute the specified action (synchronously). * @param context the context for this action. * @param actionName the name of a microflow or java action (format "ModuleName.ActionName"). * @param <API key> defines whether the action should be execute in a transaction (enables rolling back changes when exceptions are raised). * @param params action parameters by name. * @return return value of the specified action. */ public static <R> R execute(IContext context, String actionName, boolean <API key>, Map<String,Object> params) throws CoreException { return (R)component.core().execute(context, actionName, <API key>, params); } /** * Execute the specified action (asynchronously). * @param <R> result type of the action, can be any object. * @param <T> action type, subclass of CoreAction. * @param action the action to execute. */ public static <T extends CoreAction<R>,R> void executeVoid(T action) { component.core().executeVoid(action); } /** * Schedule an action on a certain date. * @param actionName the name of a microflow or java action (format "ModuleName.ActionName") * @param date the date and time on which the action should be executed * @return the <API key> object for keeping track of the result */ public static <R> <API key><?> schedule(String actionName, Date date) throws CoreException { return component.core().schedule(actionName, date); } /** * Schedule an action on a certain delay from now. * @param action the action to execute. * @param delay the delay after which the action should be executed. * @param timeUnit time unit in which the delay is specified. * @return returns <API key> object for keeping track of the result. */ public static <R> <API key><?> schedule(CoreAction<R> action, long delay, TimeUnit timeUnit) { return component.core().schedule(action, delay, timeUnit); } /** * Schedule a periodic action that runs for the first time after the given initial delay (first run), * and subsequently with the given period; that is executions will commence after initialDelay then * initialDelay+period, then initialDelay + 2 * period, and so on. * No result will be returned. * @param actionName the name of a microflow or java action (format "ModuleName.ActionName"). * @param firstRun the date on which the action will be executed the first time. * @param period the period between each start of the execution of the action. * @param timeUnit the timeUnit in which the initialDelay and the period is specified. * @param name the name of the scheduled event. * @param description the description of the scheduled event. */ public static <R> void scheduleAtFixedRate(String actionName, Date firstRun, long period, TimeUnit timeUnit, String name, String description) { component.core().scheduleAtFixedRate(actionName, firstRun, period, timeUnit, name, description); } /** * Schedule a periodic action that runs for the first time after the given initial delay, * and subsequently with the given period; that is executions will commence after initialDelay then * initialDelay+period, then initialDelay + 2 * period, and so on. * No result will be returned. * @param action the action to execute. * @param initialDelay the delay after which the action will be executed the first time. * @param period the period between each start of the execution of the action. * @param timeUnit the timeUnit in which the initialDelay and the period is specified. */ public static <R> void scheduleAtFixedRate(CoreAction<R> action, long initialDelay, long period, TimeUnit timeUnit) { component.core().scheduleAtFixedRate(action, initialDelay, period, timeUnit); } /** * Schedule a periodic action that run for the first time on the given date/time, * and subsequently with the given period; that is executions will commence on firstRun then * initialDelay+period, then initialDelay + 2 * period, and so on.<br> * No result will be returned. * @param action the action to execute * @param firstRun the Date/time on which the action will be executed the first time * @param period the period between each start of the execution of the action * @param timeUnit the timeUnit in which the period is specified */ public static <R> void scheduleAtFixedRate(CoreAction<R> action, Date firstRun, long period, TimeUnit timeUnit) { component.core().scheduleAtFixedRate(action, firstRun, period, timeUnit); } /** * Schedule a periodic action that runs for the first time after the given initial delay, * and subsequently with the given delay between the termination of one execution and the commencement of the next. * No result will be returned. * @param action the action to execute. * @param initialDelay the delay after which the action will be executed the first time. * @param delay the delay between the end of the execution of the action and the start of the next time the action will be executed. * @param timeUnit the timeUnit in which the initialDelay and the delay is specified. */ public static <R> void <API key>(CoreAction<R> action, long initialDelay, long delay, TimeUnit timeUnit) { component.core().<API key>(action, initialDelay, delay, timeUnit); } /** * Remove scheduled future. * @param scheduledFuture the <API key> to remove. * @return whether removing the <API key> was successful. */ public static boolean <API key>(<API key><?> scheduledFuture) { return component.core().<API key>(scheduledFuture); } /** * Reschedule an action with a new delay. * @param scheduledFuture the scheduledFuture (old action) to remove from the queue. * @param action the action to reschedule. * @param newDelay the new delay. * @param timeUnit time unit of the delay. * @return scheduled future object. */ public static <R> ScheduledFuture<?> reschedule(<API key><R> scheduledFuture, CoreAction<R> action, long newDelay, TimeUnit timeUnit) { return component.core().reschedule(scheduledFuture, action, newDelay, timeUnit); } /** * Registers the given ActionListener to the ActionManager. * @param al the ActionListener to add. */ public static <T extends CoreAction<?>> void addListener(ActionListener<T> al) { component.core().addListener(al); } /** * Commits the given object (asynchronously). This will store the object in the database and remove it from the server cache. * This action is not executed in a transaction. * @param context the context. * @param object the IMendixObject to commit. * @return returns a list of future objects with committed object lists, one for each entity type. */ public static List<Future<List<IMendixObject>>> commitAsync(IContext context, List<IMendixObject> objects) { return component.core().commitAsync(context, objects); } /** * Commits the given object. This will store the object in the database and remove it from the server cache. * This action is executed in a transaction. * @param context the context. * @param object the IMendixObject to commit. * @return returns committed object if commit was successful, otherwise null. */ public static IMendixObject commit(IContext context, IMendixObject object) throws CoreException { return component.core().commit(context, object); } /** * Commits the given objects. This will store the objects in the database and remove them from the server cache. * Before events defined for these objects are executed before any object will be committed and after events will be * executed after all objects have been committed. * This action is executed in a transaction. * @param context the context. * @param objectsToCommit the objects to commit. * @return returns committed objects if commits was successful, otherwise an empty list. */ public static List<IMendixObject> commit(IContext context, List<IMendixObject> objects) { return component.core().commit(context, objects); } /** * Commits the given object without events. This will store the object in the database and remove it from the server cache. * This action is executed in a transaction. * @param context the context. * @param object the IMendixObject to commit. * @return returns committed object if commit was successful, otherwise null. */ public static IMendixObject commitWithoutEvents(IContext context, IMendixObject object) { return component.core().commitWithoutEvents(context, object); } /** * Commit the given objects without events. This will store the objects in the database and remove it from the server cache. * This action is executed in a transaction. * @param context the context. * @param objects the objects to commit. * @return returns true if commit was successful, otherwise false. */ public static List<IMendixObject> commitWithoutEvents(IContext context, List<IMendixObject> objects) { return component.core().commitWithoutEvents(context, objects); } /** * Creates a new IMendixObject with the given object type (asynchronously). The object will NOT be stored in the * database. This action is not executed in a transaction. * @param context the context. * @param objectType type of object to create (e.g. "System.User"). * @return returns the Future object. */ public static Future<IMendixObject> instantiateAsync(IContext context, String objectType) { return component.core().instantiateAsync(context, objectType); } /** * Creates a new IMendixObject with the given object type (synchronously). The object will be stored in the * database immediately. The rollback method can be used to cancel this. * @param context the context. * @param objectType type of object to create (e.g. "System.User"). * @return returns the newly created object. * @deprecated use Core.instantiate instead. */ @Deprecated public static IMendixObject create(IContext context, String objectType) throws CoreException { return component.core().create(context, objectType); } /** * Creates a new IMendixObject with the given object type (synchronously). The object will NOT be stored in the * database. This action is executed in a transaction. * @param context the context. * @param objectType type of object to create (e.g. "System.User"). * @return returns the newly created object. */ public static IMendixObject instantiate(IContext context, String objectType) { return component.core().instantiate(context, objectType); } /** * Changes the given object in cache (synchronously). When the object is not cache yet, * the object will be retrieved from the database and put in the cache. * This action is executed in a transaction. * @param context the context. * @param object the object to change. * @param changes contains changes by member name (e.g. <"Name", "User1">). * @return returns whether the change succeeded or not. */ public static boolean change(IContext context, IMendixObject object, Map<String,String> changes) throws CoreException { return component.core().change(context, object, changes); } /** * Changes the object (asynchronously). Object will be stored in cache. * This action is not executed in a transaction. * @param context the context. * @param obj the MendixObject to change * @param changes contains changes by member name (e.g. <"Name", "User1">). * @return returns the Future object. */ public static Future<Boolean> changeAsync(IContext context, IMendixObject obj, Map<String,String> changes) { return component.core().changeAsync(context, obj, changes); } /** * Rollback changes of the object with the given id (asynchronously). * When the object's state is NORMAL: Removes the object from the cache, all performed changes without commit will be lost. * When the object's state is NEW: Removes the object from the database. * @param context the context. * @param id the identifier of the object to rollback. * @return returns the Future object. * @throws CoreException */ @Deprecated public static Future<IMendixObject> rollbackAsync(IContext context, IMendixIdentifier id) throws CoreException { return component.core().rollbackAsync(context, id); } /** * Rollback changes of the object with the given id (asynchronously). * When the object's state is NORMAL: Removes the object from the cache, all performed changes without commit will be lost. * When the object's state is NEW: Removes the object from the database. * This action is not executed in a transaction. * @param context the context. * @param id the identifier of the object to rollback. * @return returns the Future object. */ public static Future<IMendixObject> rollbackAsync(IContext context, IMendixObject object) { return component.core().rollbackAsync(context, object); } /** * Rollback changes of the object with the given id (synchronously). * When the object's state is NORMAL: Removes the object from the cache, all performed changes without commit will be lost. * When the object's state is NEW: Removes the object from the database. * @param context the context. * @param id the identifier of the object to rollback. * @return returns the Future object. */ @Deprecated public static IMendixObject rollback(IContext context, IMendixIdentifier id) throws CoreException { return component.core().rollback(context, id); } /** * Rollback changes of the object with the given id (synchronously). * When the object's state is NORMAL: Removes the object from the cache, all performed changes without commit will be lost. * When the object's state is NEW: Removes the object from the database. * This action is executed in a transaction. * @param context the context. * @param id the identifier of the object to rollback. * @return returns the Future object. */ public static IMendixObject rollback(IContext context, IMendixObject object) throws CoreException { return component.core().rollback(context, object); } /** * Removes the given objects from the database and server cache (synchronously). * Before events defined for these objects are executed before any object will be deleted and after events will be * executed after all objects have been deleted. * @param context the context. * @param objects the objects to remove. * @return returns whether the remove succeeded. * @deprecated Replaced by {{@link #delete(IContext, IMendixObject...)} */ @SuppressWarnings("unused") @Deprecated public static boolean remove(IContext context, IMendixObject... objects) throws CoreException { return delete(context, objects); } /** * Deletes the given objects from the database and server cache (synchronously). * This action is executed in a transaction. * @param context the context. * @param objects the objects to delete. * @return returns whether the delete succeeded. */ public static boolean delete(IContext context, IMendixObject... objects) { return component.core().delete(context, objects); } /** * Deletes the given objects from the database and server cache (synchronously). * This action is executed in a transaction. * @param context the context. * @param objectList the objects to delete. * @return returns whether the delete succeeded. */ public static boolean delete(IContext context, List<IMendixObject> objectList) { return component.core().delete(context, objectList); } /** * Deletes the given objects from the database and server cache (synchronously) without events * This action is executed in a transaction. * @param context the context. * @param objects the objects to delete. * @return returns whether the delete succeeded. */ public static boolean deleteWithoutEvents(IContext context, List<IMendixObject> objects, boolean useDeleteBehavior) { return component.core().deleteWithoutEvents(context, objects, useDeleteBehavior); } /** * Deletes the given object from the database and server cache (asynchronously). * This action is not executed in a transaction. * @param context the context. * @param object the object to delete. * @param useDeleteBehavior whether to use delete behavior. * @return returns a list of future booleans, one for each entity type. */ public static List<Future<Boolean>> deleteAsync(IContext context, IMendixObject object, boolean useDeleteBehavior) { return component.core().deleteAsync(context, object, useDeleteBehavior); } /** * Deletes the given object from the database and server cache (asynchronously). * This action is not executed in a transaction. * @param context the context. * @param object the object to delete. * @param useDeleteBehavior whether to use delete behavior. * @return returns a list of future booleans, one for each entity type. */ public static List<Future<Boolean>> deleteAsync(IContext context, List<IMendixObject> objects, boolean useDeleteBehavior) { return component.core().deleteAsync(context, objects, useDeleteBehavior); } /** * Retrieves objects with the given ids (asynchronously). First, objects are attempted to be retrieved from cache. * When an object cannot be retrieve from the cache it will be retrieved from the database. * When (amount > 0) || (offset > 0) || (sort.size() > 0), all objects will be retrieve from the database. * @param context the context. * @param ids ids of the objects to retrieve. * @return returns the Future object. */ public static Future<List<IMendixObject>> retrieveIdListAsync(IContext context, List<IMendixIdentifier> ids) { return component.core().retrieveIdListAsync(context, ids); } /** * Retrieves objects with the given ids (synchronously). First, objects are attempted to be retrieved from cache. * When an object cannot be retrieve from the cache it will be retrieved from the database. * When (amount > 0) || (offset > 0) || (sort.size() > 0), all objects will be retrieve from the database. * @param context the context. * @param ids ids of the objects to retrieve. * @param amount the maximum number of objects to retrieve from the database. * @param offset offset of returned objects when retrieved from the database. * @param sort sorting of returned objects when retrieved from the database (e.g. <"Name", "ASC">, <"Age", "DESC">). * @return returns the Future object. */ public static List<IMendixObject> retrieveIdList(IContext context, List<IMendixIdentifier> ids, int amount, int offset, Map<String,String> sort) throws CoreException { return component.core().retrieveIdList(context, ids, amount, offset, sort); } /** * Retrieves objects with the given ids (synchronously). First, objects are attempted to be retrieved from cache. * When an object cannot be retrieved from the cache it will be retrieved from the database. * When (amount > 0) || (offset > 0) || (sort.size() > 0), all objects will be retrieved from the database. * @param context the context. * @param ids ids of the objects to retrieve. * @return returns the objects of the given ids. */ public static List<IMendixObject> retrieveIdList(IContext context, List<IMendixIdentifier> ids) throws CoreException { return component.core().retrieveIdList(context, ids); } /** * Retrieves object with the given id (asynchronously). First, the object is attempted to be retrieved from the cache. * When the object cannot be retrieve from the cache it will be retrieved from the database. * @param context the context. * @param id id of the object to retrieve. * @return returns the Future object. */ public static Future<IMendixObject> retrieveIdAsync(IContext context, IMendixIdentifier id) { return component.core().retrieveIdAsync(context, id); } /** * Retrieves object with the given id (synchronously). First, the object is attempted to be retrieved from the cache. * When the object cannot be retrieve from the cache it will be retrieved from the database. * @param context the context. * @param id id of the object to retrieve. * @return returns the Future object. */ public static IMendixObject retrieveId(IContext context, IMendixIdentifier id) throws CoreException { return component.core().retrieveId(context, id); } /** * Retrieves objects using the given object and path. * * @param context the context. * @param mxObject the start point of the path. * @param path the path (association) to the objects to retrieve. * @return the list of retrieved objects. */ public static List<IMendixObject> retrieveByPath(IContext context, IMendixObject mxObject, String path) { return component.core().retrieveByPath(context, mxObject, path); } /** * Retrieves objects using the given object and path. * * @param context the context. * @param mxObject the start point of the path. * @param path the path (association) to the objects to retrieve. * @param <API key> defines whether the mxObject instance is the child of the path of a self association. * @return the list of retrieved objects. */ public static List<IMendixObject> retrieveByPath(IContext context, IMendixObject mxObject, String path, boolean <API key>) { return component.core().retrieveByPath(context, mxObject, path, <API key>); } /** * Retrieves object list based on the given XPath query (asynchronously). * @param context the context. * @param xpathQuery the XPath query to execute. * @param amount maximum number of objects to retrieve. * @param offset index of first object to retrieve. * @param sort sorting of returned objects when retrieved from the database (e.g. <"Name", "ASC">, <"Age", "DESC">). * @param depth indicates the level until which each reference (IMendixIdentifier) is also retrieved as an IMendixObject. * @return the Future object. */ public static Future<List<IMendixObject>> <API key>(IContext context, String xpathQuery, int amount, int offset, Map<String,String> sort, int depth) { return component.core().<API key>(context, xpathQuery, amount, offset, sort, depth); } /** * Retrieves object list based on the given XPath query (synchronously). * @param context the context. * @param xpathQuery the XPath query to execute. * @param amount maximum number of objects to retrieve. * @param offset index of first object to retrieve. * @param sort sorting of returned objects when retrieved from the database (e.g. <"Name", "ASC">, <"Age", "DESC">). * @param depth indicates the level until which each reference (IMendixIdentifier) is also retrieved as an IMendixObject. * @return the list of retrieved objects. */ public static List<IMendixObject> retrieveXPathQuery(IContext context, String xpathQuery, int amount, int offset, Map<String,String> sort, int depth) throws CoreException { return component.core().retrieveXPathQuery(context, xpathQuery, amount, offset, sort, depth); } /** * Retrieves raw data (IDataTables) based on the given XPath query (synchronously). * @param context the context. * @param xpathQuery the XPath query to execute. * @param amount maximum number of objects to retrieve. * @param offset index of first object to retrieve. * @param sort sorting of returned objects when retrieved from the database (e.g. <"Name", "ASC">, <"Age", "DESC">). * @param depth indicates the level until which each reference (IMendixIdentifier) is also retrieved as an IMendixObject. * @return the data table containing the raw data. */ public static IDataTable <API key>(IContext context, String xpathQuery, int amount, int offset, Map<String,String> sort, int depth) throws CoreException { return component.core().<API key>(context, xpathQuery, amount, offset, sort, depth); } /** * Retrieves raw data (IDataTables) based on the XPath query and given schema (synchronously). * @param context the context. * @param xpathQuery the XPath query to execute. * @param shouldRetrieveCount indicates whether the total number object corresponding to the given schema should be included in the result. * @param retrievalSchema the schema to apply. * @return the data table containing the raw data. */ public static IDataTable <API key>(IContext context, String xpathQuery, boolean shouldRetrieveCount, IRetrievalSchema retrievalSchema) throws CoreException { return component.core().<API key>(context, xpathQuery, shouldRetrieveCount, retrievalSchema); } /** * Retrieves objects based on the XPath query and given schema (synchronously). * @param context the context. * @param xpathQuery the XPath query to execute. * @param retrievalSchema the schema to apply. * @param shouldRetrieveCount indicates whether the total number object corresponding to the given schema should be included in the result. * @return the list of retrieved objects. */ public static List<IMendixObject> retrieveXPathSchema(IContext context, String xpathQuery, IRetrievalSchema retrievalSchema, boolean shouldRetrieveCount) throws CoreException { return component.core().retrieveXPathSchema(context, xpathQuery, retrievalSchema, shouldRetrieveCount, false); } /** * Retrieves objects based on the XPath query and given schema (synchronously). * @param context the context. * @param xpathQuery the XPath query to execute. * @param retrievalSchema the schema to apply. * @param shouldRetrieveCount indicates whether the total number object corresponding to the given schema should be included in the result. * @param disableSecurity indicates whether security should be applied when this query is being executed. * @return the list of retrieved objects. */ public static List<IMendixObject> retrieveXPathSchema(IContext context, String xpathQuery, IRetrievalSchema retrievalSchema, boolean shouldRetrieveCount, boolean disableSecurity) throws CoreException { return component.core().retrieveXPathSchema(context, xpathQuery, retrievalSchema, shouldRetrieveCount, disableSecurity); } /** * Retrieves object list based on the given XPath query (synchronously). * @param context the context. * @param xpathQuery the XPath query to execute. * @param amount maximum number of objects to retrieve. * @param offset index of first object to retrieve. * @param sort sorting of returned objects when retrieved from the database (e.g. <"Name", "ASC">, <"Age", "DESC">). * @return the list of retrieved objects. */ public static List<IMendixObject> retrieveXPathQuery(IContext context, String xpathQuery, int amount, int offset, Map<String, String> sort) throws CoreException { return Core.retrieveXPathQuery(context, xpathQuery, amount, offset, sort, 0); } /** * Retrieves object list based on the given XPath query (synchronously). * @param context the context. * @param xpathQuery the XPath query to execute. * @param depth indicates the level until which each reference (IMendixIdentifier) is also retrieved as an IMendixObject. * @return the list of retrieved objects. */ public static List<IMendixObject> retrieveXPathQuery(IContext context, String xpathQuery, int depth) throws CoreException { return Core.retrieveXPathQuery(context, xpathQuery, -1, -1, new LinkedHashMap<String,String>(), depth); } /** * Retrieves object list based on the given XPath query (synchronously). * @param context the context. * @param xpathQuery the XPath query to execute. * @return the list of retrieved objects. */ public static List<IMendixObject> retrieveXPathQuery(IContext context, String xpathQuery) throws CoreException { return Core.retrieveXPathQuery(context, xpathQuery, -1, -1, new LinkedHashMap<String,String>(), 0); } /** * Retrieves object list based on the given XPath query (synchronously). * @param context the context. * @param xpathFormat the XPath query to execute with %s for each param to escape. * @param amount maximum number of objects to retrieve. * @param offset index of first object to retrieve. * @param sort sorting of returned objects when retrieved from the database (e.g. <"Name", "ASC">, <"Age", "DESC">). * @param depth depth of the retrieval (0 is all attributes and association guids, 1 is also all attributes of 1-deep associations and 2-deep associaton guids etc.). * @param params xpath arguments. * @return the list of retrieved objects. */ public static List<IMendixObject> <API key>(IContext context, String xpathFormat, int amount, int offset, Map<String,String> sort, int depth, String... params) throws CoreException { return component.core().<API key>(context, xpathFormat, amount, offset, sort, depth, params); } /** * Retrieves object list based on the given XPath query (synchronously). * @param context the context. * @param xpathFormat the XPath query to execute with %s for each param to escape. * @param retrievalSchema the schema to apply. * @param shouldRetrieveCount indicates whether the total number object corresponding to the given schema should be included in the result. * @param params a collection of parameters for each %s in xpathFormat. * @return the list of retrieved objects. */ public static List<IMendixObject> <API key>(IContext context, String xpathFormat, IRetrievalSchema retrievalSchema, boolean shouldRetrieveCount, String... params) throws CoreException { return Core.<API key>(context, xpathFormat, retrievalSchema, shouldRetrieveCount, false, params); } /** * Retrieves object list based on the given XPath query (synchronously). * @param context the context. * @param xpathFormat the XPath query to execute with %s for each param to escape. * @param retrievalSchema the schema to apply. * @param shouldRetrieveCount indicates whether the total number object corresponding to the given schema should be included in the result. * @param disableSecurity indicates whether security should be disabled when executing this query. * @param params a collection of parameters for each %s in xpathFormat. * @return the list of retrieved objects. */ public static List<IMendixObject> <API key>(IContext context, String xpathFormat, IRetrievalSchema retrievalSchema, boolean shouldRetrieveCount, boolean disableSecurity, String... params) throws CoreException { return component.core().<API key>(context, xpathFormat, retrievalSchema, shouldRetrieveCount, disableSecurity, params); } /** * Retrieves object list based on the given XPath query (synchronously). * @param context the context. * @param xpathFormat the XPath query to execute with %s for each param to escape. * @param params a collection of parameters for each %s in xpathFormat. * @return the list of retrieved objects. */ public static List<IMendixObject> <API key>(IContext context, String xpathFormat, String... params) throws CoreException { return Core.<API key>(context, xpathFormat, -1, -1, new LinkedHashMap<String,String>(), 0, params); } /** * Create a new IRetrievalSchema. * @return an IRetrievalSchema. */ public static IRetrievalSchema <API key>() { return component.core().<API key>(); } /** * Create a new <API key> to specify which associations must be retrieved. * An <API key> can be added to a request by the method IRetrievalSchema.<API key>(..). * * @param metaAssociationName the name of the meta association of this schema * @param retrievalSchema the retrieval schema of the associated meta object * @return an <API key> */ public static <API key> <API key>(String metaAssociationName, IRetrievalSchema retrievalSchema) { return component.core().<API key>(metaAssociationName, retrievalSchema); } /** * Create a new <API key>. This class can be used to define an XPath retrieval query. The query must be set in textual form. * @return an <API key>. */ public static <API key> <API key>() { return component.core().<API key>(); } /** * Create a new IOQLTextGetRequest. This class can be used to define a textual OQL retrieval query. * @return an IOQLTextGetRequest. */ public static IOQLTextGetRequest <API key>() { return component.core().<API key>(); } /** * Retrieve raw data (IDataTable) using an OQL query (asynchronously). * @param context the context. * @param oqlQuery the OQL query to execute. * @return the Future object. */ public static Future<IDataTable> <API key>(IContext context, String oqlQuery) { return <API key>(context, oqlQuery, -1, -1); } /** * Retrieve raw data (IDataTable) using an IGetRequest object (asynchronously). * @param context the context. * @param request the request object. * @return the Future object. */ public static Future<IDataTable> <API key>(IContext context, IGetRequest request) { return component.core().<API key>(context, request); } /** * Retrieve raw data (IDataTable) using an OQL query (asynchronously). * @param context the context. * @param oqlQuery the OQL query to execute. * @param amount maximum number of objects to retrieve. * @param offset index of first object to retrieve. * @return the Future object. */ public static Future<IDataTable> <API key>(IContext context, String oqlQuery, int amount, int offset) { return component.core().<API key>(context, oqlQuery, amount, offset); } /** * Retrieve raw data (IDataTable) using an IGetRequest object (synchronously). * @param context the context. * @param request the request object. * @return the data table containing the raw data. */ public static IDataTable <API key>(IContext context, IGetRequest request) throws CoreException { return component.core().<API key>(context, request); } /** * Retrieve raw data (IDataTable) using an IGetRequest object (synchronously). * @param context the context. * @param oqlQuery the OQL query to execute. * @return the data table containing the raw data. */ public static IDataTable <API key>(IContext context, String oqlQuery) throws CoreException { return <API key>(context, oqlQuery, -1, -1); } /** * Retrieve raw data (IDataTable) using an OQL query (asynchronously). * @param context the context. * @param oqlQuery the OQL query to execute. * @param amount maximum number of objects to retrieve. * @param offset index of first object to retrieve. * @return the data table containing the raw data. */ public static IDataTable <API key>(IContext context, String oqlQuery, int amount, int offset) throws CoreException { return component.core().<API key>(context, oqlQuery, amount, offset); } /** * Retrieves long aggregate value based on the given query (root element of the query should be an aggregate function) (asynchronously). * @param context the context. * @param xpathQuery the aggregate xpath query (e.g. "COUNT(//System.User)"). * @return the Future object. */ public static Future<Long> <API key>(IContext context, String xpathQuery) { return component.core().<API key>(context, xpathQuery); } /** * Retrieves long aggregate value based on the given query (root element of the query should be an aggregate function) (synchronously). * @param context the context. * @param xpathQuery the aggregate xpath query (e.g. "COUNT(//System.User)"). * @return the Future object. */ public static Long <API key>(IContext context, String xpathQuery) throws CoreException { return component.core().<API key>(context, xpathQuery); } /** * Retrieves long aggregate value based on the given query and schema (root element of the query should be an aggregate function) (asynchronously). * @param context the context. * @param xpathQuery the aggregate xpath query (e.g. "COUNT(//System.User)"). * @param retrievalSchema the schema. * @return the aggregate value. */ public static Long <API key>(IContext context, String xpathQuery, IRetrievalSchema retrievalSchema) throws CoreException { return component.core().<API key>(context, xpathQuery, retrievalSchema); } /** * Retrieves long aggregate value based on the given query and schema (root element of the query should be an aggregate function) (asynchronously). * @param context the context. * @param xpathQuery the aggregate xpath query (e.g. "COUNT(//System.User)"). * @param retrievalSchema the schema. * @param disableSecurity whether security should be applied for this retrieval. * @return the aggregate value. */ public static Long <API key>(IContext context, String xpathQuery, IRetrievalSchema retrievalSchema, boolean disableSecurity) throws CoreException { return component.core().<API key>(context, xpathQuery, retrievalSchema, disableSecurity); } /** * Retrieves long value based on the given query (query should have an aggregate function as root element) * @param context * @param xpathQuery * @return returns Future object for action control and return of action result */ public static Future<Double> <API key>(IContext context, String xpathQuery) { return component.core().<API key>(context, xpathQuery); } /** * Retrieves double aggregate value based on the given query (root element of the query should be an aggregate function) (synchronously). * @param context the context. * @param xpathQuery the aggregate xpath query (e.g. "COUNT(//System.User)"). * @return the Future object. */ public static Double <API key>(IContext context, String xpathQuery) throws CoreException { return component.core().<API key>(context, xpathQuery); } /** * Returns contents of a file document as an input stream. * @param context the context. * @param fileDocument the file document from which the contents will be returned. * @return the input stream of the file content of the given file document. */ public static InputStream <API key>(IContext context, IMendixObject fileDocument) { return component.core().<API key>(context, fileDocument); } /** * Physically stores a file using the given input stream and commits the file document. * @param context the context. * @param fileDocument the file document to which the file to store is linked to. * @param fileName the original name of the file (will be stored in the Name attribute) * @param inputStream the content of the file */ public static void <API key>(IContext context, IMendixObject fileDocument, String fileName, InputStream inputStream) { component.core().<API key>(context, fileDocument, fileName, inputStream); } /** * Physically stores a file using the given input stream and commits the file document. * @param context the context. * @param fileDocument the file document to which the file to store is linked to. * @param inputStream the content of the file */ public static void <API key>(IContext context, IMendixObject fileDocument, InputStream inputStream) { component.core().<API key>(context, fileDocument, inputStream); } /** * Physically stores an image using the given input stream and commits the image document. * @param context the context. * @param imageDocument the image document to which the image to store is linked to. * @param inputStream the content of the file * @param thumbnailWidth the width of the thumbnail to create for this image. * @param thumbnailHeight the width of the thumbnail to create for this image. */ public static void <API key>(IContext context, IMendixObject imageDocument, InputStream inputStream, int thumbnailWidth, int thumbnailHeight) { component.core().<API key>(context, imageDocument, inputStream, thumbnailWidth, thumbnailHeight); } /** * Retrieve contents of the given image document. * @param context the context. * @param imageDocument the image document for which its contents are retrieved. * @param retrieveThumbnail indicates whether a thumbnail or the full image is retrieved. * @return the image as an input stream. */ public static InputStream getImage(IContext context, IMendixObject imageDocument, boolean retrieveThumbnail) { return component.core().getImage(context, imageDocument, retrieveThumbnail); } /** * Checks whether a type is a subclass of or equal to a potential super class. * @param superClass the name of the super class * @param type the name of the type to check * @return returns true if type is a subclass of superClass or if type equals superClass */ public static boolean isSubClassOf(String superClass, String type) { return component.core().isSubClassOf(superClass, type); } /** * Checks whether a type is a subclass of or equal to a potential super class. * @param superObject the super object. * @param type the name of the type to check. * @return returns true if type is a subclass of superClass or if type equals superClass. */ public static boolean isSubClassOf(IMetaObject superObject, IMetaObject type) { return component.core().isSubClassOf(superObject, type); } /** * Checks whether a type is a subclass of or equal to a potential super class. * @param superClass the name of the super class * @param typeHash the hash of the name of the type to check * @return returns true if type is a subclass of superClass or if type equals superClass * @deprecated Use the method call with a short as parameter instead. * @throws CoreException */ @Deprecated public static boolean isSubClassOf(String superClass, int typeHash) { return isSubClassOf(superClass, (short) typeHash); } /** * Checks whether a type is a subclass of or equal to a potential super class. * @param superClass the name of the super class * @param typeHash the hash of the name of the type to check * @return returns true if type is a subclass of superClass or if type equals superClass * @throws CoreException */ public static boolean isSubClassOf(String superClass, short typeHash) { return component.core().isSubClassOf(superClass, typeHash); } /** * Get all IMendixObject types. * @return returns a list with all IMendixObjects (one object for each existing type) */ public static Iterable<IMendixObject> getAllMendixObjects() { return component.core().getAllMendixObjects(); } /** * Get all subtypes for an object type (including subtypes of subtypes, etc.). * @param objectType the object type. * @return list of subtypes, in no particular order. */ public static List<String> getSubtypesOf(String objectType) { return component.core().getSubtypesOf(objectType); } /** * Get the IMetaObject corresponding to the given meta object name. * @param metaObjectName the meta object name. * @return returns the IMetaObject for the given metaObjectName */ public static IMetaObject getMetaObject(String metaObjectName) { return component.core().getMetaObject(metaObjectName); } /** * Get the IMetaPrimtive based on a qualified attribute name (e.g. "System.User.Name"). * @param <API key> the qualified attribute name. * @return the IMetaPrimtive. */ public static IMetaPrimitive getMetaPrimitive(String <API key>) { return component.core().getMetaPrimitive(<API key>); } /** * Get all IMetaObjects. * @return returns all IMetaObjects. */ public static Iterable<IMetaObject> getMetaObjects() { return component.core().getMetaObjects(); } /** * Get all IMetaAssociations. * @return returns all IMetaAssociations. */ public static Iterable<IMetaAssociation> getMetaAssociations() { return component.core().getMetaAssociations(); } /** * Get the IMetaAssociation corresponding to the given association name. * @param association the association name (e.g. "System.UserRoles"). * @return returns the IMetaAssociation for the given association name. */ public static IMetaAssociation getMetaAssociation(String association) { return component.core().getMetaAssociation(association); } /** * @param iMetaObject the meta object to get the database table name for * @return the name of the database table */ public static String <API key>(IMetaObject iMetaObject) { return component.core().<API key>(iMetaObject); } /** * @param iMetaAssociation the meta association to get the database table name for * @return the name of the database table */ public static String <API key>(IMetaAssociation iMetaAssociation) { return component.core().<API key>(iMetaAssociation); } /** * @param iMetaPrimitive the meta primitive to get the database column name for * @return the name of the database column */ public static String <API key>(IMetaPrimitive iMetaPrimitive) { return component.core().<API key>(iMetaPrimitive); } /** * @param iMetaAssociation the meta association to get the database child column name for * @return the name of the database child column name */ public static String <API key>(IMetaAssociation iMetaAssociation) { return component.core().<API key>(iMetaAssociation); } /** * @param iMetaAssociation the meta association to get the database parent column name for * @return the name of the database parent column name */ public static String <API key>(IMetaAssociation iMetaAssociation) { return component.core().<API key>(iMetaAssociation); } /** * @deprecated use createSystemContext instead */ @Deprecated public static IContext getSystemContext() { return component.core().createSystemContext(); } /** * Returns the context of the system session (this is always a sudo context). * The system session has no associated user or user roles. * @return returns the system session context. */ public static IContext createSystemContext() { return component.core().createSystemContext(); } /** * Creates a IMendixIdentifier for the given guid. * @param guid the guid. * @return returns the created MendixIdentifier. */ public static IMendixIdentifier <API key>(String guid) { return component.core().<API key>(guid); } /** * Creates a new IMendixIdentifier for the given guid. * @param guid the guid. * @return returns the created MendixIdentifier. */ public static IMendixIdentifier <API key>(long guid) { return component.core().<API key>(guid); } /** * Authenticate the given user with the given password. * @param context * @param user the user. * @param password the password. * @return returns true if authentication was successful. */ public static boolean authenticate(IContext context, IUser user, String password) throws CoreException { return component.core().authenticate(context, user, password); } /** * Generic login method (can be used in modules in combination with LoginAction replacement). * @param params the params. * @return the created session if login was successful. */ public static ISession login(Map<String,? extends Object> params) throws CoreException { return component.core().login(params); } /** * Login user with the given user name and password. * @param userName the user name. * @param password the password. * @return the created session if login is successful. */ public static ISession login(String userName, String password) throws CoreException { return component.core().login(userName, password); } /** * Login user with the given parameters. * @param userName the user name. * @param password the password. * @param locale the locale. * @param currentSessionId current session UUID. * @return the created session if login is successful. */ @Deprecated public static ISession login(String userName, String password, @SuppressWarnings("unused") String locale, String currentSessionId) throws CoreException { return Core.login(userName, password, currentSessionId); } /** * Login user with the given parameters. * @param userName the user name. * @param password the password. * @param currentSessionId current session UUID. * @return the created session if login is successful. */ public static ISession login(String userName, String password, String currentSessionId) throws CoreException { return component.core().login(userName, password, currentSessionId); } @Deprecated public static ISession login(String userName, String password, @SuppressWarnings("unused") String locale, IMxRuntimeRequest request) throws CoreException { return Core.login(userName, password, request); } public static ISession login(String userName, String password, IMxRuntimeRequest request) throws CoreException { return component.core().login(userName, password, request); } /** * Logout the given session. When the session is persistent it will be removed from the database. * If the session is not persistent it will removed from the session cache. * @param session the session to logout. */ public static void logout(ISession session) { component.core().logout(session); } /** * Returns a user using the given user name. * @param context the context. * @param userName the user name to retrieve a user for. * @return the retrieved user. */ public static IUser getUser(IContext context, String userName) throws CoreException { return component.core().getUser(context, userName); } /** * Initialize a new session for the given user. * @deprecated use initializeSession(user, currentSessionId) instead. * @param context the context. * @param user the user for which the session should be initialized. * @param currentSessionId id of the current session, will be used to transfer data when current session is associated with a guest user. * @param locale determines the user's language. * The existing language remains set if available. The default language is used when no language was set and locale is null or empty. * @return the created session. */ @Deprecated public static ISession initializeSession(@SuppressWarnings("unused") IContext context, IUser user, String currentSessionId, @SuppressWarnings("unused") String locale) throws CoreException { return Core.initializeSession(user, currentSessionId); } /** * Initialize a new session for the given user. * @param user the user for which the session should be initialized. * @param currentSessionId id of the current session, will be used to transfer data when current session is associated with a guest user. * @return the created session. */ public static ISession initializeSession(IUser user, String currentSessionId) throws CoreException { return component.core().initializeSession(user, currentSessionId); } /** * Initialize a new session for a guest user * @return the created session * @throws CoreException */ public static ISession <API key>() throws CoreException { return component.core().<API key>(); } /** * Import an xml stream, map this stream to domain objects and store those object in the Mendix database. * @param context the context. * @param xmlStream the xml stream to map and store. * @param <API key> name of the mapping from xml to domain objects (as defined in the Mendix Business Modeler, e.g. "Orders.MyMapping"). * @param mappingParameter parameter object used during the mapping (optional) */ public static void importXmlStream(IContext context, InputStream xmlStream, String <API key>, IMendixObject mappingParameter) { integration.importXmlStream(context, xmlStream, <API key>, mappingParameter); } /** * Import an xml stream, map this stream to domain objects and store those object in the Mendix database. * @param context the context. * @param xmlStream the xml stream to map and store. * @param <API key> name of the mapping from xml to domain objects (as defined in the Mendix Business Modeler, e.g. "Orders.MyMapping"). * @param mappingParameter parameter object used during the mapping (optional) * @param <API key> whether to store the result of the xml mapping in variable which will be returned by this method. * @param hasListReturnValue indicates whether the return value of the xml mapping is of type List. */ public static Object importXmlStream(IContext context, InputStream xmlStream, String <API key>, IMendixObject mappingParameter, boolean <API key>, boolean hasListReturnValue) { return integration.importXmlStream(context, xmlStream, <API key>, mappingParameter, <API key>, -1, hasListReturnValue); } public static IWebserviceResponse callWebservice(String location, String soapAction, String soapRequestMessage) { return integration.callWebservice(location, soapAction, soapRequestMessage); } public static IWebserviceResponse callWebservice(String location, String soapAction, InputStream soapRequestMessage) { return integration.callWebservice(location, soapAction, soapRequestMessage); } /** * Add a custom request handler to the Mendix Business Server. This request * handler will process MxRuntimeRequests on the given path. Responses should be * given by adding information to the MxRuntimeResponse. * @param path the path for which request should be processed. * @param requestHandler the custom request handler. */ public static void addRequestHandler(String path, RequestHandler requestHandler) { component.runtime().getConnector().addRequestHandler(path, requestHandler); } public static ILogNode getLogger(String name) { return component.core().getLogger(name); } /** * Returns the current configuration. * @return the configuration. */ public static Configuration getConfiguration() { return component.core().getConfiguration(); } /** * Resolve tokens in the given text. * Possible tokens: * - [%CurrentDateTime%] * - [%CurrentUser%] * - [%SecondLength%] * - [%MinuteLength%] * - [%HourLength%] * - [%DayLength%] * - [%WeekLength%] * - [%MonthLength%] * - [%YearLength%] * - [%<API key>%] * - [%EndOfCurrentMinute%] * - [%BeginOfCurrentHour%] * - [%BeginOfCurrentDay%] * - [%EndOfCurrentDay%] * - [%BeginOfCurrentWeek%] * - [%EndOfCurrentWeek%] * - [%BeginOfCurrentMonth%] * - [%EndOfCurrentMonth%] * - [%BeginOfCurrentYear%] * - [%EndOfCurrentYear%] * - [%UserRole_%Name%%] (e.g. [%<API key>%]) * @param text the text to resolve. * @param context the context. * @return the resolved object. */ public static Object resolveTokens(IContext context, String text) { return component.core().resolveTokens(context, text); } //////////// ActionManager statistics ////////////////////////////// /** * Returns the current number of active actions. This number represents only the actions * which were started asynchronously. * @return number of current active actions. */ public static int <API key>() { return component.core().<API key>(); } /** * Returns the number of completed actions since server startup. This number represents * only the actions which were started asynchronously. * @return number of completed actions */ public static long <API key>() { return component.core().<API key>(); } /** * Returns the current action pool queue size. * @return returns current queue size of action thread pool. */ public static int getActionQueueSize() { return component.core().getActionQueueSize(); } /** * Returns the current action pool size. * @return the current size of the action thread pool. */ public static int getCurrentPoolSize() { return component.core().getCurrentPoolSize(); } /** * Returns the largest action pool size. * @return the maximum number of threads the thread pool has ever ran. */ public static int getLargestPoolSize() { return component.core().getLargestPoolSize(); } /** * Returns the number of actions currently scheduled for future execution. * @return the number of scheduled actions. */ public static int <API key>() { return component.core().<API key>(); } /** * Returns the maximum number of concurrent users since the server was started. * @return maximum number of concurrent users. */ public static int <API key>() throws CoreException { return component.core().<API key>(); } /** * Returns current number of concurrent users (live sessions). * @deprecated use <API key> instead. */ @Deprecated public static long <API key>() { return Core.<API key>(); } /** * Returns current number of concurrent sessions. */ public static long <API key>() { return component.core().<API key>(); } /** * @return the active sessions. */ public static Collection<? extends ISession> getActiveSessions() { return component.core().getActiveSessions(); } /** * @param userName the user name associated with the session to search for. * @return the session associated with the given user name if such a session exists, otherwise null. */ public static ISession getActiveSession(String userName) { return component.core().getActiveSession(userName); } public static long getNamedUserCount() { return component.core().getNamedUserCount(); } /** * The current number of concurrent users. * @param anonymous whether anonymous users should be included in the count. * @return the number of concurrent users. */ public static long <API key>(boolean anonymous) { return component.core().<API key>(anonymous); } /** * Returns the translated string for a certain key and context. The context is used * to retrieve the language of the current user. * @param context the context. * @param key the key referring to the translatable string. * @param args the arguments which should be applied to translatable string template. * @return the translated string. */ public static String <API key>(IContext context, String key, Object ...args) { return component.core().<API key>(context, key, args); } /** * Returns the translated string for a certain key and language code. * @param languageCode the language code (ISO-639). * @param key the key referring to the translatable string. * @param args values which should replace possible templates in the translatable string ({1}, {2}, etc.). * @return the translated string. */ public static String <API key>(String languageCode, String key, Object ... args) { return component.core().<API key>(languageCode, key, args); } /** * Returns the default language of the loaded project. * @return the default langauge. */ public static ILanguage getDefaultLanguage() { return component.core().getDefaultLanguage(); } /** * Retrieve locale using the given context. * @param context the context. * @return the Locale. */ public static Locale getLocale(IContext context) { return component.core().getLocale(context); } /** * Retrieve locale using the given language code (e.g. en_US). * @param languageCode the languageCode (ISO-639). * @return the Locale. */ public static Locale getLocale(String languageCode) { return component.core().getLocale(languageCode); } /** * Returns the startup date time of the Mendix Business Server. * @return the date time on which the Mendix Business Server was started. */ public static Date getStartupDateTime() { return component.core().getStartupDateTime(); } public static void <API key>(LogSubscriber subscriber) { component.core().<API key>(subscriber); } /** * Prints the message and stacktrace of a Throwable and its cause(s). * @param trace the StringBuilder the exception is printed to. * @param e the Throwable to print. */ public static void buildException(StringBuilder trace, Throwable e) { component.core().buildException(trace, e); } /** * Add the action specified by the given action name to action registry. This enables calling * <code>Core.execute(actionName)</code> for this action. * @param actionName the fully qualified class name of the action (e.g. com.mendix.action.MyAction). */ public static void addUserAction(Class<? extends UserAction<?>> userActionClass) { component.core().addUserAction(userActionClass); } /** * Creates a DataType based on a type.<br> * Possible types:<br> * - Boolean <br> * - Integer <br> * - Long <br> * - Float <br> * - String <br> * - Datetime <br> * - {code#id} (enumeration key) <br> * - ModuleName.ObjectName (IMendixObject)<br> * - [ModuleName.ObjectName] (List<IMendixObject>) <br> * @param type the type to base the IDataType on. * @return the resulting IDataType. */ public static IDataType createDataType(String type) { return component.core().createDataType(type); } /** * Creates a DataType based on an object type and a attribute name * @param objectType the object type (format: "ModuleName.EntityName"). * @param attributeName the attribute to create the IDataType for (should be a member of above object type) * @return the resulting IDataType */ public static IDataType createDataType(String objectType, String attributeName) { return component.core().createDataType(objectType, attributeName); } public static IProfiler getProfiler() { return component.core().getProfiler(); } public static void registerProfiler(IProfiler profiler) throws MendixException { component.core().registerProfiler(profiler); } public static void unregisterProfiler() { component.core().unregisterProfiler(); } /** * Removes the object with the given id from the database and server cache (asynchronously). * @param context the context. * @param id id of the object to remove. * @return returns the Future object. * @deprecated use Core.deleteAsync() instead. This new version does not allow passing an identifier but only objects, * however within this deprecated method the object is simply retrieved using Core.retrieveId() as well. * To make this perform better, you should gather ids and retrieve all objects with Core.retrieveIdList() and then use Core.deleteAsync using the list. */ @Deprecated public static Future<Boolean> removeAsync(IContext context, IMendixIdentifier id, boolean useDeleteBehavior) throws CoreException { return component.core().removeAsync(context, id, useDeleteBehavior); } }
import copy import itertools import weakref from mopidy.models.fields import Field # Registered models for automatic deserialization _models = {} class ImmutableObject: """ Superclass for immutable objects whose fields can only be modified via the constructor. This version of this class has been retained to avoid breaking any clients relying on it's behavior. Internally in Mopidy we now use :class:`<API key>` for type safety and it's much smaller memory footprint. :param kwargs: kwargs to set as fields on the object :type kwargs: any """ # Any sub-classes that don't set slots won't be effected by the base using # slots as they will still get an instance dict. __slots__ = ["__weakref__"] def __init__(self, *args, **kwargs): for key, value in kwargs.items(): if not self._is_valid_field(key): raise TypeError( f"__init__() got an unexpected keyword argument {key!r}" ) self._set_field(key, value) def __setattr__(self, name, value): if name.startswith("_"): object.__setattr__(self, name, value) else: raise AttributeError("Object is immutable.") def __delattr__(self, name): if name.startswith("_"): object.__delattr__(self, name) else: raise AttributeError("Object is immutable.") def _is_valid_field(self, name): return hasattr(self, name) and not callable(getattr(self, name)) def _set_field(self, name, value): if value == getattr(self.__class__, name): self.__dict__.pop(name, None) else: self.__dict__[name] = value def _items(self): return self.__dict__.items() def __repr__(self): kwarg_pairs = [] for key, value in sorted(self._items()): if isinstance(value, (frozenset, tuple)): if not value: continue value = list(value) kwarg_pairs.append(f"{key}={value!r}") return f"{self.__class__.__name__}({', '.join(kwarg_pairs)})" def __hash__(self): hash_sum = 0 for key, value in self._items(): hash_sum += hash(key) + hash(value) return hash_sum def __eq__(self, other): if not isinstance(other, self.__class__): return False return all( a == b for a, b in itertools.zip_longest( self._items(), other._items(), fillvalue=object() ) ) def __ne__(self, other): return not self.__eq__(other) def replace(self, **kwargs): """ Replace the fields in the model and return a new instance Examples:: # Returns a track with a new name Track(name='foo').replace(name='bar') # Return an album with a new number of tracks Album(num_tracks=2).replace(num_tracks=5) :param kwargs: kwargs to set as fields on the object :type kwargs: any :rtype: instance of the model with replaced fields """ other = copy.copy(self) for key, value in kwargs.items(): if not self._is_valid_field(key): raise TypeError( f"replace() got an unexpected keyword argument {key!r}" ) other._set_field(key, value) return other def serialize(self): data = {} data["__model__"] = self.__class__.__name__ for key, value in self._items(): if isinstance(value, (set, frozenset, list, tuple)): value = [ v.serialize() if isinstance(v, ImmutableObject) else v for v in value ] elif isinstance(value, ImmutableObject): value = value.serialize() if not (isinstance(value, list) and len(value) == 0): data[key] = value return data class <API key>(type): """Helper that initializes fields, slots and memoizes instance creation.""" def __new__(cls, name, bases, attrs): fields = {} for base in bases: # Copy parent fields over to our state fields.update(getattr(base, "_fields", {})) for key, value in attrs.items(): # Add our own fields if isinstance(value, Field): fields[key] = "_" + key value._name = key attrs["_fields"] = fields attrs["_instances"] = weakref.WeakValueDictionary() attrs["__slots__"] = list(attrs.get("__slots__", [])) + list( fields.values() ) clsc = super().__new__(cls, name, bases, attrs) if clsc.__name__ != "<API key>": _models[clsc.__name__] = clsc return clsc def __call__(cls, *args, **kwargs): # noqa: N805 instance = super().__call__(*args, **kwargs) return cls._instances.setdefault(weakref.ref(instance), instance) class <API key>( ImmutableObject, metaclass=<API key> ): """ Superclass for immutable objects whose fields can only be modified via the constructor. Fields should be :class:`Field` instances to ensure type safety in our models. Note that since these models can not be changed, we heavily memoize them to save memory. So constructing a class with the same arguments twice will give you the same instance twice. """ __slots__ = ["_hash"] def __hash__(self): if not hasattr(self, "_hash"): hash_sum = super().__hash__() object.__setattr__(self, "_hash", hash_sum) return self._hash def _is_valid_field(self, name): return name in self._fields def _set_field(self, name, value): object.__setattr__(self, name, value) def _items(self): for field, key in self._fields.items(): if hasattr(self, key): yield field, getattr(self, key) def replace(self, **kwargs): """ Replace the fields in the model and return a new instance Examples:: # Returns a track with a new name Track(name='foo').replace(name='bar') # Return an album with a new number of tracks Album(num_tracks=2).replace(num_tracks=5) Note that internally we memoize heavily to keep memory usage down given our overly repetitive data structures. So you might get an existing instance if it contains the same values. :param kwargs: kwargs to set as fields on the object :type kwargs: any :rtype: instance of the model with replaced fields """ if not kwargs: return self other = super().replace(**kwargs) if hasattr(self, "_hash"): object.__delattr__(other, "_hash") return self._instances.setdefault(weakref.ref(other), other)
namespace GraphSharp.Algorithms.Layout { public enum LayoutDirection { LeftToRight = 0, TopToBottom = 1, RightToLeft = 2, BottomToTop = 3 } }
package com.github.<API key>.osgi; import static org.osgi.framework.Constants.*; import java.io.File; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import org.osgi.framework.launch.Framework; import org.springframework.util.Assert; /** * Value object representing {@link Framework} configuration. * * @author Laurens Fridael * */ public class <API key> { /* Configuration */ private Configuration configuration; private boolean <API key> = true; private ConfigurationValues<SystemPackage> coreSystemPackages = null; private ConfigurationValues<SystemPackage> <API key> = null; /* Main operations */ /** * Converts this configuration to a Map suitable for passing to <code>FrameworkFactory.newFramework(Map)</code>. * * @return The configuration as a Map. */ public Map<String, String> toMap() { final Map<String, String> configuration = new HashMap<String, String>(); if (getStorageDirectory() != null) { configuration.put(FRAMEWORK_STORAGE, getStorageDirectory().getAbsolutePath()); } if (<API key>()) { configuration.put(<API key>, <API key>); } if (<API key>() != null) { configuration.put(<API key>, <API key>(<API key>())); } if (<API key>() != null) { configuration.put(<API key>, <API key>(<API key>())); } return configuration; } /* Utility operations */ protected String <API key>(final ConfigurationValues<SystemPackage> systemPackages) { final StringBuilder sb = new StringBuilder(); for (final Iterator<SystemPackage> it = systemPackages.iterator(); it.hasNext();) { final SystemPackage systemPackage = it.next(); String version = systemPackage.getVersion(); if (version == null) { // TODO: find out if specifying a version for a system package is mandatory. version = SystemPackage.DEFAULT_VERSION; } sb.append(systemPackage.getName()).append(";version=").append(version); if (it.hasNext()) { sb.append(","); } } return sb.toString(); } /* Configuration */ public void setConfiguration(final Configuration configuration) { Assert.notNull(configuration); this.configuration = configuration; } public Configuration getConfiguration() { return configuration; } public File getStorageDirectory() { return getConfiguration().getStorageDirectory(); } public boolean <API key>() { return <API key>; } public void <API key>(final boolean <API key>) { this.<API key> = <API key>; } public void <API key>(final ConfigurationValues<SystemPackage> coreSystemPackages) { Assert.notNull(coreSystemPackages); this.coreSystemPackages = coreSystemPackages; } public ConfigurationValues<SystemPackage> <API key>() { return coreSystemPackages; } public void <API key>(final ConfigurationValues<SystemPackage> <API key>) { Assert.notNull(<API key>); this.<API key> = <API key>; } public ConfigurationValues<SystemPackage> <API key>() { return <API key>; } }
package liquibase.sdk.watch; import com.sun.org.apache.xpath.internal.SourceTree; import liquibase.changelog.<API key>; import liquibase.changelog.<API key>; import liquibase.command.AbstractCommand; import liquibase.command.<API key>; import liquibase.database.Database; import liquibase.database.DatabaseFactory; import liquibase.exception.DatabaseException; import liquibase.exception.<API key>; import liquibase.executor.Executor; import liquibase.executor.ExecutorService; import liquibase.integration.commandline.<API key>; import liquibase.lockservice.LockService; import liquibase.lockservice.LockServiceFactory; import liquibase.resource.<API key>; import liquibase.sdk.Main; import liquibase.sdk.TemplateService; import liquibase.snapshot.DatabaseSnapshot; import liquibase.snapshot.SnapshotControl; import liquibase.snapshot.<API key>; import liquibase.statement.core.<API key>; import liquibase.structure.DatabaseObject; import liquibase.structure.core.Schema; import liquibase.util.ISODateFormat; import liquibase.util.StringUtils; import org.eclipse.jetty.server.Handler; import org.eclipse.jetty.server.Request; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.handler.AbstractHandler; import org.eclipse.jetty.server.handler.DefaultHandler; import org.eclipse.jetty.server.handler.HandlerList; import org.eclipse.jetty.server.handler.ResourceHandler; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.FilenameFilter; import java.io.IOException; import java.io.PrintWriter; import java.net.URL; import java.net.URLClassLoader; import java.util.*; public class WatchCommand extends AbstractCommand { private String url; private String username; private String password; private int port = 8080; private Main mainApp; public WatchCommand(Main mainApp) { this.mainApp = mainApp; } @Override public String getName() { return "watch"; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public int getPort() { return port; } public void setPort(int port) { this.port = port; } @Override public <API key> validate() { return new <API key>(this); } @Override protected Object run() throws Exception { Server server = new Server(port); List<URL> jarUrls = new ArrayList<URL>(); File libDir = new File("../../lib/"); for (File file : libDir.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.endsWith("jar"); } })) { jarUrls.add(file.toURL()); } <API key> resourceAccessor = new <API key>( new <API key>(new URLClassLoader(jarUrls.toArray(new URL[jarUrls.size()]), this.getClass().getClassLoader())) ); Database database = DatabaseFactory.getInstance().openDatabase(url, username, password, resourceAccessor); ResourceHandler staticHandler = new ResourceHandler(); staticHandler.<API key>(false); staticHandler.setWelcomeFiles(new String[]{"index.html"}); staticHandler.setResourceBase(getClass().getClassLoader().getResource("liquibase/sdk/watch/index.html.vm").toExternalForm().replaceFirst("index.html.vm$", "")); HandlerList handlers = new HandlerList(); handlers.setHandlers(new Handler[]{new <API key>(database), staticHandler, new DefaultHandler()}); server.setHandler(handlers); server.start(); mainApp.out("Liquibase Watch running on http://localhost:"+getPort()+"/"); server.join(); return "Started"; } private static class <API key> extends AbstractHandler { private final Database database; private final Executor executor; public <API key>(Database database) { this.database = database; executor = ExecutorService.getInstance().getExecutor(database); } @Override public void handle(String url, Request request, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException, ServletException { try { if (url.equals("/favicon.ico")) { httpServletResponse.setStatus(HttpServletResponse.SC_NOT_FOUND); request.setHandled(true); } else if (url.equals("/index.html") || url.equals("/") || url.equals("")) { Map<String, Object> context = new HashMap<String, Object>(); this.loadIndexData(context); httpServletResponse.setContentType("text/html"); httpServletResponse.setStatus(HttpServletResponse.SC_OK); TemplateService.getInstance().write("liquibase/sdk/watch/index.html.vm", httpServletResponse.getWriter(), context); request.setHandled(true); } else if (url.equals("/liquibase-status.json")) { if (<API key>.getInstance().<API key>(database)) { LockService lockService = LockServiceFactory.getInstance().getLockService(database); lockService.waitForLock(); List<Map<String, ?>> rows; try { <API key> select = new <API key>("COUNT(*) AS ROW_COUNT", "MAX(DATEEXECUTED) AS LAST_EXEC"); rows = executor.queryForList(select); } finally { lockService.releaseLock(); } PrintWriter writer = httpServletResponse.getWriter(); httpServletResponse.setContentType("application/json"); httpServletResponse.setStatus(HttpServletResponse.SC_OK); if (rows.size() == 0) { writer.print("{\"count\": 0}"); } else { Map<String, ?> row = rows.iterator().next(); writer.print("{\"count\":" + row.get("ROW_COUNT") + ", \"lastExec\": \"" + new ISODateFormat().format((Date) row.get("LAST_EXEC")) + "\"}"); } request.setHandled(true); } else { PrintWriter writer = httpServletResponse.getWriter(); httpServletResponse.setContentType("application/json"); httpServletResponse.setStatus(HttpServletResponse.SC_OK); writer.print("{\"count\": -1}"); request.setHandled(true); } } } catch (Throwable e) { throw new ServletException(e); } } protected void <API key>(Map<String, Object> context) throws DatabaseException { String outString; String changeLogDetails = ""; if (<API key>.getInstance().<API key>(database)) { outString = "<table class='table table-striped table-bordered table-condensed'>"; outString += "<tr><th>Id</th><th>Author</th><th>Path</th><th>ExecType</th><th>Tag</th></tr>"; <API key> select = new <API key>("FILENAME", "AUTHOR", "ID", "MD5SUM", "DATEEXECUTED", "ORDEREXECUTED", "EXECTYPE", "DESCRIPTION", "COMMENTS", "TAG", "LIQUIBASE").setOrderBy("DATEEXECUTED DESC", "ORDEREXECUTED DESC"); //going in opposite order for easier reading List<Map> ranChangeSets = (List) ExecutorService.getInstance().getExecutor(database).queryForList(select); for (Map row : ranChangeSets) { String id = cleanHtmlId(row.get("ID") + ":" + row.get("AUTHOR") + ":" + row.get("FILENAME")); outString += "<tr>" + "<td><a style='color:black' class='object-name' href='#" + id + "'>" + StringUtils.escapeHtml((String) row.get("ID")) + "</a></td>" + "<td><a style='color:black' class='object-name' href='#" + id + "'>" + StringUtils.escapeHtml((String) row.get("AUTHOR")) + "</a></td>" + "<td><a style='color:black' class='object-name' href='#" + id + "'>" + StringUtils.escapeHtml((String) row.get("FILENAME")) + "</a></td>" + "<td><a style='color:black' class='object-name' href='#" + id + "'>" + row.get("EXECTYPE") + "</a></td>" + "<td><a style='color:black' class='object-name' href='#" + id + "'>" + StringUtils.escapeHtml((String) StringUtils.trimToEmpty((String) row.get("TAG"))) + "</a></td>" + "</tr>"; changeLogDetails += wrapDetails(id, row.get("ID") + " :: " + row.get("AUTHOR") + " :: " + row.get("FILENAME"), <API key>(row)); } outString += "</table>"; } else { outString = "<h2 style='margin-top:0px; padding-top: 10px; padding-left:10px'>No DatabaseChangeLog Table</h2>"; } context.put("changeLog", outString); context.put("changeLogDetails", changeLogDetails); } private String cleanHtmlId(String id) { return id.replaceAll("[^a-zA-Z0-9_\\-]", "_"); } protected String <API key>(Map row) throws DatabaseException { String outString = "<table class='table table-striped table-bordered table-condensed'>"; outString += "<tr><td><strong>Id</strong></td><td>" + row.get("ID") + "</td></tr>\n" + "<tr><td><strong>Author</strong></td><td>" + row.get("AUTHOR") + "</td></tr>\n" + "<tr><td><strong>Filename</strong></td><td>" + row.get("FILENAME") + "</td></tr>\n" + "<tr><td><strong>DateExecuted</strong></td><td>" + new ISODateFormat().format((Date) row.get("DATEEXECUTED")) + "</td></tr>\n" + "<tr><td><strong>OrderExecuted</strong></td><td>" + row.get("ORDEREXECUTED") + "</td></tr>\n" + "<tr><td><strong>ExecType</strong></td><td>" + row.get("EXECTYPE") + "</td></tr>\n" + "<tr><td><strong>MD5Sum</strong></td><td>" + row.get("MD5SUM") + "</td></tr>\n" + "<tr><td><strong>Description</strong></td><td>" + row.get("DESCRIPTION") + "</td></tr>\n" + "<tr><td><strong>Comments</strong></td><td>" + row.get("COMMENTS") + "</td></tr>\n" + "<tr><td><strong>Tag</strong></td><td>" + StringUtils.trimToNull((String) row.get("TAG")) + "</td></tr>\n" + "<tr><td><strong>Liquibase</strong></td><td>" + row.get("LIQUIBASE") + "</td></tr>\n"; outString += "</table>"; return outString; } public void loadIndexData(Map<String, Object> context) { try { DatabaseSnapshot snapshot = <API key>.getInstance().createSnapshot(database.getDefaultSchema(), database, new SnapshotControl(database)); StringBuilder buffer = new StringBuilder(); Database database = snapshot.getDatabase(); buffer.append("<div class='panel panel-primary'>"); buffer.append("<div class='panel-heading'><h2 style='margin-top:0px; margin-bottom:0px'>").append(StringUtils.escapeHtml(database.getConnection().getURL())).append("</h2></div>\n"); buffer.append("<div class='panel-body'>"); buffer.append("<strong>Database type:</strong> ").append(StringUtils.escapeHtml(database.<API key>())).append("<br>\n"); buffer.append("<strong>Database version:</strong> ").append(StringUtils.escapeHtml(database.<API key>())).append("<br>\n"); buffer.append("<strong>Database user:</strong> ").append(StringUtils.escapeHtml(database.getConnection().<API key>())).append("<br>\n"); Set<Schema> schemas = snapshot.get(Schema.class); if (schemas.size() > 1) { throw new <API key>("Can only display one schema"); } Schema schema = schemas.iterator().next(); if (database.supportsSchemas()) { buffer.append("<strong>Catalog & Schema:</strong> ").append(schema.getCatalogName()).append(" / ").append(schema.getName()).append("<br>\n"); } else { buffer.append("<strong>Catalog:</strong> ").append(schema.getCatalogName()).append("<br>\n"); } buffer.append("</div>\n"); buffer.append("</div>\n"); SnapshotControl snapshotControl = snapshot.getSnapshotControl(); List<Class> includedTypes = sort(snapshotControl.getTypesToInclude()); StringBuilder catalogBuffer = new StringBuilder(); StringBuilder detailsBuilder = new StringBuilder(); catalogBuffer.append("<ul class='nav nav-tabs' id='tabs'>\n"); catalogBuffer.append("<li><a href='#<API key>' data-toggle='tab'>DatabaseChangeLog</a></li>\n"); for (Class type : includedTypes) { if (schema.getDatabaseObjects(type).size() > 0) { catalogBuffer.append("<li><a href='#").append(type.getSimpleName()).append("-tab' data-toggle='tab'>").append(type.getSimpleName()).append("(s)</a></li>\n"); } } catalogBuffer.append("</ul>\n"); catalogBuffer.append("<div class='tab-content' style='margin-bottom:20px;'>\n"); catalogBuffer.append("<div class='tab-pane' style='border: 1px #ddd solid; border-top:none' id='<API key>'>\n"); <API key>(context); detailsBuilder.append(context.get("changeLogDetails")); catalogBuffer.append(context.get("changeLog")); catalogBuffer.append("</div>"); for (Class type : includedTypes) { List<? extends DatabaseObject> databaseObjects = sort(schema.getDatabaseObjects(type)); if (databaseObjects.size() > 0) { catalogBuffer.append("<div class='tab-pane' style='border: 1px #ddd solid; border-top:none' id='").append(type.getSimpleName()).append("-tab'>\n"); catalogBuffer.append("<div style='padding:10px; font-color:black'><ol>\n"); StringBuilder typeBuffer = new StringBuilder(); for (DatabaseObject databaseObject : databaseObjects) { String id = databaseObject.getClass().getName() + "-" + databaseObject.getName(); id = cleanHtmlId(id); typeBuffer.append("<li><a style='color:black' class='object-name' href='#" + id + "'>").append(StringUtils.escapeHtml(databaseObject.getName())).append("</a></li>\n"); detailsBuilder.append(wrapDetails(id, type.getSimpleName()+" "+databaseObject.getName(), writeDatabaseObject(databaseObject, new HashSet<String>(), databaseObject.getName()))).append("\n"); } catalogBuffer.append(StringUtils.indent(typeBuffer.toString(), 4)).append("\n"); catalogBuffer.append("</ol></div>\n"); catalogBuffer.append("</div>\n"); } } catalogBuffer.append("</div>\n"); buffer.append(StringUtils.indent(catalogBuffer.toString(), 4)); context.put("snapshot", buffer.toString()); //standardize all newline chars context.put("details", detailsBuilder.toString()); //standardize all newline chars } catch (Exception e) { throw new <API key>(e); } } protected String wrapDetails(String id, String title, String details) { StringBuilder buffer = new StringBuilder(); buffer.append("<div class='modal fade' id='"+id+"'><div class='modal-dialog modal-lg'><div class='modal-content'>"); buffer.append("<div class='modal-header'><button type='button' class='close' data-dismiss='modal' aria-hidden='true'>&times;</button><h4 class='modal-title'>").append(StringUtils.escapeHtml(title)).append("</h4></div>\n"); buffer.append("<div class='modal-body'>"); buffer.append(StringUtils.indent(details, 4)); buffer.append("</div>"); buffer.append("<div class='modal-footer'><button type='button' class='btn btn-default' data-dismiss='modal'>Close</button></div>"); buffer.append("</div></div></div>"); return buffer.toString(); } protected String writeDatabaseObject(final DatabaseObject databaseObject, Set<String> oldParentNames, String newParentName) { final Set<String> parentNames = new HashSet<String>(oldParentNames); parentNames.add(newParentName); StringBuilder singleValueOut = new StringBuilder(); StringBuilder multiValueOut = new StringBuilder(); final List<String> attributes = sort(databaseObject.getAttributes()); for (String attribute : attributes) { if (attribute.equals("name")) { continue; } if (attribute.equals("schema")) { continue; } Object value = databaseObject.getAttribute(attribute, Object.class); if (value instanceof Schema) { continue; } boolean multiValue = false; if (value instanceof DatabaseObject) { if (parentNames.contains(((DatabaseObject) value).getName())) { value = null; } else { value = databaseObject.<API key>(attribute); } } else if (value instanceof Collection) { if (((Collection) value).size() == 0) { value = null; } else { multiValue = true; Object firstValue = ((Collection) value).iterator().next(); if (firstValue instanceof DatabaseObject) { final List<String> rowAttributes = new ArrayList<String>(); rowAttributes.add("name"); for (DatabaseObject obj : ((Collection<DatabaseObject>) value)) { for (String rowAttribute : obj.getAttributes()) { if (!rowAttributes.contains(rowAttribute)) { Object cellValue = obj.getAttribute(rowAttribute, Object.class); if (cellValue instanceof DatabaseObject && parentNames.contains(((DatabaseObject) cellValue).getName())) { continue; } else { if (cellValue == null || (cellValue instanceof Collection && ((Collection) cellValue).size() == 0)) { continue; } else { rowAttributes.add(rowAttribute); } } } } } value = StringUtils.join((Collection) value, "\n", new StringUtils.<API key>() { @Override public String toString(Object obj) { if (obj instanceof DatabaseObject) { String row = "<tr>"; for (String attribute : rowAttributes) { if (((DatabaseObject) obj).getAttributes().contains(attribute)) { row += "<td>" + StringUtils.escapeHtml(((DatabaseObject) obj).<API key>(attribute).toString()); } else { row += "<td></td>"; } } row += "</tr>"; return row; } else { return obj.toString(); } } }); String header = ""; for (String rowAttribute : rowAttributes) { header += "<th>" + rowAttribute + "</th>"; } value = "<div overflow='scroll' style='overflow-x:auto'><table class='table table-bordered table-condensed' style='margin-bottom:0px'><tr>" + header + "</tr>\n" + StringUtils.indent((String) value, 4) + "</table></div>"; } else { value = databaseObject.<API key>(attribute); } } } else { value = databaseObject.<API key>(attribute); } if (value != null) { if (multiValue) { multiValueOut.append("<h4>").append(attribute).append(":</h4>"); multiValueOut.append(StringUtils.escapeHtml(value.toString())); multiValueOut.append("<br>"); } else { singleValueOut.append("<tr><td><strong>").append(attribute).append("</strong></td><td>"); singleValueOut.append(value); singleValueOut.append("</td></tr>"); } } } String finalOut = singleValueOut.toString(); if (finalOut.length() > 0) { finalOut = "<h4>attributes:</h4><table class='table table-bordered table-condensed'>" + finalOut + "</table><br>"; } finalOut = finalOut + multiValueOut.toString(); return finalOut; } private List sort(Collection objects) { return sort(objects, new Comparator() { @Override public int compare(Object o1, Object o2) { if (o1 instanceof Comparable) { return ((Comparable) o1).compareTo(o2); } else if (o1 instanceof Class) { return ((Class) o1).getName().compareTo(((Class) o2).getName()); } else { throw new ClassCastException(o1.getClass().getName() + " cannot be cast to java.lang.Comparable or java.lang.Class"); } } }); } private <T> List<T> sort(Collection objects, Comparator<T> comparator) { List returnList = new ArrayList(objects); Collections.sort(returnList, comparator); return returnList; } } }
page_title: Remote API v1.7 page_description: API Documentation for Docker page_keywords: API, Docker, rcli, REST, documentation # Docker Remote API v1.7 # 1. Brief introduction - The Remote API has replaced rcli - The daemon listens on `unix:///var/run/docker.sock` but you can bind Docker to another host/port or a Unix socket. - The API tends to be REST, but for some complex commands, like `attach` or `pull`, the HTTP connection is hijacked to transport `stdout, stdin` and `stderr` # 2. Endpoints ## 2.1 Containers List containers `GET /containers/json` List containers **Example request**: GET /containers/json?all=1&before=8dfafdbc3a40&size=1 HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "Id": "8dfafdbc3a40", "Image": "base:latest", "Command": "echo 1", "Created": 1367854155, "Status": "Exit 0", "Ports": [{"PrivatePort": 2222, "PublicPort": 3333, "Type": "tcp"}], "SizeRw": 12288, "SizeRootFs": 0 }, { "Id": "9cd87474be90", "Image": "base:latest", "Command": "echo 222222", "Created": 1367854155, "Status": "Exit 0", "Ports": [], "SizeRw": 12288, "SizeRootFs": 0 }, { "Id": "3176a2479c92", "Image": "base:latest", "Command": "echo 3333333333333333", "Created": 1367854154, "Status": "Exit 0", "Ports":[], "SizeRw":12288, "SizeRootFs":0 }, { "Id": "4cb07b47f9fb", "Image": "base:latest", "Command": "echo <API key>", "Created": 1367854152, "Status": "Exit 0", "Ports": [], "SizeRw": 12288, "SizeRootFs": 0 } ] Query Parameters: - **all** – 1/True/true or 0/False/false, Show all containers. Only running containers are shown by default (i.e., this defaults to false) - **limit** – Show `limit` last created containers, include non-running ones. - **since** – Show only containers created since Id, include non-running ones. - **before** – Show only containers created before Id, include non-running ones. - **size** – 1/True/true or 0/False/false, Show the containers sizes Status Codes: - **200** – no error - **400** – bad parameter - **500** – server error Create a container `POST /containers/create` Create a container **Example request**: POST /containers/create HTTP/1.1 Content-Type: application/json { "Hostname":"", "User":"", "Memory":0, "MemorySwap":0, "AttachStdin":false, "AttachStdout":true, "AttachStderr":true, "PortSpecs":null, "Tty":false, "OpenStdin":false, "StdinOnce":false, "Env":null, "Cmd":[ "date" ], "Dns":null, "Image":"base", "Volumes":{ "/tmp": {} }, "VolumesFrom":"", "WorkingDir":"", "ExposedPorts":{ "22/tcp": {} } } **Example response**: HTTP/1.1 201 Created Content-Type: application/json { "Id":"e90e34656806" "Warnings":[] } Json Parameters: - **config** – the container's configuration Status Codes: - **201** – no error - **404** – no such container - **406** – impossible to attach (container not running) - **500** – server error Inspect a container `GET /containers/(id)/json` Return low-level information on the container `id` **Example request**: GET /containers/4fa6e0f0c678/json HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "Id": "<SHA256-like>", "Created": "2013-05-07T14:51:42.041847+02:00", "Path": "date", "Args": [], "Config": { "Hostname": "4fa6e0f0c678", "User": "", "Memory": 0, "MemorySwap": 0, "AttachStdin": false, "AttachStdout": true, "AttachStderr": true, "PortSpecs": null, "Tty": false, "OpenStdin": false, "StdinOnce": false, "Env": null, "Cmd": [ "date" ], "Dns": null, "Image": "base", "Volumes": {}, "VolumesFrom": "", "WorkingDir": "" }, "State": { "Running": false, "Pid": 0, "ExitCode": 0, "StartedAt": "2013-05-07T14:51:42.087658+02:01360", "Ghost": false }, "Image": "<SHA256-like>", "NetworkSettings": { "IpAddress": "", "IpPrefixLen": 0, "Gateway": "", "Bridge": "", "PortMapping": null }, "SysInitPath": "/home/kitty/go/src/github.com/docker/docker/bin/docker", "ResolvConfPath": "/etc/resolv.conf", "Volumes": {} } Status Codes: - **200** – no error - **404** – no such container - **500** – server error List processes running inside a container `GET /containers/(id)/top` List processes running inside the container `id` **Example request**: GET /containers/4fa6e0f0c678/top HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "Titles": [ "USER", "PID", "%CPU", "%MEM", "VSZ", "RSS", "TTY", "STAT", "START", "TIME", "COMMAND" ], "Processes": [ ["root","20147","0.0","0.1","18060","1864","pts/4","S","10:06","0:00","bash"], ["root","20271","0.0","0.0","4312","352","pts/4","S+","10:07","0:00","sleep","10"] ] } Query Parameters: - **ps_args** – ps arguments to use (e.g., aux) Status Codes: - **200** – no error - **404** – no such container - **500** – server error Inspect changes on a container's filesystem `GET /containers/(id)/changes` Inspect changes on container `id`'s filesystem **Example request**: GET /containers/4fa6e0f0c678/changes HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "Path": "/dev", "Kind": 0 }, { "Path": "/dev/kmsg", "Kind": 1 }, { "Path": "/test", "Kind": 1 } ] Status Codes: - **200** – no error - **404** – no such container - **500** – server error Export a container `GET /containers/(id)/export` Export the contents of container `id` **Example request**: GET /containers/4fa6e0f0c678/export HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/octet-stream {{ TAR STREAM }} Status Codes: - **200** – no error - **404** – no such container - **500** – server error Start a container `POST /containers/(id)/start` Start the container `id` **Example request**: POST /containers/(id)/start HTTP/1.1 Content-Type: application/json { "Binds":["/tmp:/tmp"], "LxcConf":[{"Key":"lxc.utsname","Value":"docker"}], "PortBindings":{ "22/tcp": [{ "HostPort": "11022" }] }, "Privileged":false, "PublishAllPorts":false } Binds need to reference Volumes that were defined during container creation. **Example response**: HTTP/1.1 204 No Content Content-Type: text/plain Json Parameters: - **hostConfig** – the container's host configuration (optional) Status Codes: - **204** – no error - **404** – no such container - **500** – server error Stop a container `POST /containers/(id)/stop` Stop the container `id` **Example request**: POST /containers/e90e34656806/stop?t=5 HTTP/1.1 **Example response**: HTTP/1.1 204 OK Query Parameters: - **t** – number of seconds to wait before killing the container Status Codes: - **204** – no error - **404** – no such container - **500** – server error Restart a container `POST /containers/(id)/restart` Restart the container `id` **Example request**: POST /containers/e90e34656806/restart?t=5 HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Query Parameters: - **t** – number of seconds to wait before killing the container Status Codes: - **204** – no error - **404** – no such container - **500** – server error Kill a container `POST /containers/(id)/kill` Kill the container `id` **Example request**: POST /containers/e90e34656806/kill HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Status Codes: - **204** – no error - **404** – no such container - **500** – server error Attach to a container `POST /containers/(id)/attach` Attach to the container `id` **Example request**: POST /containers/16253994b7c4/attach?logs=1&stream=0&stdout=1 HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/vnd.docker.raw-stream {{ STREAM }} Query Parameters: - **logs** – 1/True/true or 0/False/false, return logs. Defaul false - **stream** – 1/True/true or 0/False/false, return stream. Default false - **stdin** – 1/True/true or 0/False/false, if stream=true, attach to stdin. Default false - **stdout** – 1/True/true or 0/False/false, if logs=true, return stdout log, if stream=true, attach to stdout. Default false - **stderr** – 1/True/true or 0/False/false, if logs=true, return stderr log, if stream=true, attach to stderr. Default false Status Codes: - **200** – no error - **400** – bad parameter - **404** – no such container - **500** – server error **Stream details**: When using the TTY setting is enabled in [`POST /containers/create` ](/reference/api/<API key>.7/#create-a-container), the stream is the raw data from the process PTY and client's stdin. When the TTY is disabled, then the stream is multiplexed to separate stdout and stderr. The format is a **Header** and a **Payload** (frame). **HEADER** The header will contain the information on which stream write the stream (stdout or stderr). It also contain the size of the associated frame encoded on the last 4 bytes (uint32). It is encoded on the first 8 bytes like this: header := [8]byte{STREAM_TYPE, 0, 0, 0, SIZE1, SIZE2, SIZE3, SIZE4} `STREAM_TYPE` can be: - 0: stdin (will be written on stdout) - 1: stdout - 2: stderr `SIZE1, SIZE2, SIZE3, SIZE4` are the 4 bytes of the uint32 size encoded as big endian. **PAYLOAD** The payload is the raw stream. **IMPLEMENTATION** The simplest way to implement the Attach protocol is the following: 1. Read 8 bytes 2. chose stdout or stderr depending on the first byte 3. Extract the frame size from the last 4 byets 4. Read the extracted size and output it on the correct output 5. Goto 1) Wait a container `POST /containers/(id)/wait` Block until container `id` stops, then returns the exit code **Example request**: POST /containers/16253994b7c4/wait HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"StatusCode": 0} Status Codes: - **200** – no error - **404** – no such container - **500** – server error Remove a container `DELETE /containers/(id)` Remove the container `id` from the filesystem **Example request**: DELETE /containers/16253994b7c4?v=1 HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Query Parameters: - **v** – 1/True/true or 0/False/false, Remove the volumes associated to the container. Default false Status Codes: - **204** – no error - **400** – bad parameter - **404** – no such container - **500** – server error Copy files or folders from a container `POST /containers/(id)/copy` Copy files or folders of container `id` **Example request**: POST /containers/4fa6e0f0c678/copy HTTP/1.1 Content-Type: application/json { "Resource": "test.txt" } **Example response**: HTTP/1.1 200 OK Content-Type: application/octet-stream {{ TAR STREAM }} Status Codes: - **200** – no error - **404** – no such container - **500** – server error ## 2.2 Images List Images `GET /images/json` **Example request**: GET /images/json?all=0 HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "RepoTags": [ "ubuntu:12.04", "ubuntu:precise", "ubuntu:latest" ], "Id": "<SHA256-like>", "Created": 1365714795, "Size": 131506275, "VirtualSize": 131506275 }, { "RepoTags": [ "ubuntu:12.10", "ubuntu:quantal" ], "ParentId": "27cf784147099545", "Id": "<SHA256-like>", "Created": 1364102658, "Size": 24653, "VirtualSize": 180116135 } ] Create an image `POST /images/create` Create an image, either by pull it from the registry or by importing i **Example request**: POST /images/create?fromImage=base HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"status":"Pulling..."} {"status":"Pulling", "progress":"1/? (n/a)"} {"error":"Invalid..."} When using this endpoint to pull an image from the registry, the `X-Registry-Auth` header can be used to include a base64-encoded AuthConfig object. Query Parameters: - **fromImage** – name of the image to pull - **fromSrc** – source to import, - means stdin - **repo** – repository - **tag** – tag - **registry** – the registry to pull from Request Headers: - **X-Registry-Auth** – base64-encoded AuthConfig object Status Codes: - **200** – no error - **500** – server error Insert a file in an image `POST /images/(name)/insert` Insert a file from `url` in the image `name` at `path` **Example request**: POST /images/test/insert?path=/usr&url=myurl HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"status":"Inserting..."} {"status":"Inserting", "progress":"1/? (n/a)"} {"error":"Invalid..."} Query Parameters: - **url** – The url from where the file is taken - **path** – The path where the file is stored Status Codes: - **200** – no error - **500** – server error Inspect an image `GET /images/(name)/json` Return low-level information on the image `name` **Example request**: GET /images/base/json HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "id":"<SHA256-like>", "parent":"27cf784147099545", "created":"2013-03-23T22:24:18.818426-07:00", "container":"<SHA256-like>", "container_config": { "Hostname":"", "User":"", "Memory":0, "MemorySwap":0, "AttachStdin":false, "AttachStdout":false, "AttachStderr":false, "PortSpecs":null, "Tty":true, "OpenStdin":true, "StdinOnce":false, "Env":null, "Cmd": ["/bin/bash"], "Dns":null, "Image":"base", "Volumes":null, "VolumesFrom":"", "WorkingDir":"" }, "Size": 6824592 } Status Codes: - **200** – no error - **404** – no such image - **500** – server error Get the history of an image `GET /images/(name)/history` Return the history of the image `name` **Example request**: GET /images/base/history HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "Id": "b750fe79269d", "Created": 1364102658, "CreatedBy": "/bin/bash" }, { "Id": "27cf78414709", "Created": 1364068391, "CreatedBy": "" } ] Status Codes: - **200** – no error - **404** – no such image - **500** – server error Push an image on the registry `POST /images/(name)/push` Push the image `name` on the registry **Example request**: POST /images/test/push HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"status":"Pushing..."} {"status":"Pushing", "progress":"1/? (n/a)"} {"error":"Invalid..."} Request Headers: - **X-Registry-Auth** – include a base64-encoded AuthConfig object. Status Codes: - **200** – no error - **404** – no such image - **500** – server error Tag an image into a repository `POST /images/(name)/tag` Tag the image `name` into a repository **Example request**: POST /images/test/tag?repo=myrepo&force=0&tag=v42 HTTP/1.1 **Example response**: HTTP/1.1 201 OK Query Parameters: - **repo** – The repository to tag in - **force** – 1/True/true or 0/False/false, default false - **tag** - The new tag name Status Codes: - **201** – no error - **400** – bad parameter - **404** – no such image - **409** – conflict - **500** – server error Remove an image `DELETE /images/(name)` Remove the image `name` from the filesystem **Example request**: DELETE /images/test HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-type: application/json [ {"Untagged": "3e2f21a89f"}, {"Deleted": "3e2f21a89f"}, {"Deleted": "53b4f83ac9"} ] Status Codes: - **200** – no error - **404** – no such image - **409** – conflict - **500** – server error Search images `GET /images/search` Search for an image on [Docker Hub](https://hub.docker.com). > **Note**: > The response keys have changed from API v1.6 to reflect the JSON > sent by the registry server to the docker daemon's request. **Example request**: GET /images/search?term=sshd HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "description": "", "is_official": false, "is_trusted": false, "name": "wma55/u1210sshd", "star_count": 0 }, { "description": "", "is_official": false, "is_trusted": false, "name": "jdswinbank/sshd", "star_count": 0 }, { "description": "", "is_official": false, "is_trusted": false, "name": "vgauthier/sshd", "star_count": 0 } ] Query Parameters: - **term** – term to search Status Codes: - **200** – no error - **500** – server error ## 2.3 Misc Build an image from Dockerfile via stdin `POST /build` Build an image from Dockerfile via stdin **Example request**: POST /build HTTP/1.1 {{ TAR STREAM }} **Example response**: HTTP/1.1 200 OK Content-Type: application/json {{ STREAM }} The stream must be a tar archive compressed with one of the following algorithms: identity (no compression), gzip, bzip2, xz. The archive must include a file called `Dockerfile` at its root. It may include any number of other files, which will be accessible in the build context (See the [*ADD build command*](/builder/#dockerbuilder)). Query Parameters: - **t** – repository name (and optionally a tag) to be applied to the resulting image in case of success - **q** – suppress verbose build output - **nocache** – do not use the cache when building the image Request Headers: - **Content-type** – should be set to `"application/tar"`. Status Codes: - **200** – no error - **500** – server error Check auth configuration `POST /auth` Get the default username and email **Example request**: POST /auth HTTP/1.1 Content-Type: application/json { "username":" hannibal", "password: "xxxx", "email": "hannibal@a-team.com", "serveraddress": "https://index.docker.io/v1/" } **Example response**: HTTP/1.1 200 OK Content-Type: text/plain Status Codes: - **200** – no error - **204** – no error - **500** – server error Display system-wide information `GET /info` Display system-wide information **Example request**: GET /info HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "Containers":11, "Images":16, "Debug":false, "NFd": 11, "NGoroutines":21, "MemoryLimit":true, "SwapLimit":false, "IPv4Forwarding":true } Status Codes: - **200** – no error - **500** – server error Show the docker version information `GET /version` Show the docker version information **Example request**: GET /version HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "Version":"0.2.2", "GitCommit":"5a2a5cc+CHANGES", "GoVersion":"go1.0.3" } Status Codes: - **200** – no error - **500** – server error Create a new image from a container's changes `POST /commit` Create a new image from a container's changes **Example request**: POST /commit?container=44c004db4b17&m=message&repo=myrepo HTTP/1.1 **Example response**: HTTP/1.1 201 OK Content-Type: application/vnd.docker.raw-stream {"Id": "596069db4bf5"} Query Parameters: - **container** – source container - **repo** – repository - **tag** – tag - **m** – commit message - **author** – author (e.g., "John Hannibal Smith <[hannibal@a-team.com](mailto:hannibal%40a-team.com)>") - **run** – config automatically applied when the image is run. (ex: {"Cmd": ["cat", "/world"], "PortSpecs":["22"]}) Status Codes: - **201** – no error - **404** – no such container - **500** – server error Monitor Docker's events `GET /events` Get events from docker, either in real time via streaming, or via polling (using since). Docker containers will report the following events: create, destroy, die, export, kill, pause, restart, start, stop, unpause and Docker images will report: untag, delete **Example request**: GET /events?since=1374067924 **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"status": "create", "id": "dfdf82bd3881","from": "base:latest", "time":1374067924} {"status": "start", "id": "dfdf82bd3881","from": "base:latest", "time":1374067924} {"status": "stop", "id": "dfdf82bd3881","from": "base:latest", "time":1374067966} {"status": "destroy", "id": "dfdf82bd3881","from": "base:latest", "time":1374067970} Query Parameters: - **since** – timestamp used for polling Status Codes: - **200** – no error - **500** – server error Get a tarball containing all images and tags in a repository `GET /images/(name)/get` Get a tarball containing all images and metadata for the repository specified by `name`. **Example request** GET /images/ubuntu/get **Example response**: .. sourcecode:: http HTTP/1.1 200 OK Content-Type: application/x-tar Binary data stream :statuscode 200: no error :statuscode 500: server error Load a tarball with a set of images and tags into docker `POST /images/load` Load a set of images and tags into the docker repository. **Example request** POST /images/load Tarball in body **Example response**: .. sourcecode:: http HTTP/1.1 200 OK :statuscode 200: no error :statuscode 500: server error # 3. Going further ## 3.1 Inside `docker run` Here are the steps of `docker run` : - Create the container - If the status code is 404, it means the image doesn't exist: - Try to pull it - Then retry to create the container - Start the container - If you are not in detached mode: - Attach to the container, using logs=1 (to have stdout and stderr from the container's start) and stream=1 - If in detached mode or only stdin is attached: - Display the container's id ## 3.2 Hijacking In this version of the API, /attach, uses hijacking to transport stdin, stdout and stderr on the same socket. This might change in the future. ## 3.3 CORS Requests To enable cross origin requests to the remote api add the flag "--api-enable-cors" when running docker in daemon mode. $ docker -d -H="192.168.1.9:2375" --api-enable-cors
#ifndef _zip_H #define _zip_H #ifdef __cplusplus extern "C" { #endif #if defined(USE_SYSTEM_ZLIB) #include <zlib.h> #else #include "third_party/zlib/zlib.h" #endif #ifndef _ZLIBIOAPI_H #include "ioapi.h" #endif #if defined(STRICTZIP) || defined(STRICTZIPUNZIP) /* like the STRICT of WIN32, we define a pointer that cannot be converted from (void*) without cast */ typedef struct TagzipFile__ { int unused; } zipFile__; typedef zipFile__ *zipFile; #else typedef voidp zipFile; #endif #define ZIP_OK (0) #define ZIP_EOF (0) #define ZIP_ERRNO (Z_ERRNO) #define ZIP_PARAMERROR (-102) #define ZIP_BADZIPFILE (-103) #define ZIP_INTERNALERROR (-104) #ifndef DEF_MEM_LEVEL # if MAX_MEM_LEVEL >= 8 # define DEF_MEM_LEVEL 8 # else # define DEF_MEM_LEVEL MAX_MEM_LEVEL # endif #endif /* default memLevel */ /* tm_zip contain date/time info */ typedef struct tm_zip_s { uInt tm_sec; /* seconds after the minute - [0,59] */ uInt tm_min; /* minutes after the hour - [0,59] */ uInt tm_hour; /* hours since midnight - [0,23] */ uInt tm_mday; /* day of the month - [1,31] */ uInt tm_mon; /* months since January - [0,11] */ uInt tm_year; /* years - [1980..2044] */ } tm_zip; typedef struct { tm_zip tmz_date; /* date in understandable format */ uLong dosDate; /* if dos_date == 0, tmu_date is used */ /* uLong flag; */ /* general purpose bit flag 2 bytes */ uLong internal_fa; /* internal file attributes 2 bytes */ uLong external_fa; /* external file attributes 4 bytes */ } zip_fileinfo; typedef const char* zipcharpc; #define <API key> (0) #define <API key> (1) #define <API key> (2) extern zipFile ZEXPORT zipOpen OF((const char *pathname, int append)); /* Create a zipfile. pathname contain on Windows XP a filename like "c:\\zlib\\zlib113.zip" or on an Unix computer "zlib/zlib113.zip". if the file pathname exist and append==<API key>, the zip will be created at the end of the file. (useful if the file contain a self extractor code) if the file pathname exist and append==<API key>, we will add files in existing zip (be sure you don't add file that doesn't exist) If the zipfile cannot be opened, the return value is NULL. Else, the return value is a zipFile Handle, usable with other function of this zip package. */ /* Note : there is no delete function into a zipfile. If you want delete file into a zipfile, you must open a zipfile, and create another Of couse, you can use RAW reading and writing to copy the file you did not want delte */ extern zipFile ZEXPORT zipOpen2 OF((const char *pathname, int append, zipcharpc* globalcomment, zlib_filefunc_def* pzlib_filefunc_def)); extern int ZEXPORT zipOpenNewFileInZip OF((zipFile file, const char* filename, const zip_fileinfo* zipfi, const void* extrafield_local, uInt <API key>, const void* extrafield_global, uInt <API key>, const char* comment, int method, int level)); /* Open a file in the ZIP for writing. filename : the filename in zip (if NULL, '-' without quote will be used *zipfi contain supplemental information if extrafield_local!=NULL and <API key>>0, extrafield_local contains the extrafield data the the local header if extrafield_global!=NULL and <API key>>0, extrafield_global contains the extrafield data the the local header if comment != NULL, comment contain the comment string method contain the compression method (0 for store, Z_DEFLATED for deflate) level contain the level of compression (can be <API key>) */ extern int ZEXPORT <API key> OF((zipFile file, const char* filename, const zip_fileinfo* zipfi, const void* extrafield_local, uInt <API key>, const void* extrafield_global, uInt <API key>, const char* comment, int method, int level, int raw)); /* Same than zipOpenNewFileInZip, except if raw=1, we write raw file */ extern int ZEXPORT <API key> OF((zipFile file, const char* filename, const zip_fileinfo* zipfi, const void* extrafield_local, uInt <API key>, const void* extrafield_global, uInt <API key>, const char* comment, int method, int level, int raw, int windowBits, int memLevel, int strategy, const char* password, uLong crcForCtypting)); /* Same than <API key>, except windowBits,memLevel,,strategy : see parameter strategy in deflateInit2 password : crypting password (NULL for no crypting) crcForCtypting : crc of file to compress (needed for crypting) */ extern int ZEXPORT zipWriteInFileInZip OF((zipFile file, const void* buf, unsigned len)); /* Write data in the zipfile */ extern int ZEXPORT zipCloseFileInZip OF((zipFile file)); /* Close the current file in the zipfile */ extern int ZEXPORT <API key> OF((zipFile file, uLong uncompressed_size, uLong crc32)); /* Close the current file in the zipfile, for fiel opened with parameter raw=1 in <API key> uncompressed_size and crc32 are value for the uncompressed size */ extern int ZEXPORT zipClose OF((zipFile file, const char* global_comment)); /* Close the zipfile */ #ifdef __cplusplus } #endif #endif /* _zip_H */
__author__ = 'Tom Schaul, tom@idsia.ch' from pybrain.structure.networks.feedforward import FeedForwardNetwork from pybrain.structure.connections.shared import MotherConnection, <API key> from pybrain.utilities import iterCombinations # TODO: special treatment for multi-dimensional lstm cells: identity connections on state buffers class SwipingNetwork(FeedForwardNetwork): """ A network architecture that establishes shared connections between ModuleMeshes (of identical dimensions) so that the behavior becomes equivalent to one unit (in+hidden+out components at the same coordinate) swiping over a multidimensional input space and producing a multidimensional output. """ # if all dimensions should be considered symmetric, their weights are shared symmetricdimensions = True # should the forward and backward directions be symmetric (for each dimension)? symmetricdirections = True # dimensions of the swiping grid dims = None def __init__(self, inmesh=None, hiddenmesh=None, outmesh=None, predefined=None, **args): if predefined != None: self.predefined = predefined else: self.predefined = {} super(SwipingNetwork, self).__init__(**args) # determine the dimensions if inmesh != None: self.setArgs(dims=inmesh.dims) elif self.dims == None: raise Exception('No dimensions specified, or derivable') self.swipes = 2 ** len(self.dims) if inmesh != None: self.<API key>(inmesh, hiddenmesh, outmesh) self.sortModules() def _verifyDimensions(self, inmesh, hiddenmesh, outmesh): """ verify dimension matching between the meshes """ assert self.dims == inmesh.dims assert outmesh.dims == self.dims assert tuple(hiddenmesh.dims[:-1]) == self.dims, '%s <-> %s' % ( hiddenmesh.dims[:-1], self.dims) assert hiddenmesh.dims[-1] == self.swipes assert min(self.dims) > 1 def <API key>(self, inmesh, hiddenmesh, outmesh): """ :key inmesh: a mesh of input units :key hiddenmesh: a mesh of hidden units :key outmesh: a mesh of output units """ self._verifyDimensions(inmesh, hiddenmesh, outmesh) # add the modules for c in inmesh: self.addInputModule(c) for c in outmesh: self.addOutputModule(c) for c in hiddenmesh: self.addModule(c) # create the motherconnections if they are not provided if 'inconn' not in self.predefined: self.predefined['inconn'] = MotherConnection(inmesh.componentOutdim * hiddenmesh.componentIndim, name='inconn') if 'outconn' not in self.predefined: self.predefined['outconn'] = MotherConnection(outmesh.componentIndim * hiddenmesh.componentOutdim, name='outconn') if 'hconns' not in self.predefined: self.predefined['hconns'] = {} for s in range(len(self.dims)): if self.symmetricdirections: if s > 0 and self.symmetricdimensions: self.predefined['hconns'][s] = self.predefined['hconns'][0] else: self.predefined['hconns'][s] = MotherConnection(hiddenmesh.componentIndim * hiddenmesh.componentOutdim, name='hconn' + str(s)) else: for dir in ['-', '+']: if s > 0 and self.symmetricdimensions: self.predefined['hconns'][(s, dir)] = self.predefined['hconns'][(0, dir)] else: self.predefined['hconns'][(s, dir)] = MotherConnection(hiddenmesh.componentIndim * hiddenmesh.componentOutdim, name='hconn' + str(s) + dir) # establish the connections for unit in self._iterateOverUnits(): for swipe in range(self.swipes): hunit = tuple(list(unit) + [swipe]) self.addConnection(<API key>(self.predefined['inconn'], inmesh[unit], hiddenmesh[hunit])) self.addConnection(<API key>(self.predefined['outconn'], hiddenmesh[hunit], outmesh[unit])) # one swiping connection along every dimension for dim, maxval in enumerate(self.dims): # determine where the swipe is coming from in this direction: # swipe directions are towards higher coordinates on dim D if the swipe%(2**D) = 0 # and towards lower coordinates otherwise. previousunit = list(hunit) if (swipe / 2 ** dim) % 2 == 0: previousunit[dim] -= 1 dir = '+' else: previousunit[dim] += 1 dir = '-' if self.symmetricdirections: hconn = self.predefined['hconns'][dim] else: hconn = self.predefined['hconns'][(dim, dir)] previousunit = tuple(previousunit) if previousunit[dim] >= 0 and previousunit[dim] < maxval: self.addConnection(<API key>(hconn, hiddenmesh[previousunit], hiddenmesh[hunit])) def _iterateOverUnits(self): """ iterate over the coordinates defines by the ranges of self.dims. """ return iterCombinations(self.dims) def _printPredefined(self, dic=None, indent=0): """ print the weights of the Motherconnections in the self.predefined dictionary (recursively)""" if dic == None: dic = self.predefined for k, val in sorted(dic.items()): print ' ' * indent, k, if isinstance(val, dict): print ':' self._printPredefined(val, indent + 2) elif isinstance(val, MotherConnection): print val.params else: print val
#ifndef _TIANO_BIND_H_ #define _TIANO_BIND_H_ #include <EfiBind.h> #define EFI_DXE_ENTRY_POINT(InitFunction) #define <API key>(InitFunction) #endif
import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core'; @Component({ selector: '<API key>', templateUrl: './<API key>.component.html', styleUrls: ['./<API key>.component.css'] }) export class <API key> implements OnInit { @Input() activeTabKey: string; @Input() <API key>: <API key>; @Output() outSelectViewType = new EventEmitter<string>(); @Output() outOpenDetailView = new EventEmitter<void>(); @Output() outOpenExtraView = new EventEmitter<any>(); tabList = [ { key: 'callTree', display: 'Call Tree' }, { key: 'serverMap', display: 'Server Map' }, { key: 'timeline', display: 'Timeline' }, { key: 'timelineV2', display: 'Timeline Beta' } ]; constructor() {} ngOnInit() {} isActive(key: string): boolean { return this.activeTabKey === key; } onClickTab(key: string): void { if (this.activeTabKey === key) { return; } this.outSelectViewType.next(key); } openDetailView(): void { this.outOpenDetailView.next(); } hasLogView(): boolean { return this.<API key> && this.<API key>.logLinkEnable; } openLogView(): void { this.<API key>.<API key> === true ? this.outOpenExtraView.next({open: true, url: this.<API key>.logPageUrl}) : this.outOpenExtraView.next({open: false, message: this.<API key>.<API key>}); } hasInfo(): boolean { return this.<API key> && this.<API key>.<API key>; } getStateClass(): string { return this.<API key> ? `l-transaction-${this.<API key>.completeState.toLowerCase()}` : ''; } hasState(): boolean { return !!this.<API key>; } getLogIcon(): string { return this.hasInfo() ? 'fas <API key>' : 'fas fa-ban'; } }
/ [<API key>.ts] export module a { export enum weekend { Friday, Saturday, Sunday } } export module c { export import b = a.weekend; export var bVal: b = b.Sunday; } / [<API key>.js] var a; (function (a) { (function (weekend) { weekend[weekend["Friday"] = 0] = "Friday"; weekend[weekend["Saturday"] = 1] = "Saturday"; weekend[weekend["Sunday"] = 2] = "Sunday"; })(a.weekend || (a.weekend = {})); var weekend = a.weekend; })(a = exports.a || (exports.a = {})); var c; (function (c) { c.b = a.weekend; c.bVal = 2 /* Sunday */; })(c = exports.c || (exports.c = {})); / [<API key>.d.ts] export declare module a { enum weekend { Friday = 0, Saturday = 1, Sunday = 2, } } export declare module c { export import b = a.weekend; var bVal: b; }
<!DOCTYPE html> <html> <head> <title>WebGL testing</title> <meta charset="UTF-8"> <script type="text/javascript" src="../../build/js/Cindy.js"></script> <script type="text/javascript" src="../../build/js/Cindy3D.js"></script> <script id="csinit" type="text/x-cindyscript">use("Cindy3D")</script> <script id="csdraw" type="text/x-cindyscript"> begin3d(); fillpoly3d([[-3, -1, 0], [-0.8, -0.8, 1], [-1, 1, 0], [-3, 1, 0]]); fillpoly3d(apply(1..5, gauss(1 + exp(i* end3d() </script> <script type="text/javascript"> CindyJS({canvasname:"CSCanvas",scripts:"cs*"}); </script> </head> <body> <canvas id="Cindy3D" style="border: none;" width="632" height="452"></canvas> <p>Polygons should look smooth even if they are in fact bent.</p> <div id="CSCanvas" style="width:50px; height:50px; border:none"></div> </body> </html>
#include "Math/MathFwd.h" #include "EC_PlanarMirror.h" #include "OgreRenderingModule.h" #include "Renderer.h" #include "OgreWorld.h" #include "Framework.h" #include "Entity.h" #include "EC_Placeable.h" #include "LoggingFunctions.h" #include "FrameAPI.h" #include "EC_Camera.h" #include "EC_RttTarget.h" #include "UiAPI.h" #include "UiMainWindow.h" #include <<API key>.h> #include <OgreCamera.h> #include <OgreViewport.h> #include <OgreSceneManager.h> #include <OgreEntity.h> #include <OgreMeshManager.h> #include <OgreMaterialManager.h> int EC_PlanarMirror::mirror_cam_num_ = 0; EC_PlanarMirror::EC_PlanarMirror(Scene *scene) : IComponent(scene), <API key>(<API key>, "Show reflection plane", true), mirror_texture_(0), tex_unit_state_(0), mat_(0), <API key>(0), mirror_plane_(0) { connect(this, SIGNAL(ParentEntitySet()), this, SLOT(Initialize())); } EC_PlanarMirror::~EC_PlanarMirror() { if(!renderer_) return; Ogre::SceneManager *mngr = renderer_->GetActiveOgreWorld()->OgreSceneManager(); if(tex_unit_state_) tex_unit_state_-><API key>(false); if(mngr) { if(<API key>) mngr->destroyEntity(<API key>); } SAFE_DELETE(mirror_plane_); } void EC_PlanarMirror::AttributesChanged() { if (!ViewEnabled()) return; if (<API key>.ValueChanged() && <API key>) <API key>->setVisible(<API key>.Get()); } void EC_PlanarMirror::Update(float val) { if (!ViewEnabled()) return; if (!renderer_) return; const Ogre::Camera* cam = renderer_->MainOgreCamera(); if (mirror_cam_) { mirror_cam_->setOrientation(cam->getRealOrientation()); mirror_cam_->setPosition(cam->getRealPosition()); //mirror_cam_->getViewport()->update(); } } void EC_PlanarMirror::Initialize() { if (!ViewEnabled()) return; if (framework->GetModule<OgreRenderer::OgreRenderingModule>()) renderer_ = framework->GetModule<OgreRenderer::OgreRenderingModule>()->GetRenderer(); if (!renderer_) { LogError("EC_PlanarMirror could not acquire Renderer, cannot initialize."); return; } Entity *entity = ParentEntity(); assert(entity); if (!entity) return; EC_Camera *cam = entity->GetComponent<EC_Camera>().get(); assert(cam); if (!cam) { LogError("No EC_Camera on this entity. EC_PlanarMirror can't function."); return; } EC_Placeable *placeable = entity->GetComponent<EC_Placeable>().get(); assert(placeable); if (!placeable) { LogError("No EC_Placeable on this entity. EC_PlanarMirror can't function."); return; } EC_RttTarget *target = entity->GetComponent<EC_RttTarget>().get(); assert(target); if (!target) { LogError("No EC_RttTarget on this entity. EC_PlanarMirror can't function."); return; } const Ogre::Camera* v_cam = renderer_->MainOgreCamera(); const Ogre::Viewport* vp = renderer_->MainViewport(); mirror_cam_ = cam->GetCamera(); mirror_cam_->setFarClipDistance(v_cam->getFarClipDistance()); mirror_cam_->setNearClipDistance(v_cam->getNearClipDistance()); mirror_cam_->setAutoAspectRatio(false); mirror_cam_->setAspectRatio(Ogre::Real(vp->getActualWidth())/Ogre::Real(vp->getActualHeight())); mirror_cam_->setFOVy(v_cam->getFOVy()); QString texname = target->gettextureName(); Ogre::TexturePtr tex = Ogre::TextureManager::getSingleton().getByName(Ogre::String(texname.toStdString())); if (!tex.get()) { LogError("Texture called " + texname.toStdString() + " not found. EC_PlanarMirror can't function. (Propably something wrong in the EC_RttTarget)."); return; } mirror_texture_ = tex.get(); CreatePlane(); placeable->GetSceneNode()->attachObject(<API key>); placeable->GetSceneNode()->attachObject(mirror_plane_); mirror_cam_-><API key>(mirror_plane_); mirror_cam_->enableReflection(mirror_plane_); mirror_cam_num_++; disconnect(this, SIGNAL(ParentEntitySet()), this, SLOT(Initialize())); mirror_cam_->getViewport()->setOverlaysEnabled(false); connect(framework->Frame(), SIGNAL(Updated(float)), this, SLOT(Update(float)), Qt::UniqueConnection); connect(framework->Ui()->MainWindow(), SIGNAL(WindowResizeEvent(int, int)), this, SLOT(WindowResized(int,int)), Qt::UniqueConnection); } void EC_PlanarMirror::WindowResized(int w,int h) { if (!ViewEnabled()) return; if(renderer_) { const Ogre::Viewport* vp = renderer_->MainViewport(); mirror_cam_->setAspectRatio(Ogre::Real(vp->getActualWidth())/Ogre::Real(vp->getActualHeight())); } } void EC_PlanarMirror::CreatePlane() { if (!ViewEnabled()) return; mirror_plane_ = new Ogre::MovablePlane("mirror_plane" + Ogre::StringConverter::toString(mirror_cam_num_)); mirror_plane_->d = 0; mirror_plane_->normal = Ogre::Vector3::UNIT_Y; Ogre::MeshManager::getSingleton().createPlane("mirror_plane_mesh_" + Ogre::StringConverter::toString(mirror_cam_num_), Ogre::<API key>::<API key>, *mirror_plane_, 80, 80, 1, 1, true, 1, 1, 1, Ogre::Vector3::UNIT_Z); <API key> = renderer_->GetActiveOgreWorld()->OgreSceneManager()->createEntity("mirror_plane_entity" + Ogre::StringConverter::toString(mirror_cam_num_), "mirror_plane_mesh_" + Ogre::StringConverter::toString(mirror_cam_num_)); for now mat_ = dynamic_cast<Ogre::Material*>(Ogre::MaterialManager::getSingleton().create( "MirrorMat" + Ogre::StringConverter::toString(mirror_cam_num_), Ogre::<API key>::<API key>).get()); tex_unit_state_ = mat_->getTechnique(0)->getPass(0)-><API key>(mirror_texture_->getName()); tex_unit_state_-><API key>(true, mirror_cam_); tex_unit_state_-><API key>(Ogre::TextureUnitState::TAM_CLAMP); Ogre::MaterialPtr mat(mat_); <API key>->setMaterial(mat); <API key>->setVisible(<API key>.Get()); } Ogre::Texture* EC_PlanarMirror::GetMirrorTexture() const { return mirror_texture_; }
""" Unit tests for `OpenSSL.rand`. """ import pytest from OpenSSL import rand class TestRand(object): @pytest.mark.parametrize('args', [ (b"foo", None), (None, 3), ]) def test_add_wrong_args(self, args): """ `OpenSSL.rand.add` raises `TypeError` if called with arguments not of type `str` and `int`. """ with pytest.raises(TypeError): rand.add(*args) def test_add(self): """ `OpenSSL.rand.add` adds entropy to the PRNG. """ rand.add(b'hamburger', 3) def test_status(self): """ `OpenSSL.rand.status` returns `1` if the PRNG has sufficient entropy, `0` otherwise. """ assert rand.status() == 1
// <auto-generated> // This code was generated by a tool. // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> namespace ProductLaunch.Web { public partial class About { } }
#ifndef USB_MSC_H__ #define USB_MSC_H__ /** @file usb_msc.h * @brief USB Mass Storage Class Enumerations and Structures * @defgroup public_api Public API */ /** @addtogroup public_api * @{ */ #include <stdint.h> #include "usb_config.h" #if defined(__XC16__) || defined(__XC32__) #pragma pack(push, 1) #elif __XC8 #else #error "Compiler not supported" #endif #define MSC_DEVICE_CLASS 0x08 #define <API key> 0x06 /* Many of the subclass codes (MSCO: sec 2) are omitted here. Get in * contact with Signal 11 if you need something specific. */ #define <API key> 0x50 /* Bulk-Only */ /* Many of the protocol codes (MSCO: sec 3) are omitted here. Get in * contact with Signal 11 if you need something specific. */ #if <API key> <= 8 typedef uint8_t msc_lun_mask_t; #else typedef uint16_t msc_lun_mask_t; #endif /** MSC Class Requests * * These are the class requests needed for MSC Bulk-Only Transport (MSCO: * sec 4, table 3). Others are omitted. Get in contact with Signal 11 if * you need something specific. */ enum MSCRequests { MSC_GET_MAX_LUN = 0xfe, <API key> = 0xff, }; /** MSC Command Block Status Values * * See BOT, 5.2 */ enum MSCStatus { MSC_STATUS_PASSED = 0, /* Success */ MSC_STATUS_FAILED = 1, <API key> = 2, }; /** MSC Command Block Flags (Direction is the only used bit) * * See BOT, 5.1 */ enum MSCDirection { MSC_DIRECTION_OUT = 0x0, <API key> = 0x80, }; /** MSC Bulk-Only Data Command Block Wrapper * * See BOT, 5.1 */ struct <API key> { uint32_t dCBWSignature; /* Set to 0x43425355 */ uint32_t dCBWTag; uint32_t <API key>; /** Data to be transfered */ uint8_t bmCBWFlags; /** bit 0x80=data-in, 0x00=data-out */ uint8_t bCBWLUN; /**< Lower 4 bits only */ uint8_t bCBWCBLength ; /**< Lower 4 bits only; length of CBWCB */ uint8_t CBWCB[16]; }; /** MSC Bulk-Only Data Command Block Wrapper * * See BOT, 5.2 */ struct <API key> { uint32_t dCSWSignature; /**< Set to 0x53425355 */ uint32_t dCSWTag; uint32_t dCSWDataResidue; uint8_t bCSWStatus; /**< @see enum MSCStatus */ }; /* SCSI Definitions and Structures */ enum MSCSCSICommands { <API key> = 0x04, MSC_SCSI_INQUIRY = 0x12, <API key> = 0x15, <API key> = 0x55, <API key> = 0x1a, <API key> = 0x5a, <API key> = 0x1b, MSC_SCSI_READ_6 = 0x08, MSC_SCSI_READ_10 = 0x28, <API key> = 0x25, <API key> = 0xa0, <API key> = 0x03, <API key> = 0x1d, <API key> = 0x00, MSC_SCSI_VERIFY = 0x2f, MSC_SCSI_WRITE_6 = 0x0a, MSC_SCSI_WRITE_10 = 0x2a, }; struct <API key> { uint8_t operation_code; /* 0x12 */ uint8_t evpd; /* bit 0 only */ uint8_t page_code; uint16_t allocation_length; uint8_t control; }; struct <API key> { uint8_t operation_code; /* 0x3 */ uint8_t desc; /* bit 0 only */ uint8_t reserved[2]; uint8_t allocation_length; uint8_t control; }; struct <API key> { uint8_t operation_code; /* 0x1a */ uint8_t dbd_reserved; uint8_t pc_page_code; /* bits 6-7: PC, bits 0-5: Page Code */ uint8_t subpage_code; uint8_t allocation_length; uint8_t control; }; struct <API key> { uint8_t operation_code; uint8_t immed; /* Bit 0 only */ uint8_t reserved[2]; uint8_t command; /* bit 0: start, bit 1: LOEJ, bits 4-7: power cond */ uint8_t control; }; struct <API key> { uint8_t opcode; uint8_t unused_flags; uint32_t <API key>; uint8_t group_number; uint16_t transfer_length; uint8_t control_flags; }; struct <API key> { uint8_t operation_code; uint8_t wrprotect_flags; uint32_t <API key>; uint8_t group_number; uint16_t transfer_length; uint8_t control; }; enum MSCSCSIVersion { <API key> = 4, <API key> = 5, }; struct <API key> { uint8_t peripheral; /**< Set to 0x0 */ uint8_t rmb; /**< 0x80 for removable media */ uint8_t version; /**< enum MSCSCSIVersion */ uint8_t <API key>; /**< Set to 0x2 */ uint8_t additional_length; /**< 4 less than sizeof(inquiry_response) */ uint8_t unused[3]; /**< Not used in our implementation */ char vendor[8]; /**< ASCII, no zero-termination */ char product[16]; /**< ASCII, no zero-termination */ char revision[4]; /**< ASCII, no zero-termination */ }; struct <API key> { uint32_t last_block; uint32_t block_length; }; enum <API key> { <API key> = 0x70, <API key> = 0x71, <API key> = 0x80, }; enum SCSISenseFlags { SCSI_SENSE_FILEMARK = 0x80, SCSI_SENSE_EOM = 0x40, SCSI_SENSE_ILI = 0x20, SCSI_SENSE_KEY_MASK = 0x0f, }; struct <API key> { uint8_t mode_data_length; /**< sizeof(<API key>) - 1 */ uint8_t medium_type; /**< Set to 0x00 for SBC devices */ uint8_t <API key>; /**< set to 0x80 for write-protect, else 0x0 */ uint8_t <API key>; /**< Set to 0x0 */ }; enum SCSISenseKeys { <API key> = 0x2, <API key> = 0x3, <API key> = 0x5, <API key> = 0x6, <API key> = 0x7, }; enum <API key> { <API key> = 0x21, <API key> = 0x20, <API key> = 0x24, <API key> = 0x25, /* MEDIUM_ERROR */ <API key> = 0x03, <API key> = 0x11, /* UNIT_ATTENTION */ <API key> = 0x0c, <API key> = 0x3a, /* WRITE_DATA_PROTECT */ <API key> = 0x27, }; struct scsi_sense_response { uint8_t response_code; /**< 0x70=current_errors, 0x71=deferred_errors * 0x80 bit = information_valid */ uint8_t obsolete; uint8_t flags; /**< Bitmask of SCSISenseFlags OR'd with one from SCSISenseKeys */ uint32_t information; uint8_t <API key>; uint32_t <API key>; uint8_t <API key>; /**< <API key> */ uint8_t <API key>; uint8_t <API key>; uint8_t sense_key_specific[3]; /* Additional, vendor-specific sense data goes here. */ }; #if defined(__XC16__) || defined(__XC32__) #pragma pack(pop) #elif __XC8 #else #error "Compiler not supported" #endif /** MSC Application States * * The states the transport goes through. */ enum <API key> { MSC_IDLE, <API key>, /**< Next transactions will be data sent */ <API key>, /**< Next transactions will be data received */ MSC_STALL, /**< Next transaction needs to stall */ MSC_CSW, /**< Next transaction will contain the CSW */ <API key>, /**< Reset recovery is required */ }; /** Return codes used by application callbacks. * * Success is defined to be 0 and all failures are < 0. */ enum MSCReturnCodes { MSC_SUCCESS = 0, <API key> = -1, /**< The medium is not physically present */ <API key> = -2, /**< The LUN is out of range */ <API key> = -3, /**< The LBA address is out of range */ <API key> = -4, /**< The medium is write protected */ MSC_ERROR_READ = -5, /**< Error while reading the medium */ MSC_ERROR_WRITE = -6, /**< Error while writing the medium */ MSC_ERROR_MEDIUM = -7, /**< Unspecified medium error */ }; /* Forward declare struct <API key> to enable the following: * 1. The struct be used by the callback, * 2. The callback can be used by the struct. */ struct <API key>; /** @brief MSC Transmission Complete Callback * * This is the callback function type expected to be passed to @p * <API key>(). Callback functions will be called by the stack * when the transmission of a block of data has completed. * * @param app_data Pointer to application data for this interface. * @param transfer_ok @a true if transaction completed successfully, or * @a false if there was an error */ typedef void (*<API key>) (struct <API key> *app_data, bool transfer_ok); /** MSC Applicaiton Data * * The application shall provide one of these structures for each interface * when the MSC class is initialized and keep it as a persistent object for * the lifetime of the application. Global variables work well for this. * * The Application shall initialize the variables in the first section. The * variables in the second section are used by the MSC class to keep track of * the state of the connection. * * The application will pass this structure to the MSC class whenever it needs * the MSC class to process data for an interface. */ struct <API key> { /* Application should initialize the following: */ uint8_t interface; uint8_t max_lun; /**< The maximally numbered LUN. One-less than the number of LUNs. */ uint8_t in_endpoint; uint8_t out_endpoint; uint8_t in_endpoint_size; /**< Size in bytes for IN endpoint */ msc_lun_mask_t <API key>; /**< bitmask, one bit for each LUN */ const char *vendor; /**< SCSI-assigned vendor. Pointer to global or constant. */ const char *product; /**< Pointer to global or constant. */ const char *revision; /**< Pointer to global or constant. */ /* MSC Class handler will initialize and use the following. The * applicaiton should ignore these: */ uint8_t state; /**< enum <API key> */ uint32_t current_tag; /* Error-reporting codes */ uint8_t sense_key; uint8_t <API key>; /* CSW fields */ uint32_t residue; uint8_t status; /**< enum MSCStatus */ /* READ command handling fields */ uint32_t requested_bytes; /* Bytes requested by SCSI */ uint32_t requested_bytes_cbw; /* Bytes requested by the MSC (CBW) */ uint32_t transferred_bytes; /* Block size for each LUN */ uint32_t block_size[<API key>]; /* Asynchronous transmit/receive data */ union { const uint8_t *tx_buf; /**< Data to be sent to the host. */ uint8_t *rx_buf; /**< Data received from the host. */ }; uint16_t tx_len_remaining; /**< TX data remaining in the current block */ #ifdef MSC_WRITE_SUPPORT uint8_t *rx_buf_cur; /**< Current position in the RX buffer */ size_t rx_buf_len; /**< Length of the application's block RX buffer */ /* Endpoint buffer management. */ uint8_t <API key>; /**< Number of out transactions not processed */ #endif <API key> <API key>; }; /** Initialize the MSC class for all interfaces * * Initialize all instances of the MSC class. Call this function with an * array containing an @class <API key> for each * MSC interface. The @p app_data pointer should point to an array of valid * @class <API key> structures which have been filled out properly. * * The array should be valid for the lifetime of the application. Global * variables work well for this. * * @param app_data Pointer to an array of application data structures * @param count Number of structures (size of array) in app_data * * @returns * Returns 0 on success, or -1 if some of the data is invalid. On a -1 * return, assume that none of the interfaces have been initialized * properly and fail. */ uint8_t msc_init(struct <API key> *app_data, uint8_t count); /** Process MSC Setup Request * * Process a setup request which has been unhandled as if it is potentially * an MSC setup request. This function will then call appropriate callbacks * into the appliction if the setup packet is one recognized by the MSC * specification. * * @param setup A setup packet to handle * * @returns * Returns 0 if the setup packet could be processed or -1 if it could not. */ int8_t <API key>(const struct setup_packet *setup); /** Clear Halt on MSC Endpoint * * Notify the MSC class that a CLEAR_FEATURE ENDPOINT_HALT has been * received for an MSC endpoint. * * @param endpoint_num The endpoint number affected * @param direction The endpoint direction affected. 0=out, 1=in * */ void msc_clear_halt(uint8_t endpoint_num, uint8_t direction); /** Notify of a transaction completing on the Data-IN endpoint * * Notify the MSC class that an IN transaction has completed on the Data-IN * endpoint. If using interrupts, call this function from the * @p <API key>. * * This function will not block. * * @param endpoint_num The endpoint number affected */ void <API key>(uint8_t endpoint_num); /** Notify of a transaction completing on the Data-OUT endpoint * * Notify the MSC class that an OUT transaction has completed on the * Data-OUT endpoint. This function will process the data which is * available on endpoint @p endpoint_num and will re-arm the endpoint when * appropriate. * * If using interrupts, call this function from the * @p <API key>. * * This function will not block. * * @param endpoint_num The endpoint number affected */ void <API key>(uint8_t endpoint_num); /** Send data read from the medium to the host * * Start transmission of data that has been read from the storage medium to * the host. This function simply starts the transmission and returns control * immediately to the caller without blocking. When the transmission has * completed, the @p completion_callback will be called. The application * should call this function as soon as data is available from the storage * medium, and should not call it again until the @p completion_callback has * been called. For example, if 8 blocks are requested by the host, the * application could read a single block, call @p <API key>(), * wait for the @p completion_callback to be called, then call * @p <API key>() with the second block, and so on.. * * This function does not block. * * @p completion_callback will be called from interrupt context and must * not block. * * @p len needs to be multiple of the IN endpoint size for all calls to * this function except the last in response to an @p MSC_READ() callback. * * @param app_data Pointer to application data for this interface. * @param data Pointer to the data to send. * @param len Data length in bytes. Must be a multiple of * the IN endpoint size. * @param completion_callback Pointer to a function which is called when * the transmission has completed. * * @returns * Returns 0 if the transmission could be started or -1 if it could not. */ uint8_t <API key>(struct <API key> *app_data, const uint8_t *data, uint16_t len, <API key> completion_callback); /** Notify the MSC class that a Read Operation has Completed * * Tell the MSC class that a read operation has been completed with either * success or failure. * * In the case of success, pass true to @p passed, indicating that the data * requested by an @p MSC_READ() callback has all been passed to the MSC * class using @p <API key>(). This will cause the transfer to * complete successfully. * * If the read failed, pass false to @p passed. This will cause a SCSI * MEDIUM_ERROR to be returned to the host. * * @param app_data Pointer to application data for this interface. * @param passed Whether the read operation completed successfully */ void <API key>( struct <API key> *app_data, bool passed); #ifdef MSC_WRITE_SUPPORT /** Notify Write Data Handled * * Tell the MSC class that a block of data provided to a write callback * has been handled, and that the buffer is no longer in use by the * applicaiton. The MSC stack will now provide the next block to be written * into the same buffer and call the callback provided to @p * MSC_START_WRITE(). * * Note that calling this function does not necessarily indicate that the * data was successfully written to the medium. It only indicates that the * application has received the buffer and dealt with it, and requests that * the MSC stack put the next block of data into the buffer. It is possible * the application does not know that a write operation has failed (or will * fail) until the end of the write operation. * * Note that if there are OUT transfers pending (and waiting because the * application is using the buffer), and if the application's buffer is * sufficiently small, then the MSC stack could potentially call the @p * <API key>() from this function. With small buffers, this is * a typical case. * * If there was an error in handling the data, call @p * <API key>() instead to cancel the transport. * * @param app_data Pointer to application data for this interface. */ void <API key>(struct <API key> *app_data); /** Notify Write Operation Complete * * Tell the MSC class that a write operation has completed, either with * full success, with partial success, or with failure. The MSC stack can now * complete the data transport and report the status to the host. * * In the case of a complete success, set @p passed to true, and set @p * bytes_processed to the number of bytes which were asked for and written. * * In the case of a failure or a partial success, set @p passed to false * and set @p bytes_processed to the number of bytes which were acutally * written successfully. * * Pass true as @p passed if the write succeeded or false if it failed. * * @param app_data Pointer to application data for this interface. * @param passed Whether the write operation fully completed * successfully, writing all desired data. * @param bytes_processed The number of bytes successfully written. This may * be fewer than the number of bytes asked for by the * host. */ void <API key>(struct <API key> *app_data, bool passed, uint32_t bytes_processed); #endif /** MSC Bulk-Only Mass Storage Reset callback * * The MSC class will call this function when a Bulk-Only Mass Storage Reset * request has been received from the host. This function should perform * a reset of the device indicated by @p interfce and not return until this * has been completed. * * @param interface The interface for which the command is intended * * @returns * Return 0 if the request can be handled or -1 if it cannot. Returning -1 * will cause STALL to be returned to the host. */ extern int8_t <API key>(uint8_t interface); #ifdef <API key> /** MSC Get Storage Information Callback * * The USB Stack will call this function when the host requests information * about the storage device. * * SCSI (and therefore USB) drives are required to support LBA (Logical Block * Addressing) which means every block on the drive can be addressed as an * array of fixed-sized blocks. * * This function may be called more than once as data is requested by the * host. * * @param app_data Pointer to application data for this interface. * @param lun The Logical Unit Number (LUN) of the medium requested. * @param block_size The block size for this medium. This block size is * used for both reading and writing. It should be a * multiple of both the IN and OUT endpoint sizes, but * does not strictly have to be. If it is not, the * handling of reads and writes on the application side * will likely be more complex. The block_size must be * below 2^24. * @param num_blocks The number of blocks the medium contains. * @param write_protect Whether write-protection is enabled. * * * @returns * Return a code from @p MSCReturnCodes. Returning non-success will cause * an error to be returned to the host. */ extern int8_t <API key>( const struct <API key> *app_data, uint8_t lun, uint32_t *block_size, uint32_t *num_blocks, bool *write_protect); #else #error "You must define <API key> in your usb_config.h" #endif #ifdef MSC_UNIT_READY /** MSC Check if Medium is Ready Callback * * The USB Stack will call this function when the host requests information * regarding whether the medium is ready or not. * * This function may be called more than once as data is requested by the * host. * * @param app_data Pointer to application data for this interface. * @param lun The Logical Unit Number (LUN) of the medium requested. * * @returns * Return a code from @p MSCReturnCodes. Returning non-success will cause * an error to be returned to the host. */ extern int8_t MSC_UNIT_READY( const struct <API key> *app_data, uint8_t lun); #else #error "You must define MSC_UNIT_READY in your usb_config.h" #endif #ifdef MSC_START_STOP_UNIT /** Start or Stop an MSC Unit * * The USB Stack will call this function when the host requests that a * logical unit start or stop. This is mostly used for stopping and ejecting * the medium. * * @param app_data Pointer to application data for this interface. * @param lun The Logical Unit Number (LUN) of the medium requested. * @param start Whether to start or stop the medium. true means to * start, and false means to stop the medium. * @param load_eject Whether to load or eject the medium. The desired * behavior depends on the value of @p start. When * load_eject is true, then the application should load * media if start is true, or eject media if start is * false. * * The four cases for @p start and @p load_eject: * if (start && load_eject): load the medium * if (start && !load_eject): neither load nor eject * if (!start && load_eject): eject the medium * if (!start && !load_eject): neither load nor eject * * @returns * Return a code from @p MSCReturnCodes. Returning non-success will cause * an error to be returned to the host. */ extern int8_t MSC_START_STOP_UNIT( const struct <API key> *app_data, uint8_t lun, bool start, bool load_eject); #else #error "You must define MSC_START_STOP_UNIT in your usb_config.h" #endif #ifdef MSC_START_READ /** MSC Read Callback * * The USB Stack will call this function when the host requests a read * operation from the device. This callback will initiate reading data from * the medium. The application will then call @p <API key>() * repeatedly until all data has been given to the MSC class. At that point, * the application must call @p <API key>() to * indicate that the Data-Transport is complete. * * See the documentation for @p <API key>() for additional * restrictions. * * Note that this funciton must simply kick-off the reading/sending of the * data and return quickly. In other words, this function must not block. * * @param app_data Pointer to application data for this interface. * @param lun The Logical Unit Number (LUN) of the medium requested. * @param lba_address Logical Block Address to start reading from. * @param num_blocks Number of blocks to read. * * @returns * Return a code from @p MSCReturnCodes. Returning non-success will cause * an error to be returned to the host. */ extern int8_t MSC_START_READ( struct <API key> *app_data, uint8_t lun, uint32_t lba_address, uint16_t num_blocks); #else #error "You must define MSC_START_READ in your usb_config.h" #endif #ifdef MSC_WRITE_SUPPORT #ifdef MSC_START_WRITE /** MSC Write Callback * * The USB Stack will call this function when the host requests to write * data to the device. The application's implementation of this function * will provide a buffer (@p buffer) where the USB stack will place the data * as it is received. Once the buffer is full, the USB stack will call the * provided callback function (@p callback), notifying the application that * it can begin processing the data (ie: writing it to the medium). Once * the buffer has been processed (and the application is done with the * buffer), the application must then call @p * <API key>() to notify the USB stack that it is * ready for the next buffer-full of data. * * Note that this funciton must simply set any necessary state on the * appliction side and return the requested data quickly. In other words, * this function must not block. * * @param app_data Pointer to application data for this interface. * @param lun The Logical Unit Number (LUN) of the medium requested. * @param lba_address Logical Block Address the data is intended for. * @param num_blocks Number of blocks which will eventually be written. * @param buffer The place to put the data from the USB bus * @param buffer_len The size of the buffer in bytes. It must be a * multiple of the OUT endpoint size. * @param callback A function to be called when the data has been * received from the host. It will be called from * interrupt context and must not block. * * @returns * Return a code from @p MSCReturnCodes. Returning non-success will cause * an error to be returned to the host. */ extern int8_t MSC_START_WRITE( struct <API key> *app_data, uint8_t lun, uint32_t lba_address, uint16_t num_blocks, uint8_t **buffer, size_t *buffer_len, <API key> *callback); #else #error "You must either define MSC_START_WRITE in your usb_config.h or make this MSC class read-only." #endif /* MSC_START_WRITE */ #endif /* MSC_WRITE_SUPPORT */ /* Doxygen end-of-group for msc_items */ /* Doxygen end-of-group for public_api */ #endif /* USB_MSC_H__ */
<!doctype html> <html > <head> <meta charset="utf-8"> <title>AMP Analytics</title> <link rel="canonical" href="analytics.amp.html" > <meta name="viewport" content="width=device-width,minimum-scale=1,initial-scale=1"> <style amp-custom> .box { background: #ccc; border: 1px solid #aaa; padding: 10px; margin: 10px; } #container { position: absolute; top: 10000px; height: 10px; } </style> <script async custom-element="amp-anim" src="https://cdn.ampproject.org/v0/amp-anim-0.1.js"></script> <script async custom-element="amp-analytics" src="https://cdn.ampproject.org/v0/amp-analytics-0.1.js"></script> <style amp-boilerplate>body{-webkit-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-moz-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-ms-animation:-amp-start 8s steps(1,end) 0s 1 normal both;animation:-amp-start 8s steps(1,end) 0s 1 normal both}@-webkit-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-moz-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-ms-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-o-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}</style><noscript><style amp-boilerplate>body{-webkit-animation:none;-moz-animation:none;-ms-animation:none;animation:none}</style></noscript> <script async src="https://cdn.ampproject.org/v0.js"></script> </head> <body> <div id="container"> Container for analytics tags. Positioned far away from top to make sure that doesn't matter. <amp-analytics id="analytics1"> <script type="application/json"> { "transport": {"beacon": false, "xhrpost": false}, "requests": { "endpoint": "https://raw.githubusercontent.com/ampproject/amphtml/master/examples/img/ampicon.png", "base": "${endpoint}?${type|default:foo}&path=${canonicalPath}", "event": "${base}&scrollY=${scrollTop}&scrollX=${scrollLeft}&height=${<API key>}&width=${<API key>}&scrollBoundV=${<API key>}&scrollBoundH=${<API key>}", "visibility": "${base}&a=${<API key>}&b=${totalVisibleTime}&c=${firstSeenTime}&d=${lastSeenTime}&e=${fistVisibleTime}&f=${lastVisibleTime}&g=${<API key>}&h=${<API key>}&i=${elementX}&j=${elementY}&k=${elementWidth}&l=${elementHeight}&m=${totalTime}&n=${loadTimeVisibility}&o=${backgroundedAtStart}&p=${backgrounded}&subTitle=${subTitle}", "timer": "${base}&backgroundState=${backgroundState}" }, "vars": { "title": "Example Request" }, "extraUrlParams": { "param1": "${random}", "platform": "AMP" }, "<API key>": { "param": "p" }, "triggers": { "defaultPageview": { "on": "visible", "request": "base", "vars": { "type": "pageLoad" }, "extraUrlParams": { "param1": "Another value" } }, "pageview": { "on": "visible", "request": "base", "vars": { "type": "${random}${title}" } }, "visibility": { "on": "visible", "request": "visibility", "visibilitySpec": { "selector": "#anim-id", "<API key>": 20, "<API key>": 80, "totalTimeMin": 5000, "continuousTimeMin": 2000 }, "vars": { "type": "visibility" } }, "hidden": { "on": "hidden", "request": "visibility", "visibilitySpec": { "selector": "#anim-id", "<API key>": 20, "continuousTimeMax": 5000 }, "vars": { "type": "hidden" } }, "scrollPings": { "on": "scroll", "request": "event", "scrollSpec": { "verticalBoundaries" : [1, 50, 90], "<API key>": [100] }, "vars": { "type": "scroll" } }, "clickPings": { "on": "click", "selector": "${img}", "request": ["endpoint", "base"], "vars": { "type": "click", "img": "#anim-id, #container" } }, "timer": { "on": "timer", "timerSpec": { "interval": 5, "maxTimerLength": 20 }, "request": "timer", "vars": { "type": "timer" } } } } </script> </amp-analytics> <amp-analytics id="analytics3" config="./analytics.config.json"></amp-analytics> <div class="logo"></div> <h1 id="top">AMP Analytics</h1> <span id="test1" class="box" data-vars-title="Example request with element level overrides"> Click here to generate an event </span> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam pellentesque augue quis elementum tempus. Pellentesque sit amet neque bibendum, sagittis purus vitae, pellentesque magna. Vestibulum non viverra metus, eget feugiat lacus. Nulla in maximus orci. Maecenas id turpis vel ipsum vestibulum bibendum ut sit amet magna. Nullam hendrerit ex at est eleifend, nec dignissim nibh rutrum. Aliquam quis tellus et nibh faucibus laoreet in eget turpis. Nam quam nisl, porttitor vel ex eget, dapibus placerat dui. Mauris commodo pellentesque leo, eu tempus quam. In hac habitasse platea dictumst. Suspendisse non ante finibus, luctus augue non, luctus orci. Vestibulum ornare lacinia aliquam. In sollicitudin vehicula vulputate. Sed mi elit, commodo nec sapien nec, pretium bibendum leo. Donec id justo tortor. Ut in mauris dapibus, laoreet metus vitae, dictum nisi. </p> <p> Integer dapibus egestas arcu. Nunc vitae velit congue, placerat augue quis, suscipit nisi. Donec suscipit imperdiet turpis pharetra feugiat. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Phasellus aliquam eleifend dolor, at lacinia orci semper vel. Nunc semper sem vel tincidunt posuere. Nunc lobortis velit vitae condimentum mollis. Morbi eu ullamcorper mauris. Pellentesque ac eros maximus, pulvinar sapien vitae, semper nisi. Curabitur imperdiet non mauris vitae sollicitudin. </p> <p> Nam posuere velit euismod risus pulvinar, in sollicitudin sapien consectetur. Vestibulum nec ex odio. Quisque at elit nec nunc ultricies lacinia nec non lorem. Maecenas porttitor consequat mauris, vitae porttitor ligula pellentesque ut. Pellentesque rhoncus diam vel lacus lobortis imperdiet. Sed maximus dictum hendrerit. Vivamus ornare, purus in laoreet sagittis, est ante pretium mauris, vel vulputate arcu erat eget mauris. Suspendisse eu lorem metus. Aliquam tempus aliquet urna, vitae mollis lacus pretium vitae. Etiam semper gravida commodo. Maecenas at pulvinar quam. Nullam dolor ipsum, ornare a sollicitudin et, sodales porttitor neque. </p> <p> Integer in felis at lacus mattis facilisis. Curabitur tincidunt, felis porttitor mollis finibus, tortor elit elementum dolor, vel vulputate lorem dui id ante. Vivamus in velit at lectus blandit gravida vitae quis arcu. Nam et magna magna. Fusce condimentum diam lacus, ac ullamcorper purus malesuada eu. Mauris ullamcorper elit et venenatis faucibus. Nullam lobortis molestie purus quis pellentesque. Sed at libero id nisi rhoncus tincidunt. Praesent vestibulum vehicula tristique. Etiam rutrum, nunc id porta interdum, nulla nisi molestie leo, at fermentum justo dolor at lorem. Duis in egestas sapien. </p> <p> Donec pharetra molestie sollicitudin. Duis mattis eleifend rutrum. Quisque luctus tincidunt lacus, vitae lobortis nisi malesuada ac. Aliquam mattis leo vel elit rutrum, nec consequat massa vestibulum. Maecenas bibendum metus nec ante feugiat, eu faucibus orci mattis. Cras tristique sem non elit congue malesuada. Proin ornare, lacus et porttitor consequat, sapien urna rutrum diam, ac pellentesque ligula est eget nisi. Interdum et malesuada fames ac ante ipsum primis in faucibus. Donec ultrices sollicitudin eros a placerat. Proin eget pulvinar est. Donec posuere ultrices odio at ultrices. Suspendisse potenti. Phasellus id orci id purus porttitor consectetur a at erat. Nullam volutpat ultricies nisl id maximus. Morbi porta ex ante, et egestas odio ultricies consequat. </p> <p> </p><ul> <li>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</li> <li>Aliquam in ex porta, imperdiet elit sit amet, condimentum diam.</li> <li>Etiam fermentum nisi at porta pulvinar.</li> </ul> <p></p> <p> </p><ul> <li>Proin mattis neque vel elit posuere molestie.</li> <li>Integer tincidunt sem sed nunc auctor elementum.</li> <li>Integer a felis in ipsum aliquet auctor sit amet a neque.</li> </ul> <p></p> <p> </p><ul> <li>Sed suscipit dolor molestie, rhoncus quam ac, lacinia ex.</li> <li>Curabitur et tellus vel justo ultrices aliquet sed id turpis.</li> <li>Nam finibus risus at justo elementum bibendum.</li> <li>In non lacus non urna congue feugiat at vel diam.</li> </ul> <p></p> <p> </p><ul> <li>Integer hendrerit augue interdum dui venenatis, sit amet tristique mauris cursus.</li> <li>Etiam quis eros viverra, tincidunt justo in, facilisis nunc.</li> <li>Aliquam at lacus faucibus, congue lorem interdum, semper mauris.</li> <li>Ut vulputate erat vel feugiat pharetra.</li> <li>Morbi id augue id orci sagittis tempus.</li> <li>Vestibulum varius libero ac dignissim sodales.</li> </ul> <p></p> <p> </p><ul> <li>Aenean ac sem eget libero varius viverra sit amet vitae nunc.</li> </ul> <p></p> <amp-anim src="https: <amp-img placeholder src="https: <amp-analytics id="nestedAnalytics"> <script type="application/json"> { "transport": {"beacon": false, "xhrpost": false}, "requests": { "visibility": "https://raw.githubusercontent.com/ampproject/amphtml/master/examples/img/ampicon.png?${type}&RANDOM" }, "triggers": { "visibilityScope": { "on": "visible", "request": "visibility", "visibilitySpec": { "selector": "amp-img", "selectionMethod": "scope", "<API key>": 10 }, "vars": { "type": "scope" } }, "visibilityClosest": { "on": "visible", "request": "visibility", "visibilitySpec": { "selector": "amp-anim", "selectionMethod": "closest", "<API key>": 20 }, "vars": { "type": "closest" } } } } </script> </amp-analytics> </amp-anim> </div> </body> </html>
// This file has been autogenerated. exports.setEnvironment = function() { process.env['AZURE_TEST_LOCATION'] = 'West US'; process.env['<API key>'] = '<API key>'; }; exports.scopes = [[function (nock) { var result = nock('http://management.azure.com:443') .<API key>(function (path) { return '*';}) .put('/subscriptions/<API key>/resourceGroups/cdnTestGroup1540/providers/Microsoft.Cdn/profiles/cdnTestProfile2130?api-version=2016-10-02', '*') .reply(201, "{\r\n \"name\":\"cdnTestProfile2130\",\"id\":\"/subscriptions/<API key>/resourcegroups/cdnTestGroup1540/providers/Microsoft.Cdn/profiles/cdnTestProfile2130\",\"type\":\"Microsoft.Cdn/profiles\",\"tags\":{\r\n \"tag1\":\"val1\",\"tag2\":\"val2\"\r\n },\"location\":\"EastUs\",\"sku\":{\r\n \"name\":\"Premium_Verizon\"\r\n },\"properties\":{\r\n \"provisioningState\":\"Creating\",\"resourceState\":\"Creating\"\r\n }\r\n}", { 'cache-control': 'no-cache', pragma: 'no-cache', 'content-length': '403', 'content-type': 'application/json; odata.metadata=minimal', expires: '-1', 'retry-after': '10', 'x-ms-request-id': '<API key>', '<API key>': '<API key>', '<API key>': 'https://management.azure.com/subscriptions/<API key>/resourcegroups/cdnTestGroup1540/providers/Microsoft.Cdn/operationresults/<API key>?api-version=2016-10-02', 'odata-version': '4.0', '<API key>': 'max-age=31536000; includeSubDomains', server: 'Microsoft-IIS/8.5', 'x-aspnet-version': '4.0.30319', 'x-powered-by': 'ASP.NET', '<API key>': '1198', '<API key>': '<API key>', '<API key>': 'CENTRALUS:20161027T225639Z:<API key>', date: 'Thu, 27 Oct 2016 22:56:38 GMT', connection: 'close' }); return result; }, function (nock) { var result = nock('https://management.azure.com:443') .<API key>(function (path) { return '*';}) .put('/subscriptions/<API key>/resourceGroups/cdnTestGroup1540/providers/Microsoft.Cdn/profiles/cdnTestProfile2130?api-version=2016-10-02', '*') .reply(201, "{\r\n \"name\":\"cdnTestProfile2130\",\"id\":\"/subscriptions/<API key>/resourcegroups/cdnTestGroup1540/providers/Microsoft.Cdn/profiles/cdnTestProfile2130\",\"type\":\"Microsoft.Cdn/profiles\",\"tags\":{\r\n \"tag1\":\"val1\",\"tag2\":\"val2\"\r\n },\"location\":\"EastUs\",\"sku\":{\r\n \"name\":\"Premium_Verizon\"\r\n },\"properties\":{\r\n \"provisioningState\":\"Creating\",\"resourceState\":\"Creating\"\r\n }\r\n}", { 'cache-control': 'no-cache', pragma: 'no-cache', 'content-length': '403', 'content-type': 'application/json; odata.metadata=minimal', expires: '-1', 'retry-after': '10', 'x-ms-request-id': '<API key>', '<API key>': '<API key>', '<API key>': 'https://management.azure.com/subscriptions/<API key>/resourcegroups/cdnTestGroup1540/providers/Microsoft.Cdn/operationresults/<API key>?api-version=2016-10-02', 'odata-version': '4.0', '<API key>': 'max-age=31536000; includeSubDomains', server: 'Microsoft-IIS/8.5', 'x-aspnet-version': '4.0.30319', 'x-powered-by': 'ASP.NET', '<API key>': '1198', '<API key>': '<API key>', '<API key>': 'CENTRALUS:20161027T225639Z:<API key>', date: 'Thu, 27 Oct 2016 22:56:38 GMT', connection: 'close' }); return result; }, function (nock) { var result = nock('http://management.azure.com:443') .get('/subscriptions/<API key>/resourcegroups/cdnTestGroup1540/providers/Microsoft.Cdn/operationresults/<API key>?api-version=2016-10-02') .reply(200, "{\r\n \"status\":\"InProgress\",\"error\":{\r\n \"code\":\"None\",\"message\":null\r\n }\r\n}", { 'cache-control': 'no-cache', pragma: 'no-cache', 'content-length': '78', 'content-type': 'application/json; odata.metadata=minimal; odata.streaming=true', expires: '-1', 'x-ms-request-id': '<API key>', '<API key>': '<API key>', 'odata-version': '4.0', '<API key>': 'max-age=31536000; includeSubDomains', server: 'Microsoft-IIS/8.5', 'x-aspnet-version': '4.0.30319', 'x-powered-by': 'ASP.NET', '<API key>': '14995', '<API key>': '<API key>', '<API key>': 'CENTRALUS:20161027T225709Z:<API key>', date: 'Thu, 27 Oct 2016 22:57:09 GMT', connection: 'close' }); return result; }, function (nock) { var result = nock('https://management.azure.com:443') .get('/subscriptions/<API key>/resourcegroups/cdnTestGroup1540/providers/Microsoft.Cdn/operationresults/<API key>?api-version=2016-10-02') .reply(200, "{\r\n \"status\":\"InProgress\",\"error\":{\r\n \"code\":\"None\",\"message\":null\r\n }\r\n}", { 'cache-control': 'no-cache', pragma: 'no-cache', 'content-length': '78', 'content-type': 'application/json; odata.metadata=minimal; odata.streaming=true', expires: '-1', 'x-ms-request-id': '<API key>', '<API key>': '<API key>', 'odata-version': '4.0', '<API key>': 'max-age=31536000; includeSubDomains', server: 'Microsoft-IIS/8.5', 'x-aspnet-version': '4.0.30319', 'x-powered-by': 'ASP.NET', '<API key>': '14995', '<API key>': '<API key>', '<API key>': 'CENTRALUS:20161027T225709Z:<API key>', date: 'Thu, 27 Oct 2016 22:57:09 GMT', connection: 'close' }); return result; }, function (nock) { var result = nock('http://management.azure.com:443') .get('/subscriptions/<API key>/resourcegroups/cdnTestGroup1540/providers/Microsoft.Cdn/operationresults/<API key>?api-version=2016-10-02') .reply(200, "{\r\n \"status\":\"Succeeded\",\"error\":{\r\n \"code\":\"None\",\"message\":null\r\n }\r\n}", { 'cache-control': 'no-cache', pragma: 'no-cache', 'content-length': '77', 'content-type': 'application/json; odata.metadata=minimal; odata.streaming=true', expires: '-1', 'x-ms-request-id': '<API key>', '<API key>': '<API key>', 'odata-version': '4.0', '<API key>': 'max-age=31536000; includeSubDomains', server: 'Microsoft-IIS/8.5', 'x-aspnet-version': '4.0.30319', 'x-powered-by': 'ASP.NET', '<API key>': '14997', '<API key>': '<API key>', '<API key>': 'WESTUS2:20161027T225741Z:<API key>', date: 'Thu, 27 Oct 2016 22:57:41 GMT', connection: 'close' }); return result; }, function (nock) { var result = nock('https://management.azure.com:443') .get('/subscriptions/<API key>/resourcegroups/cdnTestGroup1540/providers/Microsoft.Cdn/operationresults/<API key>?api-version=2016-10-02') .reply(200, "{\r\n \"status\":\"Succeeded\",\"error\":{\r\n \"code\":\"None\",\"message\":null\r\n }\r\n}", { 'cache-control': 'no-cache', pragma: 'no-cache', 'content-length': '77', 'content-type': 'application/json; odata.metadata=minimal; odata.streaming=true', expires: '-1', 'x-ms-request-id': '<API key>', '<API key>': '<API key>', 'odata-version': '4.0', '<API key>': 'max-age=31536000; includeSubDomains', server: 'Microsoft-IIS/8.5', 'x-aspnet-version': '4.0.30319', 'x-powered-by': 'ASP.NET', '<API key>': '14997', '<API key>': '<API key>', '<API key>': 'WESTUS2:20161027T225741Z:<API key>', date: 'Thu, 27 Oct 2016 22:57:41 GMT', connection: 'close' }); return result; }, function (nock) { var result = nock('http://management.azure.com:443') .get('/subscriptions/<API key>/resourceGroups/cdnTestGroup1540/providers/Microsoft.Cdn/profiles/cdnTestProfile2130?api-version=2016-10-02') .reply(200, "{\r\n \"name\":\"cdnTestProfile2130\",\"id\":\"/subscriptions/<API key>/resourcegroups/cdnTestGroup1540/providers/Microsoft.Cdn/profiles/cdnTestProfile2130\",\"type\":\"Microsoft.Cdn/profiles\",\"tags\":{\r\n \"tag1\":\"val1\",\"tag2\":\"val2\"\r\n },\"location\":\"EastUs\",\"sku\":{\r\n \"name\":\"Premium_Verizon\"\r\n },\"properties\":{\r\n \"provisioningState\":\"Succeeded\",\"resourceState\":\"Active\"\r\n }\r\n}", { 'cache-control': 'no-cache', pragma: 'no-cache', 'content-length': '402', 'content-type': 'application/json; odata.metadata=minimal; odata.streaming=true', expires: '-1', 'x-ms-request-id': '<API key>', '<API key>': '<API key>', 'odata-version': '4.0', '<API key>': 'max-age=31536000; includeSubDomains', server: 'Microsoft-IIS/8.5', 'x-aspnet-version': '4.0.30319', 'x-powered-by': 'ASP.NET', '<API key>': '14997', '<API key>': '<API key>', '<API key>': 'WESTUS2:20161027T225742Z:<API key>', date: 'Thu, 27 Oct 2016 22:57:42 GMT', connection: 'close' }); return result; }, function (nock) { var result = nock('https://management.azure.com:443') .get('/subscriptions/<API key>/resourceGroups/cdnTestGroup1540/providers/Microsoft.Cdn/profiles/cdnTestProfile2130?api-version=2016-10-02') .reply(200, "{\r\n \"name\":\"cdnTestProfile2130\",\"id\":\"/subscriptions/<API key>/resourcegroups/cdnTestGroup1540/providers/Microsoft.Cdn/profiles/cdnTestProfile2130\",\"type\":\"Microsoft.Cdn/profiles\",\"tags\":{\r\n \"tag1\":\"val1\",\"tag2\":\"val2\"\r\n },\"location\":\"EastUs\",\"sku\":{\r\n \"name\":\"Premium_Verizon\"\r\n },\"properties\":{\r\n \"provisioningState\":\"Succeeded\",\"resourceState\":\"Active\"\r\n }\r\n}", { 'cache-control': 'no-cache', pragma: 'no-cache', 'content-length': '402', 'content-type': 'application/json; odata.metadata=minimal; odata.streaming=true', expires: '-1', 'x-ms-request-id': '<API key>', '<API key>': '<API key>', 'odata-version': '4.0', '<API key>': 'max-age=31536000; includeSubDomains', server: 'Microsoft-IIS/8.5', 'x-aspnet-version': '4.0.30319', 'x-powered-by': 'ASP.NET', '<API key>': '14997', '<API key>': '<API key>', '<API key>': 'WESTUS2:20161027T225742Z:<API key>', date: 'Thu, 27 Oct 2016 22:57:42 GMT', connection: 'close' }); return result; }]];
package com.snowplowanalytics.snowplow.enrich.common package enrichments package registry package apirequest // Scalaz import scalaz._ import Scalaz._ // json4s import org.json4s.JInt // specs2 import org.specs2.Specification import org.specs2.scalaz.ValidationMatchers import org.specs2.mock.Mockito class CacheSpec extends Specification with ValidationMatchers with Mockito { def is = s2""" This is a specification to test the API Request enrichment cache Update on identical URLs $e1 Preserve ttl of cache $e2 Remove unused value $e3 """ def e1 = { val cache = Cache(3, 2) cache.put("http://api.acme.com/url", JInt(42).success) cache.put("http://api.acme.com/url", JInt(52).success) cache.get("http://api.acme.com/url") must beSome.like { case v => v must beSuccessful(JInt(52)) } and(cache.actualLoad must beEqualTo(1)) } def e2 = { val cache = Cache(3, 2) cache.put("http://api.acme.com/url", JInt(42).success) Thread.sleep(3000) cache.get("http://api.acme.com/url") must beNone and(cache.actualLoad must beEqualTo(0)) } def e3 = { val cache = Cache(2, 2) cache.put("http://api.acme.com/url1", JInt(32).success) cache.put("http://api.acme.com/url2", JInt(42).success) cache.put("http://api.acme.com/url3", JInt(52).success) cache.get("http://api.acme.com/url1") must beNone and(cache.actualLoad must beEqualTo(2)) } }
#include <stdarg.h> #include <stddef.h> #include <setjmp.h> #include "cmockery.h" #include "../runaway_cleaner.c" #define EXPECT_ELOG(LOG_LEVEL) \ will_be_called(elog_start); \ expect_any(elog_start, filename); \ expect_any(elog_start, lineno); \ expect_any(elog_start, funcname); \ if (LOG_LEVEL < ERROR) \ { \ will_be_called(elog_finish); \ } \ else \ { \ <API key>(elog_finish, &<API key>, NULL);\ } \ expect_value(elog_finish, elevel, LOG_LEVEL); \ expect_any(elog_finish, fmt); \ #define EXPECT_EREPORT(LOG_LEVEL) \ expect_any(errstart, elevel); \ expect_any(errstart, filename); \ expect_any(errstart, lineno); \ expect_any(errstart, funcname); \ expect_any(errstart, domain); \ if (LOG_LEVEL < ERROR) \ { \ will_return(errstart, false); \ } \ else \ { \ <API key>(errstart, false, &<API key>, NULL);\ } \ /* MySessionState will use the address of this global variable */ static SessionState fakeSessionState; /* Prepares a fake MySessionState pointer for use in the vmem tracker */ static void <API key>(int activeProcessCount, int cleanupCountdown, RunawayStatus runawayStatus, int pinCount, int vmem) { MySessionState = &fakeSessionState; MySessionState->activeProcessCount = activeProcessCount; MySessionState->cleanupCountdown = cleanupCountdown; MySessionState->runawayStatus = runawayStatus; MySessionState->next = NULL; MySessionState->pinCount = pinCount; MySessionState->sessionId = 1234; MySessionState->sessionVmem = vmem; MySessionState->spinLock = 0; } #define PG_RE_THROW() siglongjmp(*PG_exception_stack, 1) /* * This method will emulate the real <API key> * function by re-throwing the exception, essentially falling * back to the next available PG_CATCH(); */ void <API key>() { PG_RE_THROW(); } /* * Checks if <API key>() does not start cleanup if * the current session is not a runaway */ void <API key>(void **state) { <API key>(2 /* activeProcessCount */, <API key> /* cleanupCountdown */, <API key> /* runawayStatus */, 2 /* pinCount */, 0 /* vmem */); static <API key> = 10; <API key> = &<API key>; <API key> = 0; <API key>(); /* Cleanup shouldn't have begun */ assert_true(<API key> != *<API key>); } /* * Checks if <API key>() does not execute a duplicate * cleanup for the same runaway event that it already started cleaning up */ void <API key>(void **state) { <API key>(2 /* activeProcessCount */, 2 /* cleanupCountdown */, <API key> /* runawayStatus */, 2 /* pinCount */, 0 /* vmem */); static <API key> = 10; <API key> = &<API key>; <API key> = *<API key>; /* * As we are not providing IsCommitInProgress, the call itself verifies * that we are not attempting any cleanup */ <API key>(); } /* * Checks if <API key>() starts the cleanup process if * all conditions are met (i.e., no commit is in progress and vmem tracker * is initialized) */ void <API key>(void **state) { <API key>(2 /* activeProcessCount */, 2 /* cleanupCountdown */, <API key> /* runawayStatus */, 2 /* pinCount */, 12345 /* vmem */); static <API key> = 10; <API key> = &<API key>; *<API key> = 10; /* * Set <API key> to less than *<API key> * to trigger a cleanup */ <API key> = 1; <API key> = 1; isProcessActive = true; /* Make sure the cleanup goes through */ vmemTrackerInited = true; CritSectionCount = 0; <API key> = 0; /* We need a valid gp_command_count to execute cleanup */ gp_command_count = 1; will_return(superuser, false); #ifdef FAULT_INJECTOR expect_value(<API key>, identifier, RunawayCleanup); expect_value(<API key>, ddlStatement, DDLNotSpecified); expect_value(<API key>, databaseName, ""); expect_value(<API key>, tableName, ""); will_be_called(<API key>); #endif EXPECT_EREPORT(ERROR); PG_TRY(); { <API key>(); assert_false("Cleanup didn't throw error"); } PG_CATCH(); { } PG_END_TRY(); assert_true(<API key> == *<API key>); /* We should not finish the cleanup as we errored out */ assert_true(<API key> == 1); /* cleanupCountdown shouldn't change as we haven't finished cleanup */ assert_true(MySessionState->cleanupCountdown == 2); /* * If we call <API key> again for the same runaway event, * it should be a noop, therefore requiring no "will_be_called" setup */ <API key>(); } /* * Checks if <API key>() ignores cleanup if in critical section */ void <API key>(void **state) { <API key>(2 /* activeProcessCount */, 2 /* cleanupCountdown */, <API key> /* runawayStatus */, 2 /* pinCount */, 12345 /* vmem */); static EventVersion <API key> = 10; <API key> = &<API key>; /* * Set <API key> to less than *<API key> * to trigger a cleanup */ <API key> = 1; <API key> = 1; /* Make sure the cleanup goes through */ vmemTrackerInited = true; isProcessActive = true; CritSectionCount = 1; <API key> = 0; <API key>(); assert_true(<API key> == *<API key>); /* Cleanup is done, without ever throwing an ERROR */ assert_true(<API key> == <API key>); /* * cleanupCountdown is decremented by 1 as there was no error, and therefore * the cleanup is done within the same call of <API key> */ assert_true(MySessionState->cleanupCountdown == 1); CritSectionCount = 0; } /* * Checks if <API key>() ignores cleanup if interrupts are held off */ void <API key>(void **state) { <API key>(2 /* activeProcessCount */, 2 /* cleanupCountdown */, <API key> /* runawayStatus */, 2 /* pinCount */, 12345 /* vmem */); static EventVersion <API key> = 10; <API key> = &<API key>; /* * Set <API key> to less than *<API key> * to trigger a cleanup */ <API key> = 1; <API key> = 1; /* Make sure the cleanup goes through */ vmemTrackerInited = true; isProcessActive = true; CritSectionCount = 0; <API key> = 1; <API key>(); assert_true(<API key> == *<API key>); /* Cleanup is done, without ever throwing an ERROR */ assert_true(<API key> == <API key>); /* * cleanupCountdown is decremented by 1 as there was no error, and therefore * the cleanup is done within the same call of <API key> */ assert_true(MySessionState->cleanupCountdown == 1); <API key> = 0; } /* * Checks if <API key>() ignores cleanupCountdown * if optional cleanup */ void <API key>(void **state) { #define CLEANUP_COUNTDOWN 2 <API key>(2 /* activeProcessCount */, CLEANUP_COUNTDOWN /* cleanupCountdown */, <API key> /* runawayStatus */, 2 /* pinCount */, 12345 /* vmem */); static EventVersion <API key> = 10; <API key> = &<API key>; *<API key> = 10; /* * Set <API key> to less than *<API key> * to trigger a cleanup */ <API key> = 1; <API key> = 1; /* Make sure the cleanup is not ignored for vmem initialization */ vmemTrackerInited = true; /* Simulate a deactivation before the runaway */ deactivationVersion = *<API key> - 1; activationVersion = *<API key> - 1; isProcessActive = false; CritSectionCount = 0; <API key> = 0; <API key>(); /* The cleanup shouldn't even start as the QE was deactivated at the time of the runaway*/ assert_true(<API key> == 1); assert_true(<API key> == 1); /* * cleanupCountdown should not be decremented as this was an optional cleanup */ assert_true(MySessionState->cleanupCountdown == CLEANUP_COUNTDOWN); assert_true(MySessionState->runawayStatus == <API key>); /* * Now simulate a scenario where the we activated but the runaway happened * before the activation */ <API key> = 2; <API key> = 2; /* Another runaway happened after the last cleanup */ *<API key> = <API key> + 2; activationVersion = 5; deactivationVersion = 3; isProcessActive = true; <API key>(); /* The cleanup shouldn't even start as the runaway event happened before the QE became active */ assert_true(<API key> == 2); assert_true(<API key> == 2); /* * cleanupCountdown should not be decremented as this was an optional cleanup */ assert_true(MySessionState->cleanupCountdown == CLEANUP_COUNTDOWN); assert_true(MySessionState->runawayStatus == <API key>); } /* * Checks if <API key> ignores duplicate cleanup * for a single runaway event */ void <API key>(void **state) { <API key>(2 /* activeProcessCount */, 2 /* cleanupCountdown */, <API key> /* runawayStatus */, 2 /* pinCount */, 12345 /* vmem */); static <API key> = 10; <API key> = &<API key>; /* * Set <API key> and <API key> to * <API key> which should make the function call a no-op */ <API key> = *<API key>; <API key> = *<API key>; /* Make sure the cleanup goes through */ vmemTrackerInited = true; isProcessActive = true; <API key>(false /* ignoredCleanup */); /* Nothing got cleaned */ assert_true(MySessionState->cleanupCountdown == 2); } /* * Checks if <API key> prevents multiple cleanup * for a single runaway event by properly updating <API key> and * <API key> */ void <API key>(void **state) { <API key>(2 /* activeProcessCount */, 2 /* cleanupCountdown */, <API key> /* runawayStatus */, CLEANUP_COUNTDOWN /* pinCount */, 12345 /* vmem */); static <API key> = 10; <API key> = &<API key>; *<API key> = 10; /* * Some imaginary cleanup begin/end event version. The idea is to ensure * that once the <API key> call returns * we will have both set to <API key> */ <API key> = *<API key>; <API key> = 0; /* Make sure the cleanup goes through */ vmemTrackerInited = true; isProcessActive = true; <API key>(false /* ignoredCleanup */); /* cleanupCountdown should be adjusted */ assert_true(MySessionState->cleanupCountdown == CLEANUP_COUNTDOWN - 1); assert_true(<API key> == <API key>); assert_true(<API key> == *<API key>); /* Second call shouldn't change anything */ <API key>(false /* ignoredCleanup */); /* cleanupCountdown is unchanged */ assert_true(MySessionState->cleanupCountdown == CLEANUP_COUNTDOWN - 1); } /* * Checks if <API key> reactivates a process * if the deactivation process triggers cleanup for a pending runaway event */ void <API key>(void **state) { <API key>(2 /* activeProcessCount */, 2 /* cleanupCountdown */, <API key> /* runawayStatus */, 2 /* pinCount */, 12345 /* vmem */); static <API key> = 10; <API key> = &<API key>; /* * Set <API key> to <API key> and <API key> * to a smaller value to simulate an ongoing cleanup */ <API key> = *<API key>; <API key> = 1; /* Valid isRunawayDetector is necessary for Assert */ static uint32 <API key> = 1; isRunawayDetector = &<API key>; /* Make sure we became idle after a pending runaway event */ activationVersion = 1; deactivationVersion = *<API key> + 1; /* Make sure the cleanup goes through */ vmemTrackerInited = true; isProcessActive = false; /* We must undo the idle state */ will_be_called(<API key>); <API key>(false /* ignoredCleanup */); /* The cleanupCountdown must be decremented as we cleaned up */ assert_true(MySessionState->cleanupCountdown == 1); /* We updated the <API key> to indicate that we finished cleanup */ assert_true(<API key> == <API key>); } /* * Checks if <API key> reactivates the runaway detector * once all the processes of the runaway session are done cleaning */ void <API key>(void **state) { <API key>(2 /* activeProcessCount */, 2 /* cleanupCountdown */, <API key> /* runawayStatus */, 2 /* pinCount */, 12345 /* vmem */); static EventVersion <API key> = 10; <API key> = &<API key>; /* * Set <API key> to <API key> and <API key> * to a smaller value to simulate an ongoing cleanup */ <API key> = *<API key>; <API key> = 1; /* Valid isRunawayDetector is necessary for Assert */ static uint32 <API key> = 1; isRunawayDetector = &<API key>; /* Just an active process that never became idle */ activationVersion = 0; deactivationVersion = 0; isProcessActive = true; /* Make sure the cleanup goes through */ vmemTrackerInited = true; <API key>(false /* ignoredCleanup */); /* The cleanupCountdown must be decremented as we cleaned up */ assert_true(MySessionState->cleanupCountdown == 1); /* We updated the <API key> to indicate that we finished cleanup */ assert_true(<API key> == <API key>); /* The runaway detector promotion should be disabled as we still have 1 QE unclean */ assert_true(*isRunawayDetector == 1); /* * Fake a ongoing cleanup by making <API key> < <API key> * so that we can execute cleanup one more time, marking all QEs clean */ <API key> = 1; /* * cleanupCountdown should reach 0, and immediately afterwards should be set to * <API key> */ <API key>(false /* ignoredCleanup */); assert_true(MySessionState->cleanupCountdown == <API key>); /* Runaway detector should be re-enabled */ assert_true(*isRunawayDetector == 0); } /* * Checks if <API key> reactivates the runaway detector */ void test__RunawayCleaner_RunawayCleanupDoneForSession__ResetsRunawayFlagAndReactivateRunawayDetector(void **state) { <API key>(2 /* activeProcessCount */, 2 /* cleanupCountdown */, <API key> /* runawayStatus */, 2 /* pinCount */, 12345 /* vmem */); static EventVersion <API key> = 10; <API key> = &<API key>; /* * Satisfy asserts */ <API key> = *<API key>; <API key> = <API key>; MySessionState->cleanupCountdown = <API key>; *isRunawayDetector = 1; MySessionState->runawayStatus = <API key>; <API key>(); assert_true(MySessionState->runawayStatus == <API key>); /* Runaway detector should be re-enabled */ assert_true(*isRunawayDetector == 0); } int main(int argc, char* argv[]) { <API key>(argc, argv); const UnitTest tests[] = { unit_test(<API key>), unit_test(<API key>), unit_test(<API key>), unit_test(<API key>), unit_test(<API key>), unit_test(<API key>), unit_test(<API key>), unit_test(<API key>), unit_test(<API key>), unit_test(<API key>), unit_test(test__RunawayCleaner_RunawayCleanupDoneForSession__ResetsRunawayFlagAndReactivateRunawayDetector), }; return run_tests(tests); }
package com.intellij.usages.impl.rules; import com.intellij.lang.injection.<API key>; import com.intellij.navigation.<API key>; import com.intellij.openapi.actionSystem.CommonDataKeys; import com.intellij.openapi.actionSystem.DataProvider; import com.intellij.openapi.actionSystem.<API key>; import com.intellij.openapi.project.DumbAware; import com.intellij.openapi.util.Iconable; import com.intellij.openapi.util.NlsSafe; import com.intellij.openapi.vcs.FileStatus; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.*; import com.intellij.psi.util.FileTypeUtils; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.usageView.UsageInfo; import com.intellij.usages.Usage; import com.intellij.usages.UsageGroup; import com.intellij.usages.UsageTarget; import com.intellij.usages.UsageView; import com.intellij.usages.rules.PsiElementUsage; import com.intellij.usages.rules.<API key>; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.util.List; class ClassGroupingRule extends <API key> implements DumbAware { @Nullable @Override protected UsageGroup getParentGroupFor(@NotNull Usage usage, UsageTarget @NotNull [] targets) { if (!(usage instanceof PsiElementUsage)) { return null; } final PsiElement psiElement = ((PsiElementUsage)usage).getElement(); final PsiFile containingFile = psiElement.getContainingFile(); if (containingFile == null) return null; PsiFile topLevelFile = <API key>.getInstance(containingFile.getProject()).getTopLevelFile(containingFile); if (!(topLevelFile instanceof PsiJavaFile) || topLevelFile instanceof ServerPageFile) { return null; } PsiElement containingClass = topLevelFile == containingFile ? psiElement : <API key> .getInstance(containingFile.getProject()).getInjectionHost(containingFile); do { containingClass = PsiTreeUtil.getParentOfType(containingClass, PsiClass.class, true); } while (containingClass != null && ((PsiClass)containingClass).getQualifiedName() == null); if (containingClass == null) { // check whether the element is in the import list PsiImportList importList = PsiTreeUtil.getParentOfType(psiElement, PsiImportList.class, true); if (importList != null) { final String fileName = <API key>(topLevelFile); final PsiClass[] classes = ((PsiJavaFile)topLevelFile).getClasses(); for (final PsiClass aClass : classes) { if (fileName.equals(aClass.getName())) { containingClass = aClass; break; } } } } else { // skip JspClass synthetic classes. if (containingClass.getParent() instanceof PsiFile && FileTypeUtils.isInServerPageFile(containingClass)) { containingClass = null; } } if (containingClass != null) { return new ClassUsageGroup((PsiClass)containingClass); } final VirtualFile virtualFile = topLevelFile.getVirtualFile(); if (virtualFile != null) { return new FileGroupingRule.FileUsageGroup(topLevelFile.getProject(), virtualFile); } return null; } private static String <API key>(final PsiFile file) { final String name = file.getName(); final int index = name.lastIndexOf('.'); return index < 0? name : name.substring(0, index); } private static class ClassUsageGroup implements UsageGroup, DataProvider { private final <API key><PsiClass> myClassPointer; private final @NlsSafe String myText; private final String myQName; private final Icon myIcon; ClassUsageGroup(@NotNull PsiClass aClass) { myQName = aClass.getQualifiedName(); myText = createText(aClass); myClassPointer = SmartPointerManager.getInstance(aClass.getProject()).<API key>(aClass); myIcon = aClass.getIcon(Iconable.<API key> | Iconable.<API key>); } private static @NlsSafe String createText(PsiClass aClass) { String text = aClass.getName(); PsiClass containingClass = aClass.getContainingClass(); while (containingClass != null) { text = containingClass.getName() + '.' + text; containingClass = containingClass.getContainingClass(); } return text; } @Override public Icon getIcon() { return myIcon; } @Override @NotNull public String <API key>() { return myText; } @Override public FileStatus getFileStatus() { return isValid() ? <API key>.get(getPsiClass()) : null; } private PsiClass getPsiClass() { return myClassPointer.getElement(); } @Override public boolean isValid() { PsiClass psiClass = getPsiClass(); return psiClass != null && psiClass.isValid(); } public int hashCode() { return myQName.hashCode(); } public boolean equals(Object object) { return object instanceof ClassUsageGroup && myQName.equals(((ClassUsageGroup)object).myQName); } @Override public void navigate(boolean focus) throws <API key> { if (canNavigate()) { getPsiClass().navigate(focus); } } @Override public boolean canNavigate() { return isValid(); } @Override public boolean canNavigateToSource() { return canNavigate(); } @Override public int compareTo(@NotNull UsageGroup usageGroup) { return <API key>().compareToIgnoreCase(usageGroup.<API key>()); } @Nullable @Override public Object getData(@NotNull String dataId) { if (<API key>.SLOW_DATA_PROVIDERS.is(dataId)) { return List.of((DataProvider)this::getSlowData); } return null; } private @Nullable Object getSlowData(@NonNls String dataId) { if (CommonDataKeys.PSI_ELEMENT.is(dataId)) { return getPsiClass(); } else if (UsageView.USAGE_INFO_KEY.is(dataId)) { PsiClass psiClass = getPsiClass(); return psiClass == null ? null : new UsageInfo(psiClass); } return null; } } }
/** * <API key>.java * * This file was auto-generated from WSDL * by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter. */ package com.google.api.ads.adwords.axis.v201502.cm; public class <API key> implements java.io.Serializable { private java.lang.String _value_; private static java.util.HashMap _table_ = new java.util.HashMap(); // Constructor protected <API key>(java.lang.String value) { _value_ = value; _table_.put(_value_,this); } public static final java.lang.String _ACCOUNT_LIMIT = "ACCOUNT_LIMIT"; public static final java.lang.String _CAMPAIGN_LIMIT = "CAMPAIGN_LIMIT"; public static final java.lang.String _ADGROUP_LIMIT = "ADGROUP_LIMIT"; public static final java.lang.String _AD_GROUP_AD_LIMIT = "AD_GROUP_AD_LIMIT"; public static final java.lang.String <API key> = "<API key>"; public static final java.lang.String _SHARED_SET_LIMIT = "SHARED_SET_LIMIT"; public static final java.lang.String <API key> = "<API key>"; public static final java.lang.String _UNKNOWN = "UNKNOWN"; public static final <API key> ACCOUNT_LIMIT = new <API key>(_ACCOUNT_LIMIT); public static final <API key> CAMPAIGN_LIMIT = new <API key>(_CAMPAIGN_LIMIT); public static final <API key> ADGROUP_LIMIT = new <API key>(_ADGROUP_LIMIT); public static final <API key> AD_GROUP_AD_LIMIT = new <API key>(_AD_GROUP_AD_LIMIT); public static final <API key> <API key> = new <API key>(<API key>); public static final <API key> SHARED_SET_LIMIT = new <API key>(_SHARED_SET_LIMIT); public static final <API key> <API key> = new <API key>(<API key>); public static final <API key> UNKNOWN = new <API key>(_UNKNOWN); public java.lang.String getValue() { return _value_;} public static <API key> fromValue(java.lang.String value) throws java.lang.<API key> { <API key> enumeration = (<API key>) _table_.get(value); if (enumeration==null) throw new java.lang.<API key>(); return enumeration; } public static <API key> fromString(java.lang.String value) throws java.lang.<API key> { return fromValue(value); } public boolean equals(java.lang.Object obj) {return (obj == this);} public int hashCode() { return toString().hashCode();} public java.lang.String toString() { return _value_;} public java.lang.Object readResolve() throws java.io.<API key> { return fromValue(_value_);} public static org.apache.axis.encoding.Serializer getSerializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.EnumSerializer( _javaType, _xmlType); } public static org.apache.axis.encoding.Deserializer getDeserializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.EnumDeserializer( _javaType, _xmlType); } // Type metadata private static org.apache.axis.description.TypeDesc typeDesc = new org.apache.axis.description.TypeDesc(<API key>.class); static { typeDesc.setXmlType(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201502", "<API key>.Reason")); } /** * Return type metadata object */ public static org.apache.axis.description.TypeDesc getTypeDesc() { return typeDesc; } }
/*global define*/ define([ '../Core/defineProperties' ], function( defineProperties) { "use strict"; /** * A queue that can enqueue items at the end, and dequeue items from the front. * * @alias Queue * @constructor */ function Queue() { this._array = []; this._offset = 0; this._length = 0; } defineProperties(Queue.prototype, { /** * The length of the queue. * * @memberof Queue.prototype * * @type {Number} * @readonly */ length : { get : function() { return this._length; } } }); /** * Enqueues the specified item. * * @param {Object} item The item to enqueue. */ Queue.prototype.enqueue = function(item) { this._array.push(item); this._length++; }; /** * Dequeues an item. Returns undefined if the queue is empty. * * @returns {Object} The the dequeued item. */ Queue.prototype.dequeue = function() { if (this._length === 0) { return undefined; } var array = this._array; var offset = this._offset; var item = array[offset]; array[offset] = undefined; offset++; if ((offset > 10) && (offset * 2 > array.length)) { //compact array this._array = array.slice(offset); offset = 0; } this._offset = offset; this._length return item; }; /** * Returns the item at the front of the queue. Returns undefined if the queue is empty. * * @returns {Object} The item at the front of the queue. */ Queue.prototype.peek = function() { if (this._length === 0) { return undefined; } return this._array[this._offset]; }; /** * Check whether this queue contains the specified item. * * @param {Object} item The item to search for. */ Queue.prototype.contains = function(item) { return this._array.indexOf(item) !== -1; }; /** * Remove all items from the queue. */ Queue.prototype.clear = function() { this._array.length = this._offset = this._length = 0; }; /** * Sort the items in the queue in-place. * * @param {Queue~Comparator} compareFunction A function that defines the sort order. */ Queue.prototype.sort = function(compareFunction) { if (this._offset > 0) { //compact array this._array = this._array.slice(this._offset); this._offset = 0; } this._array.sort(compareFunction); }; /** * A function used to compare two items while sorting a queue. * @callback Queue~Comparator * * @param {Object} a An item in the array. * @param {Object} b An item in the array. * @returns {Number} Returns a negative value if <code>a</code> is less than <code>b</code>, * a positive value if <code>a</code> is greater than <code>b</code>, or * 0 if <code>a</code> is equal to <code>b</code>. * * @example * function compareNumbers(a, b) { * return a - b; * } */ return Queue; });
* * * title: Flappy view: page_curriculum theme: none * * * <%= partial('curriculum_header', :unittitle=>'Course 2', :lesson=>16, :title=> 'Flappy', :unplugged=>false, :time=>30) %> [content] [together] In this special level students get to build their own Flappy game by using event handlers to detect mouse clicks and object collisions. [summary] **Getting Started** [Introduction](#GetStarted) **Activity: Flappy** [Flappy](#Activity) **Разширено обучение** [Extension Activities](#Extended) [/summary] Учениците ще: * Match blocks with the appropriate event handler * Create a game using event handlers * Share a creative artifact with other students [/together] [together] ## Getting Started <a name="GetStarted"></a> Introduction * Review The Big Event activity with students: * What did we "program" the button click events to do? * Now we're going to add events to our coding. Specifically, we're going to create an event for clicking the mouse and the bird hitting an object. * In video game programming we call this kind of event collision detection; it lets us decide what to do when one thing collides with, or touches, another. * What kinds of collision events have you seen in games? [/together] [tip] Students will have the opportunity to share their final product with a link. This is a great opportunity to show your school community the great things your students are doing. Collect all of the links and keep them on your class website for all to see! [/tip] [together] ## Activity <a name="Activity"></a> [Flappy](http://learn.code.org/s/course2/stage/16/puzzle/1) In the final stage of this lesson students are able to tweak their game to make it unique - encourage them to see how different they can make each game within the constraints provided. [/together] <!--(this is left in here as an example of how to include an image in Markdown) ![](binaryphoto.png) [together] <a name="Extended"></a>Използвайте тези дейности за подобряване на Ученическия климат в класа. Те могат да бъдат използвани и като извънкласни дейности или в друга форма. Look Under the Hood When you share a link to your game, you also share all of the code that goes behind it. This is a great way for students to learn from each other. * Post links to completed games online or on the board. * Make a game of your own to share as well! * When students load up a link, have them click the "How it Works" button to see the code behind the game. * Discuss as a group the different ways your classmates coded their games. * What suprised you? * What would you like to try? * Choose someone else's game and build on it. (Don't worry; the original game will be safe.) [/together] [standards] PARCC / Smarter Balanced Assessment Skills * Click / tap * Drag and drop * Scroll * Select and drag / slide * Select object ISTE стандарти * 1.a - Apply existing knowledge to generate new ideas, products, or processes. * 1.b - Create original works as a means of personal or group expression. * 1.c - употреба модели и симулации за опознаването на сложни системи и проблеми. * 4.b - Plan and manage activities to develop a solution or complete a project. * 6.a - разбиране и използване на технологични системи. * 6.c - Troubleshoot systems and applications. * 6.d - Transfer current knowledge to learning of new technologies. CSTA К-12 Стандарти по компютърни науки * CL.L1:3-02. Work cooperatively and collaboratively with peers teachers, and others using technology. * CL.L1:6-01. Use productivity technology tools for individual and collaborative writing, communication, and publishing activities. * CPP.L1:6-05. Construct a program as a set of step-by-step instructions to be acted out. * CPP.L1:6-06. Implement problem solutions using a block-based visual programming language. * CT.L1:3-02. Use writing tools, digital cameras and drawing tools to illustrate thoughts, ideas, and stories in a step by step manner. * CT.L1:6-01. Understand and use the basic steps in algorithmic problem-solving. * CT.L2-01. Use the basic steps in algorithmic problem solving to design solutions. * CT.L2-06. Describe and analyze a sequence of instructions being followed. * CT.L2-07. Represent data in a variety of ways: text, sounds, pictures, numbers. * CT.L2-08. Use visual representations of problem states, structures, and data. * CT.L2-12. Use abstraction to decompose a problem into sub problems. Next-Gen Science Standards * K-2-PS3-2. Use tools and materials provided to design and build a device that solves a specific problem or a solution to a specific problem. * K-2-ETS1-1. Ask questions, make observations, and gather information about a situation people want to change to define a simple problem that can be solved through the development of a new or improved object or tool. * 3-5-ETS1-2. Generate and compare multiple possible solutions to a problem based on how well each is likely to meet the criteria and constraints of the problem. Общи основни математически практики * 1. Make sense of problems and persevere in solving them. * 1. Reason abstractly and quantitatively. * 1. Use appropriate tools strategically. * 1. Attend to precision. * 1. Look for and make use of structure. * 1. Look for and express regularity in repeated reasoning. Common Core Language Arts Standards * SL.1.1 - Participate in collaborative conversations with diverse partners about grade 1 topics and texts with peers and adults in small and larger groups * SL.1.2 - Ask and answer questions about key details in a text read aloud or information presented orally or through other media. * L.1.6 - Use words and phrases acquired through conversations, reading and being read to, and responding to texts, including using frequently occurring conjunctions to signal simple relationships. * SL.2.1 - Participate in collaborative conversations with diverse partners about grade 2 topics and texts with peers and adults in small and larger groups. * SL.2.2 - Recount or describe key ideas or details from a text read aloud or information presented orally or through other media. * L.2.6 - Use words and phrases acquired through conversations, reading and being read to, and responding to texts, including using adjectives and adverbs to describe. * SL.3.1 - Engage effectively in a range of collaborative discussions (one-on-one, in groups, and teacher-led) with diverse partners on grade 3 topics and texts, building on others' ideas and expressing their own clearly. * SL.3.3 - Ask and answer questions about information from a speaker, offering appropriate elaboration and detail. * L.3.6 - Acquire and use accurately grade-appropriate conversational, general academic, and domain-specific words and phrases, including those that signal spatial and temporal relationships. [/standards] [/content] <link rel="stylesheet" type="text/css" href="../docs/morestyle.css" />
package edu.isi.karma.controller.command.importdata; /** * Class <API key> * * @since 01/22/2014 */ enum <API key> { generatePreview, importTable, generateFilter }
using System; using System.Threading; using System.Collections.Concurrent; using System.Threading.Tasks; using Couchbase.Lite.Util; namespace Couchbase.Lite { public class <API key> : <API key>, IDisposable { private const string Tag = "<API key>"; private readonly Thread _thread; private readonly BlockingCollection<Task> _postQueue; private readonly <API key> _cts = new <API key>(); public bool CanReceive { get { return !_postQueue.IsAddingCompleted; } } public <API key>(String name) { _postQueue = new BlockingCollection<Task>(); _thread = new Thread(Run) { Name = name, IsBackground = true, Priority = ThreadPriority.Highest }; _thread.Start(); } public override void Post(SendOrPostCallback d, object state) { // Push into a queue. _postQueue.TryAdd(new Task(() => d(state))); } public override void Send(SendOrPostCallback d, object state) { Task t = new Task(() => d(state)); _postQueue.TryAdd(t); t.Wait(); if (t.Exception != null) throw t.Exception; } void Run() { Task nextTask; try { while (!_postQueue.IsCompleted && _postQueue.TryTake(out nextTask, -1, _cts.Token)) { nextTask.Start(); } } catch(<API key>) { } Log.V(Tag, "Consumer thread finished"); } internal int QueueLength { get { return _postQueue.Count; } } #region IDisposable implementation <summary> Releases all resource used by the <see cref="Couchbase.Lite.Shared.<API key>"/> object. </summary> <remarks>Call <see cref="Dispose"/> when you are finished using the <see cref="Couchbase.Lite.Shared.<API key>"/>. The <see cref="Dispose"/> method leaves the <see cref="Couchbase.Lite.Shared.<API key>"/> in an unusable state. After calling <see cref="Dispose"/>, you must release all references to the <see cref="Couchbase.Lite.Shared.<API key>"/> so the garbage collector can reclaim the memory that the <see cref="Couchbase.Lite.Shared.<API key>"/> was occupying.</remarks> public void Dispose() { if (!_postQueue.IsAddingCompleted) { _cts.Cancel(); _postQueue.CompleteAdding(); } } #endregion } }
# defbrowser.pl # Get default browser information - check #1 can apply to HKLM # as well as to HKCU # Change History: # 20091116 - Added Check #1 # 20081105 - created package defbrowser; use strict; my %config = (hive => "Software", osmask => 22, hasShortDescr => 1, hasDescr => 0, hasRefs => 0, version => 20091116); sub getConfig{return %config} sub getShortDescr { return "Gets default browser setting from HKLM"; } sub getDescr{} sub getRefs {} sub getHive {return $config{hive};} sub getVersion {return $config{version};} my $VERSION = getVersion(); sub pluginmain { my $class = shift; my $hive = shift; ::logMsg("Launching defbrowser v.".$VERSION); ::rptMsg("defbrowser v.".$VERSION); # banner ::rptMsg("(".$config{hive}.") ".getShortDescr()."\n"); # banner my $reg = Parse::Win32Registry->new($hive); my $root_key = $reg->get_root_key; my $key_path = "Clients\\StartMenuInternet"; if (my $key = $root_key->get_subkey($key_path)) { ::rptMsg("Default Browser Check ::rptMsg($key_path); ::rptMsg("LastWrite Time ".gmtime($key->get_timestamp())." (UTC)"); ::rptMsg(""); my $browser = $key->get_value("")->get_data(); ::rptMsg("Default Browser : ".$browser); } else { ::rptMsg($key_path." not found."); } ::rptMsg(""); my $key_path = "Classes\\HTTP\\shell\\open\\command"; my $key; if ($key = $root_key->get_subkey($key_path)) { ::rptMsg("Default Browser Check ::rptMsg($key_path); ::rptMsg("LastWrite Time ".gmtime($key->get_timestamp())." (UTC)"); ::rptMsg(""); my $browser; eval { $browser = $key->get_value("")->get_data(); }; if ($@) { ::rptMsg("Error locating default browser setting."); } else { ::rptMsg("Default Browser = ".$browser); } } else { ::rptMsg($key_path." not found."); } } 1;
cask :v1 => 'slic3r' do version '1.1.7' sha256 '<SHA256-like>' url "http://dl.slic3r.org/mac/slic3r-osx-uni-#{version.gsub('.', '-')}-stable.dmg" homepage 'http://slic3r.org/' license :unknown app 'Slic3r.app' end
cask 'wireshark' do version '2.2.5' sha256 '<SHA256-like>' url "https://www.wireshark.org/download/osx/Wireshark%20#{version}%20Intel%2064.dmg" appcast 'https: checkpoint: '<SHA256-like>' name 'Wireshark' homepage 'https: depends_on macos: '>= :mountain_lion' pkg "Wireshark #{version} Intel 64.pkg" postflight do system_command '/usr/sbin/dseditgroup', args: [ '-o', 'edit', '-a', Etc.getpwuid(Process.euid).name, '-t', 'user', '--', 'access_bpf' ], sudo: true end uninstall script: { executable: '/usr/sbin/dseditgroup', args: ['-o', 'delete', 'access_bpf'], sudo: true, }, pkgutil: 'org.wireshark.*', delete: [ '/usr/local/bin/capinfos', '/usr/local/bin/dftest', '/usr/local/bin/dumpcap', '/usr/local/bin/editcap', '/usr/local/bin/mergecap', '/usr/local/bin/randpkt', '/usr/local/bin/rawshark', '/usr/local/bin/text2pcap', '/usr/local/bin/tshark', '/usr/local/bin/wireshark', ] end
cask "lockrattler" do version "4.26,2020.07" sha256 "<SHA256-like>" # eclecticlightdotcom.files.wordpress.com/ was verified as official when first introduced to the cask url "https://eclecticlightdotcom.files.wordpress.com/#{version.after_comma.major}/#{version.after_comma.minor}/lockrattler#{version.before_comma.no_dots}.zip" appcast "https: name "Lock Rattler" desc "Checks security systems and reports issues" homepage "https://eclecticlight.co/" depends_on macos: ">= :el_capitan" app "lockrattler#{version.before_comma.major}#{version.before_comma.minor}/LockRattler.app" zap trash: [ "~/Library/Caches/co.eclecticlight.LockRattler", "~/Library/Preferences/co.eclecticlight.LockRattler.plist", "~/Library/Saved Application State/co.eclecticlight.LockRattler.savedState", ] end
class Luabind < Formula desc "Library for bindings between C++ and Lua" homepage "https://github.com/luabind/luabind" url "https://downloads.sourceforge.net/project/luabind/luabind/0.9.1/luabind-0.9.1.tar.gz" sha256 "<SHA256-like>" revision 2 bottle do cellar :any sha256 "<SHA256-like>" => :mojave sha256 "<SHA256-like>" => :high_sierra sha256 "<SHA256-like>" => :sierra sha256 "<SHA256-like>" => :el_capitan sha256 "<SHA256-like>" => :yosemite end depends_on "boost-build" => :build depends_on "boost" depends_on "lua@5.1" # boost 1.57 compatibility patch do url "https://gist.githubusercontent.com/tdsmith/<API key>/raw/<SHA1-like>/luabind.diff" sha256 "<SHA256-like>" end # patch Jamroot to perform lookup for shared objects with .dylib suffix patch do url "https://gist.githubusercontent.com/DennisOSRM/3728987/raw/<SHA1-like>/Jamroot.diff" sha256 "<SHA256-like>" end # apply upstream commit to enable building with clang patch do url "https://github.com/luabind/luabind/commit/<SHA1-like>.diff?full_index=1" sha256 "<SHA256-like>" end # include C header that is not pulled in automatically on OS X 10.9 anymore patch do url "https://gist.githubusercontent.com/DennisOSRM/<API key>/raw/<SHA1-like>/object_rep.diff" sha256 "<SHA256-like>" end def install ENV["LUA_PATH"] = Formula["lua@5.1"].opt_prefix args = %w[release install] if ENV.compiler == :clang args << "--toolset=clang" elsif ENV.compiler == :gcc args << "--toolset=darwin" end args << "--prefix=#{prefix}" system "bjam", *args (lib/"pkgconfig/luabind.pc").write pc_file end def pc_file <<~EOS prefix=#{HOMEBREW_PREFIX} exec_prefix=${prefix} libdir=${exec_prefix}/lib includedir=${exec_prefix}/include Name: luabind Description: Library for bindings between C++ and Lua Version: 0.9.1 Libs: -L${libdir} -lluabind Cflags: -I${includedir} EOS end test do (testpath/"hello.cpp").write <<~EOS extern "C" { #include <lua.h> } #include <iostream> #include <luabind/luabind.hpp> void greet() { std::cout << "hello world!\\n"; } extern "C" int init(lua_State* L) { using namespace luabind; open(L); module(L) [ def("greet", &greet) ]; return 0; } EOS system ENV.cxx, "-shared", "hello.cpp", "-o", "hello.dylib", "-I#{Formula["lua@5.1"].include}/lua-5.1", "-L#{lib}", "-lluabind", "-L#{Formula["lua@5.1"].lib}", "-llua5.1" output = `lua5.1 -e "package.loadlib('#{testpath}/hello.dylib', 'init')(); greet()"` assert_match "hello world!", output end end
local dkim_space = 0 local from_space = 1 local envfrom_space = 2 local sender_ip_space = 3 local <API key> = 4 local field_last = 4 local field_count = 10 local timeout = 0.006 local max_attempts = 5 local <API key> = { host='127.0.0.1', port=33013, reconnect_interval=0, update_interval=60, space=1} local function increment_stat3(space, key, subject, timestamp) local retry = true local count = 0 while retry do local status, result = pcall(box.update, space, key, '=p', field_last, timestamp) if status then --success update or tuple is not exist retry = false if result == nil then --insert new tuple local tuple = {} for i = 2, field_last do tuple[i] = 0 end tuple[1] = string.sub(key, -8) tuple[2] = subject tuple[3] = timestamp tuple[4] = timestamp box.insert(space, key, unpack(tuple)) end else --exception count = count + 1 if count == max_attempts then print("max attempts reached for space="..space.." key="..key) break end box.fiber.sleep(timeout) end end end -- BEG deprecated interface function increment_or_insert(space, key, field) if tostring(space) == '5' then return end local retry = true local count = 0 while retry do local status, result = pcall(box.update, space, key, '+p', field, 1) if status then --success update or tuple is not exist retry = false if result == nil then --insert new tuple local tuple = {} for i = 2, field_count do tuple[i] = 0 end tuple[1] = string.sub(key, -8) tuple[tonumber(field)] = 1 box.insert(space, key, unpack(tuple)) end else --exception count = count + 1 if count == max_attempts then print("max attempts reached for space="..space.." key="..key.." field="..field) break end box.fiber.sleep(timeout) end end end function <API key>(space, key, field, element1, element2) if tostring(space) == '5' then return end local retry = true local count = 0 while retry do local status, result = pcall(box.update, space, key, '+p', field, 1) if status then --success update or tuple is not exist retry = false if result == nil then --insert new tuple local tuple = {} for i = 2, field_count + 2 do tuple[i] = 0 end tuple[1] = string.sub(key, -8) tuple[tonumber(field)] = 1 tuple[field_count + 1] = element1 tuple[field_count + 2] = element2 box.insert(space, key, unpack(tuple)) end else --exception count = count + 1 if count == max_attempts then print("max attempts reached for space="..space.." key="..key.." field="..field) break end box.fiber.sleep(timeout) end end end function update_or_insert(space, key, subject, timestamp) if tostring(space) == '5' then return end increment_stat3(space, key, subject, timestamp) end -- END deprecated interface local function increment_stat(space, key, users, spam_users, prob_spam_users, inv_users) local retry = true local count = 0 while retry do local status, result = pcall(box.update, space, key, '+p+p+p+p', 2, users, 3, spam_users, 4, prob_spam_users, 5, inv_users) if status then --success update or tuple is not exist retry = false if result == nil then --insert new tuple local tuple = {} for i = 2, field_count do tuple[i] = 0 end tuple[1] = string.sub(key, -8) tuple[2] = users tuple[3] = spam_users tuple[4] = prob_spam_users tuple[5] = inv_users box.insert(space, key, unpack(tuple)) end else --exception count = count + 1 if count == max_attempts then print("max attempts reached for space="..space.." key="..key) break end box.fiber.sleep(timeout) end end end local function fetch_blacklist(conn, space) assert(conn:timeout(1):ping(), "Tarantool is unreachable") local response = {conn:select_range(space, 0, 9000)} print("Fetched "..#response.." rows from space "..space) local blacklist = {} for i = 1, #response do local domain = response[i][0] blacklist[domain] = true end return blacklist end local blacklist = {} box.fiber.wrap(function () local tnt = <API key> print("New Connect to tarantool "..tnt.host..":"..tnt.port) local conn = box.net.box.new(tnt.host, tnt.port, tnt.reconnect_interval) while true do print("Update blacklist") local ok, result = pcall(fetch_blacklist, conn, tnt.space) if ok then blacklist = result print("Blacklist updated") else -- exception print("Update failed. Reason: "..result) end box.fiber.sleep(tnt.update_interval) end end) function mstat_add( msgtype, sender_ip, from_domain, envfrom_domain, dkim_domain, subject, users, spam_users, prob_spam_users, inv_users, timestamp) users = box.unpack('i', users) spam_users = box.unpack('i', spam_users) prob_spam_users = box.unpack('i', prob_spam_users) inv_users = box.unpack('i', inv_users) timestamp = box.unpack('i', timestamp) local time_str = os.date("_%d_%m_%y", timestamp) -- Collect DKIM domains -- Multiple DKIM format: dkim_domain == '"mail.ru","bk.ru"' -- Single DKIM format: dkim_domain == 'mail.ru' local dkim_domains = {} if dkim_domain:sub(1, 1) == '"' and dkim_domain:sub(-1, -1) == '"' then local sep = "," local pattern = string.format("([^%s]+)", sep) dkim_domain:gsub(pattern, function(c) dkim_domains[#dkim_domains+1] = c:sub(2, -2) end) else dkim_domains[1] = dkim_domain end -- Check every DKIM for blacklist for i = 1, #dkim_domains do if blacklist[dkim_domains[i]] == true then print("DKIM:"..dkim_domains[i].." is blacklisted") return end end -- Update statistics if envfrom_domain ~= "" then increment_stat(envfrom_space, envfrom_domain..time_str, users, spam_users, prob_spam_users, inv_users) end if from_domain ~= "" then increment_stat(from_space, from_domain..time_str, users, spam_users, prob_spam_users, inv_users) end for i = 1, #dkim_domains do if dkim_domains[i] ~= "" then increment_stat(dkim_space, dkim_domains[i]..time_str, users, spam_users, prob_spam_users, inv_users) end end if sender_ip ~= "" then increment_stat(sender_ip_space, sender_ip..time_str, users, spam_users, prob_spam_users, inv_users) end for i = 1, #dkim_domains do if dkim_domains[i] ~= "" and msgtype ~= "" then local element = dkim_domains[i]..":"..msgtype..time_str increment_stat(dkim_space, element, users, spam_users, prob_spam_users, inv_users) if subject == "" then subject = " " end increment_stat3(<API key>, element, subject, timestamp) end end end
<?php abstract class <API key> extends Kwf_Test_TestCase { protected $_hubApp; protected $_hubUrl; protected $_testId; protected $_testFeedUrl; private $_storePath; private $_pipes; public function setUp() { parent::setUp(); $debugOutput = false; //echo "setUp\n"; $this->_storePath = tempnam('/tmp', 'pshb'); unlink($this->_storePath); mkdir($this->_storePath); //echo "startHub\n"; $this->_startHub($debugOutput); //echo "test hub\n"; try { $c = file_get_contents($this->_hubUrl); $this->assertContains('Welcome to the demo PubSubHubbub reference Hub server', $c); //echo "OK\n"; } catch (Exception $e) { $this->fail("Failed starting hub, output: ".stream_get_contents($this->_pipes[1])); } //echo "write test feed\n"; $this->_testId = rand(0, 1000000); touch('/tmp/lastCallback'.$this->_testId); file_put_contents('/tmp/feedRequested'.$this->_testId, 0); $domain = Kwf_Registry::get('config')->server->domain; $urlPrefix = 'http://'.$domain.'/kwf/test'; $this->_testFeedUrl = $urlPrefix.'/<API key>?id='.$this->_testId; $this-><API key>(1); } private function _startHub($debugOutput) { $descriptorspec = array(); if ($debugOutput) { $descriptorspec = array( 1 => STDOUT, 2 => STDOUT ); } else { $descriptorspec = array( 1 => array('pipe', 'w'), 2 => STDOUT //should be empty ); } $address = trim(`hostname`); if ($address == 'vivid-test-server') { $d = "/var/www/library/pshb/"; } else { $d = "/www/public/library/pshb/"; } if (!file_exists("{$d}google_appengine/dev_appserver.py")) { $this->markTestSkipped("pshb server not available"); } $port = Kwf_Util_Tcp::getFreePort(8000, $address); $cmd = "python2.5 {$d}google_appengine/dev_appserver.py {$d}pubsubhubbub/hub/ ". "--port=$port --address=$address --clear_datastore ". "--datastore_path=$this->_storePath/dev_appserver.datastore ". "--history_path=$this->_storePath/dev_appserver.datastore.history". " 2>&1"; if ($debugOutput) echo "$cmd\n"; $this->_hubApp = proc_open($cmd, $descriptorspec, $this->_pipes); $this->assertTrue(is_resource($this->_hubApp)); $this->_hubUrl = "http://$address:$port"; sleep(10); $status = proc_get_status($this->_hubApp); if (!$status['running']) { throw new Kwf_Exception('can\'t start pshb server'); } } public function tearDown() { //echo "\n".date('H:i:s')."tearDown\n"; $start = time(); $status = proc_get_status($this->_hubApp); //echo "\nsending SIGINT to hub\n"; posix_kill($status['pid'], SIGINT); posix_kill($status['pid']+1, SIGINT); //+1 weil sh prozess python startet do { //echo "waiting while running\n"; if (time() - $start > 30) { //echo "\nsending SIGKILL to hub\n"; proc_terminate($this->_hubApp, SIGKILL); break; } $status = proc_get_status($this->_hubApp); if ($status['running']) sleep(1); } while ($status['running']); sleep(5); //echo "removing datastore\n"; system("rm -r $this->_storePath"); //echo "removing feeds\n"; unlink('/tmp/feed'.$this->_testId); unlink('/tmp/lastCallback'.$this->_testId); unlink('/tmp/feedRequested'.$this->_testId); parent::tearDown(); } protected function assertFeedRequested($num) { $this->assertEquals($num, file_get_contents('/tmp/feedRequested'.$this->_testId)); } protected function <API key>($entries, $advertiseHub = true) { file_put_contents('/tmp/feed'.$this->_testId, $this->_getTestFeedContent($entries, $advertiseHub)); } protected function <API key>() { $p = new <API key>($this->_hubUrl.'/'); $p->publishUpdate($this->_testFeedUrl); } protected function _getTestFeedContent($entries, $advertiseHub = true) { $ret = '<feed xmlns="http: <title>niko\'s stream</title> '; if ($advertiseHub) { $ret .= ' <link rel="hub" href="'.htmlspecialchars($this->_hubUrl).'/" /> '; } $ret .= ' <id>'.htmlspecialchars($this->_testFeedUrl).'</id> <author><name>niko</name></author> '; for ($i=$entries;$i>0;$i $ret .= ' <entry> <title>blub'.$i.'</title> <id>'.htmlspecialchars($this->_testFeedUrl).'/'.$i.'</id> <link href="'.htmlspecialchars($this->_testFeedUrl).'/'.$i.'" /> <summary>bleb'.$i.'</summary> <updated>2009-10-0'.($i).'T10:23:24+01:00</updated> </entry>'; } $ret .= ' </feed>'; return $ret; } protected function _runHubTasks($queue) { $tasks = file_get_contents($this->_hubUrl.'/_ah/admin/tasks?queue='.$queue); if (preg_match_all('#<form id="runform\\..*?" action="(.*?)" .*?</form>#s', $tasks, $tasks)) { foreach ($tasks[0] as $taskKey => $t) { $client = new Zend_Http_Client($this->_hubUrl.$tasks[1][$taskKey]); $client->setMethod(Zend_Http_Client::POST); $headers = array(); $taskName = false; preg_match_all('#<input type="hidden"\s*name="(.*?)"\s*value="(.*?)"\s*/?>#', $t, $m); foreach (array_keys($m[0]) as $i) { $name = $m[1][$i]; $value = $m[2][$i]; if (substr($name, 0, 7)=='header:') { $name = substr($name, 7); $client->setHeaders($name, $value); if ($name == '<API key>') $taskName = $value; } else if ($name == 'payload') { $client->setRawData($value); } } $response = $client->request(); if ($response->getStatus() != 200) { throw new Kwf_Exception("$mode failed, response status '{$response->getStatus()}' '{$response->getBody()}'"); } $client = new Zend_Http_Client($this->_hubUrl.'/_ah/admin/tasks'); $client->setMethod(Zend_Http_Client::POST); $client->setParameterPost(array( 'queue' => $queue, 'task' => $taskName, 'action:deletetask' => true )); $response = $client->request(); if ($response->getStatus() != 200) { throw new Kwf_Exception("$mode failed, response status '{$response->getStatus()}' '{$response->getBody()}'"); } } } } }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html><head><meta http-equiv="Content-Type" content="text/html;charset=UTF-8"> <title>Kazmath: /ich/Programmieren/KazadeEngine/NeHeKazmath/kazmath/src/aabb.h File Reference</title> <link href="doxygen.css" rel="stylesheet" type="text/css"> <link href="tabs.css" rel="stylesheet" type="text/css"> </head><body> <!-- Generated by Doxygen 1.5.6 --> <div class="navigation" id="top"> <div class="tabs"> <ul> <li><a href="index.html"><span>Main&nbsp;Page</span></a></li> <li><a href="namespaces.html"><span>Namespaces</span></a></li> <li><a href="annotated.html"><span>Data&nbsp;Structures</span></a></li> <li class="current"><a href="files.html"><span>Files</span></a></li> </ul> </div> </div> <div class="contents"> <h1>/ich/Programmieren/KazadeEngine/NeHeKazmath/kazmath/src/aabb.h File Reference</h1><code>#include &quot;<a class="el" href="vec3_8h-source.html">vec3.h</a>&quot;</code><br> <code>#include &quot;<a class="el" href="utility_8h-source.html">utility.h</a>&quot;</code><br> <p> <a href="aabb_8h-source.html">Go to the source code of this file.</a><table border="0" cellpadding="0" cellspacing="0"> <tr><td></td></tr> <tr><td colspan="2"><br><h2>Data Structures</h2></td></tr> <tr><td class="memItemLeft" nowrap align="right" valign="top">struct &nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="structkm_a_a_b_b.html">kmAABB</a></td></tr> <tr><td colspan="2"><br><h2>Functions</h2></td></tr> <tr><td class="memItemLeft" nowrap align="right" valign="top">int&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="aabb_8h.html#<API key>">kmAABBPointInBox</a> (const <a class="el" href="structkm_vec3.html">kmVec3</a> *pPoint, const <a class="el" href="structkm_a_a_b_b.html">kmAABB</a> *pBox)</td></tr> <tr><td class="memItemLeft" nowrap align="right" valign="top"><a class="el" href="structkm_a_a_b_b.html">kmAABB</a> *&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="aabb_8h.html#<API key>">kmAABBAssign</a> (<a class="el" href="structkm_a_a_b_b.html">kmAABB</a> *pOut, const <a class="el" href="structkm_a_a_b_b.html">kmAABB</a> *pIn)</td></tr> <tr><td class="memItemLeft" nowrap align="right" valign="top"><a class="el" href="structkm_a_a_b_b.html">kmAABB</a> *&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="aabb_8h.html#<API key>">kmAABBScale</a> (<a class="el" href="structkm_a_a_b_b.html">kmAABB</a> *pOut, const <a class="el" href="structkm_a_a_b_b.html">kmAABB</a> *pIn, kmScalar s)</td></tr> </table> <hr><h2>Function Documentation</h2> <a class="anchor" name="<API key>"></a><!-- doxytag: member="aabb.h::kmAABBAssign" ref="<API key>" args="(kmAABB *pOut, const kmAABB *pIn)" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname"><a class="el" href="structkm_a_a_b_b.html">kmAABB</a>* kmAABBAssign </td> <td>(</td> <td class="paramtype"><a class="el" href="structkm_a_a_b_b.html">kmAABB</a> *&nbsp;</td> <td class="paramname"> <em>pOut</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">const <a class="el" href="structkm_a_a_b_b.html">kmAABB</a> *&nbsp;</td> <td class="paramname"> <em>pIn</em></td><td>&nbsp;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td><td></td> </tr> </table> </div> <div class="memdoc"> <p> Assigns pIn to pOut, returns pOut. <p>Definition at line <a class="el" href="aabb_8c-source.html#l00041">41</a> of file <a class="el" href="aabb_8c-source.html">aabb.c</a>.</p> </div> </div><p> <a class="anchor" name="<API key>"></a><!-- doxytag: member="aabb.h::kmAABBPointInBox" ref="<API key>" args="(const kmVec3 *pPoint, const kmAABB *pBox)" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">int kmAABBPointInBox </td> <td>(</td> <td class="paramtype">const <a class="el" href="structkm_vec3.html">kmVec3</a> *&nbsp;</td> <td class="paramname"> <em>pPoint</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">const <a class="el" href="structkm_a_a_b_b.html">kmAABB</a> *&nbsp;</td> <td class="paramname"> <em>pBox</em></td><td>&nbsp;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td><td></td> </tr> </table> </div> <div class="memdoc"> <p> Returns KM_TRUE if point is in the specified AABB, returns KM_FALSE otherwise. <p>Definition at line <a class="el" href="aabb_8c-source.html#l00032">32</a> of file <a class="el" href="aabb_8c-source.html">aabb.c</a>.</p> <p>References <a class="el" href="utility_8h-source.html#l00036">KM_FALSE</a>.</p> </div> </div><p> <a class="anchor" name="<API key>"></a><!-- doxytag: member="aabb.h::kmAABBScale" ref="<API key>" args="(kmAABB *pOut, const kmAABB *pIn, kmScalar s)" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname"><a class="el" href="structkm_a_a_b_b.html">kmAABB</a>* kmAABBScale </td> <td>(</td> <td class="paramtype"><a class="el" href="structkm_a_a_b_b.html">kmAABB</a> *&nbsp;</td> <td class="paramname"> <em>pOut</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">const <a class="el" href="structkm_a_a_b_b.html">kmAABB</a> *&nbsp;</td> <td class="paramname"> <em>pIn</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">kmScalar&nbsp;</td> <td class="paramname"> <em>s</em></td><td>&nbsp;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td><td></td> </tr> </table> </div> <div class="memdoc"> <p> Scales pIn by s, stores the resulting AABB in pOut. Returns pOut <p>Definition at line <a class="el" href="aabb_8c-source.html#l00050">50</a> of file <a class="el" href="aabb_8c-source.html">aabb.c</a>.</p> </div> </div><p> </div> <hr size="1"><address style="text-align: right;"><small>Generated on Mon Dec 29 18:40:11 2008 for Kazmath by&nbsp; <a href="http: <img src="doxygen.png" alt="doxygen" align="middle" border="0"></a> 1.5.6 </small></address> </body> </html>
cask :v1 => 'diskmaker-x' do version '4b4' sha256 '<SHA256-like>' url "http://diskmakerx.com/downloads/DiskMakerX#{version}.dmg" homepage 'http://diskmakerx.com/' license :unknown app "DiskMaker X #{version}.app" end
<?php class <API key> extends Kwf_Component_Data { public function __get($var) { if ($var == 'url' || $var == 'rel') { return $this->getChildComponent('_video')->$var; } else { return parent::__get($var); } } }
#include "content/browser/frame_host/navigator_impl.h" #include <utility> #include "base/metrics/histogram.h" #include "base/time/time.h" #include "content/browser/frame_host/frame_tree.h" #include "content/browser/frame_host/frame_tree_node.h" #include "content/browser/frame_host/<API key>.h" #include "content/browser/frame_host/<API key>.h" #include "content/browser/frame_host/<API key>.h" #include "content/browser/frame_host/navigation_request.h" #include "content/browser/frame_host/<API key>.h" #include "content/browser/frame_host/navigator_delegate.h" #include "content/browser/frame_host/<API key>.h" #include "content/browser/renderer_host/<API key>.h" #include "content/browser/site_instance_impl.h" #include "content/browser/webui/<API key>.h" #include "content/browser/webui/web_ui_impl.h" #include "content/common/frame_messages.h" #include "content/common/navigation_params.h" #include "content/common/<API key>.h" #include "content/common/view_messages.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/<API key>.h" #include "content/public/browser/global_request_id.h" #include "content/public/browser/invalidate_type.h" #include "content/public/browser/<API key>.h" #include "content/public/browser/navigation_details.h" #include "content/public/browser/page_navigator.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/stream_handle.h" #include "content/public/browser/user_metrics.h" #include "content/public/common/bindings_policy.h" #include "content/public/common/<API key>.h" #include "content/public/common/content_client.h" #include "content/public/common/content_constants.h" #include "content/public/common/resource_response.h" #include "content/public/common/url_constants.h" #include "net/base/net_errors.h" namespace content { namespace { <API key>::Value GetNavigationType( BrowserContext* browser_context, const NavigationEntryImpl& entry, <API key>::ReloadType reload_type) { switch (reload_type) { case <API key>::RELOAD: return <API key>::RELOAD; case <API key>::<API key>: case <API key>::<API key>: return <API key>::<API key>; case <API key>::<API key>: return <API key>::<API key>; case <API key>::NO_RELOAD: break; // Fall through to rest of function. } // |RenderViewImpl::<API key>| differentiates // between |RESTORE_WITH_POST| and |RESTORE|. if (entry.restore_type() == NavigationEntryImpl::<API key>) { if (entry.GetHasPostData()) return <API key>::RESTORE_WITH_POST; return <API key>::RESTORE; } return <API key>::NORMAL; } } // namespace struct NavigatorImpl::<API key> { <API key>(base::TimeTicks start_time, GURL url, NavigationEntryImpl::RestoreType restore_type) : start_time_(start_time), url_(url) { <API key> = (restore_type == NavigationEntryImpl::<API key> || restore_type == NavigationEntryImpl::<API key>); } base::TimeTicks start_time_; GURL url_; bool <API key>; base::TimeTicks url_job_start_time_; base::TimeDelta <API key>; }; NavigatorImpl::NavigatorImpl( <API key>* <API key>, NavigatorDelegate* delegate) : controller_(<API key>), delegate_(delegate) { } NavigatorImpl::~NavigatorImpl() {} NavigatorDelegate* NavigatorImpl::GetDelegate() { return delegate_; } <API key>* NavigatorImpl::GetController() { return controller_; } void NavigatorImpl::<API key>( RenderFrameHostImpl* render_frame_host, const GURL& url, const base::TimeTicks& navigation_start) { bool is_main_frame = render_frame_host->frame_tree_node()->IsMainFrame(); bool is_error_page = (url.spec() == <API key>); bool is_iframe_srcdoc = (url.spec() == kAboutSrcDocURL); GURL validated_url(url); RenderProcessHost* render_process_host = render_frame_host->GetProcess(); render_process_host->FilterURL(false, &validated_url); if (is_main_frame && !is_error_page) { <API key>(validated_url, render_frame_host->GetSiteInstance()); } if (delegate_) { // Notify the observer about the start of the provisional load. delegate_-><API key>(render_frame_host, validated_url, is_error_page, is_iframe_srcdoc); } if (is_error_page || <API key>()) return; if (render_frame_host->navigation_handle()) { if (render_frame_host->navigation_handle()->is_transferring()) { // If the navigation is completing a transfer, this // <API key> should not correspond to a new navigation. DCHECK_EQ(url, render_frame_host->navigation_handle()->GetURL()); render_frame_host->navigation_handle()->set_is_transferring(false); return; } // This ensures that notifications about the end of the previous // navigation are sent before notifications about the start of the // new navigation. render_frame_host->SetNavigationHandle(scoped_ptr<<API key>>()); } render_frame_host->SetNavigationHandle(<API key>::Create( validated_url, render_frame_host->frame_tree_node(), navigation_start)); } void NavigatorImpl::<API key>( RenderFrameHostImpl* render_frame_host, const <API key>& params) { VLOG(1) << "Failed Provisional Load: " << params.url.<API key>() << ", error_code: " << params.error_code << ", error_description: " << params.error_description << ", <API key>: " << params.<API key> << ", frame_id: " << render_frame_host->GetRoutingID(); GURL validated_url(params.url); RenderProcessHost* render_process_host = render_frame_host->GetProcess(); render_process_host->FilterURL(false, &validated_url); if (net::ERR_ABORTED == params.error_code) { // EVIL HACK ALERT! Ignore failed loads when we're showing interstitials. // This means that the interstitial won't be torn down properly, which is // bad. But if we have an interstitial, go back to another tab type, and // then load the same interstitial again, we could end up getting the first // interstitial's "failed" message (as a result of the cancel) when we're on // the second one. We can't tell this apart, so we think we're tearing down // the current page which will cause a crash later on. // Because this will not tear down the interstitial properly, if "back" is // back to another tab type, the interstitial will still be somewhat alive // in the previous tab type. If you navigate somewhere that activates the // tab with the interstitial again, you'll see a flash before the new load // commits of the interstitial page. FrameTreeNode* root = render_frame_host->frame_tree_node()->frame_tree()->root(); if (root->render_manager()->interstitial_page() != NULL) { LOG(WARNING) << "Discarding message during interstitial."; return; } // We used to cancel the pending renderer here for cross-site downloads. // However, it's not safe to do that because the download logic repeatedly // looks for this WebContents based on a render ID. Instead, we just // leave the pending renderer around until the next navigation event // (Navigate, DidNavigate, etc), which will clean it up properly. // TODO(creis): Find a way to cancel any pending RFH here. } // We usually clear the pending entry when it fails, so that an arbitrary URL // isn't left visible above a committed page. This must be enforced when // the pending entry isn't visible (e.g., renderer-initiated navigations) to // prevent URL spoofs for in-page navigations that don't go through // <API key>. // However, we do preserve the pending entry in some cases, such as on the // initial navigation of an unmodified blank tab. We also allow the delegate // to say when it's safe to leave aborted URLs in the omnibox, to let the user // edit the URL and try again. This may be useful in cases that the committed // page cannot be attacker-controlled. In these cases, we still allow the // view to clear the pending entry and typed URL if the user requests // (e.g., hitting Escape with focus in the address bar). // Note: don't touch the transient entry, since an interstitial may exist. bool <API key> = controller_-><API key>() || delegate_-><API key>(); if (controller_->GetPendingEntry() != controller_->GetVisibleEntry() || !<API key>) { controller_->DiscardPendingEntry(true); // Also force the UI to refresh. controller_->delegate()-><API key>(INVALIDATE_TYPE_URL); } if (delegate_) delegate_-><API key>(render_frame_host, params); } void NavigatorImpl::<API key>( RenderFrameHostImpl* render_frame_host, const GURL& url, int error_code, const base::string16& error_description, bool <API key>) { if (delegate_) { delegate_-><API key>( render_frame_host, url, error_code, error_description, <API key>); } } bool NavigatorImpl::NavigateToEntry( FrameTreeNode* frame_tree_node, const <API key>& frame_entry, const NavigationEntryImpl& entry, <API key>::ReloadType reload_type, bool <API key>, bool is_pending_entry) { TRACE_EVENT0("browser,navigation", "NavigatorImpl::NavigateToEntry"); GURL dest_url = frame_entry.url(); Referrer dest_referrer = frame_entry.referrer(); if (reload_type == <API key>::ReloadType::<API key> && entry.<API key>().is_valid() && !entry.GetHasPostData()) { // We may have been redirected when navigating to the current URL. // Use the URL the user originally intended to visit, if it's valid and if a // POST wasn't involved; the latter case avoids issues with sending data to // the wrong page. dest_url = entry.<API key>(); dest_referrer = Referrer(); } // Don't attempt to navigate to non-empty invalid URLs. if (!dest_url.is_valid() && !dest_url.is_empty()) { LOG(WARNING) << "Refusing to load invalid URL: " << dest_url.<API key>(); return false; } // The renderer will reject IPC messages with URLs longer than // this limit, so don't attempt to navigate with a longer URL. if (dest_url.spec().size() > kMaxURLChars) { LOG(WARNING) << "Refusing to load URL as it exceeds " << kMaxURLChars << " characters."; return false; } // This will be used to set the Navigation Timing API navigationStart // parameter for browser navigations in new tabs (intents, tabs opened through // "Open link in new tab"). We need to keep it above RFHM::Navigate() call to // capture the time needed for the RenderFrameHost initialization. base::TimeTicks navigation_start = base::TimeTicks::Now(); <API key>( "navigation", "NavigationTiming navigationStart", <API key>, navigation_start.ToInternalValue()); // PlzNavigate: the RenderFrameHosts are no longer asked to navigate. if (<API key>()) { navigation_data_.reset(new <API key>(navigation_start, dest_url, entry.restore_type())); RequestNavigation(frame_tree_node, dest_url, dest_referrer, frame_entry, entry, reload_type, <API key>, navigation_start); if (frame_tree_node->IsMainFrame() && frame_tree_node->navigation_request()) { // TODO(carlosk): extend these traces to support subframes and // non-PlzNavigate navigations. // For these traces below we're using the navigation handle as the async // trace id, |navigation_start| as the timestamp and reporting the // FrameTreeNode id as a parameter. For navigations where no network // request is made (data URLs, JavaScript URLs, etc) there is no handle // and so no tracing is done. <API key>( "navigation", "Navigation timeToNetworkStack", frame_tree_node->navigation_request()->navigation_handle(), navigation_start.ToInternalValue(), "FrameTreeNode id", frame_tree_node->frame_tree_node_id()); <API key>( "navigation", "Navigation timeToCommit", frame_tree_node->navigation_request()->navigation_handle(), navigation_start.ToInternalValue(), "FrameTreeNode id", frame_tree_node->frame_tree_node_id()); } // Notify observers about navigation if this is for the pending entry. if (delegate_ && is_pending_entry) delegate_-><API key>(dest_url, reload_type); return true; } RenderFrameHostImpl* <API key> = frame_tree_node->render_manager()->Navigate(dest_url, frame_entry, entry); if (!<API key>) return false; // Unable to create the desired RenderFrameHost. // Make sure no code called via RFHM::Navigate clears the pending entry. if (is_pending_entry) CHECK_EQ(controller_->GetPendingEntry(), &entry); // For security, we should never send non-Web-UI URLs to a Web UI renderer. // Double check that here. <API key>(<API key>, dest_url); // Navigate in the desired RenderFrameHost. // We can skip this step in the rare case that this is a transfer navigation // which began in the chosen RenderFrameHost, since the request has already // been issued. In that case, simply resume the response. bool is_transfer_to_same = entry.<API key>().child_id != -1 && entry.<API key>().child_id == <API key>->GetProcess()->GetID(); if (!is_transfer_to_same) { navigation_data_.reset(new <API key>(navigation_start, dest_url, entry.restore_type())); // Create the navigation parameters. <API key>::Value navigation_type = GetNavigationType(controller_->GetBrowserContext(), entry, reload_type); LoFiState lofi_state = (reload_type == <API key>::ReloadType::<API key> ? LOFI_OFF : LOFI_UNSPECIFIED); <API key>->Navigate( entry.<API key>(dest_url, dest_referrer, navigation_type, lofi_state, navigation_start), entry.<API key>(), entry.<API key>( frame_entry, <API key>, frame_tree_node-><API key>(), controller_-><API key>() == -1, controller_->GetIndexOfEntry(&entry), controller_-><API key>(), controller_->GetEntryCount())); } else { // No need to navigate again. Just resume the deferred request. <API key>->GetProcess()-><API key>( entry.<API key>()); } // Make sure no code called via RFH::Navigate clears the pending entry. if (is_pending_entry) CHECK_EQ(controller_->GetPendingEntry(), &entry); if (controller_-><API key>() == -1 && dest_url.SchemeIs(url::kJavaScriptScheme)) { // If the pending entry index is -1 (which means a new navigation rather // than a history one), and the user typed in a javascript: URL, don't add // it to the session history. // This is a hack. What we really want is to avoid adding to the history any // URL that doesn't generate content, and what would be great would be if we // had a message from the renderer telling us that a new page was not // created. The same message could be used for mailto: URLs and the like. return false; } // Notify observers about navigation. if (delegate_ && is_pending_entry) delegate_-><API key>(dest_url, reload_type); return true; } bool NavigatorImpl::<API key>( FrameTreeNode* frame_tree_node, const <API key>& frame_entry, <API key>::ReloadType reload_type, bool <API key>) { return NavigateToEntry(frame_tree_node, frame_entry, *controller_->GetPendingEntry(), reload_type, <API key>, true); } bool NavigatorImpl::<API key>( RenderFrameHostImpl* render_frame_host, const std::string& unique_name) { NavigationEntryImpl* entry = controller_-><API key>(render_frame_host->nav_entry_id()); if (!entry) return false; <API key>* frame_entry = entry-><API key>(unique_name); if (!frame_entry) return false; // Update the <API key>'s FrameTreeNode ID (which is currently the // ID of the old FrameTreeNode that no longer exists) to be the ID of the // newly created frame. frame_entry-><API key>( render_frame_host->frame_tree_node()->frame_tree_node_id()); return NavigateToEntry(render_frame_host->frame_tree_node(), *frame_entry, *entry, <API key>::NO_RELOAD, false, false); } void NavigatorImpl::DidNavigate( RenderFrameHostImpl* render_frame_host, const <API key>& params) { FrameTree* frame_tree = render_frame_host->frame_tree_node()->frame_tree(); bool oopifs_possible = SiteIsolationPolicy::<API key>(); bool <API key> = controller_-><API key>( params.url, params.<API key>, render_frame_host); // If a frame claims it navigated within page, it must be the current frame, // not a pending one. if (<API key> && render_frame_host != render_frame_host->frame_tree_node() ->render_manager() ->current_frame_host()) { bad_message::ReceivedBadMessage(render_frame_host->GetProcess(), bad_message::<API key>); <API key> = false; } if (ui::<API key>(params.transition)) { if (delegate_) { // When overscroll navigation gesture is enabled, a screenshot of the page // in its current state is taken so that it can be used during the // nav-gesture. It is necessary to take the screenshot here, before // calling <API key>::<API key>, because that can // change WebContents::GetRenderViewHost to return the new host, instead // of the one that may have just been swapped out. if (delegate_-><API key>()) { // Don't take screenshots if we are staying on the same page. We want // in-page navigations to be super fast, and taking a screenshot // currently blocks GPU for a longer time than we are willing to // tolerate in this use case. if (!params.<API key>) controller_->TakeScreenshot(); } // Run tasks that must execute just before the commit. delegate_-><API key>(<API key>); } if (!oopifs_possible) frame_tree->root()->render_manager()->DidNavigateFrame( render_frame_host, params.gesture == <API key>); } // Save the origin of the new page. Do this before calling // DidNavigateFrame(), because the origin needs to be included in the SwapOut // message, which is sent inside DidNavigateFrame(). SwapOut needs the // origin because it creates a RenderFrameProxy that needs this to initialize // its security context. This origin will also be sent to RenderFrameProxies // created via ViewMsg_New and <API key>. render_frame_host->frame_tree_node()->SetCurrentOrigin(params.origin); render_frame_host->frame_tree_node()-><API key>( params.<API key>); // When using --site-per-process, we notify the RFHM for all navigations, // not just main frame navigations. if (oopifs_possible) { FrameTreeNode* frame = render_frame_host->frame_tree_node(); frame->render_manager()->DidNavigateFrame( render_frame_host, params.gesture == <API key>); } // Update the site of the SiteInstance if it doesn't have one yet, unless // assigning a site is not necessary for this URL. In that case, the // SiteInstance can still be considered unused until a navigation to a real // page. SiteInstanceImpl* site_instance = render_frame_host->GetSiteInstance(); if (!site_instance->HasSite() && <API key>(params.url)) { site_instance->SetSite(params.url); } // Need to update MIME type here because it's referred to in // <API key>() called by RendererDidNavigate() to // determine whether or not to enable the encoding menu. // It's updated only for the main frame. For a subframe, // RenderView::UpdateURL does not set params.contents_mime_type. // TODO(jungshik): Add a test for the encoding menu to avoid // regressing it again. // TODO(nasko): Verify the correctness of the above comment, since some of the // code doesn't exist anymore. Also, move this code in the // <API key> code block above. if (ui::<API key>(params.transition) && delegate_) delegate_-><API key>(params.contents_mime_type); <API key> details; bool did_navigate = controller_->RendererDidNavigate(render_frame_host, params, &details); // Keep track of each frame's URL in its FrameTreeNode. render_frame_host->frame_tree_node()->SetCurrentURL(params.url); if (did_navigate && render_frame_host->frame_tree_node()->IsMainFrame() && <API key>()) { <API key>("navigation", "Navigation timeToCommit", render_frame_host->navigation_handle()); } // Send notification about committed provisional loads. This notification is // different from the NAV_ENTRY_COMMITTED notification which doesn't include // the actual URL navigated to and isn't sent for AUTO_SUBFRAME navigations. if (details.type != <API key> && delegate_) { DCHECK_EQ(!render_frame_host->GetParent(), did_navigate ? details.is_main_frame : false); ui::PageTransition transition_type = params.transition; // Whether or not a page transition was triggered by going backward or // forward in the history is only stored in the navigation controller's // entry list. if (did_navigate && (controller_-><API key>()->GetTransitionType() & ui::<API key>)) { transition_type = ui::<API key>( params.transition | ui::<API key>); } delegate_-><API key>(render_frame_host, params.url, transition_type); render_frame_host->navigation_handle()->DidCommitNavigation( <API key>, render_frame_host); render_frame_host->SetNavigationHandle(nullptr); } if (!did_navigate) return; // No navigation happened. // DO NOT ADD MORE STUFF TO THIS FUNCTION! Your component should either listen // for the appropriate notification (best) or you can add it to // <API key> / <API key> (only if // necessary, please). // TODO(carlosk): Move this out when PlzNavigate implementation properly calls // the observer methods. <API key>(details, params, site_instance); // Run post-commit tasks. if (delegate_) { if (details.is_main_frame) { delegate_-><API key>(render_frame_host, details, params); } delegate_-><API key>( render_frame_host, details, params); } } bool NavigatorImpl::<API key>(const GURL& url) { // about:blank should not "use up" a new SiteInstance. The SiteInstance can // still be used for a normal web site. if (url == GURL(url::kAboutBlankURL)) return false; // The embedder will then have the opportunity to determine if the URL // should "use up" the SiteInstance. return GetContentClient()->browser()-><API key>(url); } void NavigatorImpl::RequestOpenURL(RenderFrameHostImpl* render_frame_host, const GURL& url, SiteInstance* <API key>, const Referrer& referrer, <API key> disposition, bool <API key>, bool user_gesture) { // This call only makes sense for subframes if OOPIFs are possible. DCHECK(!render_frame_host->GetParent() || SiteIsolationPolicy::<API key>()); // If this came from a swapped out RenderFrameHost, we only allow the request // if we are still in the same BrowsingInstance. // TODO(creis): Move this to <API key>::OpenURL. SiteInstance* <API key> = render_frame_host->frame_tree_node() ->current_frame_host() ->GetSiteInstance(); if (render_frame_host->is_swapped_out() && !render_frame_host->GetSiteInstance()-><API key>( <API key>)) { return; } // TODO(creis): Pass the redirect_chain into this method to support client std::vector<GURL> redirect_chain; GURL dest_url(url); if (!GetContentClient()->browser()->ShouldAllowOpenURL( <API key>, url)) { dest_url = GURL(url::kAboutBlankURL); } int frame_tree_node_id = -1; // Send the navigation to the current FrameTreeNode if it's destined for a // subframe in the current tab. We'll assume it's for the main frame // (possibly of a new or different WebContents) otherwise. if (SiteIsolationPolicy::<API key>() && disposition == CURRENT_TAB && render_frame_host->GetParent()) { frame_tree_node_id = render_frame_host->frame_tree_node()->frame_tree_node_id(); } OpenURLParams params(dest_url, referrer, frame_tree_node_id, disposition, ui::<API key>, true /* <API key> */); params.<API key> = <API key>; if (redirect_chain.size() > 0) params.redirect_chain = redirect_chain; params.<API key> = <API key>; params.user_gesture = user_gesture; if (render_frame_host->web_ui()) { // Web UI pages sometimes want to override the page transition type for // link clicks (e.g., so the new tab page can specify AUTO_BOOKMARK for // automatically generated suggestions). We don't override other types // like TYPED because they have different implications (e.g., autocomplete). if (ui::<API key>( params.transition, ui::<API key>)) params.transition = render_frame_host->web_ui()-><API key>(); // Note also that we hide the referrer for Web UI pages. We don't really // want web sites to see a referrer of "chrome://blah" (and some // chrome: URLs might have search terms or other stuff we don't want to // send to the site), so we send no referrer. params.referrer = Referrer(); // Navigations in Web UI pages count as browser-initiated navigations. params.<API key> = false; } if (delegate_) delegate_->RequestOpenURL(render_frame_host, params); } void NavigatorImpl::RequestTransferURL( RenderFrameHostImpl* render_frame_host, const GURL& url, const std::vector<GURL>& redirect_chain, const Referrer& referrer, ui::PageTransition page_transition, const GlobalRequestID& <API key>, bool <API key>) { // This call only makes sense for subframes if OOPIFs are possible. DCHECK(!render_frame_host->GetParent() || SiteIsolationPolicy::<API key>()); // Allow the delegate to cancel the transfer. if (!delegate_-><API key>()) return; GURL dest_url(url); Referrer referrer_to_use(referrer); FrameTreeNode* node = render_frame_host->frame_tree_node(); SiteInstance* <API key> = render_frame_host->GetSiteInstance(); if (!GetContentClient()->browser()->ShouldAllowOpenURL(<API key>, url)) { dest_url = GURL(url::kAboutBlankURL); } // TODO(creis): Determine if this transfer started as a browser-initiated bool <API key> = true; if (render_frame_host->web_ui()) { // Web UI pages sometimes want to override the page transition type for // link clicks (e.g., so the new tab page can specify AUTO_BOOKMARK for // automatically generated suggestions). We don't override other types // like TYPED because they have different implications (e.g., autocomplete). if (ui::<API key>(page_transition, ui::<API key>)) page_transition = render_frame_host->web_ui()-><API key>(); // Note also that we hide the referrer for Web UI pages. We don't really // want web sites to see a referrer of "chrome://blah" (and some // chrome: URLs might have search terms or other stuff we don't want to // send to the site), so we send no referrer. referrer_to_use = Referrer(); // Navigations in Web UI pages count as browser-initiated navigations. <API key> = false; } <API key>::LoadURLParams load_url_params(dest_url); // The <API key> only matters for navigations via RenderFrameProxy, // which go through RequestOpenURL. load_url_params.<API key> = nullptr; load_url_params.transition_type = page_transition; load_url_params.frame_tree_node_id = node->frame_tree_node_id(); load_url_params.referrer = referrer_to_use; load_url_params.redirect_chain = redirect_chain; load_url_params.<API key> = <API key>; load_url_params.<API key> = <API key>; load_url_params.<API key> = <API key>; controller_->LoadURLWithParams(load_url_params); } // PlzNavigate void NavigatorImpl::OnBeforeUnloadACK(FrameTreeNode* frame_tree_node, bool proceed) { CHECK(<API key>()); DCHECK(frame_tree_node); NavigationRequest* navigation_request = frame_tree_node->navigation_request(); // The NavigationRequest may have been canceled while the renderer was // executing the BeforeUnload event. if (!navigation_request) return; DCHECK_EQ(NavigationRequest::<API key>, navigation_request->state()); // If the navigation is allowed to proceed, send the request to the IO thread. if (proceed) navigation_request->BeginNavigation(); else CancelNavigation(frame_tree_node); } // PlzNavigate void NavigatorImpl::OnBeginNavigation( FrameTreeNode* frame_tree_node, const <API key>& common_params, const <API key>& begin_params, scoped_refptr<ResourceRequestBody> body) { // TODO(clamy): the url sent by the renderer should be validated with // FilterURL. // This is a renderer-initiated navigation. CHECK(<API key>()); DCHECK(frame_tree_node); NavigationRequest* <API key> = frame_tree_node->navigation_request(); // The renderer-initiated navigation request is ignored iff a) there is an // ongoing request b) which is browser or user-initiated and c) the renderer // request is not user-initiated. if (<API key> && (<API key>->browser_initiated() || <API key>->begin_params().has_user_gesture) && !begin_params.has_user_gesture) { return; } // In all other cases the current navigation, if any, is canceled and a new // NavigationRequest is created for the node. frame_tree_node-><API key>( NavigationRequest::<API key>( frame_tree_node, common_params, begin_params, body, controller_-><API key>(), controller_->GetEntryCount())); NavigationRequest* navigation_request = frame_tree_node->navigation_request(); navigation_request-><API key>(); if (frame_tree_node->IsMainFrame()) { // Renderer-initiated main-frame navigations that need to swap processes // will go to the browser via a OpenURL call, and then be handled by the // same code path as browser-initiated navigations. For renderer-initiated // main frame navigation that start via a BeginNavigation IPC, the // RenderFrameHost will not be swapped. Therefore it is safe to call // <API key> with the SiteInstance from the current // RenderFrameHost. <API key>( common_params.url, frame_tree_node->current_frame_host()->GetSiteInstance()); navigation_data_.reset(); } navigation_request->BeginNavigation(); } // PlzNavigate void NavigatorImpl::CommitNavigation(FrameTreeNode* frame_tree_node, ResourceResponse* response, scoped_ptr<StreamHandle> body) { CHECK(<API key>()); NavigationRequest* navigation_request = frame_tree_node->navigation_request(); DCHECK(navigation_request); DCHECK(response || !<API key>( navigation_request->common_params().url)); // HTTP 204 (No Content) and HTTP 205 (Reset Content) responses should not // commit; they leave the frame showing the previous page. if (response && response->head.headers.get() && (response->head.headers->response_code() == 204 || response->head.headers->response_code() == 205)) { CancelNavigation(frame_tree_node); return; } // Select an appropriate renderer to commit the navigation. RenderFrameHostImpl* render_frame_host = frame_tree_node->render_manager()-><API key>( *navigation_request); // The renderer can exit view source mode when any error or cancellation // happen. When reusing the same renderer, overwrite to recover the mode. if (navigation_request->is_view_source() && render_frame_host == frame_tree_node->render_manager()->current_frame_host()) { DCHECK(!render_frame_host->GetParent()); render_frame_host->render_view_host()->Send( new <API key>( render_frame_host->render_view_host()->GetRoutingID())); } <API key>( render_frame_host, navigation_request->common_params().url); navigation_request-><API key>(render_frame_host); render_frame_host->navigation_handle()-><API key>( render_frame_host, response ? response->head.headers : nullptr); render_frame_host->CommitNavigation(response, std::move(body), navigation_request->common_params(), navigation_request->request_params()); } // PlzNavigate void NavigatorImpl::FailedNavigation(FrameTreeNode* frame_tree_node, bool <API key>, int error_code) { CHECK(<API key>()); NavigationRequest* navigation_request = frame_tree_node->navigation_request(); DCHECK(navigation_request); // If the request was canceled by the user do not show an error page. if (error_code == net::ERR_ABORTED) { frame_tree_node-><API key>(false); return; } // Select an appropriate renderer to show the error page. RenderFrameHostImpl* render_frame_host = frame_tree_node->render_manager()-><API key>( *navigation_request); <API key>( render_frame_host, navigation_request->common_params().url); navigation_request-><API key>(render_frame_host); render_frame_host->navigation_handle()-><API key>( render_frame_host, scoped_refptr<net::HttpResponseHeaders>()); render_frame_host->FailedNavigation(navigation_request->common_params(), navigation_request->request_params(), <API key>, error_code); } // PlzNavigate void NavigatorImpl::CancelNavigation(FrameTreeNode* frame_tree_node) { CHECK(<API key>()); frame_tree_node-><API key>(false); if (frame_tree_node->IsMainFrame()) navigation_data_.reset(); } void NavigatorImpl::<API key>( base::TimeTicks timestamp, const GURL& url) { if (navigation_data_ && navigation_data_->url_ == url) { navigation_data_->url_job_start_time_ = timestamp; UMA_HISTOGRAM_TIMES( "Navigation.TimeToURLJobStart", navigation_data_->url_job_start_time_ - navigation_data_->start_time_); } } void NavigatorImpl::LogBeforeUnloadTime( const base::TimeTicks& <API key>, const base::TimeTicks& <API key>) { // Only stores the beforeunload delay if we're tracking a browser initiated // navigation and it happened later than the navigation request. if (navigation_data_ && <API key> > navigation_data_->start_time_) { navigation_data_-><API key> = <API key> - <API key>; } } void NavigatorImpl::<API key>( RenderFrameHostImpl* render_frame_host, const GURL& url) { int enabled_bindings = render_frame_host->render_view_host()->GetEnabledBindings(); bool <API key> = <API key>::GetInstance()-><API key>( controller_->GetBrowserContext(), url); if ((enabled_bindings & <API key>) && !<API key>) { // Log the URL to help us diagnose any future failures of this CHECK. GetContentClient()->SetActiveURL(url); CHECK(0); } } // PlzNavigate void NavigatorImpl::RequestNavigation( FrameTreeNode* frame_tree_node, const GURL& dest_url, const Referrer& dest_referrer, const <API key>& frame_entry, const NavigationEntryImpl& entry, <API key>::ReloadType reload_type, bool <API key>, base::TimeTicks navigation_start) { CHECK(<API key>()); DCHECK(frame_tree_node); // This value must be set here because creating a NavigationRequest might // change the renderer live/non-live status and change this result. bool <API key> = frame_tree_node->current_frame_host()-><API key>(); <API key>::Value navigation_type = GetNavigationType(controller_->GetBrowserContext(), entry, reload_type); frame_tree_node-><API key>( NavigationRequest::<API key>( frame_tree_node, dest_url, dest_referrer, frame_entry, entry, navigation_type, <API key>, navigation_start, controller_)); NavigationRequest* navigation_request = frame_tree_node->navigation_request(); navigation_request-><API key>(); // Have the current renderer execute its beforeunload event if needed. If it // is not needed (when beforeunload dispatch is not needed or this navigation // is synchronous and same-site) then NavigationRequest::BeginNavigation // should be directly called instead. if (<API key> && <API key>( navigation_request->common_params().url)) { navigation_request-><API key>(); frame_tree_node->current_frame_host()-><API key>(true); } else { navigation_request->BeginNavigation(); } } void NavigatorImpl::<API key>( const <API key>& details, const <API key>& params, SiteInstance* site_instance) { DCHECK(site_instance->HasProcess()); if (!details.is_in_page) RecordAction(base::UserMetricsAction("FrameLoad")); if (!details.is_main_frame || !navigation_data_ || navigation_data_->url_job_start_time_.is_null() || navigation_data_->url_ != params.<API key>) { return; } base::TimeDelta time_to_commit = base::TimeTicks::Now() - navigation_data_->start_time_; UMA_HISTOGRAM_TIMES("Navigation.TimeToCommit", time_to_commit); time_to_commit -= navigation_data_-><API key>; base::TimeDelta time_to_network = navigation_data_->url_job_start_time_ - navigation_data_->start_time_ - navigation_data_-><API key>; if (navigation_data_-><API key>) { UMA_HISTOGRAM_TIMES( "Navigation.<API key>", time_to_commit); UMA_HISTOGRAM_TIMES( "Navigation.<API key>", time_to_network); navigation_data_.reset(); return; } bool <API key> = site_instance->GetProcess()-><API key>() > navigation_data_->start_time_; if (<API key>) { UMA_HISTOGRAM_TIMES( "Navigation.<API key>", time_to_commit); UMA_HISTOGRAM_TIMES( "Navigation.<API key>", time_to_network); } else { UMA_HISTOGRAM_TIMES( "Navigation.<API key>", time_to_commit); UMA_HISTOGRAM_TIMES( "Navigation.<API key>", time_to_network); } navigation_data_.reset(); } void NavigatorImpl::<API key>( const GURL& url, SiteInstanceImpl* site_instance) { // If there is no browser-initiated pending entry for this navigation and it // is not for the error URL, create a pending entry using the current // SiteInstance, and ensure the address bar updates accordingly. We don't // know the referrer or extra headers at this point, but the referrer will // be set properly upon commit. NavigationEntryImpl* pending_entry = controller_->GetPendingEntry(); bool <API key> = pending_entry && !pending_entry-><API key>(); if (!<API key>) { scoped_ptr<NavigationEntryImpl> entry = NavigationEntryImpl::FromNavigationEntry( controller_-><API key>( url, content::Referrer(), ui::<API key>, true /* <API key> */, std::string(), controller_->GetBrowserContext())); entry->set_site_instance(site_instance); // TODO(creis): If there's a pending entry already, find a safe way to // update it instead of replacing it and copying over things like this. if (pending_entry) { entry-><API key>( pending_entry-><API key>()); entry-><API key>(pending_entry-><API key>()); entry->SetRedirectChain(pending_entry->GetRedirectChain()); } controller_->SetPendingEntry(std::move(entry)); if (delegate_) delegate_-><API key>(content::INVALIDATE_TYPE_URL); } } } // namespace content
package com.vmware.vim25; @SuppressWarnings("all") public class <API key> extends DynamicData { public String eventID; public String eventTypeSchema; public String getEventID() { return this.eventID; } public String getEventTypeSchema() { return this.eventTypeSchema; } public void setEventID(String eventID) { this.eventID = eventID; } public void setEventTypeSchema(String eventTypeSchema) { this.eventTypeSchema = eventTypeSchema; } }
#include "config.h" #include "modules/encryptedmedia/<API key>.h" #include "bindings/core/v8/<API key>.h" #include "bindings/core/v8/ScriptState.h" #include "core/dom/DOMException.h" #include "core/dom/Document.h" #include "core/dom/ExceptionCode.h" #include "core/frame/<API key>.h" #include "core/frame/UseCounter.h" #include "modules/encryptedmedia/EncryptedMediaUtils.h" #include "modules/encryptedmedia/MediaKeySession.h" #include "modules/encryptedmedia/<API key>.h" #include "modules/encryptedmedia/MediaKeysController.h" #include "platform/<API key>.h" #include "platform/Logging.h" #include "platform/network/ParsedContentType.h" #include "public/platform/<API key>.h" #include "public/platform/<API key>.h" #include "public/platform/<API key>.h" #include "public/platform/<API key>.h" #include "public/platform/WebVector.h" #include "wtf/Vector.h" #include "wtf/text/WTFString.h" namespace blink { namespace { static WebVector<<API key>> <API key>(const Vector<String>& initDataTypes) { WebVector<<API key>> result(initDataTypes.size()); for (size_t i = 0; i < initDataTypes.size(); ++i) result[i] = EncryptedMediaUtils::<API key>(initDataTypes[i]); return result; } static WebVector<<API key>> convertCapabilities(const HeapVector<<API key>>& capabilities) { WebVector<<API key>> result(capabilities.size()); for (size_t i = 0; i < capabilities.size(); ++i) { const WebString& contentType = capabilities[i].contentType(); result[i].contentType = contentType; if (isValidContentType(contentType)) { // FIXME: Fail if there are unrecognized parameters. ParsedContentType type(capabilities[i].contentType()); result[i].mimeType = type.mimeType(); result[i].codecs = type.<API key>("codecs"); } result[i].robustness = capabilities[i].robustness(); } return result; } static <API key>::Requirement <API key>(const String& requirement) { if (requirement == "required") return <API key>::Requirement::Required; if (requirement == "optional") return <API key>::Requirement::Optional; if (requirement == "not-allowed") return <API key>::Requirement::NotAllowed; // Everything else gets the default value. ASSERT_NOT_REACHED(); return <API key>::Requirement::Optional; } static WebVector<<API key>> convertSessionTypes(const Vector<String>& sessionTypes) { WebVector<<API key>> result(sessionTypes.size()); for (size_t i = 0; i < sessionTypes.size(); ++i) result[i] = EncryptedMediaUtils::<API key>(sessionTypes[i]); return result; } // This class allows capabilities to be checked and a <API key> // object to be created asynchronously. class <API key> final : public <API key> { <API key>(<API key>); public: <API key>(ScriptState*, const String& keySystem, const HeapVector<<API key>>& <API key>); ~<API key>() override { } // <API key> implementation. WebString keySystem() const override { return m_keySystem; } const WebVector<<API key>>& <API key>() const override { return <API key>; } SecurityOrigin* securityOrigin() const override { return m_resolver->executionContext()->securityOrigin(); } void requestSucceeded(<API key>*) override; void requestNotSupported(const WebString& errorMessage) override; ScriptPromise promise() { return m_resolver->promise(); } <API key>() { visitor->trace(m_resolver); <API key>::trace(visitor); } private: Member<<API key>> m_resolver; const String m_keySystem; WebVector<<API key>> <API key>; }; <API key>::<API key>(ScriptState* scriptState, const String& keySystem, const HeapVector<<API key>>& <API key>) : m_resolver(<API key>::create(scriptState)) , m_keySystem(keySystem) , <API key>(<API key>.size()) { for (size_t i = 0; i < <API key>.size(); ++i) { const <API key>& config = <API key>[i]; <API key> webConfig; if (config.hasInitDataTypes()) { webConfig.hasInitDataTypes = true; webConfig.initDataTypes = <API key>(config.initDataTypes()); } if (config.<API key>()) { webConfig.<API key> = true; webConfig.audioCapabilities = convertCapabilities(config.audioCapabilities()); } if (config.<API key>()) { webConfig.<API key> = true; webConfig.videoCapabilities = convertCapabilities(config.videoCapabilities()); } ASSERT(config.<API key>()); webConfig.<API key> = <API key>(config.<API key>()); ASSERT(config.hasPersistentState()); webConfig.persistentState = <API key>(config.persistentState()); if (config.hasSessionTypes()) { webConfig.hasSessionTypes = true; webConfig.sessionTypes = convertSessionTypes(config.sessionTypes()); } // If |label| is not present, it will be a null string. webConfig.label = config.label(); <API key>[i] = webConfig; } } void <API key>::requestSucceeded(<API key>* access) { m_resolver->resolve(new <API key>(m_keySystem, adoptPtr(access))); m_resolver.clear(); } void <API key>::requestNotSupported(const WebString& errorMessage) { m_resolver->reject(DOMException::create(NotSupportedError, errorMessage)); m_resolver.clear(); } } // namespace ScriptPromise <API key>::<API key>( ScriptState* scriptState, Navigator& navigator, const String& keySystem, const HeapVector<<API key>>& <API key>) { WTF_LOG(Media, "<API key>::<API key>()"); // From https://w3c.github.io/encrypted-media/#<API key> // When this method is invoked, the user agent must run the following steps: // 1. If keySystem is an empty string, return a promise rejected with a // new DOMException whose name is InvalidAccessError. if (keySystem.isEmpty()) { return ScriptPromise::<API key>( scriptState, DOMException::create(InvalidAccessError, "The keySystem parameter is empty.")); } // 2. If <API key> was provided and is empty, return a // promise rejected with a new DOMException whose name is // InvalidAccessError. if (!<API key>.size()) { return ScriptPromise::<API key>( scriptState, DOMException::create(InvalidAccessError, "The <API key> parameter is empty.")); } // 3-4. 'May Document use powerful features?' check. ExecutionContext* executionContext = scriptState->executionContext(); String errorMessage; if (executionContext->isPrivilegedContext(errorMessage)) { UseCounter::count(executionContext, UseCounter::<API key>); } else { UseCounter::countDeprecation(executionContext, UseCounter::<API key>); // TODO(ddorwin): Implement the following: // Reject promise with a new DOMException whose name is NotSupportedError. } // 5. Let origin be the origin of document. // (Passed with the execution context in step 7.) // 6. Let promise be a new promise. Document* document = toDocument(executionContext); if (!document->page()) { return ScriptPromise::<API key>( scriptState, DOMException::create(InvalidStateError, "The context provided is not associated with a page.")); } <API key>* initializer = new <API key>(scriptState, keySystem, <API key>); ScriptPromise promise = initializer->promise(); // 7. Asynchronously determine support, and if allowed, create and // initialize the <API key> object. MediaKeysController* controller = MediaKeysController::from(document->page()); <API key>* mediaClient = controller-><API key>(executionContext); mediaClient-><API key>(<API key>(initializer)); // 8. Return promise. return promise; } } // namespace blink
/* generic function for adding a message to message area through JS alone */ function addMessage(status, text) { $('.messages').addClass('new').empty().append('<ul><li class="' + status + '">' + text + '</li></ul>'); var addMsgTimeout = setTimeout(function() { $('.messages').addClass('appear'); clearTimeout(addMsgTimeout); }, 100); } function escapeHtml(text) { var map = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', '\'': '&#039;' }; return text.replace(/[&<>"']/g, function(m) { return map[m]; }); } $(function() { // Add class to the body from which transitions may be hung so they don't appear to transition as the page loads $('body').addClass('ready'); // Enable toggle to open/close nav $(document).on('click', '#nav-toggle', function() { $('body').toggleClass('nav-open'); if (!$('body').hasClass('nav-open')) { $('body').addClass('nav-closed'); } else { $('body').removeClass('nav-closed'); } }); // Resize nav to fit height of window. This is an unimportant bell/whistle to make it look nice var fitNav = function() { $('.nav-wrapper').css('min-height', $(window).height()); $('.nav-main').each(function() { var thisHeight = $(this).height(); var footerHeight = $('.footer', $(this)).height(); }); }; fitNav(); $(window).resize(function() { fitNav(); }); // Apply auto-height sizing to text areas // NB .richtext (hallo.js-enabled) divs do not need this as they expand to fit their content by default // $('.page-editor textarea').autosize(); // Enable nice focus effects on all fields. This enables help text on hover. $(document).on('focus mouseover', 'input,textarea,select', function() { $(this).closest('.field').addClass('focused'); $(this).closest('fieldset').addClass('focused'); $(this).closest('li').addClass('focused'); }); $(document).on('blur mouseout', 'input,textarea,select', function() { $(this).closest('.field').removeClass('focused'); $(this).closest('fieldset').removeClass('focused'); $(this).closest('li').removeClass('focused'); }); /* tabs */ $(document).on('click', '.tab-nav a', function(e) { e.preventDefault(); $(this).tab('show'); }); $(document).on('click', '.tab-toggle', function(e) { e.preventDefault(); $('.tab-nav a[href="' + $(this).attr('href') + '"]').click(); }); $('.dropdown-toggle').bind('click', function() { $(this).closest('.dropdown').toggleClass('open'); // Stop event propagating so the "close all dropdowns on body clicks" code (below) doesn't immediately close the dropdown return false; }); /* close all dropdowns on body clicks */ $(document).on('click', function(e) { var relTarg = e.relatedTarget || e.toElement; if (!$(relTarg).hasClass('dropdown-toggle')) { $('.dropdown').removeClass('open'); } }); /* Dropzones */ $('.drop-zone').on('dragover', function() { $(this).addClass('hovered'); }).on('dragleave dragend drop', function() { $(this).removeClass('hovered'); }); /* Header search behaviour */ if (window.headerSearch) { var searchCurrentIndex = 0; var searchNextIndex = 0; $(window.headerSearch.termInput).on('input', function() { clearTimeout($.data(this, 'timer')); var wait = setTimeout(search, 200); $(this).data('timer', wait); }); // auto focus on search box $(window.headerSearch.termInput).trigger('focus'); function search() { var workingClasses = 'icon-spinner'; $(window.headerSearch.termInput).parent().addClass(workingClasses); searchNextIndex++; var index = searchNextIndex; $.ajax({ url: window.headerSearch.url, data: {q: $(window.headerSearch.termInput).val()}, success: function(data, status) { if (index > searchCurrentIndex) { searchCurrentIndex = index; $(window.headerSearch.targetOutput).html(data).slideDown(800); window.history.pushState(null, 'Search results', '?q=' + $(window.headerSearch.termInput).val()); } }, complete: function() { $(window.headerSearch.termInput).parent().removeClass(workingClasses); } }); } } });
#include "Open3DMotion/OpenORM/Branches/TreeCompoundNode.h" namespace Open3DMotion { TreeCompoundNode::TreeCompoundNode() : value(NULL) { } TreeCompoundNode::TreeCompoundNode(const char* _name, TreeValue* _value) : name(_name), value(_value) { } TreeCompoundNode::~TreeCompoundNode() { ClearValue(); } void TreeCompoundNode::ClearValue() { if (value != NULL) { delete value; value = NULL; } } void TreeCompoundNode::ChangeValue(TreeValue* _value) { ClearValue(); value = _value; } }
<?php require_once 'phing/Task.php'; require_once 'phing/system/io/PhingFile.php'; require_once 'phing/system/io/Writer.php'; require_once 'phing/util/LogWriter.php'; require_once 'phing/tasks/ext/phpunit/BatchTest.php'; require_once 'phing/tasks/ext/phpunit/FormatterElement.php'; /** * Runs PHPUnit tests. * * @author Michiel Rook <mrook@php.net> * @version $Id$ * @package phing.tasks.ext.phpunit * @see BatchTest * @since 2.1.0 */ class PHPUnitTask extends Task { private $batchtests = array(); private $formatters = array(); private $bootstrap = ""; private $haltonerror = false; private $haltonfailure = false; private $haltonincomplete = false; private $haltonskipped = false; private $errorproperty; private $failureproperty; private $incompleteproperty; private $skippedproperty; private $printsummary = false; private $testfailed = false; private $testfailuremessage = ""; private $codecoverage = null; private $groups = array(); private $excludeGroups = array(); private $processIsolation = false; private $<API key> = true; /** * @var string */ private $pharLocation = ""; /** * @var PhingFile */ private $configuration = null; /** * Initialize Task. * This method includes any necessary PHPUnit libraries and triggers * appropriate error if they cannot be found. This is not done in header * because we may want this class to be loaded w/o triggering an error. */ public function init() { } private function loadPHPUnit() { /** * Determine PHPUnit version number, try * PEAR old-style, then composer, then PHAR */ @include_once 'PHPUnit/Runner/Version.php'; @include_once 'phpunit/Runner/Version.php'; if (! empty($this->pharLocation)) { $GLOBALS['_SERVER']['SCRIPT_NAME'] = '-'; ob_start(); @include $this->pharLocation; ob_end_clean(); } @include_once 'PHPUnit/Autoload.php'; if (!class_exists('<API key>')) { throw new BuildException("PHPUnitTask requires PHPUnit to be installed", $this->getLocation()); } $version = <API key>::id(); if (version_compare($version, '3.6.0') < 0) { throw new BuildException("PHPUnitTask requires PHPUnit version >= 3.6.0", $this->getLocation()); } /** * Other dependencies that should only be loaded when class is actually used. */ require_once 'phing/tasks/ext/phpunit/PHPUnitTestRunner.php'; /** * point PHPUnit_MAIN_METHOD define to non-existing method */ if (!defined('PHPUnit_MAIN_METHOD')) { define('PHPUnit_MAIN_METHOD', 'PHPUnitTask::undefined'); } } /** * Sets the name of a bootstrap file that is run before * executing the tests * * @param string $bootstrap the name of the bootstrap file */ public function setBootstrap($bootstrap) { $this->bootstrap = $bootstrap; } public function setErrorproperty($value) { $this->errorproperty = $value; } public function setFailureproperty($value) { $this->failureproperty = $value; } public function <API key>($value) { $this->incompleteproperty = $value; } public function setSkippedproperty($value) { $this->skippedproperty = $value; } public function setHaltonerror($value) { $this->haltonerror = $value; } public function setHaltonfailure($value) { $this->haltonfailure = $value; } public function getHaltonfailure() { return $this->haltonfailure; } public function setHaltonincomplete($value) { $this->haltonincomplete = $value; } public function getHaltonincomplete() { return $this->haltonincomplete; } public function setHaltonskipped($value) { $this->haltonskipped = $value; } public function getHaltonskipped() { return $this->haltonskipped; } public function setPrintsummary($printsummary) { $this->printsummary = $printsummary; } public function setCodecoverage($codecoverage) { $this->codecoverage = $codecoverage; } public function setProcessIsolation($processIsolation) { $this->processIsolation = $processIsolation; } public function <API key>($<API key>) { $this-><API key> = $<API key>; } public function setGroups($groups) { $token = ' ,;'; $this->groups = array(); $tok = strtok($groups, $token); while ($tok !== false) { $this->groups[] = $tok; $tok = strtok($token); } } public function setExcludeGroups($excludeGroups) { $token = ' ,;'; $this->excludeGroups = array(); $tok = strtok($excludeGroups, $token); while ($tok !== false) { $this->excludeGroups[] = $tok; $tok = strtok($token); } } /** * Add a new formatter to all tests of this task. * * @param FormatterElement formatter element */ public function addFormatter(FormatterElement $fe) { $fe->setParent($this); $this->formatters[] = $fe; } /** * @param PhingFile $configuration */ public function setConfiguration(PhingFile $configuration) { $this->configuration = $configuration; } /** * @param string $pharLocation */ public function setPharLocation($pharLocation) { $this->pharLocation = $pharLocation; } /** * Load and processes the PHPUnit configuration */ protected function <API key>($configuration) { if (!$configuration->exists()) { throw new BuildException("Unable to find PHPUnit configuration file '" . (string) $configuration . "'"); } $config = <API key>::getInstance($configuration->getAbsolutePath()); if (empty($config)) { return; } $phpunit = $config-><API key>(); if (empty($phpunit)) { return; } $config-><API key>(); if (isset($phpunit['bootstrap'])) { $this->setBootstrap($phpunit['bootstrap']); } if (isset($phpunit['stopOnFailure'])) { $this->setHaltonfailure($phpunit['stopOnFailure']); } if (isset($phpunit['stopOnError'])) { $this->setHaltonerror($phpunit['stopOnError']); } if (isset($phpunit['stopOnSkipped'])) { $this->setHaltonskipped($phpunit['stopOnSkipped']); } if (isset($phpunit['stopOnIncomplete'])) { $this->setHaltonincomplete($phpunit['stopOnIncomplete']); } if (isset($phpunit['processIsolation'])) { $this->setProcessIsolation($phpunit['processIsolation']); } $browsers = $config-><API key>(); if (!empty($browsers) && class_exists('<API key>')) { <API key>::$browsers = $browsers; } return $phpunit; } /** * The main entry point * * @throws BuildException */ public function main() { if ($this->codecoverage && !extension_loaded('xdebug')) { throw new Exception("PHPUnitTask depends on Xdebug being installed to gather code coverage information."); } $this->loadPHPUnit(); $suite = new <API key>('AllTests'); if ($this->configuration) { $arguments = $this-><API key>($this->configuration); if ($arguments['backupGlobals'] === FALSE) { $suite->setBackupGlobals(FALSE); } if ($arguments['<API key>'] === TRUE) { $suite-><API key>(TRUE); } } if ($this->printsummary) { $fe = new FormatterElement(); $fe->setParent($this); $fe->setType("summary"); $fe->setUseFile(false); $this->formatters[] = $fe; } $autoloadSave = <API key>(); if ($this->bootstrap) { require $this->bootstrap; } foreach ($this->batchtests as $batchTest) { $this-><API key>($batchTest, $suite); } $this->execute($suite); if ($this->testfailed) { throw new BuildException($this->testfailuremessage); } $autoloadNew = <API key>(); foreach ($autoloadNew as $autoload) { <API key>($autoload); } foreach ($autoloadSave as $autoload) { <API key>($autoload); } } /** * @throws BuildException */ protected function execute($suite) { $runner = new PHPUnitTestRunner($this->project, $this->groups, $this->excludeGroups, $this->processIsolation); if ($this->codecoverage) { /** * Add some defaults to the PHPUnit filter */ $pwd = dirname(__FILE__); $path = realpath($pwd . '/../../../'); $filter = new <API key>(); $filter-><API key>($path); $runner->setCodecoverage(new PHP_CodeCoverage(null, $filter)); } $runner-><API key>($this-><API key>); foreach ($this->formatters as $fe) { $formatter = $fe->getFormatter(); if ($fe->getUseFile()) { $destFile = new PhingFile($fe->getToDir(), $fe->getOutfile()); $writer = new FileWriter($destFile->getAbsolutePath()); $formatter->setOutput($writer); } else { $formatter->setOutput($this->getDefaultOutput()); } $runner->addFormatter($formatter); $formatter->startTestRun(); } $runner->run($suite); foreach ($this->formatters as $fe) { $formatter = $fe->getFormatter(); $formatter->endTestRun(); } $retcode = $runner->getRetCode(); if ($retcode == PHPUnitTestRunner::ERRORS) { if ($this->errorproperty) { $this->project->setNewProperty($this->errorproperty, true); } if ($this->haltonerror) { $this->testfailed = true; $this->testfailuremessage = $runner->getLastErrorMessage(); } } elseif ($retcode == PHPUnitTestRunner::FAILURES) { if ($this->failureproperty) { $this->project->setNewProperty($this->failureproperty, true); } if ($this->haltonfailure) { $this->testfailed = true; $this->testfailuremessage = $runner-><API key>(); } } elseif ($retcode == PHPUnitTestRunner::INCOMPLETES) { if ($this->incompleteproperty) { $this->project->setNewProperty($this->incompleteproperty, true); } if ($this->haltonincomplete) { $this->testfailed = true; $this->testfailuremessage = $runner-><API key>(); } } elseif ($retcode == PHPUnitTestRunner::SKIPPED) { if ($this->skippedproperty) { $this->project->setNewProperty($this->skippedproperty, true); } if ($this->haltonskipped) { $this->testfailed = true; $this->testfailuremessage = $runner-><API key>(); } } } /** * Add the tests in this batchtest to a test suite * * @param BatchTest $batchTest * @param <API key> $suite */ protected function <API key>(BatchTest $batchTest, <API key> $suite) { foreach ($batchTest->elements() as $element) { $testClass = new $element(); if (! ($testClass instanceof <API key>)) { $testClass = new ReflectionClass($element); } $suite->addTestSuite($testClass); } } protected function getDefaultOutput() { return new LogWriter($this); } /** * Adds a set of tests based on pattern matching. * * @return BatchTest a new instance of a batch test. */ public function createBatchTest() { $batchtest = new BatchTest($this->getProject()); $this->batchtests[] = $batchtest; return $batchtest; } }
#ifndef <API key> #define <API key> #include <export.hpp> #include <string> namespace graphlab { /** * Configures the system global environment. This should be the first thing * (or close to the first thing) called on program startup. */ void EXPORT <API key>(std::string argv0); /** * This class centralizes all startup functions */ class EXPORT global_startup { public: global_startup() = default; global_startup(const global_startup&) = delete; global_startup(global_startup&&) = delete; global_startup& operator=(global_startup&&) = delete; global_startup& operator=(const global_startup&) = delete; /** * Performs all the startup calls immediately. Further calls to this * function does nothing. */ void perform_startup(); /** * Performs the startup if startup has not yet been performed. */ ~global_startup(); static global_startup& get_instance(); private: bool startup_performed = false; }; /** * This class centralizes all tear down functions allowing destruction * to happen in a prescribed order. * * TODO This can be more intelligent as required. For now, it is kinda dumb. */ class EXPORT global_teardown { public: global_teardown() = default; global_teardown(const global_teardown&) = delete; global_teardown(global_teardown&&) = delete; global_teardown& operator=(global_teardown&&) = delete; global_teardown& operator=(const global_teardown&) = delete; /** * Performs all the teardown calls immediately. Further calls to this * function does nothing. */ void perform_teardown(); /** * Performs the teardown if teardown has not yet been performed. */ ~global_teardown(); static global_teardown& get_instance(); private: bool teardown_performed = false; }; namespace teardown_impl { extern EXPORT global_teardown teardown_instance; } } // graphlab #endif
{-# LANGUAGE LambdaCase, RankNTypes, ScopedTypeVariables #-} module Stream.Folding.Prelude ( break , concats , cons , drop , lenumFrom , lenumFromStepN , lenumFromTo , lenumFromToStep , filter , filterM , foldl , iterate , iterateM , joinFold , map , mapM , maps , repeat , repeatM , replicate , replicateM , scanr , span , splitAt , splitAt_ , sum , take , takeWhile , yield ) where import Stream.Types import Control.Monad hiding (filterM, mapM, replicateM) import Data.Functor.Identity import Control.Monad.Trans import qualified System.IO as IO import Prelude hiding (map, filter, drop, take, sum , iterate, repeat, replicate, splitAt , takeWhile, enumFrom, enumFromTo , mapM, scanr, span, break, foldl) -- Prelude -- yield yield :: Monad m => a -> Folding (Of a) m () yield r = Folding (\construct wrap done -> construct (r :> done ())) {-# INLINE yield #-} -- sum sum :: (Monad m, Num a) => Folding (Of a) m () -> m a sum = \(Folding phi) -> phi (\(n :> mm) -> mm >>= \m -> return (m+n)) join (\_ -> return 0) {-# INLINE sum #-} -- replicate replicate :: Monad m => Int -> a -> Folding (Of a) m () replicate n a = Folding (take_ (repeat_ a) n) {-# INLINE replicate #-} replicateM :: Monad m => Int -> m a -> Folding (Of a) m () replicateM n a = Folding (take_ (repeatM_ a) n) {-# INLINE replicateM #-} -- iterate -- this can clearly be made non-recursive with eg numbers iterate_ :: (a -> a) -> a -> Folding_ (Of a) m r iterate_ f a = \construct wrap done -> construct (a :> iterate_ f (f a) construct wrap done) {-# INLINE iterate_ #-} iterate :: (a -> a) -> a -> Folding (Of a) m r iterate f a = Folding (iterate_ f a) {-# INLINE iterate #-} iterateM_ :: Monad m => (a -> m a) -> m a -> Folding_ (Of a) m r iterateM_ f ma = \construct wrap done -> let loop mx = wrap $ liftM (\x -> construct (x :> loop (f x))) mx in loop ma {-# INLINE iterateM_ #-} iterateM :: Monad m => (a -> m a) -> m a -> Folding (Of a) m r iterateM f a = Folding (iterateM_ f a) {-# INLINE iterateM #-} -- repeat repeat_ :: a -> Folding_ (Of a) m r repeat_ = \a construct wrap done -> let loop = construct (a :> loop) in loop {-# INLINE repeat_ #-} repeat :: a -> Folding (Of a) m r repeat a = Folding (repeat_ a) {-# INLINE repeat #-} repeatM_ :: Monad m => m a -> Folding_ (Of a) m r repeatM_ ma = \construct wrap done -> let loop = liftM (\a -> construct (a :> wrap loop)) ma in wrap loop {-# INLINE repeatM_ #-} repeatM :: Monad m => m a -> Folding (Of a) m r repeatM ma = Folding (repeatM_ ma) {-# INLINE repeatM #-} -- filter filter :: Monad m => (a -> Bool) -> Folding (Of a) m r -> Folding (Of a) m r filter pred = \(Folding phi) -> Folding (filter_ phi pred) {-# INLINE filter #-} filter_ :: (Monad m) => Folding_ (Of a) m r -> (a -> Bool) -> Folding_ (Of a) m r filter_ phi pred0 = \construct wrap done -> phi (\aa@(a :> x) pred-> if pred a then construct (a :> x pred) else x pred) (\mp pred -> wrap $ liftM ($pred) mp) (\r pred -> done r) pred0 {-# INLINE filter_ #-} filterM_ :: (Monad m) => Folding_ (Of a) m r -> (a -> m Bool) -> Folding_ (Of a) m r filterM_ phi pred0 = \construct wrap done -> phi ( \aa@(a :> x) pred -> wrap $ do p <- pred a return $ if p then construct (a :> x pred) else x pred ) ( \mp pred -> wrap $ liftM ($pred) mp ) ( \r pred -> done r ) pred0 {-# INLINE filterM_ #-} filterM :: Monad m => (a -> m Bool) -> Folding (Of a) m r -> Folding (Of a) m r filterM pred = \(Folding phi) -> Folding (filterM_ phi pred) -- drop drop :: Monad m => Int -> Folding (Of a) m r -> Folding (Of a) m r drop n = \(Folding phi) -> Folding (drop_ phi n) {-# INLINE drop #-} jdrop :: Monad m => Int -> Folding_ (Of a) m r -> Folding_ (Of a) m r jdrop = \m phi construct wrap done -> phi (\(a :> fn) n -> if n <= m then fn (n+1) else construct (a :> (fn (n+1)))) (\m n -> wrap (m >>= \fn -> return (fn n))) (\r _ -> done r) 1 {-# INLINE jdrop #-} drop_ :: Monad m => Folding_ (Of a) m r -> Int -> Folding_ (Of a) m r drop_ phi n0 = \construct wrap done -> phi (\(a :> fn) n -> if n >= 0 then fn (n-1) else construct (a :> (fn (n-1)))) (\m n -> wrap (m >>= \fn -> return (fn n))) (\r _ -> done r) n0 {-# INLINE drop_ #-} -- concats concat/join concats :: Monad m => Folding (Folding (Of a) m) m r -> Folding (Of a) m r concats (Folding phi) = Folding $ \construct wrap done -> phi (\(Folding phi') -> phi' construct wrap id) wrap done {-# INLINE concats #-} concats1 :: Monad m => Folding_ (Folding (Of a) m) m r -> Folding_ (Of a) m r concats1 phi = \construct wrap done -> phi (\(Folding phi') -> phi' construct wrap id) wrap done {-# INLINE concats1 #-} concats0 :: Monad m => Folding_ (Folding_ (Of a) m) m r -> Folding_ (Of a) m r concats0 phi = \construct wrap done -> phi (\phi' -> phi' construct wrap id) wrap done {-# INLINE concats0 #-} joinFold_ :: (Monad m, Functor f) => Folding_ f m (Folding_ f m r) -> Folding_ f m r joinFold_ phi = \c w d -> phi c w (\folding -> folding c w d) {-# INLINE joinFold_ #-} joinFold (Folding phi) = Folding $ \c w d -> phi c w (\folding -> getFolding folding c w d) {-# INLINE joinFold #-} -- map map :: Monad m => (a -> b) -> Folding (Of a) m r -> Folding (Of b) m r map f = \(Folding phi) -> Folding (map_ phi f) {-# INLINE map #-} map_ :: Monad m => Folding_ (Of a) m r -> (a -> b) -> Folding_ (Of b) m r map_ phi f0 = \construct wrap done -> phi (\(a :> x) f -> construct (f a :> x f)) (\mf f -> wrap (liftM ($f) mf)) (\r f -> done r) f0 {-# INLINE map_ #-} mapM :: Monad m => (a -> m b) -> Folding (Of a) m r -> Folding (Of b) m r mapM f = \(Folding phi) -> Folding (mapM__ phi f) where mapM__ :: Monad m => Folding_ (Of a) m r -> (a -> m b) -> Folding_ (Of b) m r mapM__ phi f0 = \construct wrap done -> phi (\(a :> x) f -> wrap $ liftM (\z -> construct (z :> x f)) (f a) ) (\mff f -> wrap (liftM ($f) mff)) (\r _ -> done r) f0 {-# INLINE mapM__ #-} {-# INLINE mapM #-} maps :: (Monad m, Functor g) => (forall x . f x -> g x) -> Folding f m r -> Folding g m r maps morph (Folding phi) = Folding $ \construct wrap done -> phi (construct . morph) wrap done -- take take_ :: (Monad m, Functor f) => Folding_ f m r -> Int -> Folding_ f m () take_ phi n = \construct wrap done -> phi (\fx n -> if n <= 0 then done () else construct (fmap ($(n-1)) fx)) (\mx n -> if n <= 0 then done () else wrap (liftM ($n) mx)) (\r n -> done ()) n {-# INLINE take_ #-} take :: (Monad m, Functor f) => Int -> Folding f m r -> Folding f m () take n = \(Folding phi) -> Folding (take_ phi n) {-# INLINE take #-} takeWhile :: Monad m => (a -> Bool) -> Folding (Of a) m r -> Folding (Of a) m () takeWhile pred = \(Folding fold) -> Folding (takeWhile_ fold pred) {-# INLINE takeWhile #-} takeWhile_ :: Monad m => Folding_ (Of a) m r -> (a -> Bool) -> Folding_ (Of a) m () takeWhile_ phi pred0 = \construct wrap done -> phi (\(a :> fn) p pred_ -> if not (pred_ a) then done () else construct (a :> (fn True pred_))) (\m p pred_ -> if not p then done () else wrap (liftM (\fn -> fn p pred_) m)) (\r p pred_ -> done ()) True pred0 {-# INLINE takeWhile_ #-} lenumFrom n = \construct wrap done -> let loop m = construct (m :> loop (succ m)) in loop n lenumFromTo n m = \construct wrap done -> let loop k = if k <= m then construct (k :> loop (succ k)) else done () in loop n lenumFromToStep n m k = \construct wrap done -> let loop p = if p <= k then construct (p :> loop (p + m)) else done () in loop n lenumFromStepN start step n = \construct wrap done -> let loop p 0 = done () loop p now = construct (p :> loop (p + step) (now-1)) in loop start n foldl_ :: Monad m => Folding_ (Of a) m r -> (b -> a -> b) -> b -> m b foldl_ phi = \ op b0 -> phi (\(a :> fn) b -> fn $! flip op a $! b) (\mf b -> mf >>= \f -> f b) (\_ b -> return $! b) b0 {-# INLINE foldl_ #-} foldl :: Monad m => (b -> a -> b) -> b -> Folding (Of a) m r -> m b foldl op b = \(Folding phi) -> foldl_ phi op b {-# INLINE foldl #-} jscanr :: Monad m => (a -> b -> b) -> b -> Folding_ (Of a) m r -> Folding_ (Of b) m r jscanr op b phi = phi (\(a :> fx) b c w d -> c (b :> fx (op a b) c w d)) (\mfx b c w d -> w (liftM (\fx -> c (b :> fx b c w d)) mfx)) (\r b c w d -> c (b :> d r)) b {-# INLINE jscanr #-} scanr :: Monad m => (a -> b -> b) -> b -> Folding (Of a) m r -> Folding (Of b) m r scanr op b = \(Folding phi) -> Folding (lscanr_ phi op b) lscanr_ :: Monad m => Folding_ (Of a) m r -> (a -> b -> b) -> b -> Folding_ (Of b) m r lscanr_ phi = phi (\(a :> fx) op b c w d -> c (b :> fx op (op a b) c w d)) (\mfx op b c w d -> w (liftM (\fx -> c (b :> fx op b c w d)) mfx)) (\r op b c w d -> c (b :> d r)) {-# INLINE lscanr_ #-} chunksOf :: Monad m => Int -> Folding (Of a) m r -> Folding (Folding (Of a) m) m r chunksOf = undefined {-# INLINE chunksOf #-} chunksOf_ :: Monad m => Folding_ (Of a) m r -> Int -> Folding_ (Folding_ (Of a) m) m r chunksOf_ phi n = \construct wrap done -> undefined -- cons cons :: Monad m => a -> Folding (Of a) m r -> Folding (Of a) m r cons a_ (Folding phi) = Folding $ \construct wrap done -> phi (\(a :> a2p) a0 -> construct (a0 :> a2p a) ) (\m a0 -> wrap $ liftM ($ a0) m ) (\r a0 -> construct (a0 :> done r) ) a_ -- span span :: Monad m => (a -> Bool) -> Folding (Of a) m r -> Folding (Of a) m (Folding (Of a) m r) span pred0 (Folding phi) = phi (\ (a :> folding) -> \pred -> if pred a then Folding $ \construct wrap done -> construct (a :> getFolding (folding pred) construct wrap done) else Folding $ \construct wrap done -> done $ a `cons` joinFold (folding pred) ) (\m -> \pred -> Folding $ \c w r -> w (m >>= \folding -> return $ getFolding (folding pred) c w r) ) (\r -> \pred -> Folding $ \construct wrap done -> done (Folding $ \c w d -> d r) ) pred0 {-# INLINE span #-} -- break break :: Monad m => (a -> Bool) -> Folding (Of a) m r -> Folding (Of a) m (Folding (Of a) m r) break predicate = span (not . predicate) -- splitAt splitAt_ :: Monad m => Int -> Folding (Of a) m r -> Folding (Of a) m (Folding (Of a) m r) splitAt_ m (Folding phi) = phi (\ (a :> n2prod) n -> if n > (0 :: Int) then Folding $ \construct wrap done -> construct (a :> getFolding (n2prod (n-1)) construct wrap done) else Folding $ \construct wrap done -> done $ a `cons` joinFold (n2prod (n)) ) (\m n -> Folding $ \c w r -> w (m >>= \n2fold -> return $ getFolding (n2fold n) c w r) ) (\r n -> Folding $ \construct wrap done -> done (Folding $ \c w d -> d r) ) m {-# INLINE splitAt_ #-} splitAt :: (Monad m, Functor f) => Int -> Folding f m r -> Folding f m (Folding f m r) splitAt m (Folding phi) = phi (\ fold n -> -- fold :: f (Int -> Folding f m (Folding f m r)) if n > (0 :: Int) then Folding $ \construct wrap done -> construct $ fmap (\f -> getFolding (f (n-1)) construct wrap done) fold else Folding $ \construct wrap done -> done $ Folding $ \c w d -> c $ fmap (\f -> getFolding (f n) c w (\(Folding psi) -> psi c w d)) fold ) (\m n -> Folding $ \c w r -> w (m >>= \n2fold -> return $ getFolding (n2fold n) c w r) ) (\r n -> Folding $ \construct wrap done -> done (Folding $ \c w d -> d r) ) m {-# INLINE splitAt #-} j :: (Monad m, Functor f) => f (Folding f m (Folding f m r)) -> Folding f m r j ffolding = Folding $ \cons w nil -> cons $ fmap (\f -> getFolding f cons w (\(Folding psi) -> psi cons w nil)) ffolding
Copyright (c) 2015, Vladimir Babin 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. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 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.
# 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. reduce: main.cu *.h nvcc -O3 main.cu -o reduce -arch=sm_35 clean: rm -f reduce
#include "chrome/browser/ui/views/<API key>.h" #include "base/metrics/histogram.h" #include "build/build_config.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/ui/layout_constants.h" #include "chrome/browser/ui/views/<API key>.h" #include "chrome/browser/upgrade_detector.h" #include "chrome/common/pref_names.h" #include "chrome/grit/chromium_strings.h" #include "chrome/grit/generated_resources.h" #include "components/prefs/pref_service.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/page_navigator.h" #include "content/public/browser/user_metrics.h" #include "grit/theme_resources.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/resource/resource_bundle.h" #include "ui/views/controls/label.h" #include "ui/views/layout/fill_layout.h" #include "ui/views/layout/layout_constants.h" #include "ui/views/widget/widget.h" #include "url/gurl.h" #if defined(OS_WIN) #include "chrome/installer/util/google_update_util.h" #endif namespace { // Fixed width of the description label of the bubble. // TODO(mad): Make sure there is enough room for all languages. const int <API key> = 330; // The URL to be used to re-install Chrome when auto-update failed for too long. const char kDownloadChromeUrl[] = "https: "&utm_campaign=en&utm_source=<API key>&utm_medium=et"; // The maximum number of ignored bubble we track in the <API key> // histogram. const int kMaxIgnored = 50; // The number of buckets we want the <API key> histogram to use. const int kNumIgnoredBuckets = 5; // The currently showing bubble. <API key>* g_upgrade_bubble = nullptr; // The number of times the user ignored the bubble before finally choosing to // reinstall. int <API key> = 0; } // namespace // static void <API key>::ShowBubble(views::View* anchor_view, content::PageNavigator* navigator, bool auto_update_enabled) { if (g_upgrade_bubble) return; g_upgrade_bubble = new <API key>(anchor_view, navigator, auto_update_enabled); views::<API key>::CreateBubble(g_upgrade_bubble)->Show(); content::RecordAction(auto_update_enabled ? base::UserMetricsAction("<API key>.Show") : base::UserMetricsAction("<API key>.ShowNoAU")); } bool <API key>::IsAvailable() { // This should only work on non-Chrome OS desktop platforms. #if defined(OS_WIN) || defined(OS_MACOSX) || \ (defined(OS_LINUX) && !defined(OS_CHROMEOS)) return true; #else return false; #endif } <API key>::~<API key>() { // Increment the ignored bubble count (if this bubble wasn't ignored, this // increment is offset by a decrement in Accept()). if (<API key> < kMaxIgnored) ++<API key>; } void <API key>::WindowClosing() { // Reset |g_upgrade_bubble| here, not in destructor, because destruction is // asynchronous and ShowBubble may be called before full destruction and // would attempt to show a bubble that is closing. DCHECK_EQ(g_upgrade_bubble, this); g_upgrade_bubble = nullptr; } base::string16 <API key>::GetWindowTitle() const { return l10n_util::GetStringUTF16(<API key>); } gfx::ImageSkia <API key>::GetWindowIcon() { return *ui::ResourceBundle::GetSharedInstance().GetImageSkiaNamed( <API key>); } bool <API key>::<API key>() const { return true; } bool <API key>::Cancel() { content::RecordAction(base::UserMetricsAction("<API key>.Later")); return true; } bool <API key>::Accept() { // Offset the +1 in the dtor. --<API key>; if (<API key>) { DCHECK(UpgradeDetector::GetInstance()->is_outdated_install()); <API key>("<API key>.<API key>", <API key>, 0, kMaxIgnored, kNumIgnoredBuckets); content::RecordAction( base::UserMetricsAction("<API key>.Reinstall")); navigator_->OpenURL(content::OpenURLParams( GURL(kDownloadChromeUrl), content::Referrer(), NEW_FOREGROUND_TAB, ui::<API key>, false)); #if defined(OS_WIN) } else { DCHECK(UpgradeDetector::GetInstance()-><API key>()); <API key>("<API key>.NumLaterPerEnableAU", <API key>, 0, kMaxIgnored, kNumIgnoredBuckets); content::RecordAction( base::UserMetricsAction("<API key>.EnableAU")); // Record that the autoupdate flavour of the dialog has been shown. if (g_browser_process->local_state()) { g_browser_process->local_state()->SetBoolean( prefs::<API key>, true); } // Re-enable updates by shelling out to setup.exe in the blocking pool. content::BrowserThread::<API key>( FROM_HERE, base::Bind(&google_update::<API key>)); #endif // defined(OS_WIN) } return true; } void <API key>::UpdateButton(views::LabelButton* button, ui::DialogButton type) { <API key>::UpdateButton(button, type); if (type == ui::DIALOG_BUTTON_OK) { <API key>.reset(new ElevationIconSetter( button, base::Bind(&<API key>::SizeToContents, base::Unretained(this)))); } } base::string16 <API key>::<API key>( ui::DialogButton button) const { return l10n_util::GetStringUTF16( button == ui::<API key> ? IDS_LATER : <API key> ? IDS_REINSTALL_APP : <API key>); } void <API key>::Init() { SetLayoutManager(new views::FillLayout()); views::Label* text_label = new views::Label(l10n_util::GetStringUTF16( <API key> ? <API key> : <API key>)); text_label->SetMultiLine(true); text_label-><API key>(gfx::ALIGN_LEFT); text_label->SizeToFit(<API key>); AddChildView(text_label); } <API key>::<API key>( views::View* anchor_view, content::PageNavigator* navigator, bool auto_update_enabled) : <API key>(anchor_view, views::BubbleBorder::TOP_RIGHT), <API key>(auto_update_enabled), navigator_(navigator) { // Compensate for built-in vertical padding in the anchor view's image. <API key>(gfx::Insets( GetLayoutConstant(<API key>), 0)); }
/* $Id: node.h,v 1.36 2010/08/11 14:08:44 ragge Exp $ */ #ifndef NODE_H #define NODE_H union aarg { int iarg; char *sarg; void *varg; }; struct attr { struct attr *next; int atype; union aarg aa[]; }; /* * The node structure is the basic element in the compiler. * Depending on the operator, it may be one of several types. * * This is rewritten to be a struct instead of a union as it * was in the old compiler. */ typedef unsigned int TWORD; #define NIL (NODE *)0 struct symtab; struct suedef; struct regw; typedef struct node { struct node *next; int n_op; union { int _reg; struct regw *_regw; } n_3; #define n_reg n_3._reg #define n_regw n_3._regw TWORD n_type; TWORD n_qual; int n_su; union { char * _name; int _stsize; union dimfun *_df; } n_5; union { int _label; int _stalign; int _flags; #if 0 /* not anymore */ struct suedef *_sue; #else struct attr *_ap; #endif } n_6; union { struct { union { struct node *_left; CONSZ _lval; #ifdef SPECIAL_INTEGERS SPECLVAL _slval; #endif } n_l; union { struct node *_right; int _rval; struct symtab *_sp; } n_r; } n_u; #ifdef SOFTFLOAT #ifdef FDFLOAT /* To store F- or D-floats */ struct softfloat { unsigned short fd1, fd2, fd3, fd4; } _dcon; #else #error missing softfloat structure definition #endif #else long double _dcon; #endif } n_f; } NODE; #define n_name n_5._name #define n_stsize n_5._stsize #define n_df n_5._df #define n_label n_6._label #define n_stalign n_6._stalign #define n_flags n_6._flags #define n_ap n_6._ap #define n_left n_f.n_u.n_l._left #define n_lval n_f.n_u.n_l._lval #define n_slval n_f.n_u.n_l._slval #define n_right n_f.n_u.n_r._right #define n_rval n_f.n_u.n_r._rval #define n_sp n_f.n_u.n_r._sp #define n_dcon n_f._dcon #define NLOCAL1 010000 #define NLOCAL2 020000 #define NLOCAL3 040000 /* * Node types. * * MAXOP is the highest number used by the backend. */ #define FREE 1 /* * Value nodes. */ #define NAME 2 #define ICON 4 #define FCON 5 #define REG 6 #define OREG 7 #define TEMP 8 #define XARG 9 /* * Arithmetic nodes. */ #define PLUS 10 #define MINUS 11 #define DIV 12 #define MOD 13 #define MUL 14 /* * Bitwise operations. */ #define AND 15 #define OR 16 #define ER 17 #define LS 18 #define RS 19 #define COMPL 20 #define UMUL 23 #define UMINUS 24 /* * Logical compare nodes. */ #define EQ 25 #define NE 26 #define LE 27 #define LT 28 #define GE 29 #define GT 30 #define ULE 31 #define ULT 32 #define UGE 33 #define UGT 34 /* * Branch nodes. */ #define CBRANCH 35 /* * Convert types. */ #define FLD 36 #define SCONV 37 #define PCONV 38 #define PMCONV 39 #define PVCONV 40 /* * Function calls. */ #define CALL 41 #define UCALL 42 #define FORTCALL 43 #define UFORTCALL 44 #define STCALL 45 #define USTCALL 46 /* * Other used nodes. */ #define CCODES 47 #define CM 48 #define ASSIGN 49 #define STASG 50 #define STARG 51 #define FORCE 52 #define XASM 53 #define GOTO 54 #define RETURN 55 #define STREF 56 #define FUNARG 57 #define ADDROF 58 #define MAXOP 58 #endif
#include "cc/input/<API key>.h" #include "base/memory/ptr_util.h" #include "base/time/time.h" #include "cc/layers/layer_impl.h" #include "cc/layers/<API key>.h" namespace cc { std::unique_ptr<<API key>> <API key>::Create( int scroll_layer_id, <API key>* client, base::TimeDelta <API key>, base::TimeDelta <API key>, base::TimeDelta duration) { return base::WrapUnique(new <API key>( scroll_layer_id, client, <API key>, <API key>, duration)); } <API key>::<API key>( int scroll_layer_id, <API key>* client, base::TimeDelta <API key>, base::TimeDelta <API key>, base::TimeDelta duration) : <API key>(scroll_layer_id, client, <API key>, <API key>, duration) {} <API key>:: ~<API key>() {} void <API key>::RunAnimationFrame(float progress) { <API key>(1.f - progress); client_-><API key>(); if (progress == 1.f) StopAnimation(); } void <API key>::DidScrollUpdate(bool on_resize) { <API key>::DidScrollUpdate(on_resize); <API key>(1.f); } void <API key>::<API key>( float opacity) { for (<API key>* scrollbar : Scrollbars()) { if (!scrollbar-><API key>()) continue; scrollbar->OnOpacityAnimated(scrollbar-><API key>() ? opacity : 0); } } } // namespace cc
// modification, are permitted provided that the following conditions are // met: // documentation and/or other materials provided with the distribution. // * Neither the name of Image Engine Design nor the names of any // other contributors to this software may be used to endorse or // promote products derived from this software without specific prior // 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. #include "IECoreGL/Buffer.h" #include "IECore/Exception.h" using namespace IECoreGL; // ScopedBinding implementation Buffer::ScopedBinding::ScopedBinding( const Buffer &buffer, GLenum target ) : m_target( target ), m_buffer( buffer.m_buffer ), m_prevBuffer( 0 ) { switch( target ) { case GL_ARRAY_BUFFER : glGetIntegerv( <API key>, &m_prevBuffer ); break; case <API key> : glGetIntegerv( <API key>, &m_prevBuffer ); break; case <API key> : glGetIntegerv( <API key>, &m_prevBuffer ); break; case <API key> : glGetIntegerv( <API key>, &m_prevBuffer ); break; default : throw IECore::Exception( "IECoreGL::Buffer::ScopedBinding : Unknown target type" ); } glBindBuffer( m_target, m_buffer ); } Buffer::ScopedBinding::~ScopedBinding() { glBindBuffer( m_target, m_prevBuffer ); } // Buffer implementation <API key>( Buffer ) Buffer::Buffer( GLuint buffer ) : m_buffer( buffer ) { } Buffer::Buffer( const void *data, size_t sizeInBytes, GLenum target, GLenum usage ) { glGenBuffers( 1, &m_buffer ); ScopedBinding binding( *this, target ); glBufferData( target, sizeInBytes, data, usage ); } Buffer::~Buffer() { glDeleteBuffers( 1, &m_buffer ); } size_t Buffer::size() const { ScopedBinding binding( *this, GL_ARRAY_BUFFER ); int result = 0; <API key>( GL_ARRAY_BUFFER, GL_BUFFER_SIZE, &result ); return result; }
package org.hisp.dhis.trackedentity.action.programrule; import java.util.List; import org.hisp.dhis.program.Program; import org.hisp.dhis.program.ProgramService; import org.hisp.dhis.programrule.ProgramRule; import org.hisp.dhis.programrule.ProgramRuleService; import org.hisp.dhis.programrule.ProgramRuleVariable; import org.hisp.dhis.programrule.<API key>; import org.springframework.beans.factory.annotation.Autowired; import com.opensymphony.xwork2.Action; /** * @author Chau Thu Tran * * @version $ <API key>.java Mar 29, 2015 10:19:42 PM $ */ public class <API key> implements Action { // Dependencies @Autowired private ProgramRuleService programRuleService; @Autowired private <API key> variableService; @Autowired private ProgramService programService; // Input/Output private Integer id; public void setId( Integer id ) { this.id = id; } private ProgramRule programRule; public ProgramRule getProgramRule() { return programRule; } private Program program; public Program getProgram() { return program; } private List<ProgramRuleVariable> ruleVariables; public List<ProgramRuleVariable> getRuleVariables() { return ruleVariables; } // Action implementation @Override public String execute() throws Exception { programRule = programRuleService.getProgramRule( id ); program = programService.getProgram( programRule.getProgram().getId() ); ruleVariables = variableService.<API key>( program ); return SUCCESS; } }
/* This file was auto-generated by ensurePackage() in @jupyterlab/buildutils */ import '@fortawesome/fontawesome-free/css/all.min.css'; import '@fortawesome/fontawesome-free/css/v4-shims.min.css'; import '@lumino/widgets/style/index.js'; import '@jupyterlab/ui-components/style/index.js'; import '@jupyterlab/apputils/style/index.js'; import '@jupyterlab/docregistry/style/index.js'; import './base.css';
#import <string> #import <unordered_map> #import <UIKit/UIKit.h> #import <ComponentKit/<API key>.h> #import <ComponentKit/<API key>.h> #import <ComponentKit/<API key>.h> #import <ComponentKit/<API key>.h> #import <ComponentKit/<API key>.h> #import <ComponentKit/CKContainerWrapper.h> class <API key>; typedef void (^<API key>)(UIView *); struct <API key> { /** The no-argument default constructor, which specifies that the component should not have a corresponding view. */ <API key>() noexcept; /** Specifies that the component should have a view of the given class. The class will be instantiated with UIView's designated initializer -initWithFrame:. */ <API key>(Class viewClass) noexcept; /** A variant that allows you to specify two selectors that are sent as a view is hidden/unhidden for future reuse. Note that a view can be reused but not hidden so never enters the pool (in which case these selectors won't be sent). @param <API key> Sent to the view just after it has been hidden for future reuse. @param willLeaveReusePool Sent to the view just before it is revealed after being reused. */ <API key>(Class viewClass, SEL <API key>, SEL <API key>) noexcept; /** Specifies a view class that cannot be instantiated with -initWithFrame:. Allows you to specify two blocks that are invoked as a view is hidden/unhidden for future reuse. Note that a view can be reused but not hidden so never enters the pool (in which case these blocks won't be invoked). @param factory A pointer to a function that returns a new instance of a view. @param didEnterReusePool Executed after a view has been hidden for future reuse. @param willLeaveReusePool Executed just before a view is revealed after being reused. */ <API key>(UIView *(*factory)(void), <API key> didEnterReusePool = nil, <API key> willLeaveReusePool = nil) noexcept; /** Invoked by the infrastructure to create a new instance of the view. You should not call this directly. */ UIView *createView() const; /** Invoked by the infrastructure to determine if this will create a view or not. */ BOOL hasView() const; bool operator==(const <API key> &other) const noexcept { return other.identifier == identifier; } bool operator!=(const <API key> &other) const noexcept { return other.identifier != identifier; } const std::string &getIdentifier() const noexcept { return identifier; } private: <API key>(const std::string &ident, UIView *(^factory)(void), <API key> didEnterReusePool = nil, <API key> willLeaveReusePool = nil) noexcept; std::string identifier; UIView *(^factory)(void); <API key> didEnterReusePool; <API key> willLeaveReusePool; friend class CK::Component::ViewReuseUtilities; }; namespace std { template<> struct hash<<API key>> { size_t operator()(const <API key> &cl) const { return hash<std::string>()(cl.getIdentifier()); } }; } /** A <API key> specifies the class of a view and the attributes that should be applied to it. Initialize a configuration with brace syntax, for example: {[UIView class]} {[UIView class], {{@selector(setBackgroundColor:), [UIColor redColor]}, {@selector(setAlpha:), @0.5}}} */ struct <API key> { <API key>() noexcept; <API key>(<API key> &&cls, CKContainerWrapper<<API key>> &&attrs = {}) noexcept; <API key>(<API key> &&cls, CKContainerWrapper<<API key>> &&attrs, <API key> &&accessibilityCtx) noexcept; ~<API key>(); bool operator==(const <API key> &other) const noexcept; const <API key> &viewClass() const noexcept; std::shared_ptr<const <API key>> attributes() const noexcept; const <API key> &<API key>() const noexcept; private: struct Repr { <API key> viewClass; std::shared_ptr<const <API key>> attributes; <API key> <API key>; CK::Component::<API key> attributeShape; }; static std::shared_ptr<const Repr> <API key>(); std::shared_ptr<const Repr> rep; // const is important for the <API key> optimization. friend class CK::Component::ViewReusePoolMap; // uses attributeShape }; namespace std { template<> struct hash<<API key>> { size_t operator()(const <API key> &cl) const noexcept; }; }
#include "media/blink/<API key>.h" #include <utility> #include "base/bind.h" #include "base/logging.h" #include "base/numerics/safe_conversions.h" #include "base/strings/string_util.h" #include "base/strings/<API key>.h" #include "media/base/cdm_promise.h" #include "media/base/key_systems.h" #include "media/base/media_keys.h" #include "media/blink/cdm_result_promise.h" #include "media/blink/cdm_session_adapter.h" #include "media/blink/<API key>.h" #include "third_party/WebKit/public/platform/URLConversion.h" #include "third_party/WebKit/public/platform/WebSecurityOrigin.h" #include "third_party/WebKit/public/platform/WebString.h" #include "url/gurl.h" namespace media { void <API key>::Create( media::CdmFactory* cdm_factory, const base::string16& key_system, const blink::WebSecurityOrigin& security_origin, const CdmConfig& cdm_config, std::unique_ptr<blink::<API key>> result) { DCHECK(!security_origin.isNull()); DCHECK(!key_system.empty()); // TODO(ddorwin): Guard against this in supported types check and remove this. // Chromium only supports ASCII key systems. if (!base::IsStringASCII(key_system)) { NOTREACHED(); result->completeWithError( blink::<API key>, 0, "Invalid keysystem."); return; } // TODO(ddorwin): This should be a DCHECK. std::string key_system_ascii = base::UTF16ToASCII(key_system); if (!media::KeySystems::GetInstance()-><API key>( key_system_ascii)) { std::string message = "Keysystem '" + key_system_ascii + "' is not supported."; result->completeWithError( blink::<API key>, 0, blink::WebString::fromUTF8(message)); return; } // If unique security origin, don't try to create the CDM. if (security_origin.isUnique() || security_origin.toString() == "null") { result->completeWithError( blink::<API key>, 0, "EME use is not allowed on unique origins."); return; } GURL <API key>( blink::WebStringToGURL(security_origin.toString())); // CdmSessionAdapter::CreateCdm() will keep a reference to |adapter|. Then // if <API key> is successfully created (returned in // |result|), it will keep a reference to |adapter|. Otherwise, |adapter| will // be destructed. scoped_refptr<CdmSessionAdapter> adapter(new CdmSessionAdapter()); adapter->CreateCdm(cdm_factory, key_system_ascii, <API key>, cdm_config, std::move(result)); } <API key>::<API key>( scoped_refptr<CdmSessionAdapter> adapter) : adapter_(adapter) { } <API key>::~<API key>() { } // The caller owns the created session. blink::<API key>* <API key>::createSession() { return adapter_->CreateSession(); } void <API key>::<API key>( const uint8_t* server_certificate, size_t <API key>, blink::<API key> result) { DCHECK(server_certificate); adapter_-><API key>( std::vector<uint8_t>(server_certificate, server_certificate + <API key>), std::unique_ptr<SimpleCdmPromise>( new CdmResultPromise<>(result, std::string()))); } CdmContext* <API key>::GetCdmContext() { return adapter_->GetCdmContext(); } } // namespace media
(function (root, factory) { // CommonJS if (typeof exports === 'object') { module.exports = factory(); } // AMD module else if (typeof define === 'function' && define.amd) { define([ 'spin' ], factory); } // Browser global else { root.Ladda = factory(root.Spinner); } } (this, function (Spinner) { 'use strict'; // All currently instantiated instances of Ladda var ALL_INSTANCES = []; /** * Creates a new instance of Ladda which wraps the * target button element. * * @return An API object that can be used to control * the loading animation state. */ function create(button) { if (typeof button === 'undefined') { console.warn("Ladda button target must be defined."); return; } // The text contents must be wrapped in a ladda-label // element, create one if it doesn't already exist if (!button.querySelector('.ladda-label')) { button.innerHTML = '<span class="ladda-label">' + button.innerHTML + '</span>'; } // The spinner component var spinner; // Wrapper element for the spinner var spinnerWrapper = document.createElement('span'); spinnerWrapper.className = 'ladda-spinner'; button.appendChild(spinnerWrapper); // Timer used to delay starting/stopping var timer; var instance = { /** * Enter the loading state. */ start: function () { // Create the spinner if it doesn't already exist if (!spinner) spinner = createSpinner(button); button.setAttribute('disabled', ''); button.setAttribute('data-loading', ''); clearTimeout(timer); spinner.spin(spinnerWrapper); this.setProgress(0); return this; // chain }, /** * Enter the loading state, after a delay. */ startAfter: function (delay) { clearTimeout(timer); timer = setTimeout(function () { instance.start(); }, delay); return this; // chain }, /** * Exit the loading state. */ stop: function () { button.removeAttribute('disabled'); button.removeAttribute('data-loading'); // Kill the animation after a delay to make sure it // runs for the duration of the button transition clearTimeout(timer); if (spinner) { timer = setTimeout(function () { spinner.stop(); }, 1000); } return this; // chain }, /** * Toggle the loading state on/off. */ toggle: function () { if (this.isLoading()) { this.stop(); } else { this.start(); } return this; // chain }, /** * Sets the width of the visual progress bar inside of * this Ladda button * * @param {Number} progress in the range of 0-1 */ setProgress: function (progress) { // Cap it progress = Math.max(Math.min(progress, 1), 0); var progressElement = button.querySelector('.ladda-progress'); // Remove the progress bar if we're at 0 progress if (progress === 0 && progressElement && progressElement.parentNode) { progressElement.parentNode.removeChild(progressElement); } else { if (!progressElement) { progressElement = document.createElement('div'); progressElement.className = 'ladda-progress'; button.appendChild(progressElement); } progressElement.style.width = ( ( progress || 0 ) * button.offsetWidth ) + 'px'; } }, enable: function () { this.stop(); return this; // chain }, disable: function () { this.stop(); button.setAttribute('disabled', ''); return this; // chain }, isLoading: function () { return button.hasAttribute('data-loading'); } }; ALL_INSTANCES.push(instance); return instance; } /** * Get the first ancestor node from an element, having a * certain type. * * @param elem An HTML element * @param type an HTML tag type (uppercased) * * @return An HTML element */ function <API key>(elem, type) { while (elem.parentNode && elem.tagName !== type) { elem = elem.parentNode; } return ( type === elem.tagName ) ? elem : undefined; } /** * Returns a list of all inputs in the given form that * have their `required` attribute set. * * @param form The from HTML element to look in * * @return A list of elements */ function getRequiredFields(form) { var requirables = [ 'input', 'textarea' ]; var inputs = []; for (var i = 0; i < requirables.length; i++) { var candidates = form.<API key>(requirables[i]); for (var j = 0; j < candidates.length; j++) { if (candidates[j].hasAttribute('required')) { inputs.push(candidates[j]); } } } return inputs; } /** * Binds the target buttons to automatically enter the * loading state when clicked. * * @param target Either an HTML element or a CSS selector. * @param options * - timeout Number of milliseconds to wait before * automatically cancelling the animation. */ function bind(target, options) { options = options || {}; var targets = []; if (typeof target === 'string') { targets = toArray(document.querySelectorAll(target)); } else if (typeof target === 'object' && typeof target.nodeName === 'string') { targets = [ target ]; } for (var i = 0, len = targets.length; i < len; i++) { (function () { var element = targets[i]; // Make sure we're working with a DOM element if (typeof element.addEventListener === 'function') { var instance = create(element); var timeout = -1; element.addEventListener('click', function (event) { // If the button belongs to a form, make sure all the // fields in that form are filled out var valid = true; var form = <API key>(element, 'FORM'); if (typeof form !== 'undefined') { var requireds = getRequiredFields(form); for (var i = 0; i < requireds.length; i++) { // Alternatively to this trim() check, // we could have use .checkValidity() or .validity.valid if (requireds[i].value.replace(/^\s+|\s+$/g, '') === '') { valid = false; } } } if (valid) { // This is asynchronous to avoid an issue where setting // the disabled attribute on the button prevents forms // from submitting instance.startAfter(1); // Set a loading timeout if one is specified if (typeof options.timeout === 'number') { clearTimeout(timeout); timeout = setTimeout(instance.stop, options.timeout); } // Invoke callbacks if (typeof options.callback === 'function') { options.callback.apply(null, [ instance ]); } } }, false); } })(); } } /** * Stops ALL current loading animations. */ function stopAll() { for (var i = 0, len = ALL_INSTANCES.length; i < len; i++) { ALL_INSTANCES[i].stop(); } } function createSpinner(button) { var height = button.offsetHeight, spinnerColor; if (height === 0) { // We may have an element that is not visible so // we attempt to get the height in a different way height = parseFloat(window.getComputedStyle(button).height); } // If the button is tall we can afford some padding if (height > 32) { height *= 0.8; } // Prefer an explicit height if one is defined if (button.hasAttribute('data-spinner-size')) { height = parseInt(button.getAttribute('data-spinner-size'), 10); } // Allow buttons to specify the color of the spinner element if (button.hasAttribute('data-spinner-color')) { spinnerColor = button.getAttribute('data-spinner-color'); } var lines = 12, radius = height * 0.2, length = radius * 0.6, width = radius < 7 ? 2 : 3; return new Spinner({ color: spinnerColor || '#fff', lines: lines, radius: radius, length: length, width: width, zIndex: 'auto', top: 'auto', left: 'auto', className: '' }); } function toArray(nodes) { var a = []; for (var i = 0; i < nodes.length; i++) { a.push(nodes[ i ]); } return a; } // Public API return { bind: bind, create: create, stopAll: stopAll }; }));
html { height: 100%; } body { display: flex; flex-direction: column; height: 100%; margin: 0; padding: 0; width: 100%; } [hidden] { display: none !important; } .title-bar { -webkit-align-items: center; -webkit-app-region: drag; background-color: var(--feedback-bg-color); box-shadow: 0 1px var(--<API key>); color: var(--<API key>); display: flex; flex-grow: 0; font-size: 15px; min-height: 48px; } .title-bar #page-title { flex: 1 1 auto; margin-inline-start: 20px; } .title-bar .button-bar { flex: 0 1 auto; } #content-pane { flex-grow: 1; flex-shrink: 1; overflow: auto; padding: 20px; } .content { color: var(--<API key>); font-size: 12px; } .content #free-form-text { margin-top: 0; /* the content frame already gives enough margin. */ } .content #description-text { border-color: var(--<API key>); box-sizing: border-box; height: 120px; line-height: 18px; padding: 10px; resize: none; width: 100%; } .content #<API key> { margin-inline-start: 10px; } .content .<API key> { -webkit-align-items: center; display: flex; height: 29px; margin-top: 10px; <API key>: 10px; } :is(input:not([type=file]), select, textarea) { background-color: var(--<API key>); } :is(input, select, textarea):active, :is(input, select, textarea):focus { caret-color: var(--<API key>); outline: 2px solid var(--<API key>); } .content .<API key> > label { flex: 0 1 auto; width: 100px; } .content .<API key> > select { border: 1px solid var(--<API key>); color: var(--<API key>); flex: 1 1 auto; height: 100%; <API key>: 5px; } .content .<API key> > input[type=text] { border: 1px solid; border-color: var(--<API key>); color: var(--<API key>); flex: 1 1 auto; height: 100%; <API key>: 5px; } .content .<API key> > input:focus { color: var(--<API key>); } .content .<API key> > input[type=checkbox] { margin-inline-end: 9px; } .content .<API key> { color: var(--<API key>); font-weight: bold; } .content .<API key> { -webkit-align-items: center; display: flex; height: 29px; } #<API key> { align-items: flex-start; line-height: 20px; margin-bottom: 20px; margin-top: 7px; vertical-align: text-top; } #<API key> { margin-top: 10px; } .content #screenshot-image { display: block; height: 60px; margin-inline-end: 25px; margin-top: 40px; transition: all 250ms ease; } .content #screenshot-image:hover { height: 125px; margin-inline-end: 0; margin-top: 80px; z-index: 1; } .content #screenshot-image.wide-screen { height: auto; width: 100px; } .content #screenshot-image.wide-screen:hover { height: auto; width: 200px; } .content #<API key> { flex: auto; } .content #sys-info-container { margin-inline-end: 130px; } .content #privacy-note { font-size: 12px; line-height: 20px; margin-bottom: 0; margin-top: 20px; text-align: justify; text-justify: inter-word; } .content .buttons-pane { bottom: 20px; display: flex; justify-content: flex-end; left: 20px; position: absolute; right: 20px; } .content .top-buttons { position: absolute; } #<API key> { box-shadow: 0 -1px #d0d0d0; margin: 0; padding: 0 20px; } .content .bottom-buttons { margin: 20px; position: static; } .content .remove-file-button { background-color: transparent; background-image: -webkit-image-set( url(../images/<API key>.png) 1x, url(../images/2x/<API key>.png) 2x); background-position: 50% 80%; background-repeat: no-repeat; border: none; height: 16px; margin-inline-start: 5px; pointer-events: auto; width: 16px; } .content .remove-file-button:hover { background-image: -webkit-image-set( url(../images/<API key>.png) 1x, url(../images/2x/<API key>.png) 2x); } .content .remove-file-button:active { background-image: -webkit-image-set( url(../images/<API key>.png) 1x, url(../images/2x/<API key>.png) 2x); } .content #attach-file-note { margin-bottom: 10px; margin-inline-start: 112px; margin-top: 10px; } .content .<API key> { color: var(--<API key>); font-weight: bold; } button.white-button { color: #000; margin-inline-end: 10px; } button.blue-button { color: #fff; text-shadow: 1px sharp drop shadow var(--<API key>); } /* Used for elements that are hidden but not ignored by screen reader. */ .off-screen { height: 1px; overflow: hidden; position: absolute; top: -1000px; width: 1px; } option { background: var(--feedback-bg-color) linear-gradient( rgba(255,255,255, 0.06),rgba(255,255,255, 0.06)); box-shadow: 0 1px 2px rgba(var(--<API key>), 0.3), 0 1px 6px rgba(var(--<API key>), 0.15); }
layout: demo title: Light7 Demo <div id="page-calendar" class="page"> <header class="bar bar-nav"> <a class="button button-link button-nav pull-left back" href="/demos"> <span class="icon icon-left"></span> Back </a> <h1 class='title'>Calendar</h1> </header> <div class="content"> <div class="content-block"> <div class="list-block"> <ul> <!-- Text inputs --> <li> <div class="item-content"> <div class="item-inner"> <div class="item-title label">Birthday</div> <div class="item-input"> <input type="text" placeholder="Your name" id='birthday' data-toggle='date'/> </div> </div> </div> </li> </ul> </div> </div> </div> </div>
// .NAME vtkFreeTypeTools - FreeType library support // .SECTION Description // vtkFreeTypeTools provides a low-level interface to the FreeType2 library, // including font-cache and rasterization. // .Section Caveats // Internal use only. #ifndef <API key> #define <API key> #include "<API key>.h" // For export macro #include "vtkObject.h" class vtkImageData; class vtkPath; class vtkTextProperty; class vtkStdString; class vtkUnicodeString; // FreeType #include "vtk_freetype.h" //since ft2build.h could be in the path #include FT_FREETYPE_H #include FT_GLYPH_H #include FT_CACHE_H class FTFont; // PIMPL class for FTC_FaceID->vtkTextProperty lookup class <API key>; // Singleton cleanup class <API key> <API key> { public: <API key>(); ~<API key>(); }; // Singleton font cache class <API key> vtkFreeTypeTools : public vtkObject { public: vtkTypeMacro(vtkFreeTypeTools, vtkObject); void PrintSelf(ostream& os, vtkIndent indent); // Description: // Return the singleton instance with no reference counting. static vtkFreeTypeTools* GetInstance(); // Description: // Supply a user defined instance. Call Delete() on the supplied // instance after setting it to fix the reference count. static void SetInstance(vtkFreeTypeTools *instance); // Description: // Get the FreeType library singleton. FT_Library* GetLibrary(); // Description: // Set/Get the maximum number of faces (FT_Face), sizes (FT_Size) and // bytes used by the cache. These settings can be changed as long as // it is done prior to accessing any of the caches or the cache manager. vtkSetClampMacro(<API key>,unsigned int,1,<API key>); vtkGetMacro(<API key>, unsigned int); vtkSetClampMacro(<API key>,unsigned int,1,<API key>); vtkGetMacro(<API key>, unsigned int); vtkSetClampMacro(<API key>,unsigned long,1,<API key>); vtkGetMacro(<API key>, unsigned long); // Description: // Given a text property and a string, get the bounding box [xmin, xmax] x // [ymin, ymax]. Note that this is the bounding box of the area // where actual pixels will be written, given a text/pen/baseline location // of (0,0). // For example, if the string starts with a 'space', or depending on the // orientation, you can end up with a [-20, -10] x [5, 10] bbox (the math // to get the real bbox is straightforward). // Return 1 on success, 0 otherwise. // You can use IsBoundingBoxValid() to test if the computed bbox // is valid (it may not if GetBoundingBox() failed or if the string // was empty). bool GetBoundingBox(vtkTextProperty *tprop, const vtkStdString& str, int bbox[4]); bool GetBoundingBox(vtkTextProperty *tprop, const vtkUnicodeString& str, int bbox[4]); bool IsBoundingBoxValid(int bbox[4]); // Description: // Given a text property and a string, this function initializes the // vtkImageData *data and renders it in a vtkImageData. textDims, if provided, // will be overwritten by the pixel width and height of the rendered string. // This is useful when ScaleToPowerOfTwo is true, and the image dimensions may // not match the dimensions of the rendered text. bool RenderString(vtkTextProperty *tprop, const vtkStdString& str, vtkImageData *data, int textDims[2] = NULL); bool RenderString(vtkTextProperty *tprop, const vtkUnicodeString& str, vtkImageData *data, int textDims[2] = NULL); // Description: // Given a text property and a string, this function populates the vtkPath // path with the outline of the rendered string. bool StringToPath(vtkTextProperty *tprop, const vtkStdString& str, vtkPath *path); bool StringToPath(vtkTextProperty *tprop, const vtkUnicodeString& str, vtkPath *path); // Description: // This function returns the font size (in points) required to fit the string // in the target rectangle. The font size of tprop is updated to the computed // value as well. If an error occurs, -1 is returned. int <API key>(const vtkStdString &str, vtkTextProperty *tprop, int targetWidth, int targetHeight); int <API key>(const vtkUnicodeString &str, vtkTextProperty *tprop, int targetWidth, int targetHeight); // Description: // Turn a string into a hash. This is not a general purpose hash // function, and is only used to generate identifiers for cached fonts. static vtkTypeUInt16 HashString(const char *str); // Description: // Given a text property 'tprop', get its unique ID in our cache framework. // In the same way, given a unique ID in our cache, retrieve the // corresponding text property and assign its parameters to 'tprop'. // Warning: there is no one to one mapping between a single text property // the corresponding ID, and vice-versa. The ID is just a fast hash, a // binary mask concatenating the attributes of the text property that are // relevant to our cache (Color, Opacity, Justification setting are not // stored). void MapTextPropertyToId(vtkTextProperty *tprop, unsigned long *tprop_cache_id); void MapIdToTextProperty(unsigned long tprop_cache_id, vtkTextProperty *tprop); // Description: // Set whether the image produced should be scaled up to the nearest power of // 2. This is normally required for older graphics cards where all textures // must be a power of 2. This defaults to false, and should be fine on modern // hardware. vtkSetMacro(ScaleToPowerTwo, bool); vtkGetMacro(ScaleToPowerTwo, bool); vtkBooleanMacro(ScaleToPowerTwo, bool); // Description: // Force use of the fonts compiled into VTK, ignoring any FontConfig or // embedded fonts. Useful for generating test images consistently across // platforms. This flag is on by default. vtkSetMacro(ForceCompiledFonts, bool); vtkGetMacro(ForceCompiledFonts, bool); vtkBooleanMacro(ForceCompiledFonts, bool); // Description: // Lookup and set the FreeType font face @a face best matching the text // property @a tprop using the compiled Arial, Times, and Courier fonts. If // an unrecognized font family is requested, Arial will be substituted. // Returns true if the face is set, false otherwise. static bool LookupFace(vtkTextProperty *tprop, FT_Library lib, FT_Face *face); protected: // Description: // Create the FreeType Cache manager instance and set this->CacheManager virtual FT_Error CreateFTCManager(); // Description: // Used to store state about a particular rendering and cache constant values class MetaData; class ImageMetaData; bool PrepareMetaData(vtkTextProperty *tprop, MetaData &metaData); bool <API key>(vtkTextProperty *tprop, vtkImageData *image, ImageMetaData &metaData); // Description: // Internal helper called by RenderString methods template <typename StringType> bool <API key>(vtkTextProperty *tprop, const StringType &str, vtkImageData *data, int textDims[2]); // Description: // Internal helper method called by StringToPath methods template <typename StringType> bool <API key>(vtkTextProperty *tprop, const StringType &str, vtkPath *path); // Description: // This function initializes calculates the size of the required bounding box // and stores it in the MetaData provided. Both the rotated and unrotated // bounding boxes are set, along with the lineWidths. template <typename T> bool <API key>(const T& str, MetaData &metaData); // Description: // This function initializes the extent of the ImageData to eventually // receive the text stored in str void PrepareImageData(vtkImageData *data, int bbox[4]); // Description: // Internal helper method called by RenderString. // metaData is passed through the the character renderer and caches properties // about data (e.g. range, dimensions, increments, etc). template <typename StringType, typename DataType> bool PopulateData(const StringType& str, DataType data, MetaData &metaData); // Description: // Renders a single line of text (between begin and end) to the image data. template <typename IteratorType, typename DataType> bool RenderLine(IteratorType begin, IteratorType end, int lineIndex, DataType data, MetaData &metaData); // Description: // Implementations for rendering a single character to a specific target. template <typename CharType> bool RenderCharacter(CharType character, int &x, int &y, FT_UInt &previousGlyphIndex, vtkImageData *image, MetaData &metaData); template <typename CharType> bool RenderCharacter(CharType character, int &x, int &y, FT_UInt &previousGlyphIndex, vtkPath *path, MetaData &metaData); // Description: // Internal helper method called by StringToPath void JustifyPath(vtkPath *path, MetaData &metaData); // Description: // Internal helper method called by <API key>. Returns the // fontsize (in points) that will fit the return string @a str into the @a // targetWidth and @a targetHeight. template <typename T> int FitStringToBBox(const T &str, MetaData &metaData, int targetWidth, int targetHeight); // Description: // Given a text property, get the corresponding FreeType size object // (a structure storing both a face and a specific size metric). // The size setting of the text property is used to set the size's face // to the corresponding size. // Return true on success, false otherwise. bool GetSize(vtkTextProperty *tprop, FT_Size *size); // Description: // Given a text property, get the corresponding FreeType face. // The size parameter of the text property is ignored and a face with // unknown current size is returned. Use GetSize() to get a specific size. // Return true on success, false otherwise bool GetFace(vtkTextProperty *tprop, FT_Face *face); // Description: // Given a text property and a character, get the corresponding FreeType // glyph index. // Return true on success, false otherwise bool GetGlyphIndex(vtkTextProperty *tprop, FT_UInt32 c, FT_UInt *gindex); // Description: // Given a text property and a character, get the corresponding FreeType // glyph. The 'request' parameter can be used to request the glyph to be // in a specific format. If <API key>, the glyph might be either // an outline (most of the time) or a bitmap if the face includes a set of // pre-rendered glyphs (called "strikes") for a given size. // If <API key>, the glyph is rendered immediately and can // be safely cast to a FT_BitmapGlyph. If <API key>, no // pre-rendered "strike" is considered, the glyph is an outline and can be // safely cast to a FT_OutlineGlyph. // Return true on success, false otherwise enum { <API key> = 0, <API key> = 1, <API key> = 2 }; bool GetGlyph(vtkTextProperty *tprop, FT_UInt32 c, FT_Glyph *glyph, int request = <API key>); bool GetSize(unsigned long tprop_cache_id, int font_size, FT_Size *size); bool GetFace(unsigned long tprop_cache_id, FT_Face *face); bool GetGlyphIndex(unsigned long tprop_cache_id, FT_UInt32 c, FT_UInt *gindex); bool GetGlyph(unsigned long tprop_cache_id, int font_size, FT_UInt gindex, FT_Glyph *glyph, int request = <API key>); // Description: // Should the image be scaled to the next highest power of 2? bool ScaleToPowerTwo; vtkFreeTypeTools(); virtual ~vtkFreeTypeTools(); // Description: // Attempt to get the typeface of the specified font. bool GetFace(vtkTextProperty *prop, unsigned long &prop_cache_id, FT_Face &face, bool &face_has_kerning); // Description: // Now attempt to get the bitmap for the specified character. FT_Bitmap* GetBitmap(FT_UInt32 c, unsigned long prop_cache_id, int prop_font_size, FT_UInt &gindex, FT_BitmapGlyph &bitmap_glyph); // Description: // Attempt to get the outline for the specified character. FT_Outline* GetOutline(FT_UInt32 c, unsigned long prop_cache_id, int prop_font_size, FT_UInt &gindex, FT_OutlineGlyph &outline_glyph); // Description: // Get the width of the rendered string between iterators // begin and end. Width is calculated as the sum of advances and kernings // along the baseline (i.e. rotations are ignored), while bbox is the // is a tight fitting bbox around the rendering string, assuming (0, 0) // is the pen origin. template<typename T> void GetLineMetrics(T begin, T end, MetaData &metaData, int &width, int bbox[4]); // Description: // The singleton instance and the singleton cleanup instance static vtkFreeTypeTools* Instance; static <API key> Cleanup; // Description: // Lookup table that maps free type font cache face ids to vtkTextProperties <API key> *TextPropertyLookup; // Description: // The cache manager, image cache and charmap cache FTC_Manager *CacheManager; FTC_ImageCache *ImageCache; FTC_CMapCache *CMapCache; // Description: // Get the FreeType cache manager, image cache and charmap cache FTC_Manager* GetCacheManager(); FTC_ImageCache* GetImageCache(); FTC_CMapCache* GetCMapCache(); unsigned int <API key>; unsigned int <API key>; unsigned long <API key>; bool ForceCompiledFonts; void <API key>(); void ReleaseCacheManager(); private: vtkFreeTypeTools(const vtkFreeTypeTools&); // Not implemented. void operator=(const vtkFreeTypeTools&); // Not implemented. }; #endif
#.rst: # FindIcotool # Find icotool # This module looks for icotool. This module defines the following # values: # ICOTOOL_EXECUTABLE: the full path to the icotool tool. # ICOTOOL_FOUND: True if icotool has been found. # <API key>: the version of icotool found. find_program(ICOTOOL_EXECUTABLE icotool ) if(ICOTOOL_EXECUTABLE) execute_process( COMMAND ${ICOTOOL_EXECUTABLE} --version OUTPUT_VARIABLE _icotool_version ERROR_QUIET <API key> ) if("${_icotool_version}" MATCHES "^icotool \\([^\\)]*\\) ([0-9\\.]+[^ \n]*)") set( <API key> "${CMAKE_MATCH_1}" ) else() set( <API key> "" ) endif() unset(_icotool_version) endif() include(${<API key>}/<API key>.cmake) <API key>( Icotool REQUIRED_VARS ICOTOOL_EXECUTABLE VERSION_VAR <API key> ) mark_as_advanced( ICOTOOL_EXECUTABLE )
#ifndef <API key> #define <API key> #pragma once #include <deque> #include <vector> #include "base/compiler_specific.h" #include "base/memory/linked_ptr.h" #include "base/memory/scoped_ptr.h" #include "base/observer_list.h" #include "base/time.h" #include "ui/base/animation/<API key>.h" #include "ui/base/animation/tween.h" #include "ui/gfx/compositor/compositor_export.h" #include "ui/gfx/compositor/<API key>.h" namespace gfx { class Rect; } namespace ui { class Animation; class Layer; class <API key>; class <API key>; class <API key>; class <API key>; class Transform; // When a property of layer needs to be changed it is set by way of // LayerAnimator. This enables LayerAnimator to animate property changes. // NB: during many tests, <API key> is used and causes // all animations to complete immediately. class COMPOSITOR_EXPORT LayerAnimator : public <API key> { public: enum PreemptionStrategy { <API key>, <API key>, <API key>, <API key>, <API key> }; explicit LayerAnimator(base::TimeDelta transition_duration); virtual ~LayerAnimator(); // No implicit animations when properties are set. static LayerAnimator* <API key>(); // Implicitly animates when properties are set. static LayerAnimator* <API key>(); // Sets the transform on the delegate. May cause an implicit animation. virtual void SetTransform(const Transform& transform); Transform GetTargetTransform() const; // Sets the bounds on the delegate. May cause an implicit animation. virtual void SetBounds(const gfx::Rect& bounds); gfx::Rect GetTargetBounds() const; // Sets the opacity on the delegate. May cause an implicit animation. virtual void SetOpacity(float opacity); float GetTargetOpacity() const; // Sets the visibility of the delegate. May cause an implicit animation. virtual void SetVisibility(bool visibility); bool GetTargetVisibility() const; // Sets the layer animation delegate the animator is associated with. The // animator does not own the delegate. void SetDelegate(<API key>* delegate); // Sets the animation preemption strategy. This determines the behaviour if // a property is set during an animation. The default is // <API key> (see <API key> below). void <API key>(PreemptionStrategy strategy) { <API key> = strategy; } PreemptionStrategy preemption_strategy() const { return <API key>; } // Start an animation sequence. If an animation for the same property is in // progress, it needs to be interrupted with the new animation. The animator // takes ownership of this animation sequence. void StartAnimation(<API key>* animation); // Schedule an animation to be run when possible. The animator takes ownership // of this animation sequence. void ScheduleAnimation(<API key>* animation); // Schedules the animations to be run together. Obviously will no work if // they animate any common properties. The animator takes ownership of the // animation sequences. void ScheduleTogether(const std::vector<<API key>*>& animations); // Returns true if there is an animation in the queue (animations remain in // the queue until they complete, so this includes running animations). bool is_animating() const { return !animation_queue_.empty(); } // Returns true if there is an animation in the queue that animates the given // property (animations remain in the queue until they complete, so this // includes running animations). bool IsAnimatingProperty( <API key>::AnimatableProperty property) const; // Stops animating the given property. No effect if there is no running // animation for the given property. Skips to the final state of the // animation. void <API key>( <API key>::AnimatableProperty property); // Stops all animation and clears any queued animations. void StopAnimating(); // These functions are used for adding or removing observers from the observer // list. The observers are notified when animations end. void AddObserver(<API key>* observer); void RemoveObserver(<API key>* observer); // This determines how implicit animations will be tweened. This has no // effect on animations that are explicitly started or scheduled. The default // is Tween::LINEAR. void set_tween_type(Tween::Type tween_type) { tween_type_ = tween_type; } Tween::Type tween_type() const { return tween_type_; } // For testing purposes only. void <API key>(bool disable_timer) { <API key> = disable_timer; } base::TimeTicks last_step_time() const { return last_step_time_; } // When set to true, all animations complete immediately. static void <API key>(bool disable_animations) { <API key> = disable_animations; } static bool <API key>() { return <API key>; } protected: <API key>* delegate() { return delegate_; } const <API key>* delegate() const { return delegate_; } // Virtual for testing. virtual bool ProgressAnimation(<API key>* sequence, base::TimeDelta delta); // Returns true if the sequence is owned by this animator. bool HasAnimation(<API key>* sequence) const; private: friend class <API key>; // We need to keep track of the start time of every running animation. struct RunningAnimation { RunningAnimation(<API key>* sequence, base::TimeTicks start_time) : sequence(sequence), start_time(start_time) { } <API key>* sequence; base::TimeTicks start_time; }; typedef std::vector<RunningAnimation> RunningAnimations; typedef std::deque<linked_ptr<<API key>> > AnimationQueue; // Implementation of <API key> virtual void SetStartTime(base::TimeTicks start_time) OVERRIDE; virtual void Step(base::TimeTicks time_now) OVERRIDE; virtual base::TimeDelta GetTimerInterval() const OVERRIDE; // Starts or stops stepping depending on whether thare are running animations. void <API key>(); // Removes the sequences from both the running animations and the queue. // Returns a pointer to the removed animation, if any. NOTE: the caller is // responsible for deleting the returned pointer. <API key>* RemoveAnimation( <API key>* sequence) WARN_UNUSED_RESULT; // Progresses to the end of the sequence before removing it. void FinishAnimation(<API key>* sequence); // Finishes any running animation with zero duration. void <API key>(); // Clears the running animations and the queue. No sequences are progressed. void ClearAnimations(); // Returns the running animation animating the given property, if any. RunningAnimation* GetRunningAnimation( <API key>::AnimatableProperty property); // Checks if the sequence has already been added to the queue and adds it // to the front if note. void <API key>(<API key>* sequence); // Any running or queued animation that affects a property in common with // |sequence| is either finished or aborted depending on |abort|. void <API key>(<API key>* sequence, bool abort); // Preempts a running animation by progressing both the running animation and // the given sequence to the end. void <API key>(<API key>* sequence); // Preempts by aborting the running animation, and starts the given animation. void <API key>(<API key>* sequence); // Preempts by adding the new animation to the queue. void EnqueueNewAnimation(<API key>* sequence); // Preempts by wiping out any unstarted animation in the queue and then // enqueuing this animation. void <API key>(<API key>* sequence); // If there's an animation in the queue that doesn't animate the same property // as a running animation, or an animation schedule to run before it, start it // up. Repeat until there are no such animations. void ProcessQueue(); // Attempts to add the sequence to the list of running animations. Returns // false if there is an animation running that already animates one of the // properties affected by |sequence|. bool <API key>(<API key>* sequence); // Sets the value of target as if all the running and queued animations were // allowed to finish. void GetTargetValue(<API key>::TargetValue* target) const; // Called whenever an animation is added to the animation queue. Either by // starting the animation or adding to the queue. void OnScheduled(<API key>* sequence); // This is the queue of animations to run. AnimationQueue animation_queue_; // The target of all layer animations. <API key>* delegate_; // The currently running animations. RunningAnimations running_animations_; // Determines how animations are replaced. PreemptionStrategy <API key>; // The default length of animations. base::TimeDelta <API key>; // The default tween type for implicit transitions Tween::Type tween_type_; // Used for coordinating the starting of animations. base::TimeTicks last_step_time_; // True if we are being stepped by our container. bool is_started_; // This prevents the animator from automatically stepping through animations // and allows for manual stepping. bool <API key>; // This causes all animations to complete immediately. static bool <API key>; // Observers are notified when layer animations end, are scheduled or are // aborted. ObserverList<<API key>> observers_; <API key>(LayerAnimator); }; } // namespace ui #endif // <API key>
package xsbti; import java.net.URL; public interface IvyRepository extends Repository { String id(); URL url(); String ivyPattern(); String artifactPattern(); boolean mavenCompatible(); boolean <API key>(); boolean descriptorOptional(); }
from __future__ import print_function import os INFO = { 'name': 'Version Updater', 'description': 'Add a version to /versions.txt after each deploy' } # Set up extra django template tags def templateTags(): pass # Build actions # def preBuild(site): # print 'preBuild' # def postBuild(site): # print 'postBuild' # Build page actions # def preBuildPage(site, path, context, data): # print 'preBuildPage', path # return context, data # def postBuildPage(site, path): # print 'postBuildPage', path # pass # Deploy actions def preDeploy(site): # Add a deploy log at /versions.txt import urllib2 import datetime import platform import codecs import getpass url = site.config.get('aws-bucket-website') data = u'' # If this is the first deploy we don't have to fetch the old file if url: try: data = urllib2.urlopen('http://%s/versions.txt' % url, timeout=8.0).read() + u'\n' except: print("Could not fetch the previous versions.txt, skipping...") return data += u'\t'.join([datetime.datetime.now().isoformat(), platform.node(), getpass.getuser()]) codecs.open(os.path.join(site.paths['build'], 'versions.txt'), 'w', 'utf8').write(data) def postDeploy(site): pass
// clang-format off import 'chrome://resources/cr_elements/cr_icon_button/cr_icon_button.m.js'; import 'chrome://resources/cr_elements/icons.m.js'; import 'chrome://resources/polymer/v3_0/iron-icon/iron-icon.js'; import {CrIconButtonElement} from 'chrome://resources/cr_elements/cr_icon_button/cr_icon_button.m.js'; import {downAndUp, <API key>} from 'chrome://resources/polymer/v3_0/iron-test-helpers/mock-interactions.js'; import {assertEquals, assertFalse, assertTrue} from 'chrome://webui-test/chai_assert.js'; import {eventToPromise, flushTasks} from 'chrome://webui-test/test_util.js'; // clang-format on suite('cr-icon-button', function() { let button: CrIconButtonElement; function press(key: string) { button.dispatchEvent(new KeyboardEvent('keydown', {key})); button.dispatchEvent(new KeyboardEvent('keyup', {key})); } setup(async () => { document.body.innerHTML = ''; button = document.createElement('cr-icon-button'); document.body.appendChild(button); await flushTasks(); }); test('enabled/disabled', () => { assertEquals('0', button.getAttribute('tabindex')); assertEquals('false', button.getAttribute('aria-disabled')); button.disabled = true; assertEquals('-1', button.getAttribute('tabindex')); assertEquals('true', button.getAttribute('aria-disabled')); }); test('iron-icon is created, reused and removed based on |ironIcon|', () => { assertFalse(!!button.shadowRoot!.querySelector('iron-icon')); button.ironIcon = 'icon-key'; assertTrue(!!button.shadowRoot!.querySelector('iron-icon')); button.shadowRoot!.querySelector('iron-icon')!.icon = 'icon-key'; button.ironIcon = 'another-icon-key'; assertEquals(1, button.shadowRoot!.querySelectorAll('iron-icon').length); button.shadowRoot!.querySelector('iron-icon')!.icon = 'another-icon-key'; button.ironIcon = ''; assertFalse(!!button.shadowRoot!.querySelector('iron-icon')); }); test('iron-icon children svg and img elements have role set to none', () => { button.ironIcon = 'cr:clear'; assertTrue(!!button.shadowRoot); const ironIcons = button.shadowRoot!.querySelectorAll('iron-icon'); assertEquals(1, ironIcons.length); const iconChildren = ironIcons[0]!.shadowRoot!.querySelectorAll('svg, img'); assertEquals(1, iconChildren.length); assertEquals(iconChildren[0]!.getAttribute('role'), 'none'); }); test('enter emits click event', async () => { const wait = eventToPromise('click', button); <API key>(button, -1, [], 'Enter'); await wait; }); test('space emits click event', async () => { const wait = eventToPromise('click', button); <API key>(button, -1, [], ' '); await wait; }); test('space up does not click without space down', () => { let clicked = false; button.addEventListener('click', () => { clicked = true; }, {once: true}); button.dispatchEvent(new KeyboardEvent('keyup', {key: ' '})); assertFalse(clicked); press(' '); assertTrue(clicked); }); test('space up events will not result in one click if loses focus', () => { let clicked = false; button.addEventListener('click', () => { clicked = true; }, {once: true}); button.dispatchEvent(new KeyboardEvent('keydown', {key: ' '})); button.dispatchEvent(new Event('blur')); button.dispatchEvent(new KeyboardEvent('keyup', {key: ' '})); assertFalse(clicked); press(' '); assertTrue(clicked); }); test('disabled prevents UI and programmatic clicks', async () => { let clickCount = 0; const clickHandler = () => { clickCount++; }; button.addEventListener('click', clickHandler); button.disabled = true; await flushTasks(); <API key>(button, -1, [], 'Enter'); <API key>(button, -1, [], ' '); downAndUp(button); button.click(); await flushTasks(); assertEquals(0, clickCount); button.disabled = false; await flushTasks(); <API key>(button, -1, [], 'Enter'); <API key>(button, -1, [], ' '); downAndUp(button); button.click(); await flushTasks(); assertEquals(4, clickCount); button.removeEventListener('click', clickHandler); }); test('when tabindex is -1, it stays -1', async () => { document.body.innerHTML = '<cr-icon-button custom-tab-index="-1"></cr-icon-button>'; await flushTasks(); button = document.body.querySelector('cr-icon-button')!; assertEquals('-1', button.getAttribute('tabindex')); button.disabled = true; assertEquals('-1', button.getAttribute('tabindex')); button.disabled = false; assertEquals('-1', button.getAttribute('tabindex')); }); test('tabindex update', async () => { document.body.innerHTML = '<cr-icon-button></cr-icon-button>'; button = document.body.querySelector('cr-icon-button')!; assertEquals('0', button.getAttribute('tabindex')); button.customTabIndex = 1; assertEquals('1', button.getAttribute('tabindex')); }); test('multiple iron icons', () => { button.ironIcon = 'icon1,icon2'; const elements = button.shadowRoot!.querySelectorAll('iron-icon'); assertEquals(2, elements.length); assertEquals('icon1', elements[0]!.icon); assertEquals('icon2', elements[1]!.icon); }); });
//>>built define( ({ fontSize: "Veličina", fontName: "Font", formatBlock: "Oblikovanje", serif: "serif", "sans-serif": "sans-serif", monospace: "jednaki razmak", cursive: "rukopisni", fantasy: "fantastika", noFormat: "Nijedan", p: "Odlomak", h1: "Naslov", h2: "Podnaslov", h3: "Pod-podnaslov", pre: "Prethodno formatirano", 1: "vrlo vrlo malo", 2: "vrlo malo", 3: "malo", 4: "srednje", 5: "veliko", 6: "vrlo veliko", 7: "vrlo vrlo veliko" }) );
# modification, are permitted provided that the following conditions are # met: # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # "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. import os import platform import sys from webkitpy.common.system import environment, executive, filesystem, platforminfo, user, workspace class SystemHost(object): def __init__(self): self.executable = sys.executable self.executive = executive.Executive() self.filesystem = filesystem.FileSystem() self.user = user.User() self.platform = platforminfo.PlatformInfo(sys, platform, self.filesystem, self.executive) self.workspace = workspace.Workspace(self.filesystem, self.executive) self.stdin = sys.stdin self.stdout = sys.stdout self.stderr = sys.stderr def <API key>(self): return environment.Environment(os.environ.copy()) def print_(self, *args, **kwargs): sep = kwargs.get('sep', ' ') end = kwargs.get('end', '\n') stream = kwargs.get('stream', self.stdout) stream.write(sep.join([str(arg) for arg in args]) + end) def exit(self, returncode): sys.exit(returncode)
<!DOCTYPE HTML PUBLIC "- <!--NewPage <HTML> <HEAD> <!-- Generated by javadoc (build 1.5.0_22) on Sun Oct 21 11:03:15 GMT+01:00 2012 --> <META http-equiv="Content-Type" content="text/html; charset=UTF-8"> <TITLE> Uses of Class org.apache.http.impl.client.<API key> (HttpComponents Client 4.2.2 API) </TITLE> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { parent.document.title="Uses of Class org.apache.http.impl.client.<API key> (HttpComponents Client 4.2.2 API)"; } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <A NAME="navbar_top"></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../org/apache/http/impl/client/<API key>.html" title="class in org.apache.http.impl.client"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../index.html?org/apache/http/impl/client/class-use/<API key>.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="<API key>.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <! if(window==top) { document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <HR> <CENTER> <H2> <B>Uses of Class<br>org.apache.http.impl.client.<API key></B></H2> </CENTER> No usage of org.apache.http.impl.client.<API key> <P> <HR> <A NAME="navbar_bottom"></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="<API key>"></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../org/apache/http/impl/client/<API key>.html" title="class in org.apache.http.impl.client"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../index.html?org/apache/http/impl/client/class-use/<API key>.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="<API key>.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <! if(window==top) { document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <HR> Copyright & </BODY> </HTML>
\section{Evaluation} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \label{sec:eval} We performed several independent studies of our pattern matching solution to test its efficiency. In the first study we compare various functions written with pattern matching and hand-optimized manually in order to estimate the overhead added by the composition of patterns (\textsection\ref{sec:patcmp}). We demonstrate this overhead for both our solution based on compile-time composition of patterns and the suggested alternatives based on the run-time composition of patterns. In the second study we looked at how well our extension of \code{Match}-statement to $N$-arguments using the Morton order deals with large real-world class hierarchies (\textsection\ref{sec:morton}). In the third study we compare the performance of matching $N$ polymorphic arguments against double, triple and quadruple dispatch via visitor design pattern as well as open multi-methods extension to \Cpp{} (\textsection\ref{sec:dd}). In the fourth study, we rewrote a code optimizer of an experimental language from Haskell into \Cpp{} with \emph{Mach7}. We compare the ease of use, readability and maintainability of the original Haskell code and its \emph{Mach7} equivalent (\textsection\ref{sec:qualcmp}). The studies involving performance comparisons have been performed on Sony VAIO\textsuperscript{\textregistered} laptop with Intel\textsuperscript{\textregistered} Core\texttrademark i5 460M CPU at 2.53 GHz; 6GB of RAM; Windows 7 Professional. All the code was compiled with G++ (versions 4.5.2, 4.6.1 and 4.7.2; executed with -O2 to produce x86 binaries under MinGW) as well as Visual \Cpp{} (versions 10.0 and 11.0 with profile-guided optimizations enabled). To improve accuracy, timing was performed with the help of \code{RDTSC} instruction available on x86 processors. For every number reported we ran 101 experiments timing 1,000,000 top-level calls each (depending on arguments, there may have been a different number of recursive calls). The first experiment was serving as a warm-up, and typically resulted in an outlier with the largest time. Averaged over 1,000,000 calls, the number of cycles per top-level call in each of the 101 experiments was sorted and the median was chosen. We preferred median to average to diminish the influence of other applications and OS interrupts as well as to improve reproducibility of timings between the runs of application. In particular, in the diagnostic boot of Windows, where the minimum of drivers and applications are loaded, we were getting the same number of cycles per iteration 70-80 out of 101 times. Timings in non-diagnostic boots had somewhat larger absolute values, however the relative performance remained unchanged and equally well reproducible. \subsection{Pattern Matching Overhead} \label{sec:patcmp} The overhead associated with pattern matching may originate from several different sources: \begin{itemize} \setlength{\itemsep}{0pt} \setlength{\parskip}{0pt} \item Naive (sequential and often duplicated) order of tests due to a pure library solution. \item Compiler's inability to inline the test expressed by the pattern in the left-hand side of the case clause (e.g. due to lack of [type] information or complexity of the expression). \item Compiler's inability to elide construction of pattern trees when used in the right-hand side of the case clause. \end{itemize} \noindent To estimate the overhead introduced by commonly used \emph{patterns as objects} approach (\textsection\ref{sec:pao}) and our \emph{patterns as expression templates} approach (\textsection\ref{sec:pat}), we implemented several simple functions with and without pattern matching. The handcrafted code we compared against was hand-optimized by us to render the same results, without changes to the underlying algorithm. Some functions were implemented in several ways with different patterns in order to show the impact of different patterns and pattern combinations on performance. The overhead of both approaches on a range of recent \Cpp{} compilers is shown in Figure~\ref{fig:overhead}. \begin{figure}[htbp] \scriptsize \begin{tabular}{|@{}l@{}|@{}l@{}||@{}r@{}|@{}r@{}|@{}r@{}|@{}r@{}|@{}r@{}||@{}r@{}|@{}r@{}|@{}r@{}|@{}r@{}|@{}r@{}|} \hline % & & \multicolumn{5}{@{}c@{}||}{Patterns as Expr. Templates} & \multicolumn{5}{@{}c@{}|}{Patterns as Objects} \\ \hline % & & \multicolumn{3}{@{}c@{}|}{G++} & \multicolumn{2}{@{}c@{}||}{Visual C++} & \multicolumn{3}{@{}c@{}|}{G++} & \multicolumn{2}{@{}c@{}|}{Visual C++} \\ \hline % Test & Patterns & 4.5.2 & 4.6.1 & 4.7.2 & 10.0 & 11.0 & 4.5.2 & 4.6.1 & 4.7.2 & 10.0 & 11.0 \\ % & NLOC$_h$ & NLOC$_p$ \hline % factorial$^*_0$& 1,v,\_ & \f{15} & \f{13} & \f{17} &\s{ 85} &\s{ 35} &\s{ 347}&\s{ 408}&\s{ 419}&\s{2121}&\s{1788} \\ % & 6 & 7 factorial$_1$& 1,v & \s{ 0} & \s{ 6} & \s{ 0} &\s{ 83} &\s{ 21} &\s{ 410}&\s{ 519}&\s{ 504}&\s{2380}&\s{1812} \\ % & 6 & 7 factorial$_2$& 1,n+k & \s{ 7} & \s{ 9} & \s{ 6} &\s{ 78} &\s{ } &\s{ 797}&\s{ 911}&\s{ 803}&\s{3554}&\s{3057} \\ % & & fibonacci$^*$& 1,n+k & \s{17} & \f{ 2} & \s{ 2} &\s{ 62} &\s{ 15} &\s{ 340}&\s{ 431}&\s{ 395}&\s{2730}&\s{2597} \\ % & 7 & 8 gcd$^*_1$ & v,n+k,+ & \s{21} & \s{25} & \s{25} &\s{309} &\s{179} &\s{1503}&\s{1333}&\s{1208}&\s{8876}&\s{7810} \\ % & 6 & 7 gcd$_2$ & 1,n+k,\_ & \s{ 5} & \s{13} & \s{19} &\s{373} &\s{303} &\s{ 962}&\s{1080}&\s{ 779}&\s{5332}&\s{4674} \\ % & 6 & 7 gcd$_3$ & 1,v & \f{ 1} & \s{ 0} & \f{ 1} &\s{ 38} &\s{ 15} &\s{ 119}&\s{ 102}&\s{ 108}&\s{1575}&\s{1319} \\ % & 6 & 7 lambdas$^*$ & \&,v,C,+ & \s{58} & \s{54} & \s{56} &\f{ 29} &\f{ 34} &\s{ 837}&\s{ 780}&\s{ 875}&\s{ 259}&\s{ 289} \\ % & 15 & 10 power & 1,n+k & \s{10} & \s{ 8} & \s{13} &\s{ 50} &\s{ 6} &\s{ 291}&\s{ 337}&\s{ 338}&\s{1950}&\s{1648} \\ % & 9 & 8 balance$^*$ & 1,v,C & \s{ } & \s{ } & \s{ } &\s{ } &\s{ } &\s{ }&\s{ }&\s{ }&\s{ }&\s{ } \\ % & & 10 \hline % \end{tabular} \caption{Pattern Matching Overhead} \label{fig:overhead} \end{figure} % %Figure~\ref{fig:overhead} lists several functions we compared, the kinds of %patterns that were involved in the pattern-matching implementation of them, the %overhead our implementation as well as implementation in patterns-as-objects %approach had over the hand crafted implementation. We also list the number of %non-empty lines of code corresponding functions of handcrafted, our approach %and patterns-as-objects approach had. \noindent The experiments marked with $*$ correspond to the code of their respective functions shown in \textsection\ref{sec:cpppat}. The rest of the functions, including all the implementations with ``patterns as objects'' approach, are available among the files accompanying this submission and will be made available later on the project's web page. The patterns involved in each experiment are abbreviated as following: %\begin{figure}[htb] % \centering % \scriptsize \begin{minipage}[t]{0.20\textwidth} {\bf 1} -- value pattern \\ {\bf v} -- variable pattern \\ {\bf \_} -- wildcard pattern \end{minipage} \begin{minipage}[t]{0.25\textwidth} {\bf n+k} -- n+k pattern \\ {\bf +} -- equivalence combinator \\ {\bf \&} -- address combinator \\ {\bf C} -- constructor pattern \end{minipage} %\end{figure} \noindent It is easy to see that the overhead incurred by compile-time composition of patterns in \emph{patterns as expression templates} approach is significantly smaller than the overhead of run-time composition of patterns in \emph{patterns as objects} approach. In fact, in several cases, shown in the table in bold font, the compiler was able to eliminate the overhead entirely and even generate a faster code. In case of ``lambdas'' experiment, the advantage was mainly due to the underlying type switch, while in the rest of the cases the generated code was feeding better the instruction pipeline and the branch predictor. In each experiment, the handcrafted baseline implementation was the same in both cases (compile-time and run-time composition) and reflected our idea of the fastest code without pattern matching describing the same algorithm. For example, gcd$_3$ was implementing the fast Euclidian algorithm with remainders, while gcd$_1$ and gcd$_2$ were implementing its slower version with subtractions. The baseline code was correspondingly implementing fast Euclidian algorithm for gcd$_3$ and slow for gcd$_1$ and gcd$_2$. The comparison of the overhead incurred by both approaches would be incomplete without detailing the implementation of patterns as objects solution. In particular, dealing with objects in object-oriented languages often involves heap allocation, subtype tests, garbage collection etc., which all can significantly affect the performance. To make this comparison applicable to a wider range of object-oriented languages, we took the following precautions in the ``objects as patterns'' implementations: \begin{itemize} \setlength{\itemsep}{0pt} \setlength{\parskip}{0pt} \item All the objects involved were stack-allocated or statically allocated. This measure was taken to avoid allocating objects on the heap, which is known to be much slower and is an optimization compilers of many object-oriented languages undertake. \item Objects representing constant values as well as patterns whose state does not change during pattern matching (e.g. wildcard and value patterns) were all statically allocated. \item Patterns that modify their own state were constructed only when they were actually used, since a successful match by a previous pattern may return early from the function. \item Only the arguments on which pattern matching was effectively performed were boxed into the \code{object} class hierarchy, e.g. in case of power function only the second argument was boxed. \item Boxed arguments were statically typed with their most derived type to avoid unnecessary type checks and conversions: e.g. \code{object_of<int>&}, which is a class derived from \code{object} to represent a boxed integer, instead of just \code{object&}. \item No objects were returned as a result of a function as in truly object-oriented approach that would typically require heap allocation. \item n+k patterns that effectively require evaluating a result of an expression where implemented with an additional virtual function instead that simply checks whether a result is a given value. This does not allow expressing all n+k patterns of \emph{Mach7}, but was sufficient to express all those involved in the experiments and allowed us to avoid heap allocating the results. \item When run-time type checks were unavoidable (e.g. inside \code{pattern::match} implementation) we were comparing type-ids first, and only when the comparison failed were invoking the dynamic cast. This typical optimization avoids the much slower dynamic cast in the common case. \end{itemize} \noindent With these precautions in place, we believe that the main overhead of the patterns-as-objects solution that we were measuring was in the cost of a virtual function call \\ (\code{pattern::match}) and the cost of run-time type identification and conversion on its argument -- the subject. Both are specific to the approach and not to our implementation of it, which is why we believe a similar overhead will be present in other object-oriented languages following this strategy to pattern matching. \subsection{Multi-argument Hashing} \label{sec:morton} To check the efficiency of hashing in the multi-argument \code{Match}-statement (\textsection\ref{sec:matchstmt}) we used the same class hierarchy benchmark we used to test the efficiency of hashing in type switch~\cite[\textsection 4.4]{TS12}. The benchmark consists of 13 libraries describing 15246 classes totally. Not all the class hierarchies originated from \Cpp{}, but all were written by humans and represent actual relationships in their problem domains. While \code{Match}-statement works with both polymorphic and non-polymorphic arguments, only the polymorphic arguments are taken into consideration for efficient type switching and thus efficient hashing. It also generally makes sense to apply type switching to non-leaf nodes of the class hierarchy only. 71\% of the classes in the entire benchmarks suite were leaf classes. For each of the remaining 4369 non-leaf classes we created 4 functions, performing case analysis on derived class on a combination of 1, 2, 3 and 4 arguments respectively. Each of the functions was executed with different combinations of possible derived types, including, in case of repeated multiple inheritance, different sub-objects within the same type. There was 63963 different subobjects when the class hierarchies used repeated multiple inheritance and 38856 different subobjects when the virtual multiple inheritance was used. As with type switching, for each of the 4369 functions (per same number of arguments) we were measuring the number of conflicts $m$ in cache -- the number of entries mapped to the same location in cache by the optimal hash function. We then computed the percentage of functions that achieved a given number of conflicts, which we show in Figure~\ref{fig:hashing}. % NOTE: Data from 2013-02-24, see <API key>.xlsx \begin{figure}[htbp] \small \begin{tabular} {@{}c@{ }|@{}c@{}||@{ }r@{}|@{ }r@{}|@{ }r@{}|@{ }r@{}|@{ }r@{}|@{ }r@{}|@{ }r@{}} \hline % \multicolumn{2}{@{}c@{}||}{$N/m$} & [0] & [1] & $\cdots$ 10] & $\cdots$ 100] & $\cdots$ 1000] & $\cdots$ 10000] & \textgreater 10000 \\ \hline % \multirow{4}{*}{\begin{sideways}{\scriptsize Repeated}\end{sideways}} & 1 & 88.37\% & 10.78\% & 0.85\% & \none{} & \none{} & \none{} &\none{} \\ & 2 & 76.42\% & 5.51\% & 10.60\% & 4.89\% & 2.22\% & 0.37\% &\none{} \\ & 3 & 65.18\% & \none{} & 15.04\% & 8.92\% & 5.83\% & 5.03\% &\none{} \\ & 4 & 64.95\% & \none{} & 0.14\% & 14.81\% & 7.57\% & 12.54\% &\none{} \\ \hline % \multirow{4}{*}{\begin{sideways}{\scriptsize Virtual}\end{sideways}} & 1 & 89.72\% & 9.04\% & 1.24\% & \none{} & \none{} & \none{} &\none{} \\ & 2 & 80.55\% & 4.20\% & 8.46\% & 4.59\% & 1.67\% & 0.53\% &\none{} \\ & 3 & 71.26\% & 0.37\% & 12.03\% & 7.32\% & 4.87\% & 4.16\% &\none{} \\ & 4 & 71.55\% & \none{} & 0.23\% & 11.83\% & 6.49\% & 9.90\% &\none{} \\ \hline % \end{tabular} \caption{Percentage of $N$-argument \code{Match}-statements with given number of conflicts ($m$) in cache} \label{fig:hashing} \end{figure} We grouped the results in ranges of exponentially increasing size because we noticed that the number of conflicts per \code{Match}-statement for multiple arguments was not as tightly distributed around 0 as it was for a single argument. The main observation however still holds: in most of the cases, we could achieve hashing without conflicts, as can be seen in the first column (marked [0]). The numbers are slightly better when virtual inheritance is used because the overall number of possible subobjects is smaller. \subsection{Comparison to Multiple Dispatch Alternatives} \label{sec:dd} Type switching on multiple arguments can be seen as a form of multiple dispatch. In this study we compare the efficiency of type switching on multiple arguments in comparison to alternatives based on double, triple and quadruple dispatch~\cite{Ingalls86}, as well as our own implementation of open multi-methods for \Cpp{}~\cite{OpenMM}. The need for multiple dispatch rarely happens in practice, diminishing with the number of arguments involved in dispatch. Muschevici et al~\cite{MPTN08} studied a large corpus of applications in 6 languages and estimate that single dispatch amounts to about 30\% of all the functions, while multiple dispatch is only used in 3\% of functions. In application to type switching, this indicates that we can expect case analysis on dynamic type of a single argument much more often than that on dynamic types of two or more arguments. Note, however, that this does not mean that pattern matching in general reflects the same trend as additional arguments are often introduced into the \code{Match}-statement to check some relational properties. These additional arguments are typically non-polymorphic and thus do not participate in type switching, which is why in this experiment we only deal with polymorphic arguments. %Because the need for multiple dispatch on multiple arguments drops significantly %with the number of arguments, we only compared the performance of various %approaches on up to 4 arguments. None of the approaches presented here are %limited by this number, and our solution is provided by a single implementation %parameterized by the number of arguments. Figure~\ref{fig:dispatch} contains 4 bar groups that corresponding to the number of arguments used for multiple dispatch. Each group contains 3 wide bars representing the number of cycles per iteration it took N-Dispatch, Open Type Switch and Open Multi-Methods solution to perform the same task. Each of the 3 wide bars is subsequently split into 5 narrow sub-bars representing performance achieved by G++ 4.5.2, 4.6.1, 4.7.2 and Visual \Cpp{} 10 and 11 in that order from left to right. \begin{figure}[htbp] \centering \includegraphics[width=0.49\textwidth]{Timing-N-arg.pdf} \caption{N-argument \code{Match}-statement vs. visitor design pattern and open multi-methods} \label{fig:dispatch} \end{figure} Open multi-methods provide the fastest performance because the dispatch is implemented with an $N$-dimensional array lookup, requiring only $4N+1$ memory references before an indirect call. N-Dispatch provides the slowest solution, requiring $2N$ virtual function calls (accept/visit per each dimension). Open type switch falls in between the two, thanks to its efficient hashing combined with a jump table. In terms of memory, given a class hierarchy of $n$ classes (or $n$ subobjects in the subobject graph to be more precise) and a multiple dispatch on $N$ arguments from it, all 3 solutions will require the memory proportional to $O\of{n^N}$. More specifically, if $\delta$ is the number of bytes used by a pointer, then each of the approaches will use: \begin{itemize} \setlength{\itemsep}{0pt} \setlength{\parskip}{0pt} \item Open Multi-Methods: $\delta\of{n^N+Nn+N}$ \item N-Dispatch: $\delta\of{n^N+n^{N-1}+\cdots+n^2+n}$ \item Open Type Switch: $\delta\of{\of{2N+3}n^N+N+7}$ \end{itemize} \noindent bytes of memory. In all 3 cases the memory counted represents the non-reusable memory specific to the implementation of a single function dispatched through $N$ polymorphic arguments. Note that $n$ is a variable here since new classes may be loaded at run-time through dynamic linking in all 3 solutions, while $N$ is a constant, representing the number of arguments to dispatch on. The memory used by each approach is allocated at different stages. The memory used by the virtual tables involved in the N-dispatch solution as well as dispatch tables used by open multi-methods will be allocated at compile/link time and will be reflected in the size of the final executable. Open multi-methods might require additional allocations and/or recomputation at load time to account for dynamic linking. In both cases, the memory allocated covers all possible combinations of $n$ classes in $N$ argument positions. In case of open type switch, the memory is only allocated at run-time and grows proportionally to the number of actual argument combinations seen by the type switch (\textsection\ref{sec:multiarg}). Only in the worst case when all possible combinations have been seen by the type switch does it reach the size described by the above formula. This is an important distinction as in many applications all possible combinations will never be seen: for example, in a compiler the entities representing expressions and types might all be derived from a common base class, however they will rarely appear in the same type switch together. There is also a significant difference in the ease of use of these solutions. N-Dispatch is the most restrictive solution as it is intrusive (and thus cannot be applied retroactively), hinders extensibility (by limiting the set of distinguishable cases) and is surprisingly hard to teach students. While analyzing Java idioms used to emulate multiple dispatch in practice, Muschevici et al~\cite[Figure 13]{MPTN08} noted that there are significantly more uses of cascading \code{instanceof} in the real code than the uses of double dispatch, which they also attribute to the obscurity of the second idiom. Both N-Dispatch and open multi-methods also introduce control inversion in which the case analysis is effectively structured in the form of callbacks. Open multi-methods are also subject to ambiguities, which have to be resolved at compile time and in some cases might require the addition of numerous overriders. Neither is the case with open type switch where the case analysis is performed directly, while ambiguities are avoided by the use of first-fit semantics. %Although instanceof cascades may be slower than %double dispatching, and are certainly less extensible, by %being localised to a single class they are signi?cantly more %straightforward to code than double dispatching. This may %account for the relative popularity of each idiom. \subsection{Rewriting Haskell code in \Cpp{}} \label{sec:qualcmp} For this experiment we took an existing code in Haskell and asked its author to rewrite it in \Cpp{} with \emph{Mach7}. The code in question is a simple peephole optimizer for an experimental GPU language called \emph{Versity}~\cite{Versity}. We assisted the author along the way to see which patterns he uses and what kind of mistakes he makes. Somewhat surprising to us we found out that pattern-matching clauses generally became shorter, but their right-hand side became longer. The shortening of case clauses was perhaps specific to this application and mainly stemmed from the fact that Haskell does not support equivalence patterns or equivalence combinator and had to use guards to relate different arguments. This was particularly cumbersome when optimizer was looking at several arguments of several instructions in the stream, e.g.: \begin{lstlisting}[language=Haskell] peep2 (x1:x2:xs) = case x1 of InstMove a b -> case x2 of InstMove c d | (a == d) && (b == c) -> peep2 $ x1:xs \end{lstlisting} \noindent compared to \emph{Mach7} version: \begin{lstlisting} Match(*x1,*x2) { Case(C<InstMove>(a,b), C<InstMove>(+b,+a)) ... \end{lstlisting} \noindent Haskell also requires to use wildcard pattern in every unused position of a constructor pattern (e.g. \codehaskell{InstBin _ _ _ _}), while \emph{Mach7} allows one to omit all the trailing wildcards in constructor patterns (e.g. \code{C<InstBin>()}). And while this pays off only for constructor patterns with at least 3 arguments, the use of named patterns avoided many repeated pattern expressions and actually improved both performance and readability: \begin{lstlisting}[columns=flexible] auto either = val(src) || val(dst); Match(inst) { Case(C<InstMove>(_, either)) ... Case(C<InstUn> (_, _, either)) ... Case(C<InstBin> (_, _, _, either)) ... } EndMatch \end{lstlisting} \noindent The disadvantage for \emph{Mach7} was coming after pattern matching as we had to explicitly manage memory when inserting, removing or replacing instructions in the stream as well as explicitly manage the stream itself. Eventually we could hide some of this boilerplate behind smart pointers and other standard library classes. During the initial rewrite into \Cpp{} the developer simply mapped Haskell patterns into their \emph{Mach7} equivalents, at which point we intevened and showed how some of the patterns can be expressed simpler. We reiterated the process until we could not improve the patterns ourselves without getting into the details of the actual simplifier. At one point we noticed that the developer started passing data via pattern-matching variables \code{var<T>} in and out of functions, which was not the intended use. This was hard to prevent statically, because in general, as first-class citizens, patterns can be passed in and out of functions, however in this case they were not used as patterns, but rather as values. We have yet to make a performance comparison, but based on the performance of the open type swich~\cite{TS12} and the small overhead of our patterns, we expect the performance to be comparable.
int main() { int a[3] = { 1, 2, 3 }; a[0] = a[2]; return a[0]; }
#include "chrome/browser/chromeos/<API key>.h" #include "base/bind.h" #include "base/bind_helpers.h" #include "base/callback.h" #include "base/location.h" #include "base/logging.h" #include "base/values.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/chromeos/net/<API key>.h" #include "chrome/common/pref_names.h" #include "chromeos/network/network_profile.h" #include "chromeos/network/<API key>.h" #include "chromeos/network/network_state.h" #include "chromeos/network/<API key>.h" #include "chromeos/network/onc/onc_utils.h" #include "components/policy/core/common/cloud/<API key>.h" #include "components/prefs/pref_service.h" #include "components/proxy_config/<API key>.h" #include "components/proxy_config/<API key>.h" #include "components/proxy_config/proxy_prefs.h" #include "components/user_manager/user_manager.h" #include "content/public/browser/browser_thread.h" namespace chromeos { namespace { // Writes the proxy config of |network| to |proxy_config|. Set |onc_source| to // the source of this configuration. Returns false if no // proxy was configured for this network. bool GetProxyConfig(const PrefService* profile_prefs, const PrefService* local_state_prefs, const NetworkState& network, net::ProxyConfig* proxy_config, ::onc::ONCSource* onc_source) { std::unique_ptr<<API key>> proxy_dict = proxy_config::<API key>(profile_prefs, local_state_prefs, network, onc_source); if (!proxy_dict) return false; return <API key>::<API key>(*proxy_dict, proxy_config); } } // namespace <API key>::<API key>(PrefService* profile_prefs, PrefService* local_state_prefs) : <API key>( profile_prefs ? profile_prefs : local_state_prefs, content::BrowserThread::<API key>( content::BrowserThread::IO)), <API key>(ProxyPrefs::CONFIG_UNSET), profile_prefs_(profile_prefs), local_state_prefs_(local_state_prefs), pointer_factory_(this) { const base::Closure <API key> = base::Bind( &<API key>::OnProxyPrefChanged, base::Unretained(this)); if (profile_prefs) { <API key>.Init(profile_prefs); <API key>.Add(prefs::<API key>, <API key>); <API key>.Add(prefs::kUseSharedProxies, <API key>); } <API key>.Init(local_state_prefs); <API key>.Add(prefs::<API key>, <API key>); // Register for changes to the default network. NetworkStateHandler* state_handler = NetworkHandler::Get()-><API key>(); state_handler->AddObserver(this, FROM_HERE); <API key>(state_handler->DefaultNetwork()); } <API key>::~<API key>() { if (NetworkHandler::IsInitialized()) { NetworkHandler::Get()-><API key>()->RemoveObserver( this, FROM_HERE); } } void <API key>::<API key>( ProxyPrefs::ConfigState config_state, const net::ProxyConfig& config) { VLOG(1) << "Got prefs change: " << ProxyPrefs::<API key>(config_state) << ", mode=" << config.proxy_rules().type; <API key>(); } void <API key>::OnProxyPrefChanged() { <API key>(); } void <API key>::<API key>( const NetworkState* new_network) { std::string new_network_path; if (new_network) new_network_path = new_network->path(); VLOG(1) << "<API key> to '" << new_network_path << "'."; VLOG_IF(1, new_network) << "New network: name=" << new_network->name() << ", profile=" << new_network->profile_path(); // Even if the default network is the same, its proxy config (e.g. if private // version of network replaces the shared version after login), or // use-shared-proxies setting (e.g. after login) may have changed, so // re-determine effective proxy config, and activate if different. <API key>(); } void <API key>::OnShuttingDown() { // Ownership of this class is complicated. Stop observing NetworkStateHandler // when the class shuts down. NetworkHandler::Get()-><API key>()->RemoveObserver(this, FROM_HERE); } // static bool <API key>::IgnoreProxy(const PrefService* profile_prefs, const std::string <API key>, ::onc::ONCSource onc_source) { if (!profile_prefs) { // If the profile preference are not available, this must be the object // associated to local state used for system requests or login-profile. Make // sure that proxies are enabled. VLOG(1) << "Use proxy for system requests and sign-in screen."; return false; } if (<API key>.empty()) return true; const NetworkProfile* profile = NetworkHandler::Get() -><API key>()->GetProfileForPath(<API key>); if (!profile) { VLOG(1) << "Unknown profile_path '" << <API key> << "'. Ignoring proxy."; return true; } if (profile->type() == NetworkProfile::TYPE_USER) { VLOG(1) << "Respect proxy of not-shared networks."; return false; } if (onc_source == ::onc::<API key>) { // Note that this case can occur if the network is shared (e.g. ethernet) // but the proxy is determined by user policy. VLOG(1) << "Respect proxy from user policy although network is shared."; return false; } if (onc_source == ::onc::<API key>) { const user_manager::User* logged_in_user = user_manager::UserManager::Get()->GetLoggedInUser(); if (logged_in_user->IsAffiliated()) { VLOG(1) << "Respecting proxy for network, as logged-in user belongs to " << "the domain the device is enrolled to."; return false; } } // This network is shared and not managed by the user's domain. bool use_shared_proxies = profile_prefs->GetBoolean(prefs::kUseSharedProxies); VLOG(1) << "Use proxy of shared network: " << use_shared_proxies; return !use_shared_proxies; } void <API key>::<API key>() { if (!NetworkHandler::IsInitialized()) return; NetworkStateHandler* handler = NetworkHandler::Get()-><API key>(); const NetworkState* network = handler->DefaultNetwork(); // Get prefs proxy config if available. net::ProxyConfig pref_config; ProxyPrefs::ConfigState pref_state = GetProxyConfig(&pref_config); // Get network proxy config if available. net::ProxyConfig network_config; net::ProxyConfigService::ConfigAvailability <API key> = net::ProxyConfigService::CONFIG_UNSET; bool ignore_proxy = true; if (network) { ::onc::ONCSource onc_source = ::onc::ONC_SOURCE_NONE; const bool <API key> = chromeos::GetProxyConfig( prefs(), local_state_prefs_, *network, &network_config, &onc_source); ignore_proxy = IgnoreProxy(profile_prefs_, network->profile_path(), onc_source); // If network is shared but use-shared-proxies is off, use direct mode. if (ignore_proxy) { network_config = net::ProxyConfig(); <API key> = net::ProxyConfigService::CONFIG_VALID; } else if (<API key>) { // Network is private or shared with user using shared proxies. VLOG(1) << this << ": using proxy of network " << network->path(); <API key> = net::ProxyConfigService::CONFIG_VALID; } } // Determine effective proxy config, either from prefs or network. ProxyPrefs::ConfigState <API key>; net::ProxyConfig effective_config; <API key>(pref_state, pref_config, <API key>, network_config, ignore_proxy, &<API key>, &effective_config); // Activate effective proxy and store into |active_config_|. // If last update didn't complete, we definitely update now. bool update_now = update_pending(); if (!update_now) { // Otherwise, only update now if there're changes. update_now = <API key> != <API key> || (<API key> != ProxyPrefs::CONFIG_UNSET && !active_config_.Equals(effective_config)); } if (update_now) { // Activate and store new effective config. <API key> = <API key>; if (<API key> != ProxyPrefs::CONFIG_UNSET) active_config_ = effective_config; // If effective config is from system (i.e. network), it's considered a // special kind of prefs that ranks below policy/extension but above // others, so bump it up to <API key> to force its precedence // when <API key> pushes it to <API key>. if (<API key> == ProxyPrefs::CONFIG_SYSTEM) <API key> = ProxyPrefs::<API key>; // If config is manual, add rule to bypass local host. if (effective_config.proxy_rules().type != net::ProxyConfig::ProxyRules::TYPE_NO_RULES) { effective_config.proxy_rules().bypass_rules.<API key>(); } <API key>::<API key>(<API key>, effective_config); if (VLOG_IS_ON(1) && !update_pending()) { // Update was successful. std::unique_ptr<base::DictionaryValue> config_dict( effective_config.ToValue()); VLOG(1) << this << ": Proxy changed: " << ProxyPrefs::<API key>(<API key>) << ", " << *config_dict; } } } } // namespace chromeos
#ifndef GamepadEvent_h #define GamepadEvent_h #include "modules/EventModules.h" #include "modules/gamepad/Gamepad.h" #include "modules/gamepad/GamepadEventInit.h" namespace blink { class GamepadEvent final : public Event { <API key>(); public: static <API key><GamepadEvent> create() { return adoptRefWillBeNoop(new GamepadEvent); } static <API key><GamepadEvent> create(const AtomicString& type, bool canBubble, bool cancelable, Gamepad* gamepad) { return adoptRefWillBeNoop(new GamepadEvent(type, canBubble, cancelable, gamepad)); } static <API key><GamepadEvent> create(const AtomicString& type, const GamepadEventInit& initializer) { return adoptRefWillBeNoop(new GamepadEvent(type, initializer)); } virtual ~GamepadEvent(); Gamepad* gamepad() const { return m_gamepad.get(); } virtual const AtomicString& interfaceName() const override; virtual void trace(Visitor*) override; private: GamepadEvent(); GamepadEvent(const AtomicString& type, bool canBubble, bool cancelable, Gamepad*); GamepadEvent(const AtomicString&, const GamepadEventInit&); <API key><Gamepad> m_gamepad; }; } // namespace blink #endif // GamepadEvent_h
#ifndef <API key> #define <API key> #include <stddef.h> #include <stdint.h> #include <map> #include <set> #include <string> #include <vector> #include "base/command_line.h" #include "base/containers/span.h" #include "base/metrics/histogram_base.h" #include "base/values.h" #include "build/build_config.h" #include "components/flags_ui/feature_entry.h" #include "components/flags_ui/flags_state.h" namespace base { class FeatureList; } namespace flags_ui { class FlagsStorage; } namespace about_flags { // Returns true if the FeatureEntry should not be shown. bool <API key>(const flags_ui::FlagsStorage* storage, const flags_ui::FeatureEntry& entry); // Reads the state from |flags_storage| and adds the command line flags // belonging to the active feature entries to |command_line|. void <API key>(flags_ui::FlagsStorage* flags_storage, base::CommandLine* command_line, flags_ui::SentinelsMode sentinels); // Registers variations parameter values selected for features in about:flags. // The selected flags are retrieved from |flags_storage|, the registered // variation parameters are connected to their corresponding features in // |feature_list|. Returns the (possibly empty) list of additional variation ids // to register in the MetricsService that come from variations selected using // chrome://flags. std::vector<std::string> <API key>( flags_ui::FlagsStorage* flags_storage, base::FeatureList* feature_list); // Gets the list of feature entries. Entries that are available for the current // platform are appended to |supported_entries|; all other entries are appended // to |unsupported_entries|. void <API key>(flags_ui::FlagsStorage* flags_storage, flags_ui::FlagAccess access, base::Value::ListStorage& supported_entries, base::Value::ListStorage& unsupported_entries); // Gets the list of feature entries for the deprecated flags page. Entries that // are available for the current platform are appended to |supported_entries|; // all other entries are appended to |unsupported_entries|. void <API key>( flags_ui::FlagsStorage* flags_storage, flags_ui::FlagAccess access, base::Value::ListStorage& supported_entries, base::Value::ListStorage& unsupported_entries); // Gets the FlagsState used in about_flags. flags_ui::FlagsState* <API key>(); // Returns true if one of the feature entry flags has been flipped since // startup. bool <API key>(); // Enables or disables the current with id |internal_name|. void <API key>(flags_ui::FlagsStorage* flags_storage, const std::string& internal_name, bool enable); // Sets a flag value with a list of origins given by |value|. Origins in |value| // can be separated by a comma or whitespace. Invalid URLs will be dropped when // setting the command line flag. // E.g. SetOriginListFlag("test-flag", // flags_storage); void SetOriginListFlag(const std::string& internal_name, const std::string& value, flags_ui::FlagsStorage* flags_storage); // Removes all switches that were added to a command line by a previous call to // |<API key>()|. void RemoveFlagsSwitches(base::CommandLine::SwitchMap* switch_list); // Reset all flags to the default state by clearing all flags. void ResetAllFlags(flags_ui::FlagsStorage* flags_storage); #if BUILDFLAG(IS_CHROMEOS) // Show flags of the other browser (Lacros/Ash). void <API key>(); #endif // Sends UMA stats about experimental flag usage. This should be called once per // startup. void RecordUMAStatistics(flags_ui::FlagsStorage* flags_storage, const std::string& histogram_name); namespace testing { // This class sets the testing feature entries to the feature entries passed in // to Init. It clears the testing feature entries on destruction, so // the feature entries return to their non test values. class <API key> final { public: explicit <API key>( const std::vector<flags_ui::FeatureEntry>& entries); ~<API key>(); }; base::span<const flags_ui::FeatureEntry> GetFeatureEntries(); } // namespace testing } // namespace about_flags #endif // <API key>
#include "content/browser/xr/service/<API key>.h" #include <memory> #include "base/callback.h" #include "build/build_config.h" #include "components/viz/host/<API key>.h" #include "content/browser/browser_thread_impl.h" #include "content/browser/compositor/surface_utils.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/render_frame_host.h" #include "services/viz/privileged/mojom/compositing/frame_sink_manager.mojom.h" #if BUILDFLAG(IS_ANDROID) #include "content/browser/renderer_host/<API key>.h" #endif namespace content { <API key>::<API key>(int32_t render_process_id, int32_t render_frame_id) : <API key>(<API key>({})), render_process_id_(render_process_id), render_frame_id_(render_frame_id) { DCHECK(IsOnUiThread()) << "<API key> must be constructed on the UI thread."; } <API key>::~<API key>() { DCHECK(IsOnUiThread()) << "<API key> must be destructed on the UI thread."; if (!initialized_) return; SurfaceDestroyed(); } bool <API key>::IsOnUiThread() const { return <API key>-><API key>(); } void <API key>::SurfaceDestroyed() { DCHECK(IsOnUiThread()); if (!initialized_) return; auto* frame_sink_manager = <API key>(); // Since this code can be run during destruction, it's theoretically possible, // though unlikely, that the FrameSinkManager no longer exists. if (frame_sink_manager) frame_sink_manager-><API key>(root_frame_sink_id_); // Reset the initialized state and the root FrameSinkId to an invalid value. initialized_ = false; root_frame_sink_id_ = viz::FrameSinkId(); } absl::optional<viz::SurfaceId> <API key>::GetDOMSurface() { base::AutoLock lock(dom_surface_lock_); return dom_surface_id_; } viz::FrameSinkId <API key>::FrameSinkId() { return root_frame_sink_id_; } void <API key>::<API key>( viz::mojom::<API key> root_params, device::DomOverlaySetup dom_setup, base::OnceClosure on_initialized) { DCHECK(!initialized_); DVLOG(1) << __func__; <API key>->PostTask( FROM_HERE, base::BindOnce(&<API key>::<API key>, weak_ptr_factory_.GetWeakPtr(), std::move(root_params), dom_setup, std::move(on_initialized))); } void <API key>::<API key>( viz::mojom::<API key> root_params, device::DomOverlaySetup dom_setup, base::OnceClosure on_initialized) { // AllocateFrameSinkId needs to be called from the UI thread. DCHECK(IsOnUiThread()); DVLOG(1) << __func__; root_frame_sink_id_ = AllocateFrameSinkId(); root_params->frame_sink_id = root_frame_sink_id_; <API key>()->RegisterFrameSinkId( root_params->frame_sink_id, this, viz::<API key>::kNo); <API key>()-><API key>( std::move(root_params)); if (dom_setup != device::DomOverlaySetup::kNone) { ConfigureDOMOverlay(); } initialized_ = true; std::move(on_initialized).Run(); } void <API key>::ConfigureDOMOverlay() { DCHECK(IsOnUiThread()); base::AutoLock lock(dom_surface_lock_); // This is left outside of the OS_ANDROID ifdef to prevent warnings about the // render_process_id and render_frame_id from being unused. Since we check // the render_frame_host for an early return, it is in fact used. RenderFrameHost* render_frame_host = RenderFrameHost::FromID(render_process_id_, render_frame_id_); // If this is a cross-process iframe (OOPIF), its <API key> is a // <API key>. Use the main frame instead which uses a // <API key> so that we can subscribe to surface ID changes. if (render_frame_host-><API key>()) { render_frame_host = render_frame_host->GetMainFrame(); } if (!render_frame_host) return; // Since we don't have the ability to get updates to the surface id on non- // Android OS's, we let it stay null, which callers can use to as a signal that // DOMOverlay will not work. #if BUILDFLAG(IS_ANDROID) <API key>* view = static_cast<<API key>*>(render_frame_host->GetView()); if (!view) return; // The returned <API key> manages the lifetime of this callback // and thus makes Unretained safe. <API key> = view-><API key>(base::BindRepeating( &<API key>::OnSurfaceIdUpdated, base::Unretained(this))); dom_surface_id_ = view->GetCurrentSurfaceId(); #endif if (dom_surface_id_ && dom_surface_id_->is_valid()) { <API key>()-><API key>( root_frame_sink_id_, dom_surface_id_->frame_sink_id()); } } void <API key>::OnSurfaceIdUpdated( const viz::SurfaceId& dom_surface_id) { base::AutoLock lock(dom_surface_lock_); dom_surface_id_ = dom_surface_id; } } // namespace content
#include "net/quic/<API key>.h" #include "base/basictypes.h" #include "net/quic/quic_connection.h" #include "net/quic/quic_flags.h" #include "net/quic/quic_protocol.h" namespace net { #define ENDPOINT \ (perspective_ == Perspective::IS_SERVER ? "Server: " : "Client: ") QuicFlowController::QuicFlowController(QuicConnection* connection, QuicStreamId id, Perspective perspective, QuicStreamOffset send_window_offset, QuicStreamOffset <API key>, QuicByteCount max_receive_window) : connection_(connection), id_(id), perspective_(perspective), bytes_consumed_(0), <API key>(0), bytes_sent_(0), send_window_offset_(send_window_offset), <API key>(<API key>), max_receive_window_(max_receive_window), <API key>(0) { DVLOG(1) << ENDPOINT << "Created flow controller for stream " << id_ << ", setting initial receive window offset to: " << <API key> << ", max receive window to: " << max_receive_window_ << ", setting send window offset to: " << send_window_offset_; } void QuicFlowController::AddBytesConsumed(QuicByteCount bytes_consumed) { bytes_consumed_ += bytes_consumed; DVLOG(1) << ENDPOINT << "Stream " << id_ << " consumed: " << bytes_consumed_; <API key>(); } bool QuicFlowController::<API key>( QuicStreamOffset new_offset) { // Only update if offset has increased. if (new_offset <= <API key>) { return false; } DVLOG(1) << ENDPOINT << "Stream " << id_ << " highest byte offset increased from: " << <API key> << " to " << new_offset; <API key> = new_offset; return true; } void QuicFlowController::AddBytesSent(QuicByteCount bytes_sent) { if (bytes_sent_ + bytes_sent > send_window_offset_) { LOG(DFATAL) << ENDPOINT << "Stream " << id_ << " Trying to send an extra " << bytes_sent << " bytes, when bytes_sent = " << bytes_sent_ << ", and send_window_offset_ = " << send_window_offset_; bytes_sent_ = send_window_offset_; // This is an error on our side, close the connection as soon as possible. connection_->SendConnectionClose(<API key>); return; } bytes_sent_ += bytes_sent; DVLOG(1) << ENDPOINT << "Stream " << id_ << " sent: " << bytes_sent_; } bool QuicFlowController::<API key>() { if (<API key> > <API key>) { LOG(ERROR) << ENDPOINT << "Flow control violation on stream " << id_ << ", receive window offset: " << <API key> << ", highest received byte offset: " << <API key>; return true; } return false; } void QuicFlowController::<API key>() { // Send WindowUpdate to increase receive window if // (receive window offset - consumed bytes) < (max window / 2). // This is behaviour copied from SPDY. DCHECK_LT(bytes_consumed_, <API key>); QuicStreamOffset available_window = <API key> - bytes_consumed_; QuicByteCount threshold = (max_receive_window_ / 2); if (available_window < threshold) { // Update our receive window. <API key> += (max_receive_window_ - available_window); DVLOG(1) << ENDPOINT << "Sending WindowUpdate frame for stream " << id_ << ", consumed bytes: " << bytes_consumed_ << ", available window: " << available_window << ", and threshold: " << threshold << ", and max recvw: " << max_receive_window_ << ". New receive window offset is: " << <API key>; // Inform the peer of our new receive window. connection_->SendWindowUpdate(id_, <API key>); } } void QuicFlowController::MaybeSendBlocked() { if (SendWindowSize() == 0 && <API key> < send_window_offset_) { DVLOG(1) << ENDPOINT << "Stream " << id_ << " is flow control blocked. " << "Send window: " << SendWindowSize() << ", bytes sent: " << bytes_sent_ << ", send limit: " << send_window_offset_; // The entire send_window has been consumed, we are now flow control // blocked. connection_->SendBlocked(id_); // Keep track of when we last sent a BLOCKED frame so that we only send one // at a given send offset. <API key> = send_window_offset_; } } bool QuicFlowController::<API key>( QuicStreamOffset <API key>) { // Only update if send window has increased. if (<API key> <= send_window_offset_) { return false; } DVLOG(1) << ENDPOINT << "<API key> for stream " << id_ << " with new offset " << <API key> << " current offset: " << send_window_offset_ << " bytes_sent: " << bytes_sent_; const bool blocked = IsBlocked(); send_window_offset_ = <API key>; return blocked; } bool QuicFlowController::IsBlocked() const { return SendWindowSize() == 0; } uint64 QuicFlowController::SendWindowSize() const { if (bytes_sent_ > send_window_offset_) { return 0; } return send_window_offset_ - bytes_sent_; } } // namespace net
var lockFile=require("../../lockfile.js");lockFile.lockSync("never-forget");throw new Error("waaaaaaaaa");
// MessagePart.cs // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // all copies or substantial portions of the Software. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.IO; using System.Threading; namespace MimeKit { <summary> A MIME part containing a <see cref="MimeKit.MimeMessage"/> as its content. </summary> <remarks> Represents MIME entities such as those with a Content-Type of message/rfc822 or message/news. </remarks> public class MessagePart : MimeEntity { <summary> Initializes a new instance of the <see cref="MimeKit.MessagePart"/> class. </summary> <remarks>This constructor is used by <see cref="MimeKit.MimeParser"/>.</remarks> <param name="entity">Information used by the constructor.</param> public MessagePart (<API key> entity) : base (entity) { } <summary> Initializes a new instance of the <see cref="MimeKit.MessagePart"/> class. </summary> <remarks> Creates a new <see cref="MessagePart"/>. </remarks> <param name="subtype">The message subtype.</param> <param name="args">An array of initialization parameters: headers and message parts.</param> <exception cref="System.<API key>"> <para><paramref name="subtype"/> is <c>null</c>.</para> <para>-or-</para> <para><paramref name="args"/> is <c>null</c>.</para> </exception> <exception cref="System.ArgumentException"> <para><paramref name="args"/> contains more than one <see cref="MimeKit.MimeMessage"/>.</para> <para>-or-</para> <para><paramref name="args"/> contains one or more arguments of an unknown type.</para> </exception> public MessagePart (string subtype, params object[] args) : this (subtype) { if (args == null) throw new <API key> ("args"); MimeMessage message = null; foreach (object obj in args) { if (obj == null || TryInit (obj)) continue; var mesg = obj as MimeMessage; if (mesg != null) { if (message != null) throw new ArgumentException ("MimeMessage should not be specified more than once."); message = mesg; continue; } throw new ArgumentException ("Unknown initialization parameter: " + obj.GetType ()); } if (message != null) Message = message; } <summary> Initializes a new instance of the <see cref="MimeKit.MessagePart"/> class. </summary> <remarks> Creates a new MIME message entity with the specified subtype. </remarks> <param name="subtype">The message subtype.</param> <exception cref="System.<API key>"> <paramref name="subtype"/> is <c>null</c>. </exception> public MessagePart (string subtype) : base ("message", subtype) { } <summary> Initializes a new instance of the <see cref="MimeKit.MessagePart"/> class. </summary> <remarks> Creates a new message/rfc822 MIME entity. </remarks> public MessagePart () : base ("message", "rfc822") { } <summary> Gets or sets the message content. </summary> <remarks> Gets or sets the message content. </remarks> <value>The message content.</value> public MimeMessage Message { get; set; } <summary> Writes the <see cref="MimeKit.MessagePart"/> to the output stream. </summary> <remarks> Writes the MIME entity and its message to the output stream. </remarks> <param name="options">The formatting options.</param> <param name="stream">The output stream.</param> <param name="cancellationToken">A cancellation token.</param> <exception cref="System.<API key>"> <para><paramref name="options"/> is <c>null</c>.</para> <para>-or-</para> <para><paramref name="stream"/> is <c>null</c>.</para> </exception> <exception cref="System.<API key>"> The operation was canceled via the cancellation token. </exception> <exception cref="System.IO.IOException"> An I/O error occurred. </exception> public override void WriteTo (FormatOptions options, Stream stream, Cancellation<API key> = default (CancellationToken)) { base.WriteTo (options, stream, cancellationToken); if (Message != null) Message.WriteTo (options, stream, cancellationToken); } } }
#include "components/password_manager/core/browser/<API key>.h" #include "base/auto_reset.h" #include "base/location.h" #include "base/memory/scoped_vector.h" #include "base/metrics/histogram_macros.h" #include "base/strings/<API key>.h" #include "components/autofill/core/common/password_form.h" #include "components/password_manager/core/browser/<API key>.h" #include "components/password_manager/core/browser/password_store_sync.h" #include "net/base/escape.h" #include "sync/api/sync_error_factory.h" namespace password_manager { // Converts the |password| into a SyncData object. syncer::SyncData <API key>(const autofill::PasswordForm& password); // Extracts the |PasswordForm| data from sync's protobuf format. autofill::PasswordForm <API key>( const sync_pb::<API key>& password); // Returns the unique tag that will serve as the sync identifier for the // |password| entry. std::string MakePasswordSyncTag(const sync_pb::<API key>& password); std::string MakePasswordSyncTag(const autofill::PasswordForm& password); namespace { // Returns true iff |password_specifics| and |password_specifics| are equal // memberwise. bool <API key>( const sync_pb::<API key>& password_specifics, const autofill::PasswordForm& password_form) { return (password_form.scheme == password_specifics.scheme() && password_form.signon_realm == password_specifics.signon_realm() && password_form.origin.spec() == password_specifics.origin() && password_form.action.spec() == password_specifics.action() && base::UTF16ToUTF8(password_form.username_element) == password_specifics.username_element() && base::UTF16ToUTF8(password_form.password_element) == password_specifics.password_element() && base::UTF16ToUTF8(password_form.username_value) == password_specifics.username_value() && base::UTF16ToUTF8(password_form.password_value) == password_specifics.password_value() && password_form.ssl_valid == password_specifics.ssl_valid() && password_form.preferred == password_specifics.preferred() && password_form.date_created.ToInternalValue() == password_specifics.date_created() && password_form.blacklisted_by_user == password_specifics.blacklisted() && password_form.type == password_specifics.type() && password_form.times_used == password_specifics.times_used() && base::UTF16ToUTF8(password_form.display_name) == password_specifics.display_name() && password_form.avatar_url.spec() == password_specifics.avatar_url() && password_form.federation_url.spec() == password_specifics.federation_url()); } syncer::SyncChange::SyncChangeType GetSyncChangeType( PasswordStoreChange::Type type) { switch (type) { case PasswordStoreChange::ADD: return syncer::SyncChange::ACTION_ADD; case PasswordStoreChange::UPDATE: return syncer::SyncChange::ACTION_UPDATE; case PasswordStoreChange::REMOVE: return syncer::SyncChange::ACTION_DELETE; } NOTREACHED(); return syncer::SyncChange::ACTION_INVALID; } // Creates a PasswordForm from |specifics| and |sync_time|, appends it to // |entries|. void <API key>( const sync_pb::<API key>& specifics, base::Time sync_time, ScopedVector<autofill::PasswordForm>* entries) { entries->push_back( new autofill::PasswordForm(<API key>(specifics))); entries->back()->date_synced = sync_time; } bool IsEmptyPasswordForm(const autofill::PasswordForm& form) { return (form.username_value.empty() && form.password_value.empty() && !form.blacklisted_by_user); } bool <API key>( const sync_pb::<API key>& specifics) { return (specifics.username_value().empty() && specifics.password_value().empty() && !specifics.blacklisted()); } } // namespace struct <API key>::SyncEntries { ScopedVector<autofill::PasswordForm>* <API key>( syncer::SyncChange::SyncChangeType type) { switch (type) { case syncer::SyncChange::ACTION_ADD: return &new_entries; case syncer::SyncChange::ACTION_UPDATE: return &updated_entries; case syncer::SyncChange::ACTION_DELETE: return &deleted_entries; case syncer::SyncChange::ACTION_INVALID: return nullptr; } NOTREACHED(); return nullptr; } // List that contains the entries that are known only to sync. ScopedVector<autofill::PasswordForm> new_entries; // List that contains the entries that are known to both sync and the local // database but have updates in sync. They need to be updated in the local // database. ScopedVector<autofill::PasswordForm> updated_entries; // The list of entries to be deleted from the local database. ScopedVector<autofill::PasswordForm> deleted_entries; }; <API key>::<API key>( PasswordStoreSync* password_store) : password_store_(password_store), <API key>(false) { } <API key>::~<API key>() { } syncer::SyncMergeResult <API key>::<API key>( syncer::ModelType type, const syncer::SyncDataList& initial_sync_data, scoped_ptr<syncer::SyncChangeProcessor> sync_processor, scoped_ptr<syncer::SyncErrorFactory> sync_error_factory) { DCHECK(CalledOnValidThread()); DCHECK_EQ(syncer::PASSWORDS, type); base::AutoReset<bool> processing_changes(&<API key>, true); syncer::SyncMergeResult merge_result(type); // We add all the db entries as |new_local_entries| initially. During model // association entries that match a sync entry will be removed and this list // will only contain entries that are not in sync. ScopedVector<autofill::PasswordForm> password_entries; PasswordEntryMap new_local_entries; if (!<API key>(&password_entries, &new_local_entries)) { merge_result.set_error(sync_error_factory-><API key>( FROM_HERE, "Failed to get passwords from store.")); metrics_util::<API key>(metrics_util::<API key>); return merge_result; } if (password_entries.size() != new_local_entries.size()) { merge_result.set_error(sync_error_factory-><API key>( FROM_HERE, "There are passwords with identical sync tags in the database.")); metrics_util::<API key>( metrics_util::<API key>); return merge_result; } merge_result.<API key>(new_local_entries.size()); SyncEntries sync_entries; // Changes from password db that need to be propagated to sync. syncer::SyncChangeList updated_db_entries; for (syncer::SyncDataList::const_iterator sync_iter = initial_sync_data.begin(); sync_iter != initial_sync_data.end(); ++sync_iter) { CreateOrUpdateEntry(*sync_iter, &new_local_entries, &sync_entries, &updated_db_entries); } for (PasswordEntryMap::iterator it = new_local_entries.begin(); it != new_local_entries.end(); ++it) { if (IsEmptyPasswordForm(*it->second)) { // This code can be removed once all users have their password store // cleaned up. This should happen in M43 and can be verified using crash // reports. sync_entries.deleted_entries.push_back( new autofill::PasswordForm(*it->second)); } else { updated_db_entries.push_back( syncer::SyncChange(FROM_HERE, syncer::SyncChange::ACTION_ADD, <API key>(*it->second))); } } <API key>(sync_entries); merge_result.set_error( sync_processor->ProcessSyncChanges(FROM_HERE, updated_db_entries)); if (merge_result.error().IsSet()) { metrics_util::<API key>(metrics_util::<API key>); return merge_result; } merge_result.<API key>( merge_result.<API key>() + sync_entries.new_entries.size()); merge_result.set_num_items_added(sync_entries.new_entries.size()); merge_result.<API key>(sync_entries.updated_entries.size()); merge_result.<API key>(sync_entries.deleted_entries.size()); // Save |sync_processor_| only if the whole procedure succeeded. In case of // failure Sync shouldn't receive any updates from the PasswordStore. sync_error_factory_ = sync_error_factory.Pass(); sync_processor_ = sync_processor.Pass(); metrics_util::<API key>(metrics_util::SYNCING_OK); return merge_result; } void <API key>::StopSyncing(syncer::ModelType type) { DCHECK(CalledOnValidThread()); DCHECK_EQ(syncer::PASSWORDS, type); sync_processor_.reset(); sync_error_factory_.reset(); } syncer::SyncDataList <API key>::GetAllSyncData( syncer::ModelType type) const { DCHECK(CalledOnValidThread()); DCHECK_EQ(syncer::PASSWORDS, type); ScopedVector<autofill::PasswordForm> password_entries; <API key>(&password_entries, nullptr); syncer::SyncDataList sync_data; for (PasswordForms::iterator it = password_entries.begin(); it != password_entries.end(); ++it) { sync_data.push_back(<API key>(**it)); } return sync_data; } syncer::SyncError <API key>::ProcessSyncChanges( const tracked_objects::Location& from_here, const syncer::SyncChangeList& change_list) { DCHECK(CalledOnValidThread()); base::AutoReset<bool> processing_changes(&<API key>, true); SyncEntries sync_entries; base::Time time_now = base::Time::Now(); for (syncer::SyncChangeList::const_iterator it = change_list.begin(); it != change_list.end(); ++it) { const sync_pb::EntitySpecifics& specifics = it->sync_data().GetSpecifics(); ScopedVector<autofill::PasswordForm>* entries = sync_entries.<API key>(it->change_type()); if (!entries) { return sync_error_factory_-><API key>( FROM_HERE, "Failed to process sync changes for passwords datatype."); } <API key>( specifics.password().<API key>(), time_now, entries); } <API key>(sync_entries); return syncer::SyncError(); } void <API key>::<API key>( const <API key>& local_changes) { DCHECK(CalledOnValidThread()); if (!sync_processor_) { if (!flare_.is_null()) { flare_.Run(syncer::PASSWORDS); flare_.Reset(); } return; } // <API key>() can be called from ProcessSyncChanges(). Do // nothing in this case. if (<API key>) return; syncer::SyncChangeList sync_changes; for (<API key>::const_iterator it = local_changes.begin(); it != local_changes.end(); ++it) { syncer::SyncData data = (it->type() == PasswordStoreChange::REMOVE ? syncer::SyncData::CreateLocalDelete(MakePasswordSyncTag(it->form()), syncer::PASSWORDS) : <API key>(it->form())); sync_changes.push_back( syncer::SyncChange(FROM_HERE, GetSyncChangeType(it->type()), data)); } sync_processor_->ProcessSyncChanges(FROM_HERE, sync_changes); } void <API key>::<API key>( const syncer::SyncableService::StartSyncFlare& flare) { DCHECK(CalledOnValidThread()); flare_ = flare; } bool <API key>::<API key>( ScopedVector<autofill::PasswordForm>* password_entries, PasswordEntryMap* passwords_entry_map) const { DCHECK(password_entries); ScopedVector<autofill::PasswordForm> blacklist_entries; if (!password_store_-><API key>(password_entries) || !password_store_->FillBlacklistLogins(&blacklist_entries)) { // Password store often fails to load passwords. Track failures with UMA. <API key>("Sync.<API key>", <API key>(syncer::PASSWORDS), syncer::MODEL_TYPE_COUNT); return false; } // Move |blacklist_entries| to |password_entries|. password_entries->reserve(password_entries->size() + blacklist_entries.size()); password_entries->insert(password_entries->end(), blacklist_entries.begin(), blacklist_entries.end()); blacklist_entries.weak_clear(); if (!passwords_entry_map) return true; PasswordEntryMap& entry_map = *passwords_entry_map; for (PasswordForms::iterator it = password_entries->begin(); it != password_entries->end(); ++it) { autofill::PasswordForm* password_form = *it; entry_map[MakePasswordSyncTag(*password_form)] = password_form; } return true; } void <API key>::<API key>(const SyncEntries& entries) { <API key> changes; <API key>(&PasswordStoreSync::AddLoginSync, entries.new_entries.get(), &changes); <API key>(&PasswordStoreSync::UpdateLoginSync, entries.updated_entries.get(), &changes); <API key>(&PasswordStoreSync::RemoveLoginSync, entries.deleted_entries.get(), &changes); // We have to notify password store observers of the change by hand since // we use internal password store interfaces to make changes synchronously. password_store_->NotifyLoginsChanged(changes); } // static void <API key>::CreateOrUpdateEntry( const syncer::SyncData& data, PasswordEntryMap* <API key>, SyncEntries* sync_entries, syncer::SyncChangeList* updated_db_entries) { const sync_pb::EntitySpecifics& specifics = data.GetSpecifics(); const sync_pb::<API key>& password_specifics( specifics.password().<API key>()); std::string tag = MakePasswordSyncTag(password_specifics); // Check whether the data from sync is already in the password store. PasswordEntryMap::iterator <API key> = <API key>->find(tag); base::Time time_now = base::Time::Now(); if (<API key> == <API key>->end()) { if (<API key>(password_specifics)) { // server. This code can be removed once all users have their password // store cleaned up. This should happen in M43 and can be verified using // crash reports. updated_db_entries->push_back( syncer::SyncChange(FROM_HERE, syncer::SyncChange::ACTION_DELETE, data)); } else { // The sync data is not in the password store, so we need to create it in // the password store. Add the entry to the new_entries list. <API key>(password_specifics, time_now, &sync_entries->new_entries); } } else { // The entry is in password store. If the entries are not identical, then // the entries need to be merged. // If the passwords differ, take the one that was created more recently. const autofill::PasswordForm& password_form = *<API key>->second; if (!<API key>(password_specifics, password_form)) { if (base::Time::FromInternalValue(password_specifics.date_created()) < password_form.date_created) { updated_db_entries->push_back( syncer::SyncChange(FROM_HERE, syncer::SyncChange::ACTION_UPDATE, <API key>(password_form))); } else { <API key>(password_specifics, time_now, &sync_entries->updated_entries); } } else if (IsEmptyPasswordForm(password_form)) { // server and the local db. This code can be removed once all users have // their password store cleaned up. This should happen in M43 and can be // verified using crash reports. updated_db_entries->push_back( syncer::SyncChange(FROM_HERE, syncer::SyncChange::ACTION_DELETE, <API key>(password_form))); <API key>(password_specifics, time_now, &sync_entries->deleted_entries); } // Remove the entry from the entry map to indicate a match has been found. // Entries that remain in the map at the end of associating all sync entries // will be treated as additions that need to be propagated to sync. <API key>->erase(<API key>); } } void <API key>::<API key>( DatabaseOperation operation, const PasswordForms& entries, <API key>* all_changes) { for (PasswordForms::const_iterator it = entries.begin(); it != entries.end(); ++it) { <API key> new_changes = (password_store_->*operation)(**it); all_changes->insert(all_changes->end(), new_changes.begin(), new_changes.end()); } } syncer::SyncData <API key>( const autofill::PasswordForm& password_form) { sync_pb::EntitySpecifics password_data; sync_pb::<API key>* password_specifics = password_data.mutable_password()-><API key>(); #define CopyField(field) password_specifics->set_##field(password_form.field) #define CopyStringField(field) \ password_specifics->set_##field(base::UTF16ToUTF8(password_form.field)) CopyField(scheme); CopyField(signon_realm); password_specifics->set_origin(password_form.origin.spec()); password_specifics->set_action(password_form.action.spec()); CopyStringField(username_element); CopyStringField(password_element); CopyStringField(username_value); CopyStringField(password_value); CopyField(ssl_valid); CopyField(preferred); password_specifics->set_date_created( password_form.date_created.ToInternalValue()); password_specifics->set_blacklisted(password_form.blacklisted_by_user); CopyField(type); CopyField(times_used); CopyStringField(display_name); password_specifics->set_avatar_url(password_form.avatar_url.spec()); password_specifics->set_federation_url(password_form.federation_url.spec()); #undef CopyStringField #undef CopyField std::string tag = MakePasswordSyncTag(*password_specifics); return syncer::SyncData::CreateLocalData(tag, tag, password_data); } autofill::PasswordForm <API key>( const sync_pb::<API key>& password) { autofill::PasswordForm new_password; new_password.scheme = static_cast<autofill::PasswordForm::Scheme>(password.scheme()); new_password.signon_realm = password.signon_realm(); new_password.origin = GURL(password.origin()); new_password.action = GURL(password.action()); new_password.username_element = base::UTF8ToUTF16(password.username_element()); new_password.password_element = base::UTF8ToUTF16(password.password_element()); new_password.username_value = base::UTF8ToUTF16(password.username_value()); new_password.password_value = base::UTF8ToUTF16(password.password_value()); new_password.ssl_valid = password.ssl_valid(); new_password.preferred = password.preferred(); new_password.date_created = base::Time::FromInternalValue(password.date_created()); new_password.blacklisted_by_user = password.blacklisted(); new_password.type = static_cast<autofill::PasswordForm::Type>(password.type()); new_password.times_used = password.times_used(); new_password.display_name = base::UTF8ToUTF16(password.display_name()); new_password.avatar_url = GURL(password.avatar_url()); new_password.federation_url = GURL(password.federation_url()); return new_password; } std::string MakePasswordSyncTag( const sync_pb::<API key>& password) { return MakePasswordSyncTag(<API key>(password)); } std::string MakePasswordSyncTag(const autofill::PasswordForm& password) { return (net::EscapePath(password.origin.spec()) + "|" + net::EscapePath(base::UTF16ToUTF8(password.username_element)) + "|" + net::EscapePath(base::UTF16ToUTF8(password.username_value)) + "|" + net::EscapePath(base::UTF16ToUTF8(password.password_element)) + "|" + net::EscapePath(password.signon_realm)); } } // namespace password_manager
# include "trek.h" # include "getpar.h" /* ** SET WARP FACTOR ** ** The warp factor is set for future move commands. It is ** checked for consistancy. */ void setwarp() { double warpfac; warpfac = getfltpar("Warp factor"); if (warpfac < 0.0) return; if (warpfac < 1.0) { printf("Minimum warp speed is 1.0\n"); return; } if (warpfac > 10.0) { printf("Maximum speed is warp 10.0\n"); return; } if (warpfac > 6.0) printf("Damage to warp engines may occur above warp 6.0\n"); Ship.warp = warpfac; Ship.warp2 = Ship.warp * warpfac; Ship.warp3 = Ship.warp2 * warpfac; }
<div class="item addon"> <hgroup class="c"> <img id="addon-icon" src="{{ addon.get_icon_url(32) }}" class="icon"> <h1 class="addon"{{ addon.name|locale_html }}> {% if addon.is_disabled %} {{ addon.name }} {% else %} <a href="{{ addon.get_url_path() }}">{{ addon.name }}</a> {% endif %} </h1> <h4 class="author"> {{ addon_users_list(addon) }} </h4> </hgroup> </div>
#ifndef V8_BASE_ITERATOR_H_ #define V8_BASE_ITERATOR_H_ #include <iterator> namespace v8 { namespace base { template <class Category, class Type, class Diff = std::ptrdiff_t, class Pointer = Type*, class Reference = Type&> struct iterator { using iterator_category = Category; using value_type = Type; using difference_type = Diff; using pointer = Pointer; using reference = Reference; }; // The intention of the base::iterator_range class is to encapsulate two // iterators so that the range defined by the iterators can be used like // a regular STL container (actually only a subset of the full container // functionality is available usually). template <typename ForwardIterator> class iterator_range { public: using iterator = ForwardIterator; using const_iterator = ForwardIterator; using pointer = typename std::iterator_traits<iterator>::pointer; using reference = typename std::iterator_traits<iterator>::reference; using value_type = typename std::iterator_traits<iterator>::value_type; using difference_type = typename std::iterator_traits<iterator>::difference_type; iterator_range() : begin_(), end_() {} iterator_range(ForwardIterator begin, ForwardIterator end) : begin_(begin), end_(end) {} iterator begin() { return begin_; } iterator end() { return end_; } const_iterator begin() const { return begin_; } const_iterator end() const { return end_; } const_iterator cbegin() const { return begin_; } const_iterator cend() const { return end_; } bool empty() const { return cbegin() == cend(); } // Random Access iterators only. reference operator[](difference_type n) { return begin()[n]; } difference_type size() const { return cend() - cbegin(); } private: const_iterator const begin_; const_iterator const end_; }; template <typename ForwardIterator> auto make_iterator_range(ForwardIterator begin, ForwardIterator end) { return iterator_range<ForwardIterator>{begin, end}; } // {Reversed} returns a container adapter usable in a range-based "for" // statement for iterating a reversible container in reverse order. // Example: // std::vector<int> v = ...; // for (int i : base::Reversed(v)) { // // iterates through v from back to front template <typename T> auto Reversed(T& t) { // NOLINT(runtime/references): match {rbegin} and {rend} return make_iterator_range(std::rbegin(t), std::rend(t)); } } // namespace base } // namespace v8 #endif // V8_BASE_ITERATOR_H_
#ifndef <API key> #define <API key> #include <algorithm> #include <string> #include <vector> #include "base/i18n/base_i18n_export.h" #include "base/strings/string_piece.h" #include "third_party/icu/source/i18n/unicode/coll.h" namespace base { namespace i18n { // Compares the two strings using the specified collator. BASE_I18N_EXPORT UCollationResult <API key>(const icu::Collator& collator, const StringPiece16 lhs, const StringPiece16 rhs); } // namespace i18n } // namespace base #endif // <API key>
<?php if ($online->screenshot !== false) : ?> <h5><?php echo <API key>::getInstance()->getTranslation('chat/screenshot','Taken')?> <?php echo $online->screenshot->date_front?></h5> <a href="<?php echo erLhcoreClassDesign::baseurl('file/downloadfile')?>/<?php echo $online->screenshot->id?>/<?php echo $online->screenshot->security_hash?>" target="_blank" class="screnshot-container"><img id="screenshotImage" src="<?php echo erLhcoreClassDesign::baseurl('file/downloadfile')?>/<?php echo $online->screenshot->id?>/<?php echo $online->screenshot->security_hash?>" alt="" /></a> <?php else : ?> <p><?php echo <API key>::getInstance()->getTranslation('chat/screenshot','Perhaps screenshot is under way or screenshot is not supported on client browser, click refresh to check for a screenshot')?>.</p> <input type="button" value="<?php echo <API key>::getInstance()->getTranslation('chat/screenshot','Refresh')?>" class="button tiny round" onclick="lhinst.<API key>('<?php echo $online->id?>')" /> <?php endif;?>
#include "native_client/src/shared/ppapi_proxy/browser_ppp.h" #include <string.h> #include "native_client/src/include/nacl_scoped_ptr.h" #include "native_client/src/include/portability.h" #include "native_client/src/include/portability_process.h" #include "native_client/src/shared/ppapi_proxy/browser_globals.h" #include "native_client/src/shared/ppapi_proxy/browser_ppp_find.h" #include "native_client/src/shared/ppapi_proxy/<API key>.h" #include "native_client/src/shared/ppapi_proxy/<API key>.h" #include "native_client/src/shared/ppapi_proxy/<API key>.h" #include "native_client/src/shared/ppapi_proxy/<API key>.h" #include "native_client/src/shared/ppapi_proxy/<API key>.h" #include "native_client/src/shared/ppapi_proxy/<API key>.h" #include "native_client/src/shared/ppapi_proxy/browser_ppp_zoom.h" #include "native_client/src/shared/ppapi_proxy/browser_upcall.h" #include "native_client/src/shared/ppapi_proxy/trusted/srpcgen/ppb_rpc.h" #include "native_client/src/shared/ppapi_proxy/trusted/srpcgen/ppp_rpc.h" #include "native_client/src/shared/ppapi_proxy/utility.h" #include "native_client/src/trusted/desc/nacl_desc_wrapper.h" #include "native_client/src/trusted/plugin/plugin.h" #include "ppapi/c/dev/ppp_find_dev.h" #include "ppapi/c/dev/ppp_printing_dev.h" #include "ppapi/c/dev/ppp_selection_dev.h" #include "ppapi/c/dev/ppp_zoom_dev.h" #include "ppapi/c/pp_errors.h" #include "ppapi/c/ppp.h" #include "ppapi/c/ppp_input_event.h" #include "ppapi/c/ppp_mouse_lock.h" #include "ppapi/c/private/ppb_nacl_private.h" namespace ppapi_proxy { // The following methods are the SRPC dispatchers for ppapi/c/ppp.h. namespace { // PPB_GetInterface must only be called on the main thread. So as we are adding // off-the-main-thread support for various interfaces, we need to ensure that // their pointers are available on upcall thread of the the trusted proxy. void PPBGetInterfaces() { PPBCoreInterface(); // TODO(all): add more interfaces here once available off the main thread. } } // namespace int32_t BrowserPpp::InitializeModule(PP_Module module_id, PPB_GetInterface <API key>) { DebugPrintf("<API key>: module=%"NACL_PRId32"\n", module_id); // Ask the browser for an interface which provides missing functions const PPB_NaCl_Private* ppb_nacl = reinterpret_cast<const PPB_NaCl_Private*>( <API key>(<API key>)); if (ppb_nacl == NULL) { DebugPrintf("<API key>: NaCl private interface missing!\n"); return PP_ERROR_FAILED; } SetPPBGetInterface(<API key>, plugin_-><API key>(), !ppb_nacl-><API key>()); PPBGetInterfaces(); <API key>(plugin_->pp_instance(), this); CHECK(main_channel_ != NULL); nacl::scoped_ptr<nacl::DescWrapper> wrapper( BrowserUpcall::Start(&upcall_thread_, main_channel_)); if (wrapper.get() == NULL) return PP_ERROR_FAILED; // Set up the callbacks allowed on the main channel. NaClSrpcService* service = reinterpret_cast<NaClSrpcService*>( calloc(1, sizeof(*service))); if (NULL == service) { DebugPrintf("<API key>: " "could not create callback services.\n"); return PP_ERROR_FAILED; } if (!<API key>(service, PpbRpcs::srpc_methods)) { DebugPrintf("<API key>: " "could not construct callback services.\n"); free(service); return PP_ERROR_FAILED; } // Export the service on the channel. main_channel_->server = service; char* service_string = const_cast<char*>(service->service_string); <API key>(main_channel_, module_id); <API key>(main_channel_, plugin_->pp_instance()); // Do the RPC. int32_t pp_error; NaClSrpcError srpc_result = PppRpcClient::<API key>(main_channel_, module_id, wrapper->desc(), service_string, &pp_error); DebugPrintf("<API key>: %s\n", NaClSrpcErrorString(srpc_result)); is_nexe_alive_ = (srpc_result != <API key>); if (srpc_result != NACL_SRPC_RESULT_OK) return PP_ERROR_FAILED; DebugPrintf("<API key>: pp_error=%"NACL_PRId32"\n", pp_error); if (pp_error != PP_OK) return pp_error; const void* ppp_instance = GetPluginInterface(<API key>); DebugPrintf("<API key>: ppp_instance=%p\n", ppp_instance); <API key> = reinterpret_cast<const PPP_Instance*>(ppp_instance); if (<API key> == NULL) // PPP_Instance is required. return <API key>; // PPB_Messaging and PPP_InputEvent are optional, so it's OK for them to // return NULL. <API key> = reinterpret_cast<const PPP_Messaging*>( GetPluginInterface(<API key>)); <API key> = reinterpret_cast<const PPP_InputEvent*>( GetPluginInterface(<API key>)); if (!is_valid()) // Nexe died in PPP_GetInterface. return PP_ERROR_FAILED; return PP_OK; } void BrowserPpp::ShutdownModule() { DebugPrintf("PPP_Shutdown: main_channel=%p\n", static_cast<void*>(main_channel_)); if (main_channel_ == NULL) { CHECK(!is_nexe_alive_); return; // The proxy has already been shut down. } if (is_nexe_alive_) { NaClSrpcError srpc_result = PppRpcClient::PPP_ShutdownModule(main_channel_); DebugPrintf("PPP_ShutdownModule: %s\n", NaClSrpcErrorString(srpc_result)); } NaClThreadJoin(&upcall_thread_); <API key>(plugin_->pp_instance()); <API key>(main_channel_); <API key>(main_channel_); main_channel_ = NULL; is_nexe_alive_ = false; DebugPrintf("PPP_Shutdown: main_channel=NULL\n"); } const void* BrowserPpp::GetPluginInterface(const char* interface_name) { DebugPrintf("PPP_GetInterface('%s')\n", interface_name); if (!is_valid()) return NULL; int32_t <API key>; NaClSrpcError srpc_result = PppRpcClient::PPP_GetInterface(main_channel_, const_cast<char*>(interface_name), &<API key>); DebugPrintf("PPP_GetInterface('%s'): %s\n", interface_name, NaClSrpcErrorString(srpc_result)); is_nexe_alive_ = (srpc_result != <API key>); // Special case PPP_Instance versioning. The plugin side of the proxy // converts Instance 1.1 to Instance 1.0 as needed, so we want to say here // in the browser side that any time either 1.0 or 1.1 is supported, that // we'll support 1.1. if (srpc_result == NACL_SRPC_RESULT_OK && !<API key> && strcmp(interface_name, <API key>) == 0) { srpc_result = PppRpcClient::PPP_GetInterface(main_channel_, const_cast<char *>(<API key>), &<API key>); } const void* ppp_interface = NULL; if (srpc_result != NACL_SRPC_RESULT_OK || !<API key>) { ppp_interface = NULL; } else if (strcmp(interface_name, <API key>) == 0) { ppp_interface = reinterpret_cast<const void*>(BrowserInstance::GetInterface()); } else if (strcmp(interface_name, <API key>) == 0) { ppp_interface = reinterpret_cast<const void*>(BrowserMessaging::GetInterface()); } else if (strcmp(interface_name, <API key>) == 0) { ppp_interface = reinterpret_cast<const void*>(BrowserMouseLock::GetInterface()); } else if (strcmp(interface_name, <API key>) == 0) { ppp_interface = reinterpret_cast<const void*>(BrowserInputEvent::GetInterface()); } else if (strcmp(interface_name, <API key>) == 0) { ppp_interface = reinterpret_cast<const void*>(BrowserFind::GetInterface()); } else if (strcmp(interface_name, <API key>) == 0) { ppp_interface = reinterpret_cast<const void*>(BrowserPrinting::GetInterface()); } else if (strcmp(interface_name, <API key>) == 0) { ppp_interface = reinterpret_cast<const void*>(BrowserSelection::GetInterface()); } else if (strcmp(interface_name, <API key>) == 0) { ppp_interface = reinterpret_cast<const void*>(BrowserZoom::GetInterface()); } // TODO(sehr): other interfaces go here. DebugPrintf("PPP_GetInterface('%s'): %p\n", interface_name, ppp_interface); return ppp_interface; } const void* BrowserPpp::<API key>(const char* interface_name) { const void* ppp_interface = GetPluginInterface(interface_name); if (ppp_interface == NULL) DebugPrintf("PPB_GetInterface: %s not found\n", interface_name); CHECK(ppp_interface != NULL); return ppp_interface; } } // namespace ppapi_proxy
<! This software is licensed as described in the file COPYING, which you should have received as part of this distribution. The terms are also available at http: This software consists of voluntary contributions made by many individuals. For the exact contribution history, see the revision history and logs, available at http://trac.edgewall.org/. Conditionally render an ''Attach File'' button. Arguments: - alist: the data for the list of attachments - add_button_title=None: the title of the "Attach" button <form xmlns="http: xmlns:py="http://genshi.edgewall.org/" xmlns:xi="http: xmlns:i18n="http://genshi.edgewall.org/i18n" py:if="alist.can_create" method="get" action="${alist.attach_href}" id="attachfile"> <div> <input type="hidden" name="action" value="new" /> <input type="submit" id="attachfilebutton" value="${value_of('add_button_title') or (_('Attach another file') if alist.attachments else _('Attach file'))}"/> </div> </form>
var Suite=require("../suite"),Test=require("../test"),escapeRe=require("<API key>"),utils=require("../utils");module.exports=function(a){var b=[a];a.on("pre-require",function(e,d,c){var f=require("./common")(b,e);e.before=f.before;e.after=f.after;e.beforeEach=f.beforeEach;e.afterEach=f.afterEach;e.run=c.options.delay&&f.runWithSuite(a);e.suite=function(h){if(b.length>1){b.shift()}var g=Suite.create(b[0],h);g.file=d;b.unshift(g);return g};e.suite.only=function(i,h){var g=e.suite(i,h);c.grep(g.fullTitle())};e.test=function(h,g){var i=new Test(h,g);i.file=d;b[0].addTest(i);return i};e.test.only=function(i,h){var j=e.test(i,h);var g="^"+escapeRe(j.fullTitle())+"$";c.grep(new RegExp(g))};e.test.skip=f.test.skip})};
#include "components/country_codes/country_codes.h" #include "build/build_config.h" #if BUILDFLAG(IS_POSIX) && !BUILDFLAG(IS_APPLE) #include <locale.h> #endif #include "base/strings/string_util.h" #include "build/build_config.h" #include "components/pref_registry/<API key>.h" #include "components/prefs/pref_service.h" #if BUILDFLAG(IS_WIN) #include <windows.h> #undef IN // On Windows, windef.h defines this, which screws up "India" cases. #elif BUILDFLAG(IS_APPLE) #include "base/mac/scoped_cftyperef.h" #endif #if BUILDFLAG(IS_ANDROID) #include "base/android/locale_utils.h" #endif namespace country_codes { namespace { // TODO(hcarmona/johntlee): remove this function after confirming if it only // pertains to obsolete OSes. int <API key>(char c1, char c2) { // SPECIAL CASE: In 2003, Yugoslavia renamed itself to Serbia and Montenegro. // Serbia and Montenegro dissolved their union in June 2006. Yugoslavia was // ISO 'YU' and Serbia and Montenegro were ISO 'CS'. Serbia was subsequently // issued 'RS' and Montenegro 'ME'. Windows XP and Mac OS X Leopard still use // the value 'YU'. If we get a value of 'YU' or 'CS' we will map it to 'RS'. if ((c1 == 'Y' && c2 == 'U') || (c1 == 'C' && c2 == 'S')) { c1 = 'R'; c2 = 'S'; } // SPECIAL CASE: Timor-Leste changed from 'TP' to 'TL' in 2002. Windows XP // predates this; we therefore map this value. if (c1 == 'T' && c2 == 'P') c2 = 'L'; return <API key>(c1, c2); } #if BUILDFLAG(IS_WIN) // For reference, a list of GeoIDs can be found at int GeoIDToCountryID(GEOID geo_id) { const int kISOBufferSize = 3; // Two plus one for the terminator. wchar_t isobuf[kISOBufferSize] = {}; int retval = GetGeoInfo(geo_id, GEO_ISO2, isobuf, kISOBufferSize, 0); if (retval == kISOBufferSize && !(isobuf[0] == L'X' && isobuf[1] == L'X')) { return <API key>(static_cast<char>(isobuf[0]), static_cast<char>(isobuf[1])); } // Various locations have ISO codes that Windows does not return. switch (geo_id) { case 0x144: // Guernsey return <API key>('G', 'G'); case 0x148: // Jersey return <API key>('J', 'E'); case 0x3B16: // Isle of Man return <API key>('I', 'M'); // 'UM' (U.S. Minor Outlying Islands) case 0x7F: // Johnston Atoll case 0x102: // Wake Island case 0x131: // Baker Island case 0x146: // Howland Island case 0x147: // Jarvis Island case 0x149: // Kingman Reef case 0x152: // Palmyra Atoll case 0x52FA: // Midway Islands return <API key>('U', 'M'); // 'SH' (Saint Helena) case 0x12F: // Ascension Island case 0x15C: // Tristan da Cunha return <API key>('S', 'H'); // 'IO' (British Indian Ocean Territory) case 0x13A: // Diego Garcia return <API key>('I', 'O'); // Other cases where there is no ISO country code; we assign countries that // can serve as reasonable defaults. case 0x154: // Rota Island case 0x155: // Saipan case 0x15A: // Tinian Island return <API key>('U', 'S'); case 0x134: // Channel Islands return <API key>('G', 'B'); case 0x143: // Guantanamo Bay default: return kCountryIDUnknown; } } #endif // BUILDFLAG(IS_WIN) } // namespace const char kCountryIDAtInstall[] = "<API key>"; int <API key>(const std::string& country) { return (country.length() == 2) ? <API key>(country[0], country[1]) : kCountryIDUnknown; } int <API key>(PrefService* prefs) { if (!prefs) return GetCurrentCountryID(); // Cache first run Country ID value in prefs, and use it afterwards. This // ensures that just because the user moves around, we won't automatically // make major changes to their available search providers, which would feel // surprising. if (!prefs->HasPrefPath(country_codes::kCountryIDAtInstall)) { prefs->SetInteger(country_codes::kCountryIDAtInstall, GetCurrentCountryID()); } return prefs->GetInteger(country_codes::kCountryIDAtInstall); } void <API key>(user_prefs::<API key>* registry) { registry->RegisterIntegerPref(country_codes::kCountryIDAtInstall, kCountryIDUnknown); } #if BUILDFLAG(IS_WIN) int GetCurrentCountryID() { return GeoIDToCountryID(GetUserGeoID(GEOCLASS_NATION)); } #elif BUILDFLAG(IS_APPLE) int GetCurrentCountryID() { base::ScopedCFTypeRef<CFLocaleRef> locale(CFLocaleCopyCurrent()); CFStringRef country = (CFStringRef)CFLocaleGetValue(locale.get(), <API key>); if (!country) return kCountryIDUnknown; UniChar isobuf[2]; CFRange char_range = CFRangeMake(0, 2); <API key>(country, char_range, isobuf); return <API key>(static_cast<char>(isobuf[0]), static_cast<char>(isobuf[1])); } #elif BUILDFLAG(IS_ANDROID) int GetCurrentCountryID() { return <API key>(base::android::<API key>()); } #elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA) int GetCurrentCountryID() { const char* locale = setlocale(LC_MESSAGES, nullptr); if (!locale) return kCountryIDUnknown; // The format of a locale name is: // language[_territory][.codeset][@modifier], where territory is an ISO 3166 // country code, which is what we want. // First remove the language portion. std::string locale_str(locale); size_t territory_delim = locale_str.find('_'); if (territory_delim == std::string::npos) return kCountryIDUnknown; locale_str.erase(0, territory_delim + 1); // Next remove any codeset/modifier portion and uppercase. return <API key>( base::ToUpperASCII(locale_str.substr(0, locale_str.find_first_of(".@")))); } #endif } // namespace country_codes
/*[clinic input] preserve [clinic start generated code]*/ PyDoc_STRVAR(cmath_acos__doc__, "acos($module, z, /)\n" " "\n" "Return the arc cosine of z."); #define <API key> \ {"acos", (PyCFunction)cmath_acos, METH_O, cmath_acos__doc__}, static Py_complex cmath_acos_impl(PyModuleDef *module, Py_complex z); static PyObject * cmath_acos(PyModuleDef *module, PyObject *arg) { PyObject *return_value = NULL; Py_complex z; Py_complex _return_value; if (!PyArg_Parse(arg, "D:acos", &z)) goto exit; /* modifications for z */ errno = 0; PyFPE_START_PROTECT("complex function", goto exit); _return_value = cmath_acos_impl(module, z); PyFPE_END_PROTECT(_return_value); if (errno == EDOM) { PyErr_SetString(PyExc_ValueError, "math domain error"); goto exit; } else if (errno == ERANGE) { PyErr_SetString(PyExc_OverflowError, "math range error"); goto exit; } else { return_value = <API key>(_return_value); } exit: return return_value; } PyDoc_STRVAR(cmath_acosh__doc__, "acosh($module, z, /)\n" " "\n" "Return the inverse hyperbolic cosine of z."); #define <API key> \ {"acosh", (PyCFunction)cmath_acosh, METH_O, cmath_acosh__doc__}, static Py_complex cmath_acosh_impl(PyModuleDef *module, Py_complex z); static PyObject * cmath_acosh(PyModuleDef *module, PyObject *arg) { PyObject *return_value = NULL; Py_complex z; Py_complex _return_value; if (!PyArg_Parse(arg, "D:acosh", &z)) goto exit; /* modifications for z */ errno = 0; PyFPE_START_PROTECT("complex function", goto exit); _return_value = cmath_acosh_impl(module, z); PyFPE_END_PROTECT(_return_value); if (errno == EDOM) { PyErr_SetString(PyExc_ValueError, "math domain error"); goto exit; } else if (errno == ERANGE) { PyErr_SetString(PyExc_OverflowError, "math range error"); goto exit; } else { return_value = <API key>(_return_value); } exit: return return_value; } PyDoc_STRVAR(cmath_asin__doc__, "asin($module, z, /)\n" " "\n" "Return the arc sine of z."); #define <API key> \ {"asin", (PyCFunction)cmath_asin, METH_O, cmath_asin__doc__}, static Py_complex cmath_asin_impl(PyModuleDef *module, Py_complex z); static PyObject * cmath_asin(PyModuleDef *module, PyObject *arg) { PyObject *return_value = NULL; Py_complex z; Py_complex _return_value; if (!PyArg_Parse(arg, "D:asin", &z)) goto exit; /* modifications for z */ errno = 0; PyFPE_START_PROTECT("complex function", goto exit); _return_value = cmath_asin_impl(module, z); PyFPE_END_PROTECT(_return_value); if (errno == EDOM) { PyErr_SetString(PyExc_ValueError, "math domain error"); goto exit; } else if (errno == ERANGE) { PyErr_SetString(PyExc_OverflowError, "math range error"); goto exit; } else { return_value = <API key>(_return_value); } exit: return return_value; } PyDoc_STRVAR(cmath_asinh__doc__, "asinh($module, z, /)\n" " "\n" "Return the inverse hyperbolic sine of z."); #define <API key> \ {"asinh", (PyCFunction)cmath_asinh, METH_O, cmath_asinh__doc__}, static Py_complex cmath_asinh_impl(PyModuleDef *module, Py_complex z); static PyObject * cmath_asinh(PyModuleDef *module, PyObject *arg) { PyObject *return_value = NULL; Py_complex z; Py_complex _return_value; if (!PyArg_Parse(arg, "D:asinh", &z)) goto exit; /* modifications for z */ errno = 0; PyFPE_START_PROTECT("complex function", goto exit); _return_value = cmath_asinh_impl(module, z); PyFPE_END_PROTECT(_return_value); if (errno == EDOM) { PyErr_SetString(PyExc_ValueError, "math domain error"); goto exit; } else if (errno == ERANGE) { PyErr_SetString(PyExc_OverflowError, "math range error"); goto exit; } else { return_value = <API key>(_return_value); } exit: return return_value; } PyDoc_STRVAR(cmath_atan__doc__, "atan($module, z, /)\n" " "\n" "Return the arc tangent of z."); #define <API key> \ {"atan", (PyCFunction)cmath_atan, METH_O, cmath_atan__doc__}, static Py_complex cmath_atan_impl(PyModuleDef *module, Py_complex z); static PyObject * cmath_atan(PyModuleDef *module, PyObject *arg) { PyObject *return_value = NULL; Py_complex z; Py_complex _return_value; if (!PyArg_Parse(arg, "D:atan", &z)) goto exit; /* modifications for z */ errno = 0; PyFPE_START_PROTECT("complex function", goto exit); _return_value = cmath_atan_impl(module, z); PyFPE_END_PROTECT(_return_value); if (errno == EDOM) { PyErr_SetString(PyExc_ValueError, "math domain error"); goto exit; } else if (errno == ERANGE) { PyErr_SetString(PyExc_OverflowError, "math range error"); goto exit; } else { return_value = <API key>(_return_value); } exit: return return_value; } PyDoc_STRVAR(cmath_atanh__doc__, "atanh($module, z, /)\n" " "\n" "Return the inverse hyperbolic tangent of z."); #define <API key> \ {"atanh", (PyCFunction)cmath_atanh, METH_O, cmath_atanh__doc__}, static Py_complex cmath_atanh_impl(PyModuleDef *module, Py_complex z); static PyObject * cmath_atanh(PyModuleDef *module, PyObject *arg) { PyObject *return_value = NULL; Py_complex z; Py_complex _return_value; if (!PyArg_Parse(arg, "D:atanh", &z)) goto exit; /* modifications for z */ errno = 0; PyFPE_START_PROTECT("complex function", goto exit); _return_value = cmath_atanh_impl(module, z); PyFPE_END_PROTECT(_return_value); if (errno == EDOM) { PyErr_SetString(PyExc_ValueError, "math domain error"); goto exit; } else if (errno == ERANGE) { PyErr_SetString(PyExc_OverflowError, "math range error"); goto exit; } else { return_value = <API key>(_return_value); } exit: return return_value; } PyDoc_STRVAR(cmath_cos__doc__, "cos($module, z, /)\n" " "\n" "Return the cosine of z."); #define CMATH_COS_METHODDEF \ {"cos", (PyCFunction)cmath_cos, METH_O, cmath_cos__doc__}, static Py_complex cmath_cos_impl(PyModuleDef *module, Py_complex z); static PyObject * cmath_cos(PyModuleDef *module, PyObject *arg) { PyObject *return_value = NULL; Py_complex z; Py_complex _return_value; if (!PyArg_Parse(arg, "D:cos", &z)) goto exit; /* modifications for z */ errno = 0; PyFPE_START_PROTECT("complex function", goto exit); _return_value = cmath_cos_impl(module, z); PyFPE_END_PROTECT(_return_value); if (errno == EDOM) { PyErr_SetString(PyExc_ValueError, "math domain error"); goto exit; } else if (errno == ERANGE) { PyErr_SetString(PyExc_OverflowError, "math range error"); goto exit; } else { return_value = <API key>(_return_value); } exit: return return_value; } PyDoc_STRVAR(cmath_cosh__doc__, "cosh($module, z, /)\n" " "\n" "Return the hyperbolic cosine of z."); #define <API key> \ {"cosh", (PyCFunction)cmath_cosh, METH_O, cmath_cosh__doc__}, static Py_complex cmath_cosh_impl(PyModuleDef *module, Py_complex z); static PyObject * cmath_cosh(PyModuleDef *module, PyObject *arg) { PyObject *return_value = NULL; Py_complex z; Py_complex _return_value; if (!PyArg_Parse(arg, "D:cosh", &z)) goto exit; /* modifications for z */ errno = 0; PyFPE_START_PROTECT("complex function", goto exit); _return_value = cmath_cosh_impl(module, z); PyFPE_END_PROTECT(_return_value); if (errno == EDOM) { PyErr_SetString(PyExc_ValueError, "math domain error"); goto exit; } else if (errno == ERANGE) { PyErr_SetString(PyExc_OverflowError, "math range error"); goto exit; } else { return_value = <API key>(_return_value); } exit: return return_value; } PyDoc_STRVAR(cmath_exp__doc__, "exp($module, z, /)\n" " "\n" "Return the exponential value e**z."); #define CMATH_EXP_METHODDEF \ {"exp", (PyCFunction)cmath_exp, METH_O, cmath_exp__doc__}, static Py_complex cmath_exp_impl(PyModuleDef *module, Py_complex z); static PyObject * cmath_exp(PyModuleDef *module, PyObject *arg) { PyObject *return_value = NULL; Py_complex z; Py_complex _return_value; if (!PyArg_Parse(arg, "D:exp", &z)) goto exit; /* modifications for z */ errno = 0; PyFPE_START_PROTECT("complex function", goto exit); _return_value = cmath_exp_impl(module, z); PyFPE_END_PROTECT(_return_value); if (errno == EDOM) { PyErr_SetString(PyExc_ValueError, "math domain error"); goto exit; } else if (errno == ERANGE) { PyErr_SetString(PyExc_OverflowError, "math range error"); goto exit; } else { return_value = <API key>(_return_value); } exit: return return_value; } PyDoc_STRVAR(cmath_log10__doc__, "log10($module, z, /)\n" " "\n" "Return the base-10 logarithm of z."); #define <API key> \ {"log10", (PyCFunction)cmath_log10, METH_O, cmath_log10__doc__}, static Py_complex cmath_log10_impl(PyModuleDef *module, Py_complex z); static PyObject * cmath_log10(PyModuleDef *module, PyObject *arg) { PyObject *return_value = NULL; Py_complex z; Py_complex _return_value; if (!PyArg_Parse(arg, "D:log10", &z)) goto exit; /* modifications for z */ errno = 0; PyFPE_START_PROTECT("complex function", goto exit); _return_value = cmath_log10_impl(module, z); PyFPE_END_PROTECT(_return_value); if (errno == EDOM) { PyErr_SetString(PyExc_ValueError, "math domain error"); goto exit; } else if (errno == ERANGE) { PyErr_SetString(PyExc_OverflowError, "math range error"); goto exit; } else { return_value = <API key>(_return_value); } exit: return return_value; } PyDoc_STRVAR(cmath_sin__doc__, "sin($module, z, /)\n" " "\n" "Return the sine of z."); #define CMATH_SIN_METHODDEF \ {"sin", (PyCFunction)cmath_sin, METH_O, cmath_sin__doc__}, static Py_complex cmath_sin_impl(PyModuleDef *module, Py_complex z); static PyObject * cmath_sin(PyModuleDef *module, PyObject *arg) { PyObject *return_value = NULL; Py_complex z; Py_complex _return_value; if (!PyArg_Parse(arg, "D:sin", &z)) goto exit; /* modifications for z */ errno = 0; PyFPE_START_PROTECT("complex function", goto exit); _return_value = cmath_sin_impl(module, z); PyFPE_END_PROTECT(_return_value); if (errno == EDOM) { PyErr_SetString(PyExc_ValueError, "math domain error"); goto exit; } else if (errno == ERANGE) { PyErr_SetString(PyExc_OverflowError, "math range error"); goto exit; } else { return_value = <API key>(_return_value); } exit: return return_value; } PyDoc_STRVAR(cmath_sinh__doc__, "sinh($module, z, /)\n" " "\n" "Return the hyperbolic sine of z."); #define <API key> \ {"sinh", (PyCFunction)cmath_sinh, METH_O, cmath_sinh__doc__}, static Py_complex cmath_sinh_impl(PyModuleDef *module, Py_complex z); static PyObject * cmath_sinh(PyModuleDef *module, PyObject *arg) { PyObject *return_value = NULL; Py_complex z; Py_complex _return_value; if (!PyArg_Parse(arg, "D:sinh", &z)) goto exit; /* modifications for z */ errno = 0; PyFPE_START_PROTECT("complex function", goto exit); _return_value = cmath_sinh_impl(module, z); PyFPE_END_PROTECT(_return_value); if (errno == EDOM) { PyErr_SetString(PyExc_ValueError, "math domain error"); goto exit; } else if (errno == ERANGE) { PyErr_SetString(PyExc_OverflowError, "math range error"); goto exit; } else { return_value = <API key>(_return_value); } exit: return return_value; } PyDoc_STRVAR(cmath_sqrt__doc__, "sqrt($module, z, /)\n" " "\n" "Return the square root of z."); #define <API key> \ {"sqrt", (PyCFunction)cmath_sqrt, METH_O, cmath_sqrt__doc__}, static Py_complex cmath_sqrt_impl(PyModuleDef *module, Py_complex z); static PyObject * cmath_sqrt(PyModuleDef *module, PyObject *arg) { PyObject *return_value = NULL; Py_complex z; Py_complex _return_value; if (!PyArg_Parse(arg, "D:sqrt", &z)) goto exit; /* modifications for z */ errno = 0; PyFPE_START_PROTECT("complex function", goto exit); _return_value = cmath_sqrt_impl(module, z); PyFPE_END_PROTECT(_return_value); if (errno == EDOM) { PyErr_SetString(PyExc_ValueError, "math domain error"); goto exit; } else if (errno == ERANGE) { PyErr_SetString(PyExc_OverflowError, "math range error"); goto exit; } else { return_value = <API key>(_return_value); } exit: return return_value; } PyDoc_STRVAR(cmath_tan__doc__, "tan($module, z, /)\n" " "\n" "Return the tangent of z."); #define CMATH_TAN_METHODDEF \ {"tan", (PyCFunction)cmath_tan, METH_O, cmath_tan__doc__}, static Py_complex cmath_tan_impl(PyModuleDef *module, Py_complex z); static PyObject * cmath_tan(PyModuleDef *module, PyObject *arg) { PyObject *return_value = NULL; Py_complex z; Py_complex _return_value; if (!PyArg_Parse(arg, "D:tan", &z)) goto exit; /* modifications for z */ errno = 0; PyFPE_START_PROTECT("complex function", goto exit); _return_value = cmath_tan_impl(module, z); PyFPE_END_PROTECT(_return_value); if (errno == EDOM) { PyErr_SetString(PyExc_ValueError, "math domain error"); goto exit; } else if (errno == ERANGE) { PyErr_SetString(PyExc_OverflowError, "math range error"); goto exit; } else { return_value = <API key>(_return_value); } exit: return return_value; } PyDoc_STRVAR(cmath_tanh__doc__, "tanh($module, z, /)\n" " "\n" "Return the hyperbolic tangent of z."); #define <API key> \ {"tanh", (PyCFunction)cmath_tanh, METH_O, cmath_tanh__doc__}, static Py_complex cmath_tanh_impl(PyModuleDef *module, Py_complex z); static PyObject * cmath_tanh(PyModuleDef *module, PyObject *arg) { PyObject *return_value = NULL; Py_complex z; Py_complex _return_value; if (!PyArg_Parse(arg, "D:tanh", &z)) goto exit; /* modifications for z */ errno = 0; PyFPE_START_PROTECT("complex function", goto exit); _return_value = cmath_tanh_impl(module, z); PyFPE_END_PROTECT(_return_value); if (errno == EDOM) { PyErr_SetString(PyExc_ValueError, "math domain error"); goto exit; } else if (errno == ERANGE) { PyErr_SetString(PyExc_OverflowError, "math range error"); goto exit; } else { return_value = <API key>(_return_value); } exit: return return_value; } PyDoc_STRVAR(cmath_log__doc__, "log($module, x, y_obj=None, /)\n" " "\n" "The logarithm of z to the given base.\n" "\n" "If the base not specified, returns the natural logarithm (base e) of z."); #define CMATH_LOG_METHODDEF \ {"log", (PyCFunction)cmath_log, METH_VARARGS, cmath_log__doc__}, static PyObject * cmath_log_impl(PyModuleDef *module, Py_complex x, PyObject *y_obj); static PyObject * cmath_log(PyModuleDef *module, PyObject *args) { PyObject *return_value = NULL; Py_complex x; PyObject *y_obj = NULL; if (!PyArg_ParseTuple(args, "D|O:log", &x, &y_obj)) goto exit; return_value = cmath_log_impl(module, x, y_obj); exit: return return_value; } PyDoc_STRVAR(cmath_phase__doc__, "phase($module, z, /)\n" " "\n" "Return argument, also known as the phase angle, of a complex."); #define <API key> \ {"phase", (PyCFunction)cmath_phase, METH_O, cmath_phase__doc__}, static PyObject * cmath_phase_impl(PyModuleDef *module, Py_complex z); static PyObject * cmath_phase(PyModuleDef *module, PyObject *arg) { PyObject *return_value = NULL; Py_complex z; if (!PyArg_Parse(arg, "D:phase", &z)) goto exit; return_value = cmath_phase_impl(module, z); exit: return return_value; } PyDoc_STRVAR(cmath_polar__doc__, "polar($module, z, /)\n" " "\n" "Convert a complex from rectangular coordinates to polar coordinates.\n" "\n" "r is the distance from 0 and phi the phase angle."); #define <API key> \ {"polar", (PyCFunction)cmath_polar, METH_O, cmath_polar__doc__}, static PyObject * cmath_polar_impl(PyModuleDef *module, Py_complex z); static PyObject * cmath_polar(PyModuleDef *module, PyObject *arg) { PyObject *return_value = NULL; Py_complex z; if (!PyArg_Parse(arg, "D:polar", &z)) goto exit; return_value = cmath_polar_impl(module, z); exit: return return_value; } PyDoc_STRVAR(cmath_rect__doc__, "rect($module, r, phi, /)\n" " "\n" "Convert from polar coordinates to rectangular coordinates."); #define <API key> \ {"rect", (PyCFunction)cmath_rect, METH_VARARGS, cmath_rect__doc__}, static PyObject * cmath_rect_impl(PyModuleDef *module, double r, double phi); static PyObject * cmath_rect(PyModuleDef *module, PyObject *args) { PyObject *return_value = NULL; double r; double phi; if (!PyArg_ParseTuple(args, "dd:rect", &r, &phi)) goto exit; return_value = cmath_rect_impl(module, r, phi); exit: return return_value; } PyDoc_STRVAR(<API key>, "isfinite($module, z, /)\n" " "\n" "Return True if both the real and imaginary parts of z are finite, else False."); #define <API key> \ {"isfinite", (PyCFunction)cmath_isfinite, METH_O, <API key>}, static PyObject * cmath_isfinite_impl(PyModuleDef *module, Py_complex z); static PyObject * cmath_isfinite(PyModuleDef *module, PyObject *arg) { PyObject *return_value = NULL; Py_complex z; if (!PyArg_Parse(arg, "D:isfinite", &z)) goto exit; return_value = cmath_isfinite_impl(module, z); exit: return return_value; } PyDoc_STRVAR(cmath_isnan__doc__, "isnan($module, z, /)\n" " "\n" "Checks if the real or imaginary part of z not a number (NaN)."); #define <API key> \ {"isnan", (PyCFunction)cmath_isnan, METH_O, cmath_isnan__doc__}, static PyObject * cmath_isnan_impl(PyModuleDef *module, Py_complex z); static PyObject * cmath_isnan(PyModuleDef *module, PyObject *arg) { PyObject *return_value = NULL; Py_complex z; if (!PyArg_Parse(arg, "D:isnan", &z)) goto exit; return_value = cmath_isnan_impl(module, z); exit: return return_value; } PyDoc_STRVAR(cmath_isinf__doc__, "isinf($module, z, /)\n" " "\n" "Checks if the real or imaginary part of z is infinite."); #define <API key> \ {"isinf", (PyCFunction)cmath_isinf, METH_O, cmath_isinf__doc__}, static PyObject * cmath_isinf_impl(PyModuleDef *module, Py_complex z); static PyObject * cmath_isinf(PyModuleDef *module, PyObject *arg) { PyObject *return_value = NULL; Py_complex z; if (!PyArg_Parse(arg, "D:isinf", &z)) goto exit; return_value = cmath_isinf_impl(module, z); exit: return return_value; } PyDoc_STRVAR(<API key>, "isclose($module, /, a, b, *, rel_tol=1e-09, abs_tol=0.0)\n" " "\n" "Determine whether two complex numbers are close in value.\n" "\n" " rel_tol\n" " maximum difference for being considered \"close\", relative to the\n" " magnitude of the input values\n" " abs_tol\n" " maximum difference for being considered \"close\", regardless of the\n" " magnitude of the input values\n" "\n" "Return True if a is close in value to b, and False otherwise.\n" "\n" "For the values to be considered close, the difference between them must be\n" "smaller than at least one of the tolerances.\n" "\n" "-inf, inf and NaN behave similarly to the IEEE 754 Standard. That is, NaN is\n" "not close to anything, even itself. inf and -inf are only close to themselves."); #define <API key> \ {"isclose", (PyCFunction)cmath_isclose, METH_VARARGS|METH_KEYWORDS, <API key>}, static int cmath_isclose_impl(PyModuleDef *module, Py_complex a, Py_complex b, double rel_tol, double abs_tol); static PyObject * cmath_isclose(PyModuleDef *module, PyObject *args, PyObject *kwargs) { PyObject *return_value = NULL; static char *_keywords[] = {"a", "b", "rel_tol", "abs_tol", NULL}; Py_complex a; Py_complex b; double rel_tol = 1e-09; double abs_tol = 0.0; int _return_value; if (!<API key>(args, kwargs, "DD|$dd:isclose", _keywords, &a, &b, &rel_tol, &abs_tol)) goto exit; _return_value = cmath_isclose_impl(module, a, b, rel_tol, abs_tol); if ((_return_value == -1) && PyErr_Occurred()) goto exit; return_value = PyBool_FromLong((long)_return_value); exit: return return_value; } /*[clinic end generated code: output=229e9c48c9d27362 input=a9049054013a1b77]*/
#ifndef <API key> #define <API key> #if (defined(__ASSEMBLY__) || defined(__IAR_SYSTEMS_ASM__)) #define REG_ICM_CFG (0x40048000U) /**< \brief (ICM) Configuration Register */ #define REG_ICM_CTRL (0x40048004U) /**< \brief (ICM) Control Register */ #define REG_ICM_SR (0x40048008U) /**< \brief (ICM) Status Register */ #define REG_ICM_IER (0x40048010U) /**< \brief (ICM) Interrupt Enable Register */ #define REG_ICM_IDR (0x40048014U) /**< \brief (ICM) Interrupt Disable Register */ #define REG_ICM_IMR (0x40048018U) /**< \brief (ICM) Interrupt Mask Register */ #define REG_ICM_ISR (0x4004801CU) /**< \brief (ICM) Interrupt Status Register */ #define REG_ICM_UASR (0x40048020U) /**< \brief (ICM) Undefined Access Status Register */ #define REG_ICM_DSCR (0x40048030U) /**< \brief (ICM) Region Descriptor Area Start Address Register */ #define REG_ICM_HASH (0x40048034U) /**< \brief (ICM) Region Hash Area Start Address Register */ #define REG_ICM_UIHVAL (0x40048038U) /**< \brief (ICM) User Initial Hash Value 0 Register */ #else #define REG_ICM_CFG (*(__IO uint32_t*)0x40048000U) /**< \brief (ICM) Configuration Register */ #define REG_ICM_CTRL (*(__O uint32_t*)0x40048004U) /**< \brief (ICM) Control Register */ #define REG_ICM_SR (*(__O uint32_t*)0x40048008U) /**< \brief (ICM) Status Register */ #define REG_ICM_IER (*(__O uint32_t*)0x40048010U) /**< \brief (ICM) Interrupt Enable Register */ #define REG_ICM_IDR (*(__O uint32_t*)0x40048014U) /**< \brief (ICM) Interrupt Disable Register */ #define REG_ICM_IMR (*(__I uint32_t*)0x40048018U) /**< \brief (ICM) Interrupt Mask Register */ #define REG_ICM_ISR (*(__I uint32_t*)0x4004801CU) /**< \brief (ICM) Interrupt Status Register */ #define REG_ICM_UASR (*(__I uint32_t*)0x40048020U) /**< \brief (ICM) Undefined Access Status Register */ #define REG_ICM_DSCR (*(__IO uint32_t*)0x40048030U) /**< \brief (ICM) Region Descriptor Area Start Address Register */ #define REG_ICM_HASH (*(__IO uint32_t*)0x40048034U) /**< \brief (ICM) Region Hash Area Start Address Register */ #define REG_ICM_UIHVAL (*(__O uint32_t*)0x40048038U) /**< \brief (ICM) User Initial Hash Value 0 Register */ #endif /* (defined(__ASSEMBLY__) || defined(__IAR_SYSTEMS_ASM__)) */ #endif /* <API key> */
#ifndef <API key> #define <API key> namespace switches { // These constants are duplicated from chrome/common/chrome_switches.cc // in order to avoid dependency problems. // TODO(abodenha@chromium.org) Reunify them in some sensible manner. // Location of Chrome user profile. Optional. extern const char <API key>[]; // Used with kCloudPrintFile. Tells Chrome to delete the file when // finished displaying the print dialog. extern const char <API key>[]; // Tells chrome to display the cloud print dialog and upload the // specified file for printing. extern const char kCloudPrintFile[]; // Used with kCloudPrintFile to specify a title for the resulting print // job. extern const char kCloudPrintJobTitle[]; // Specifies the mime type to be used when uploading data from the // file referenced by cloud-print-file. // Defaults to "application/pdf" if unspecified. extern const char kCloudPrintFileType[]; // Used with kCloudPrintFile to specify a JSON print ticket for the resulting // print job. // Defaults to null if unspecified. extern const char <API key>[]; } // namespace switches #endif // <API key>
// modification, are permitted provided that the following conditions // are met: // and/or other materials provided with the distribution. // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // 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. #if !NET_CF && !MONO namespace NLog.LayoutRenderers { using System; using System.ComponentModel; using System.Globalization; using System.Text; <summary> The information about the garbage collector. </summary> [LayoutRenderer("gc")] public class <API key> : LayoutRenderer { <summary> Initializes a new instance of the <see cref="<API key>" /> class. </summary> public <API key>() { this.Property = <API key>.TotalMemory; } <summary> Gets or sets the property to retrieve. </summary> <docgen category='Rendering Options' order='10' /> [DefaultValue("TotalMemory")] public <API key> Property { get; set; } <summary> Renders the selected process information. </summary> <param name="builder">The <see cref="StringBuilder"/> to append the rendered data to.</param> <param name="logEvent">Logging event.</param> protected override void Append(StringBuilder builder, LogEventInfo logEvent) { object value = null; switch (this.Property) { case <API key>.TotalMemory: value = GC.GetTotalMemory(false); break; case <API key>.<API key>: value = GC.GetTotalMemory(true); break; #if !SILVERLIGHT case <API key>.CollectionCount0: value = GC.CollectionCount(0); break; case <API key>.CollectionCount1: value = GC.CollectionCount(1); break; case <API key>.CollectionCount2: value = GC.CollectionCount(2); break; #endif case <API key>.MaxGeneration: value = GC.MaxGeneration; break; } builder.Append(Convert.ToString(value, CultureInfo.InvariantCulture)); } } } #endif
# What is Apache Storm? Apache Storm is a distributed computation framework written predominantly in the Clojure programming language. Originally created by Nathan Marz and team at BackType, the project was open sourced after being acquired by Twitter. It uses custom created "spouts" and "bolts" to define information sources and manipulations to allow batch, distributed processing of streaming data. The initial release was on 17 September 2011. > [wikipedia.org/wiki/Storm_(event_processor)](https://en.wikipedia.org/wiki/Storm_(event_processor)) %%LOGO%% # How to use this image ## Running topologies in local mode Assuming you have `topology.jar` in the current directory. console $ docker run -it -v $(pwd)/topology.jar:/topology.jar %%IMAGE%% storm jar /topology.jar org.apache.storm.starter.ExclamationTopology ## Setting up a minimal Storm cluster 1. [Apache Zookeeper](https://zookeeper.apache.org/) is a must for running a Storm cluster. Start it first. Since the Zookeeper "fails fast" it's better to always restart it. console $ docker run -d --restart always --name some-zookeeper zookeeper 2. The Nimbus daemon has to be connected with the Zookeeper. It's also a "fail fast" system. console $ docker run -d --restart always --name some-nimbus --link some-zookeeper:zookeeper %%IMAGE%% storm nimbus 3. Finally start a single Supervisor node. It will talk to the Nimbus and Zookeeper. console $ docker run -d --restart always --name supervisor --link some-zookeeper:zookeeper --link some-nimbus:nimbus %%IMAGE%% storm supervisor 4. Now you can submit a topology to our cluster. console $ docker run --link some-nimbus:nimbus -it --rm -v $(pwd)/topology.jar:/topology.jar %%IMAGE%% storm jar /topology.jar org.apache.storm.starter.WordCountTopology topology 5. Optionally, you can start the Storm UI. console $ docker run -d -p 8080:8080 --restart always --name ui --link some-nimbus:nimbus %%IMAGE%% storm ui ## %%STACK%% Run `docker stack deploy -c stack.yml storm` (or `docker-compose -f stack.yml up`) and wait for it to initialize completely. The Nimbus will be available at `http: ## Configuration This image uses [default configuration](https://github.com/apache/storm/blob/v1.1.0/conf/defaults.yaml) of the Apache Storm. There are two main ways to change it. 1. Using command line arguments. console $ docker run -d --restart always --name nimbus %%IMAGE%% storm nimbus -c storm.zookeeper.servers='["zookeeper"]' 2. Assuming you have `storm.yaml` in the current directory you can mount it as a volume. console $ docker run -it -v $(pwd)/storm.yaml:/conf/storm.yaml %%IMAGE%% storm nimbus ## Logging This image uses [default logging configuration](https://github.com/apache/storm/tree/v1.1.0/log4j2). All logs go to the `/logs` directory by default. ## Data persistence No data are persisted by default. For convenience there are `/data` and `/logs` directories in the image owned by `storm` user. Use them accordingly to persist data and logs using volumes. console $ docker run -it -v /logs -v /data %%IMAGE%% storm nimbus *Please be noticed that using paths other than those predefined is likely to cause permission denied errors. It's because for [security reasons](https://docs.docker.com/engine/userguide/eng-image/<API key>/#user) the Storm is running under the non-root `storm` user.*
var util = require("util"); var choreography = require("temboo/core/choreography"); /* Account Retrieves the account information for the user associated with the given authorized access token. */ var Account = function(session) { /* Create a new instance of the Account Choreo. A TembooSession object, containing a valid set of Temboo credentials, must be supplied. */ var location = "/Library/Dwolla/Users/Account" Account.super_.call(this, session, location); /* Define a callback that will be used to appropriately format the results of this Choreo. */ var newResultSet = function(resultStream) { return new AccountResultSet(resultStream); } /* Obtain a new InputSet object, used to specify the input values for an execution of this Choreo. */ this.newInputSet = function() { return new AccountInputSet(); } /* Execute this Choreo with the specified inputs, calling the specified callback upon success, and the specified errorCallback upon error. */ this.execute = function(inputs, callback, errorCallback) { this._execute(inputs, newResultSet, callback, errorCallback); } } /* An InputSet with methods appropriate for specifying the inputs to the Account Choreo. The InputSet object is used to specify input parameters when executing this Choreo. */ var AccountInputSet = function() { AccountInputSet.super_.call(this); /* Set the value of the AccessToken input for this Choreo. ((required, string) A valid OAuth token.) */ this.set_AccessToken = function(value) { this.setInput("AccessToken", value); } } /* A ResultSet with methods tailored to the values returned by the Account Choreo. The ResultSet object is used to retrieve the results of a Choreo execution. */ var AccountResultSet = function(resultStream) { AccountResultSet.super_.call(this, resultStream); /* Retrieve the value for the "Response" output from this Choreo execution. ((json) The response from Dwolla.) */ this.get_Response = function() { return this.getResult("Response"); } } util.inherits(Account, choreography.Choreography); util.inherits(AccountInputSet, choreography.InputSet); util.inherits(AccountResultSet, choreography.ResultSet); exports.Account = Account; /* Basic Retrieves the Dwolla account information for the user associated with the specified consumer credentials and Dwolla account identifier. */ var Basic = function(session) { /* Create a new instance of the Basic Choreo. A TembooSession object, containing a valid set of Temboo credentials, must be supplied. */ var location = "/Library/Dwolla/Users/Basic" Basic.super_.call(this, session, location); /* Define a callback that will be used to appropriately format the results of this Choreo. */ var newResultSet = function(resultStream) { return new BasicResultSet(resultStream); } /* Obtain a new InputSet object, used to specify the input values for an execution of this Choreo. */ this.newInputSet = function() { return new BasicInputSet(); } /* Execute this Choreo with the specified inputs, calling the specified callback upon success, and the specified errorCallback upon error. */ this.execute = function(inputs, callback, errorCallback) { this._execute(inputs, newResultSet, callback, errorCallback); } } /* An InputSet with methods appropriate for specifying the inputs to the Basic Choreo. The InputSet object is used to specify input parameters when executing this Choreo. */ var BasicInputSet = function() { BasicInputSet.super_.call(this); /* Set the value of the AccountIdentifier input for this Choreo. ((required, string) Dwolla account identifier or email address of the Dwolla account.) */ this.<API key> = function(value) { this.setInput("AccountIdentifier", value); } /* Set the value of the ClientID input for this Choreo. ((required, string) The Client ID provided by Dwolla (AKA the Consumer Key).) */ this.set_ClientID = function(value) { this.setInput("ClientID", value); } /* Set the value of the ClientSecret input for this Choreo. ((required, string) The Client Secret provided by Dwolla (AKA the Consumer Secret).) */ this.set_ClientSecret = function(value) { this.setInput("ClientSecret", value); } } /* A ResultSet with methods tailored to the values returned by the Basic Choreo. The ResultSet object is used to retrieve the results of a Choreo execution. */ var BasicResultSet = function(resultStream) { BasicResultSet.super_.call(this, resultStream); /* Retrieve the value for the "Response" output from this Choreo execution. ((json) The response from Dwolla.) */ this.get_Response = function() { return this.getResult("Response"); } } util.inherits(Basic, choreography.Choreography); util.inherits(BasicInputSet, choreography.InputSet); util.inherits(BasicResultSet, choreography.ResultSet); exports.Basic = Basic;
<?php namespace Iverberk\Larasearch; use Illuminate\Support\Facades\App; use Illuminate\Support\Facades\Facade; use Illuminate\Support\Facades\Config; use Mockery as m; use AspectMock\Test as am; class IndexTest extends \<API key> { protected function tearDown() { m::close(); am::clean(); } /** * @test */ public function it_should_import() { /** * * Set * * @var \Mockery\Mock $index */ list($index) = $this->getMocks(); $test = $this; /** * * Expectation * */ /* @var \Mockery\Mock $model */ $model = m::mock('Illuminate\Database\Eloquent\Model')->makePartial(); $model->shouldReceive('with->skip->take->get') ->twice() ->andReturn([ $model, $model, $model ], []); $model->shouldReceive('getEsId') ->times(3) ->andReturn(1); $model->shouldReceive('transform') ->times(3) ->andReturn(['mock', 'data']); $index->shouldReceive('bulk') ->andReturn(); /** * * Assertion * */ $index->import($model, [], 750, function ($batch) use ($test) { $test->assertEquals(1, $batch); }); } /** * @test */ public function it_should_set_name() { /** * * Set * * @var \Mockery\Mock $index */ list($index) = $this->getMocks('bar_'); /** * * Assertion * */ $this->assertEquals($index, $index->setName('Mock')); $this->assertEquals('bar_mock', $index->getName()); } /** * @test */ public function <API key>() { /** * * Set * * @var \Mockery\Mock $index */ list($index) = $this->getMocks('baz_'); /** * Assertions */ $this->assertEquals($index, $index->setName('baz_MockMe')); $this->assertEquals('baz_mockme', $index->getName()); } /** * @test */ public function it_should_get_name() { /** * * Set * * @var \Mockery\Mock $index */ list($index) = $this->getMocks(); /** * * Assertion * */ $this->assertEquals('husband', $index->getName()); } /** * @test */ public function <API key>() { /** * * Set * * @var \Mockery\Mock $index * @var \Mockery\Mock $proxy * @var \Mockery\Mock $client */ list($index, $proxy, $client) = $this->getMocks(); $test = $this; /** * * Expectation * */ Config::shouldReceive('get') ->with('larasearch.elasticsearch.analyzers') ->andReturn([ 'autocomplete', 'suggest', 'text_start', 'text_middle', 'text_end', 'word_start', 'word_middle', 'word_end' ]); Config::shouldReceive('get') ->with('larasearch.elasticsearch.defaults.index') ->andReturn([ 'settings' => [ 'number_of_shards' => 1, 'number_of_replicas' => 0, 'analysis' => [ 'analyzer' => [ 'larasearch_keyword' => [ 'type' => "custom", 'tokenizer' => "keyword", 'filter' => ["lowercase", "larasearch_stemmer"] ], 'default_index' => [ 'type' => "custom", 'tokenizer' => "standard", 'filter' => ["standard", "lowercase", "asciifolding", "<API key>", "larasearch_stemmer"] ], 'larasearch_search' => [ 'type' => "custom", 'tokenizer' => "standard", 'filter' => ["standard", "lowercase", "asciifolding", "<API key>", "larasearch_stemmer"] ], 'larasearch_search2' => [ 'type' => "custom", 'tokenizer' => "standard", 'filter' => ["standard", "lowercase", "asciifolding", "larasearch_stemmer"] ], '<API key>' => [ 'type' => "custom", 'tokenizer' => "<API key>", 'filter' => ["lowercase", "asciifolding"] ], '<API key>' => [ 'type' => "custom", 'tokenizer' => "keyword", 'filter' => ["lowercase", "asciifolding"] ], '<API key>' => [ 'type' => "custom", 'tokenizer' => "standard", 'filter' => ["lowercase", "asciifolding"] ], '<API key>' => [ 'type' => "custom", 'tokenizer' => "standard", 'filter' => ["lowercase", "asciifolding", "<API key>"] ], '<API key>' => [ 'type' => "custom", 'tokenizer' => "keyword", 'filter' => ["lowercase", "asciifolding", "<API key>"] ], '<API key>' => [ 'type' => "custom", 'tokenizer' => "keyword", 'filter' => ["lowercase", "asciifolding", "larasearch_ngram"] ], '<API key>' => [ 'type' => "custom", 'tokenizer' => "keyword", 'filter' => ["lowercase", "asciifolding", "reverse", "<API key>", "reverse"] ], '<API key>' => [ 'type' => "custom", 'tokenizer' => "standard", 'filter' => ["lowercase", "asciifolding", "<API key>"] ], '<API key>' => [ 'type' => "custom", 'tokenizer' => "standard", 'filter' => ["lowercase", "asciifolding", "larasearch_ngram"] ], '<API key>' => [ 'type' => "custom", 'tokenizer' => "standard", 'filter' => ["lowercase", "asciifolding", "reverse", "<API key>", "reverse"] ] ], 'filter' => [ '<API key>' => [ 'type' => "shingle", 'token_separator' => "" ], '<API key>' => [ 'type' => "shingle", 'token_separator' => "", 'output_unigrams' => false, '<API key>' => true ], '<API key>' => [ 'type' => "shingle", 'max_shingle_size' => 5 ], '<API key>' => [ 'type' => "edgeNGram", 'min_gram' => 1, 'max_gram' => 50 ], 'larasearch_ngram' => [ 'type' => "nGram", 'min_gram' => 1, 'max_gram' => 50 ], 'larasearch_stemmer' => [ 'type' => "snowball", 'language' => "English" ] ], 'tokenizer' => [ '<API key>' => [ 'type' => "edgeNGram", 'min_gram' => 1, 'max_gram' => 50 ] ] ] ]]); $client->shouldReceive('indices->create') ->andReturnUsing(function ($params) use ($test) { $test->assertEquals(json_decode( '{ "index": "husband", "body": { "settings": { "number_of_shards": 1, "number_of_replicas": 0, "analysis": { "analyzer": { "larasearch_keyword": { "type": "custom", "tokenizer": "keyword", "filter": [ "lowercase", "larasearch_stemmer" ] }, "default_index": { "type": "custom", "tokenizer": "standard", "filter": [ "standard", "lowercase", "asciifolding", "<API key>", "larasearch_stemmer" ] }, "larasearch_search": { "type": "custom", "tokenizer": "standard", "filter": [ "standard", "lowercase", "asciifolding", "<API key>", "larasearch_stemmer" ] }, "larasearch_search2": { "type": "custom", "tokenizer": "standard", "filter": [ "standard", "lowercase", "asciifolding", "larasearch_stemmer" ] }, "<API key>": { "type": "custom", "tokenizer": "<API key>", "filter": [ "lowercase", "asciifolding" ] }, "<API key>": { "type": "custom", "tokenizer": "keyword", "filter": [ "lowercase", "asciifolding" ] }, "<API key>": { "type": "custom", "tokenizer": "standard", "filter": [ "lowercase", "asciifolding" ] }, "<API key>": { "type": "custom", "tokenizer": "standard", "filter": [ "lowercase", "asciifolding", "<API key>" ] }, "<API key>": { "type": "custom", "tokenizer": "keyword", "filter": [ "lowercase", "asciifolding", "<API key>" ] }, "<API key>": { "type": "custom", "tokenizer": "keyword", "filter": [ "lowercase", "asciifolding", "larasearch_ngram" ] }, "<API key>": { "type": "custom", "tokenizer": "keyword", "filter": [ "lowercase", "asciifolding", "reverse", "<API key>", "reverse" ] }, "<API key>": { "type": "custom", "tokenizer": "standard", "filter": [ "lowercase", "asciifolding", "<API key>" ] }, "<API key>": { "type": "custom", "tokenizer": "standard", "filter": [ "lowercase", "asciifolding", "larasearch_ngram" ] }, "<API key>": { "type": "custom", "tokenizer": "standard", "filter": [ "lowercase", "asciifolding", "reverse", "<API key>", "reverse" ] } }, "filter": { "<API key>": { "type": "shingle", "token_separator": "" }, "<API key>": { "type": "shingle", "token_separator": "", "output_unigrams": false, "<API key>": true }, "<API key>": { "type": "shingle", "max_shingle_size": 5 }, "<API key>": { "type": "edgeNGram", "min_gram": 1, "max_gram": 50 }, "larasearch_ngram": { "type": "nGram", "min_gram": 1, "max_gram": 50 }, "larasearch_stemmer": { "type": "snowball", "language": "English" } }, "tokenizer": { "<API key>": { "type": "edgeNGram", "min_gram": 1, "max_gram": 50 } } } }, "mappings": { "_default_": { "properties": { "name": { "type": "multi_field", "fields": { "name": { "type": "string", "index": "not_analyzed" }, "analyzed": { "type": "string", "index": "analyzed" }, "autocomplete": { "type": "string", "index": "analyzed", "analyzer": "<API key>" }, "suggest": { "type": "string", "index": "analyzed", "analyzer": "<API key>" }, "text_start": { "type": "string", "index": "analyzed", "analyzer": "<API key>" }, "text_middle": { "type": "string", "index": "analyzed", "analyzer": "<API key>" }, "text_end": { "type": "string", "index": "analyzed", "analyzer": "<API key>" }, "word_start": { "type": "string", "index": "analyzed", "analyzer": "<API key>" }, "word_middle": { "type": "string", "index": "analyzed", "analyzer": "<API key>" }, "word_end": { "type": "string", "index": "analyzed", "analyzer": "<API key>" } } }, "wife": { "type": "object", "properties": { "name": { "type": "multi_field", "fields": { "name": { "type": "string", "index": "not_analyzed" }, "analyzed": { "type": "string", "index": "analyzed" }, "autocomplete": { "type": "string", "index": "analyzed", "analyzer": "<API key>" } } }, "children": { "type": "object", "properties": { "name": { "type": "multi_field", "fields": { "name": { "type": "string", "index": "not_analyzed" }, "analyzed": { "type": "string", "index": "analyzed" }, "text_start": { "type": "string", "index": "analyzed", "analyzer": "<API key>" }, "text_middle": { "type": "string", "index": "analyzed", "analyzer": "<API key>" }, "text_end": { "type": "string", "index": "analyzed", "analyzer": "<API key>" }, "word_start": { "type": "string", "index": "analyzed", "analyzer": "<API key>" }, "word_middle": { "type": "string", "index": "analyzed", "analyzer": "<API key>" }, "word_end": { "type": "string", "index": "analyzed", "analyzer": "<API key>" } } } } } } } } } }, "index": "husband", "type": "Husband" } }', true) , $params); }); $proxy->shouldReceive('getType')->andReturn('Husband'); $proxy->shouldReceive('getConfig')->andReturn([ 'autocomplete' => ['name', 'wife.name'], 'suggest' => ['name'], 'text_start' => ['name', 'wife.children.name'], 'text_middle' => ['name', 'wife.children.name'], 'text_end' => ['name', 'wife.children.name'], 'word_start' => ['name', 'wife.children.name'], 'word_middle' => ['name', 'wife.children.name'], 'word_end' => ['name', 'wife.children.name'] ]); /** * * Assertion * */ $index->create(); } /** * @test */ public function <API key>() { /** * * Set * * @var \Mockery\Mock $index * @var \Mockery\Mock $proxy * @var \Mockery\Mock $client */ list($index, $proxy, $client) = $this->getMocks('bar_'); $test = $this; /** * * Expectation * */ Config::shouldReceive('get') ->with('larasearch.elasticsearch.analyzers') ->andReturn([ 'autocomplete', 'suggest', 'text_start', 'text_middle', 'text_end', 'word_start', 'word_middle', 'word_end' ]); Config::shouldReceive('get') ->with('larasearch.elasticsearch.defaults.index') ->andReturn([ 'settings' => [ 'number_of_shards' => 1, 'number_of_replicas' => 0, 'analysis' => [ 'analyzer' => [ 'larasearch_keyword' => [ 'type' => "custom", 'tokenizer' => "keyword", 'filter' => ["lowercase", "larasearch_stemmer"] ], 'default_index' => [ 'type' => "custom", 'tokenizer' => "standard", 'filter' => ["standard", "lowercase", "asciifolding", "<API key>", "larasearch_stemmer"] ], 'larasearch_search' => [ 'type' => "custom", 'tokenizer' => "standard", 'filter' => ["standard", "lowercase", "asciifolding", "<API key>", "larasearch_stemmer"] ], 'larasearch_search2' => [ 'type' => "custom", 'tokenizer' => "standard", 'filter' => ["standard", "lowercase", "asciifolding", "larasearch_stemmer"] ], '<API key>' => [ 'type' => "custom", 'tokenizer' => "<API key>", 'filter' => ["lowercase", "asciifolding"] ], '<API key>' => [ 'type' => "custom", 'tokenizer' => "keyword", 'filter' => ["lowercase", "asciifolding"] ], '<API key>' => [ 'type' => "custom", 'tokenizer' => "standard", 'filter' => ["lowercase", "asciifolding"] ], '<API key>' => [ 'type' => "custom", 'tokenizer' => "standard", 'filter' => ["lowercase", "asciifolding", "<API key>"] ], '<API key>' => [ 'type' => "custom", 'tokenizer' => "keyword", 'filter' => ["lowercase", "asciifolding", "<API key>"] ], '<API key>' => [ 'type' => "custom", 'tokenizer' => "keyword", 'filter' => ["lowercase", "asciifolding", "larasearch_ngram"] ], '<API key>' => [ 'type' => "custom", 'tokenizer' => "keyword", 'filter' => ["lowercase", "asciifolding", "reverse", "<API key>", "reverse"] ], '<API key>' => [ 'type' => "custom", 'tokenizer' => "standard", 'filter' => ["lowercase", "asciifolding", "<API key>"] ], '<API key>' => [ 'type' => "custom", 'tokenizer' => "standard", 'filter' => ["lowercase", "asciifolding", "larasearch_ngram"] ], '<API key>' => [ 'type' => "custom", 'tokenizer' => "standard", 'filter' => ["lowercase", "asciifolding", "reverse", "<API key>", "reverse"] ] ], 'filter' => [ '<API key>' => [ 'type' => "shingle", 'token_separator' => "" ], '<API key>' => [ 'type' => "shingle", 'token_separator' => "", 'output_unigrams' => false, '<API key>' => true ], '<API key>' => [ 'type' => "shingle", 'max_shingle_size' => 5 ], '<API key>' => [ 'type' => "edgeNGram", 'min_gram' => 1, 'max_gram' => 50 ], 'larasearch_ngram' => [ 'type' => "nGram", 'min_gram' => 1, 'max_gram' => 50 ], 'larasearch_stemmer' => [ 'type' => "snowball", 'language' => "English" ] ], 'tokenizer' => [ '<API key>' => [ 'type' => "edgeNGram", 'min_gram' => 1, 'max_gram' => 50 ] ] ] ]]); $client->shouldReceive('indices->create') ->andReturnUsing(function ($params) use ($test) { $test->assertEquals(json_decode( '{ "index": "bar_husband", "body": { "settings": { "number_of_shards": 1, "number_of_replicas": 0, "analysis": { "analyzer": { "larasearch_keyword": { "type": "custom", "tokenizer": "keyword", "filter": [ "lowercase", "larasearch_stemmer" ] }, "default_index": { "type": "custom", "tokenizer": "standard", "filter": [ "standard", "lowercase", "asciifolding", "<API key>", "larasearch_stemmer" ] }, "larasearch_search": { "type": "custom", "tokenizer": "standard", "filter": [ "standard", "lowercase", "asciifolding", "<API key>", "larasearch_stemmer" ] }, "larasearch_search2": { "type": "custom", "tokenizer": "standard", "filter": [ "standard", "lowercase", "asciifolding", "larasearch_stemmer" ] }, "<API key>": { "type": "custom", "tokenizer": "<API key>", "filter": [ "lowercase", "asciifolding" ] }, "<API key>": { "type": "custom", "tokenizer": "keyword", "filter": [ "lowercase", "asciifolding" ] }, "<API key>": { "type": "custom", "tokenizer": "standard", "filter": [ "lowercase", "asciifolding" ] }, "<API key>": { "type": "custom", "tokenizer": "standard", "filter": [ "lowercase", "asciifolding", "<API key>" ] }, "<API key>": { "type": "custom", "tokenizer": "keyword", "filter": [ "lowercase", "asciifolding", "<API key>" ] }, "<API key>": { "type": "custom", "tokenizer": "keyword", "filter": [ "lowercase", "asciifolding", "larasearch_ngram" ] }, "<API key>": { "type": "custom", "tokenizer": "keyword", "filter": [ "lowercase", "asciifolding", "reverse", "<API key>", "reverse" ] }, "<API key>": { "type": "custom", "tokenizer": "standard", "filter": [ "lowercase", "asciifolding", "<API key>" ] }, "<API key>": { "type": "custom", "tokenizer": "standard", "filter": [ "lowercase", "asciifolding", "larasearch_ngram" ] }, "<API key>": { "type": "custom", "tokenizer": "standard", "filter": [ "lowercase", "asciifolding", "reverse", "<API key>", "reverse" ] } }, "filter": { "<API key>": { "type": "shingle", "token_separator": "" }, "<API key>": { "type": "shingle", "token_separator": "", "output_unigrams": false, "<API key>": true }, "<API key>": { "type": "shingle", "max_shingle_size": 5 }, "<API key>": { "type": "edgeNGram", "min_gram": 1, "max_gram": 50 }, "larasearch_ngram": { "type": "nGram", "min_gram": 1, "max_gram": 50 }, "larasearch_stemmer": { "type": "snowball", "language": "English" } }, "tokenizer": { "<API key>": { "type": "edgeNGram", "min_gram": 1, "max_gram": 50 } } } }, "mappings": { "_default_": { "properties": { "name": { "type": "multi_field", "fields": { "name": { "type": "string", "index": "not_analyzed" }, "analyzed": { "type": "string", "index": "analyzed" }, "autocomplete": { "type": "string", "index": "analyzed", "analyzer": "<API key>" }, "suggest": { "type": "string", "index": "analyzed", "analyzer": "<API key>" }, "text_start": { "type": "string", "index": "analyzed", "analyzer": "<API key>" }, "text_middle": { "type": "string", "index": "analyzed", "analyzer": "<API key>" }, "text_end": { "type": "string", "index": "analyzed", "analyzer": "<API key>" }, "word_start": { "type": "string", "index": "analyzed", "analyzer": "<API key>" }, "word_middle": { "type": "string", "index": "analyzed", "analyzer": "<API key>" }, "word_end": { "type": "string", "index": "analyzed", "analyzer": "<API key>" } } }, "wife": { "type": "object", "properties": { "name": { "type": "multi_field", "fields": { "name": { "type": "string", "index": "not_analyzed" }, "analyzed": { "type": "string", "index": "analyzed" }, "autocomplete": { "type": "string", "index": "analyzed", "analyzer": "<API key>" } } }, "children": { "type": "object", "properties": { "name": { "type": "multi_field", "fields": { "name": { "type": "string", "index": "not_analyzed" }, "analyzed": { "type": "string", "index": "analyzed" }, "text_start": { "type": "string", "index": "analyzed", "analyzer": "<API key>" }, "text_middle": { "type": "string", "index": "analyzed", "analyzer": "<API key>" }, "text_end": { "type": "string", "index": "analyzed", "analyzer": "<API key>" }, "word_start": { "type": "string", "index": "analyzed", "analyzer": "<API key>" }, "word_middle": { "type": "string", "index": "analyzed", "analyzer": "<API key>" }, "word_end": { "type": "string", "index": "analyzed", "analyzer": "<API key>" } } } } } } } } } }, "index": "bar_husband", "type": "Husband" } }', true) , $params); }); $proxy->shouldReceive('getType')->andReturn('Husband'); $proxy->shouldReceive('getConfig')->andReturn([ 'autocomplete' => ['name', 'wife.name'], 'suggest' => ['name'], 'text_start' => ['name', 'wife.children.name'], 'text_middle' => ['name', 'wife.children.name'], 'text_end' => ['name', 'wife.children.name'], 'word_start' => ['name', 'wife.children.name'], 'word_middle' => ['name', 'wife.children.name'], 'word_end' => ['name', 'wife.children.name'] ]); /** * * Assertion * */ $index->create(); } /** * @test */ public function <API key>() { /** * * Set * * @var \Mockery\Mock $index * @var \Mockery\Mock $proxy * @var \Mockery\Mock $client */ list($index, $proxy, $client) = $this->getMocks(); /** * * Expectation * */ $client->shouldReceive('indices->delete') ->with(['index' => 'husband']) ->andReturn(); /** * * Assertion * */ $index->delete(); } /** * @test */ public function <API key>() { /** * * Set * * @var \Mockery\Mock $index * @var \Mockery\Mock $proxy * @var \Mockery\Mock $client */ list($index, $proxy, $client) = $this->getMocks('bar_'); /** * * Expectation * */ $client->shouldReceive('indices->delete') ->with(['index' => 'bar_husband']) ->andReturn(); /** * * Assertion * */ $index->delete(); } /** * @test */ public function <API key>() { /** * * Set * * @var \Mockery\Mock $index * @var \Mockery\Mock $proxy * @var \Mockery\Mock $client */ list($index, $proxy, $client) = $this->getMocks(); /** * * Expectation * */ $client->shouldReceive('indices->exists') ->with(['index' => 'husband']) ->andReturn(); /** * * Assertion * */ $index->exists(); } /** * @test */ public function <API key>() { /** * * Set * * @var \Mockery\Mock $index * @var \Mockery\Mock $proxy * @var \Mockery\Mock $client */ list($index, $proxy, $client) = $this->getMocks('bar_'); /** * * Expectation * */ $client->shouldReceive('indices->exists') ->with(['index' => 'bar_husband']) ->andReturn(); /** * * Assertion * */ $index->exists(); } /** * @test */ public function <API key>() { /** * * Set * * @var \Mockery\Mock $index * @var \Mockery\Mock $proxy * @var \Mockery\Mock $client */ list($index, $proxy, $client) = $this->getMocks(); /** * * Expectation * */ $client->shouldReceive('indices->existsAlias') ->with(['name' => 'Alias']) ->andReturn(); /** * * Assertion * */ $index->aliasExists('Alias'); } /** * @test */ public function <API key>() { /** * * Set * * @var \Mockery\Mock $index * @var \Mockery\Mock $proxy * @var \Mockery\Mock $client */ list($index, $proxy, $client) = $this->getMocks('bar_'); /** * * Expectation * */ $client->shouldReceive('indices->existsAlias') ->twice() ->with(['name' => 'bar_alias']) ->andReturn(); /** * * Assertion * */ $index->aliasExists('alias'); $index->aliasExists('bar_alias'); } /** * @test */ public function <API key>() { /** * * Set * * @var \Mockery\Mock $index * @var \Mockery\Mock $proxy * @var \Mockery\Mock $client */ list($index, $proxy, $client) = $this->getMocks(); /** * * Expectation * */ $client->shouldReceive('index') ->with([ 'index' => 'husband', 'type' => 'Husband', 'id' => 1, 'body' => 'data' ]) ->andReturn(); /** * * Assertion * */ $index->store([ 'type' => 'Husband', 'id' => 1, 'data' => 'data' ]); } /** * @test */ public function <API key>() { /** * * Set * * @var \Mockery\Mock $index * @var \Mockery\Mock $proxy * @var \Mockery\Mock $client */ list($index, $proxy, $client) = $this->getMocks('bar_'); /** * * Expectation * */ $client->shouldReceive('index') ->twice() ->with([ 'index' => 'bar_husband', 'type' => 'Husband', 'id' => 1, 'body' => 'data' ]) ->andReturn(); /** * * Assertion * */ $index->store([ 'type' => 'Husband', 'id' => 1, 'data' => 'data' ]); $index->setName('bar_Husband'); $index->store([ 'type' => 'Husband', 'id' => 1, 'data' => 'data' ]); } /** * @test */ public function <API key>() { /** * * Set * * @var \Mockery\Mock $index * @var \Mockery\Mock $proxy * @var \Mockery\Mock $client */ list($index, $proxy, $client) = $this->getMocks(); /** * * Expectation * */ $client->shouldReceive('get') ->with([ 'index' => 'husband', 'type' => 'Husband', 'id' => 1, ]) ->andReturn(); /** * * Assertion * */ $index->retrieve([ 'type' => 'Husband', 'id' => 1, 'data' => 'data' ]); } /** * @test */ public function <API key>() { /** * * Set * * @var \Mockery\Mock $index * @var \Mockery\Mock $proxy * @var \Mockery\Mock $client */ list($index, $proxy, $client) = $this->getMocks('bar_'); /** * * Expectation * */ $client->shouldReceive('get') ->twice() ->with([ 'index' => 'bar_husband', 'type' => 'Husband', 'id' => 1, ]) ->andReturn(); /** * * Assertion * */ $index->retrieve([ 'type' => 'Husband', 'id' => 1, 'data' => 'data' ]); $index->setName('bar_Husband'); $index->retrieve([ 'type' => 'Husband', 'id' => 1, 'data' => 'data' ]); } /** * @test */ public function <API key>() { /** * * Set * * @var \Mockery\Mock $index * @var \Mockery\Mock $proxy * @var \Mockery\Mock $client */ list($index, $proxy, $client) = $this->getMocks(); /** * * Expectation * */ $client->shouldReceive('delete') ->with([ 'index' => 'husband', 'type' => 'Husband', 'id' => 1 ]) ->andReturn(); /** * * Assertion * */ $index->remove([ 'type' => 'Husband', 'id' => 1 ]); } /** * @test */ public function <API key>() { /** * * Set * * @var \Mockery\Mock $index * @var \Mockery\Mock $proxy * @var \Mockery\Mock $client */ list($index, $proxy, $client) = $this->getMocks('bar_'); /** * * Expectation * */ $client->shouldReceive('delete') ->twice() ->with([ 'index' => 'bar_husband', 'type' => 'Husband', 'id' => 1 ]) ->andReturn(); /** * * Assertion * */ $index->remove([ 'type' => 'Husband', 'id' => 1 ]); $index->setName('bar_Husband'); $index->remove([ 'type' => 'Husband', 'id' => 1 ]); } /** * @test */ public function <API key>() { /** * * Set * * @var \Mockery\Mock $index * @var \Mockery\Mock $proxy * @var \Mockery\Mock $client */ list($index, $proxy, $client) = $this->getMocks(); /** * * Expectation * */ $client->shouldReceive('indices->analyze') ->with([ 'index' => 'husband', 'text' => 'text', 'option1' => 1, 'option2' => 2 ]) ->andReturn(); /** * * Assertion * */ $index->tokens('text', [ 'option1' => 1, 'option2' => 2 ]); } /** * @test */ public function it_should_inspect_<API key>() { /** * * Set * * @var \Mockery\Mock $index * @var \Mockery\Mock $proxy * @var \Mockery\Mock $client */ list($index, $proxy, $client) = $this->getMocks('bar_'); /** * * Expectation * */ $client->shouldReceive('indices->analyze') ->twice() ->with([ 'index' => 'bar_husband', 'text' => 'text', 'option1' => 1, 'option2' => 2 ]) ->andReturn(); /** * * Assertion * */ $index->tokens('text', [ 'option1' => 1, 'option2' => 2 ]); $index->setName('bar_Husband'); $index->tokens('text', [ 'option1' => 1, 'option2' => 2 ]); } /** * @test */ public function <API key>() { /** * * Set * * @var \Mockery\Mock $index * @var \Mockery\Mock $proxy * @var \Mockery\Mock $client */ list($index, $proxy, $client) = $this->getMocks(); $index->setParams(['mock' => 'data']); $this->assertEquals(['mock' => 'data'], $index->getParams()); } /** * @test * @expectedException \Iverberk\Larasearch\Exceptions\ImportException */ public function <API key>() { /** * * Set * * @var \Mockery\Mock $index * @var \Mockery\Mock $proxy * @var \Mockery\Mock $client */ list($index, $proxy, $client) = $this->getMocks('bar_'); /** * * Expectation * */ $proxy->shouldReceive('getType')->andReturn('Husband'); $client->shouldReceive('bulk') ->with([ 'index' => 'bar_husband', 'type' => 'Husband', 'body' => 'records' ]) ->andReturn([ 'errors' => true, 'items' => [ [ 'index' => [ 'error' => true ] ] ] ]); /** * * Assertion * */ $index->bulk('records'); } /** * @test * @expectedException \Iverberk\Larasearch\Exceptions\ImportException */ public function <API key>() { /** * * Set * * @var \Mockery\Mock $index * @var \Mockery\Mock $proxy * @var \Mockery\Mock $client */ list($index, $proxy, $client) = $this->getMocks('bar_'); /** * * Expectation * */ $proxy->shouldReceive('getType')->andReturn('Husband'); $client->shouldReceive('bulk') ->with([ 'index' => 'bar_husband', 'type' => 'Husband', 'body' => 'records' ]) ->andReturn([ 'errors' => true, 'items' => [ [ 'index' => [ 'error' => true ] ] ] ]); /** * * Assertion * */ $index->bulk('records'); $index->setName('bar_Husband'); $index->bulk('records');; } /** * @test * @expectedException \Iverberk\Larasearch\Exceptions\ImportException */ public function <API key>() { /** * * Set * * @var \Mockery\Mock $index * @var \Mockery\Mock $proxy * @var \Mockery\Mock $client */ list($index, $proxy, $client) = $this->getMocks('bar_'); /** * * Expectation * */ $proxy->shouldReceive('getType')->andReturn('Husband'); $client->shouldReceive('bulk') ->with([ 'index' => 'bar_husband', 'type' => 'Husband', 'body' => 'records' ]) ->andReturn([ 'errors' => true, 'items' => [ [ 'index' => [ 'error' => true ] ] ] ]); /** * * Assertion * */ $index->setName('bar_Husband'); $index->bulk('records');; } /** * @test */ public function <API key>() { /** * * Set * * @var \Mockery\Mock $index * @var \Mockery\Mock $proxy * @var \Mockery\Mock $client */ list($index, $proxy, $client) = $this->getMocks(); /** * * Expectation * */ $proxy->shouldReceive('getType')->andReturn('Husband'); $client->shouldReceive('bulk') ->with([ 'index' => 'husband', 'type' => 'Husband', 'body' => 'records' ]) ->andReturn([ 'errors' => false ]); /** * * Assertion * */ $index->bulk('records'); } /** * @test */ public function <API key>() { /** * * Set * * @var \Mockery\Mock $index * @var \Mockery\Mock $proxy * @var \Mockery\Mock $client */ list($index, $proxy, $client) = $this->getMocks('bar_'); /** * * Expectation * */ $proxy->shouldReceive('getType')->andReturn('Husband'); $client->shouldReceive('bulk') ->twice() ->with([ 'index' => 'bar_husband', 'type' => 'Husband', 'body' => 'records' ]) ->andReturn([ 'errors' => false ]); /** * * Assertion * */ $index->bulk('records'); $index->setName('bar_Husband'); $index->bulk('records'); } /** * @test */ public function <API key>() { /** * * Set * * @var \Mockery\Mock $index * @var \Mockery\Mock $proxy * @var \Mockery\Mock $client */ list($index, $proxy, $client) = $this->getMocks(); // Mock the self::$client variable am::double('Iverberk\Larasearch\Index', ['self::$client' => $client]); /** * * Expectation * */ $client->shouldReceive('indices->getAliases') ->andReturn([ '<API key>' => [ 'aliases' => [] ] ]); $client->shouldReceive('indices->delete') ->with([ 'index' => '<API key>' ]); /** * * Assertion * */ Index::clean('index'); } /** * @test */ public function <API key>() { /** * * Set * * @var \Mockery\Mock $index * @var \Mockery\Mock $proxy * @var \Mockery\Mock $client */ list($index, $proxy, $client) = $this->getMocks('bar_'); // Mock the self::$client variable am::double('Iverberk\Larasearch\Index', ['self::$client' => $client]); /** * * Expectation * */ $client->shouldReceive('indices->getAliases') ->twice() ->andReturn([ '<API key>' => [ 'aliases' => [] ] ]); $client->shouldReceive('indices->delete') ->twice() ->with([ 'index' => '<API key>' ]); /** * * Assertion * */ Index::clean('index'); Index::clean('bar_index'); } /** * @test */ public function <API key>() { /** * * Set * * @var \Mockery\Mock $index * @var \Mockery\Mock $proxy * @var \Mockery\Mock $client */ list($index, $proxy, $client) = $this->getMocks(); // Mock the self::$client variable am::double('Iverberk\Larasearch\Index', ['self::$client' => $client]); /** * * Expectation * */ $client->shouldReceive('indices->updateAliases') ->with([ 'body' => ['actions' => []] ]); /** * * Assertion * */ Index::updateAliases(['actions' => []]); } /** * @test */ public function <API key>() { /** * * Set * * @var \Mockery\Mock $index * @var \Mockery\Mock $proxy * @var \Mockery\Mock $client */ list($index, $proxy, $client) = $this->getMocks('bar_'); // Mock the self::$client variable am::double('Iverberk\Larasearch\Index', ['self::$client' => $client]); /** * * Expectation * */ $client->shouldReceive('indices->updateAliases') ->twice() ->with([ 'body' => ['actions' => [['add' => ['index' => 'bar_Husband', 'alias' => 'bar_Father']]]] ]); /** * * Assertion * */ Index::updateAliases(['actions' => [['add' => ['index' => 'Husband', 'alias' => 'Father']]]]); Index::updateAliases(['actions' => [['add' => ['index' => 'bar_Husband', 'alias' => 'bar_Father']]]]); } /** * @test */ public function <API key>() { /** * * Set * * @var \Mockery\Mock $index * @var \Mockery\Mock $proxy * @var \Mockery\Mock $client */ list($index, $proxy, $client) = $this->getMocks(); // Mock the self::$client variable am::double('Iverberk\Larasearch\Index', ['self::$client' => $client]); /** * * Expectation * */ $client->shouldReceive('indices->getAlias') ->with([ 'name' => 'mock' ]); /** * * Assertion * */ Index::getAlias('mock'); } /** * @test */ public function <API key>() { /** * * Set * * @var \Mockery\Mock $index * @var \Mockery\Mock $proxy * @var \Mockery\Mock $client */ list($index, $proxy, $client) = $this->getMocks('bar_'); // Mock the self::$client variable am::double('Iverberk\Larasearch\Index', ['self::$client' => $client]); /** * * Expectation * */ $client->shouldReceive('indices->getAlias') ->twice() ->with([ 'name' => 'bar_mock' ]); /** * * Assertion * */ Index::getAlias('mock'); Index::getAlias('bar_mock'); } /** * @test */ public function it_should_refresh() { /** * * Set * * @var \Mockery\Mock $index * @var \Mockery\Mock $proxy * @var \Mockery\Mock $client */ list($index, $proxy, $client) = $this->getMocks(); // Mock the self::$client variable am::double('Iverberk\Larasearch\Index', ['self::$client' => $client]); /** * * Expectation * */ $client->shouldReceive('indices->refresh') ->with([ 'index' => 'mock' ]); /** * * Assertion * */ Index::refresh('mock'); } /** * @test */ public function <API key>() { /** * * Set * * @var \Mockery\Mock $index * @var \Mockery\Mock $proxy * @var \Mockery\Mock $client */ list($index, $proxy, $client) = $this->getMocks('bar_'); // Mock the self::$client variable am::double('Iverberk\Larasearch\Index', ['self::$client' => $client]); /** * * Expectation * */ $client->shouldReceive('indices->refresh') ->twice() ->with([ 'index' => 'bar_mock' ]); /** * * Assertion * */ Index::refresh('mock'); Index::refresh('bar_mock'); } /** * Construct an Index mock * * @return array */ private function getMocks($index_prefix = '') { /** * * Expectation * */ Facade::<API key>(); $client = m::mock('Elasticsearch\Client'); App::shouldReceive('make') ->with('Elasticsearch') ->andReturn($client); Config::shouldReceive('get') ->with('larasearch.elasticsearch.index_prefix', '') ->andReturn($index_prefix); $proxy = m::mock('Iverberk\Larasearch\Proxy'); $proxy->shouldReceive('getModel->getTable') ->andReturn('Husband'); $index = m::mock('Iverberk\Larasearch\Index', [$proxy], [m::BLOCKS => ['setName', 'setProxy']])->makePartial(); return [$index, $proxy, $client]; } }
<script async charset="utf-8" src="//cdn.iframe.ly/embed.js?api_key=__key__"></script> <script> function bx_embed_link(e) { iframely.load(e); } </script>
<!DOCTYPE html> {% load bootstrap_toolkit %} {% load compress %} {% load url from future %} {% load menu %} <html lang="en"> <head> <meta charset="utf-8"> <title>{% block title %}GeoQ{% endblock %}</title> <style type="text/css"> body { padding-top: 60px; } </style> <!--[if lt IE 9]> <script src="{{ STATIC_URL }}core/js/html5.js"></script> <![endif] <script src="{{ STATIC_URL }}core/js/jquery.min.js"></script> {% <API key> %} {% <API key> "responsive" %} {% compress css %} <link href="{{ STATIC_URL }}core/less/geoq.less" media="all" rel="stylesheet" type="text/less" /> <link rel="stylesheet" href="{{ STATIC_URL }}font-awesome-2/css/font-awesome.min.css"> {% endcompress %} {% compress js %} <script src="{{ STATIC_URL }}core/js/underscore-min.js"></script> <script src="{{ STATIC_URL }}core/js/underscore.string.min.js" type="text/javascript"></script> <script src="{{ STATIC_URL }}core/js/base.js"></script> {% endcompress %} {% block static_libraries %} {% endblock %} {% <API key> %} </head> <body> {% get_menu request %} {% bootstrap_messages %} {% block container %} <div class="container"> {% block content %}Empty page{% endblock %} <!--<footer class="row"> {% block footer %} <div class="span6">GeoQ</div> {% endblock %} </footer> </div> <!-- container --> {% endblock %} </body> </html>
namespace TouchScript.InputSources { <summary> An object which represents an input source. </summary> <remarks> <para>In TouchScript all touch points (<see cref="ITouch"/>) come from input sources.</para> <para>If you want to feed the library with touches the best way to do it is to create a custom input source.</para> </remarks> public interface IInputSource { <summary> Gets or sets current coordinates remapper. </summary> <value>An object used to change coordinates of touch points coming from this input source.</value> <API key> CoordinatesRemapper { get; set; } } }
<?php namespace Dissect\Parser; use <API key>; class GrammarTest extends <API key> { protected $grammar; protected function setUp() { $this->grammar = new ExampleGrammar(); } /** * @test */ public function <API key>() { $rules = $this->grammar->getRules(); $this->assertEquals('Foo', $rules[1]->getName()); $this->assertEquals('Foo', $rules[2]->getName()); } /** * @test */ public function <API key>() { $this->assertEquals( Grammar::START_RULE_NAME, $this->grammar->getStartRule()->getName() ); $this->assertEquals( array('Foo'), $this->grammar->getStartRule()->getComponents() ); } /** * @test */ public function <API key>() { $rules = $this->grammar->getGroupedRules(); $this->assertCount(2, $rules['Foo']); } }
require 'spec_helper' describe Phony::CountryCodes do before(:all) do @countries = Phony::CountryCodes.instance end describe 'formatted' do it 'formats correctly' do @countries.formatted('41443643532', :format => :international, :spaces => :-).should eql '+41-44-364-35-32' end it 'formats correctly' do @countries.formatted('41443643532', :format => :<API key>, :spaces => :-).should eql '0041-44-364-35-32' end it 'formats correctly' do @countries.formatted('41443643532', :format => :national, :spaces => :-).should eql '044-364-35-32' end context 'specific' do it 'formats Ireland correctly' do @countries.formatted("3533451234", :format => :national).should eql '0345 1234' end it 'formats Ireland correctly' do @countries.formatted("353411231234", :format => :national).should eql '041 123 1234' end it 'formats Spain correctly' do @countries.formatted("34123456789", :format => :national).should eql '123 456 789' end it 'formats Cambodia correctly' do @countries.formatted('85512239123', :format => :national).should eql '012 239 123' end it 'formats the US correctly' do @countries.formatted('18005551212', :format => :national, :spaces => :-).should eql '(800)-555-1212' end it 'formats the US correctly' do @countries.formatted('18005551212', :format => :national, :spaces => :-).should eql '(800)-555-1212' end end context 'default' do it "should format swiss numbers" do @countries.formatted('41443643532').should eql '+41 44 364 35 32' end it "should format swiss service numbers" do @countries.formatted('41800112233').should eql '+41 800 112 233' end it "should format austrian numbers" do @countries.formatted('43198110').should eql '+43 1 98110' end it "should format american numbers" do @countries.formatted('18705551122').should eql '+1 (870) 555-1122' end it "should format irish numbers" do @countries.formatted('35311234567').should eql '+353 1 123 4567' end end describe "international" do it "should format north american numbers" do @countries.formatted('18091231234', :format => :international).should eql '+1 (809) 123-1234' end it "should format austrian numbers" do @countries.formatted('43198110', :format => :international).should eql '+43 1 98110' end it "should format austrian numbers" do @countries.formatted('43198110', :format => :<API key>).should eql '+43 1 98110' end it "should format french numbers" do @countries.formatted('33142278186', :format => :+).should eql '+33 1 42 27 81 86' end it "should format austrian numbers" do @countries.formatted('43198110', :format => :<API key>).should eql '0043 1 98110' end it 'should format liechtensteiner numbers' do @countries.formatted('4233841148', :format => :<API key>).should eql '00423 384 11 48' end it "should format irish numbers" do @countries.formatted('35311234567', :format => :international).should eql '+353 1 123 4567' end it "should format luxembourgian numbers" do @countries.formatted('352222809', :format => :international).should eql '+352 22 28 09' end it "should format luxembourgian 4-digit ndc numbers" do @countries.formatted('35226222809', :format => :international).should eql '+352 26 22 28 09' end it "should format luxembourgian mobile numbers" do @countries.formatted('352621123456', :format => :international).should eql '+352 621 123 456' end it "should format luxembourgian city numbers" do @countries.formatted('3524123456', :format => :international).should eql '+352 4 12 34 56' end it "should format luxembourgian machine to machine numbers" do @countries.formatted('352602112345678', :format => :international).should eql '+352 6021 12 34 56 78' end it "should format luxembourgian numbers" do @countries.formatted('352370431', :format => :international).should eql '+352 37 04 31' end it "should format luxembourgian numbers" do @countries.formatted('35227855', :format => :international).should eql '+352 27 85 5' end it "should format nigerian numbers" do @countries.formatted('23414480000', :format => :international).should eql '+234 1 448 0000' end it "should format nigerian mobile numbers" do @countries.formatted('2347061234567', :format => :international).should eql '+234 706 123 4567' end context 'with no spaces' do it "should format north american numbers" do Phony.formatted('18091231234', :format => :international, :spaces => '').should eql '+1(809)123-1234' end it "should format austrian numbers" do Phony.formatted('43198110', :format => :international, :spaces => '').should eql '+43198110' end it "should format austrian numbers" do Phony.formatted('43198110', :format => :<API key>, :spaces => '').should eql '+43198110' end it "should format french numbers" do Phony.formatted('33142278186', :format => :+, :spaces => '').should eql '+33142278186' end it "should format austrian numbers" do Phony.formatted('43198110', :format => :<API key>, :spaces => '').should eql '0043198110' end it 'should format liechtensteiner numbers' do Phony.formatted('4233841148', :format => :<API key>, :spaces => '').should eql '004233841148' end end context 'with special spaces' do it "should format swiss numbers" do Phony.formatted('41443643532', :format => :international).should eql '+41 44 364 35 32' end it "should format north american numbers" do Phony.formatted('18091231234', :format => :international, :spaces => :-).should eql '+1-(809)-123-1234' end it "should format austrian numbers" do Phony.formatted('43198110', :format => :international, :spaces => :-).should eql '+43-1-98110' end it "should format austrian numbers" do Phony.formatted('43198110', :format => :<API key>, :spaces => :-).should eql '+43-1-98110' end it "should format french numbers" do Phony.formatted('33142278186', :format => :+, :spaces => :-).should eql '+33-1-42-27-81-86' end it "should format austrian numbers" do Phony.formatted('43198110', :format => :<API key>, :spaces => :-).should eql '0043-1-98110' end it 'should format liechtensteiner numbers' do Phony.formatted('4233841148', :format => :<API key>, :spaces => :-).should eql '00423-384-11-48' end end end end end