text:
<Type Name="CCCamera" FullName="CocosSharp.CCCamera">
  <TypeSignature Language="C#" Value="public class CCCamera" />
  <TypeSignature Language="ILAsm" Value=".class public auto ansi beforefieldinit CCCamera extends System.Object" />
  <AssemblyInfo>
    <AssemblyName>CocosSharp</AssemblyName>
  </AssemblyInfo>
  <Base>
    <BaseTypeName>System.Object</BaseTypeName>
  </Base>
  <Interfaces />
  <Docs>
    Represents a camera whose properties specify the underlying view and projection matrices.
    <remarks>

      <para>
	A user can alter a camera's position, target, projection etc. and in-turn this will update the camera's corresponding view and projection matrices.
      </para>

	<para>
	A camera is associated with a <see cref="T:CocosSharp.CCLayer" />  layer when rendering. All children of the layer will then be rendered relative to the parent's camera.
	</para>
      <example>

// Using a custom camera

public class AppDelegate : CCApplicationDelegate
{
    public override void ApplicationDidFinishLaunching(CCApplication application, CCWindow mainWindow)
    {
        mainWindow.SetDesignResolutionSize(960, 640, CCSceneResolutionPolicy.ShowAll);

        var scene = new CCScene(mainWindow);
        var layer = new MyLayer();

        var cameraVisibleBounds = new CCSize(1000, 500);
        var cameraTarget = new CCPoint3(0, 0, 3);
        var cameraPosition = new CCPoint3(0, 0, 100);
        var camera = new CCCamera(cameraVisibleBounds, cameraPosition, cameraTarget);

        layer.Camera = Camera;

        scene.AddChild(layer);
        sharedWindow.RunWithScene(scene);
    }
}

      </example>
    </remarks>
  </Docs>
  <Members>
    <Member MemberName=".ctor">
      <MemberSignature Language="C#" Value="public CCCamera (CocosSharp.CCSize orthographicViewSizeWorldspaceIn);" />
      <MemberSignature Language="ILAsm" Value=".method public hidebysig specialname rtspecialname instance void .ctor(valuetype CocosSharp.CCSize orthographicViewSizeWorldspaceIn) cil managed" />
      <MemberType>Constructor</MemberType>
      <Parameters>
        <Parameter Name="orthographicViewSizeWorldspaceIn" Type="CocosSharp.CCSize" />
      </Parameters>
      <Docs>
        <param name="orthographicViewSizeWorldspaceIn">To be added.</param>
        To be added.
        <remarks>To be added.</remarks>
      </Docs>
    </Member>
    <Member MemberName=".ctor">
      <MemberSignature Language="C#" Value="public CCCamera (CocosSharp.CCSize orthographicViewSizeWorldspaceIn, CocosSharp.CCPoint3 cameraCenterPositionWorldspaceIn, CocosSharp.CCPoint3 targetInWorldspaceIn);" />
      <MemberSignature Language="ILAsm" Value=".method public hidebysig specialname rtspecialname instance void .ctor(valuetype CocosSharp.CCSize orthographicViewSizeWorldspaceIn, valuetype CocosSharp.CCPoint3 cameraCenterPositionWorldspaceIn, valuetype CocosSharp.CCPoint3 targetInWorldspaceIn) cil managed" />
      <MemberType>Constructor</MemberType>
      <Parameters>
        <Parameter Name="orthographicViewSizeWorldspaceIn" Type="CocosSharp.CCSize" />
        <Parameter Name="cameraCenterPositionWorldspaceIn" Type="CocosSharp.CCPoint3" />
        <Parameter Name="targetInWorldspaceIn" Type="CocosSharp.CCPoint3" />
      </Parameters>
      <Docs>
        <param name="orthographicViewSizeWorldspaceIn">To be added.</param>
        <param name="cameraCenterPositionWorldspaceIn">To be added.</param>
        <param name="targetInWorldspaceIn">To be added.</param>
        To be added.
        <remarks>To be added.</remarks>
      </Docs>
    </Member>
    <Member MemberName=".ctor">
      <MemberSignature Language="C#" Value="public CCCamera (float perspectiveFieldOfViewIn, float perspectiveAspectRatioIn, CocosSharp.CCPoint3 cameraCenterPositionWorldspaceIn, CocosSharp.CCPoint3 targetInWorldspaceIn);" />
      <MemberSignature Language="ILAsm" Value=".method public hidebysig specialname rtspecialname instance void .ctor(float32 perspectiveFieldOfViewIn, float32 perspectiveAspectRatioIn, valuetype CocosSharp.CCPoint3 cameraCenterPositionWorldspaceIn, valuetype CocosSharp.CCPoint3 targetInWorldspaceIn) cil managed" />
      <MemberType>Constructor</MemberType>
      <Parameters>
        <Parameter Name="perspectiveFieldOfViewIn" Type="System.Single" />
        <Parameter Name="perspectiveAspectRatioIn" Type="System.Single" />
        <Parameter Name="cameraCenterPositionWorldspaceIn" Type="CocosSharp.CCPoint3" />
        <Parameter Name="targetInWorldspaceIn" Type="CocosSharp.CCPoint3" />
      </Parameters>
      <Docs>
        <param name="perspectiveFieldOfViewIn">To be added.</param>
        <param name="perspectiveAspectRatioIn">To be added.</param>
        <param name="cameraCenterPositionWorldspaceIn">To be added.</param>
        <param name="targetInWorldspaceIn">To be added.</param>
        To be added.
        <remarks>To be added.</remarks>
      </Docs>
    </Member>
    <Member MemberName="CenterInWorldspace">
      <MemberSignature Language="C#" Value="public CocosSharp.CCPoint3 CenterInWorldspace { get; set; }" />
      <MemberSignature Language="ILAsm" Value=".property instance valuetype CocosSharp.CCPoint3 CenterInWorldspace" />
      <MemberType>Property</MemberType>
      <ReturnValue>
        <ReturnType>CocosSharp.CCPoint3</ReturnType>
      </ReturnValue>
      <Docs>
        To be added.
        <value>To be added.</value>
        <remarks>To be added.</remarks>
      </Docs>
    </Member>
    <Member MemberName="NearAndFarOrthographicZClipping">
      <MemberSignature Language="C#" Value="public CocosSharp.CCPoint NearAndFarOrthographicZClipping { get; set; }" />
      <MemberSignature Language="ILAsm" Value=".property instance valuetype CocosSharp.CCPoint NearAndFarOrthographicZClipping" />
      <MemberType>Property</MemberType>
      <ReturnValue>
        <ReturnType>CocosSharp.CCPoint</ReturnType>
      </ReturnValue>
      <Docs>
        To be added.
        <value>To be added.</value>
        <remarks>To be added.</remarks>
      </Docs>
    </Member>
    <Member MemberName="NearAndFarPerspectiveClipping">
      <MemberSignature Language="C#" Value="public CocosSharp.CCPoint NearAndFarPerspectiveClipping { get; set; }" />
      <MemberSignature Language="ILAsm" Value=".property instance valuetype CocosSharp.CCPoint NearAndFarPerspectiveClipping" />
      <MemberType>Property</MemberType>
      <ReturnValue>
        <ReturnType>CocosSharp.CCPoint</ReturnType>
      </ReturnValue>
      <Docs>
        To be added.
        <value>To be added.</value>
        <remarks>To be added.</remarks>
      </Docs>
    </Member>
    <Member MemberName="OrthographicViewSizeWorldspace">
      <MemberSignature Language="C#" Value="public CocosSharp.CCSize OrthographicViewSizeWorldspace { get; set; }" />
      <MemberSignature Language="ILAsm" Value=".property instance valuetype CocosSharp.CCSize OrthographicViewSizeWorldspace" />
      <MemberType>Property</MemberType>
      <ReturnValue>
        <ReturnType>CocosSharp.CCSize</ReturnType>
      </ReturnValue>
      <Docs>
        To be added.
        <value>To be added.</value>
        <remarks>To be added.</remarks>
      </Docs>
    </Member>
    <Member MemberName="PerspectiveAspectRatio">
      <MemberSignature Language="C#" Value="public float PerspectiveAspectRatio { get; set; }" />
      <MemberSignature Language="ILAsm" Value=".property instance float32 PerspectiveAspectRatio" />
      <MemberType>Property</MemberType>
      <ReturnValue>
        <ReturnType>System.Single</ReturnType>
      </ReturnValue>
      <Docs>
        To be added.
        <value>To be added.</value>
        <remarks>To be added.</remarks>
      </Docs>
    </Member>
    <Member MemberName="PerspectiveFieldOfView">
      <MemberSignature Language="C#" Value="public float PerspectiveFieldOfView { get; set; }" />
      <MemberSignature Language="ILAsm" Value=".property instance float32 PerspectiveFieldOfView" />
      <MemberType>Property</MemberType>
      <ReturnValue>
        <ReturnType>System.Single</ReturnType>
      </ReturnValue>
      <Docs>
        To be added.
        <value>To be added.</value>
        <remarks>To be added.</remarks>
      </Docs>
    </Member>
    <Member MemberName="Projection">
      <MemberSignature Language="C#" Value="public CocosSharp.CCCameraProjection Projection { get; set; }" />
      <MemberSignature Language="ILAsm" Value=".property instance valuetype CocosSharp.CCCameraProjection Projection" />
      <MemberType>Property</MemberType>
      <ReturnValue>
        <ReturnType>CocosSharp.CCCameraProjection</ReturnType>
      </ReturnValue>
      <Docs>
        To be added.
        <value>To be added.</value>
        <remarks>To be added.</remarks>
      </Docs>
    </Member>
    <Member MemberName="TargetInWorldspace">
      <MemberSignature Language="C#" Value="public CocosSharp.CCPoint3 TargetInWorldspace { get; set; }" />
      <MemberSignature Language="ILAsm" Value=".property instance valuetype CocosSharp.CCPoint3 TargetInWorldspace" />
      <MemberType>Property</MemberType>
      <ReturnValue>
        <ReturnType>CocosSharp.CCPoint3</ReturnType>
      </ReturnValue>
      <Docs>
        To be added.
        <value>To be added.</value>
        <remarks>To be added.</remarks>
      </Docs>
    </Member>
    <Member MemberName="UpDirection">
      <MemberSignature Language="C#" Value="public CocosSharp.CCPoint3 UpDirection { get; set; }" />
      <MemberSignature Language="ILAsm" Value=".property instance valuetype CocosSharp.CCPoint3 UpDirection" />
      <MemberType>Property</MemberType>
      <ReturnValue>
        <ReturnType>CocosSharp.CCPoint3</ReturnType>
      </ReturnValue>
      <Docs>
        To be added.
        <value>To be added.</value>
        <remarks>To be added.</remarks>
      </Docs>
    </Member>
  </Members>
</Type>


text:
from CapturingRendererTest import CapturingRendererTest

if __name__ == "__main__":
	import unittest
	unittest.main()

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Basic Tabs | unfinishedToggler examples</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="../style/css/normalize.css">

    <link rel="stylesheet" href="../style/css/tabs-basic.css">

UFT Basic Tabs

  <button id="first-tab" class="uft-trigger uft-on" data-uft-group="1">First</button>
  <button id="second-tab"  class="uft-trigger uft-off" data-uft-group="2">Second</button>
  <button id="third-tab"  class="uft-trigger uft-off" data-uft-group="3">Third</button>

First

Test anchor This elusive quality it is, which causes the thought of whiteness, when divorced from more kindly associations, and coupled with any object terrible in itself, to heighten that terror to the furthest bounds. Witness the white bear of the poles, and the white shark of the tropics; what but their smooth, flaky whiteness makes them the transcendent horrors they are?

Second

<button href="#">Test anchor</button> That ghastly whiteness it is which imparts such an abhorrent mildness, even more loathsome than terrific, to the dumb gloating of their aspect. So that not the fierce-fanged tiger in his heraldic coat can so stagger courage as the white-shrouded bear or shark.

Third

Test anchor With reference to the Polar bear, it may possibly be urged by him who would fain go still deeper into this matter, that it is not the whiteness, separately regarded, which heightens the intolerable hideousness of that brute; for, analysed, that heightened hideousness, it might be said, only rises from the circumstance, that the irresponsible ferociousness of the creature stands invested in the fleece of celestial innocence and love; and hence, by bringing together two such opposite emotions in our minds, the Polar bear frightens us with so unnatural a contrast.


text:
// Template Source: BaseEntity.java.tt
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation.  All Rights Reserved.  Licensed under the MIT License.  See License in the project root for license information.
// ------------------------------------------------------------------------------

package com.microsoft.graph.models;
import com.microsoft.graph.serializer.ISerializer;
import com.microsoft.graph.serializer.IJsonBackedObject;
import com.microsoft.graph.serializer.AdditionalDataManager;
import java.util.EnumSet;
import com.microsoft.graph.http.BaseCollectionPage;
import com.microsoft.graph.models.AccessReviewNotificationRecipientItem;
import com.microsoft.graph.models.UserIdentity;
import com.microsoft.graph.models.AccessReviewReviewerScope;
import com.microsoft.graph.models.AccessReviewScope;
import com.microsoft.graph.models.AccessReviewScheduleSettings;
import com.microsoft.graph.models.AccessReviewStageSettings;
import com.microsoft.graph.models.Entity;
import com.microsoft.graph.requests.AccessReviewInstanceCollectionPage;

import com.google.gson.JsonObject;
import com.google.gson.annotations.SerializedName;
import com.google.gson.annotations.Expose;
import javax.annotation.Nullable;
import javax.annotation.Nonnull;

// **NOTE** This file was generated by a tool and any changes will be overwritten.

/**
 * The class for the Access Review Schedule Definition.
 */
public class AccessReviewScheduleDefinition extends Entity implements IJsonBackedObject {

    /**
     * The Additional Notification Recipients.
     * Defines the list of additional users or group members to be notified of the access review progress.
     */
    @SerializedName(value = "additionalNotificationRecipients", alternate = {"AdditionalNotificationRecipients"})
    @Expose
	@Nullable
    public java.util.List<AccessReviewNotificationRecipientItem> additionalNotificationRecipients;

    /**
     * The Created By.
     * User who created this review. Read-only.
     */
    @SerializedName(value = "createdBy", alternate = {"CreatedBy"})
    @Expose
	@Nullable
    public UserIdentity createdBy;

    /**
     * The Created Date Time.
     * Timestamp when the access review series was created. Supports $select. Read-only.
     */
    @SerializedName(value = "createdDateTime", alternate = {"CreatedDateTime"})
    @Expose
	@Nullable
    public java.time.OffsetDateTime createdDateTime;

    /**
     * The Description For Admins.
     * Description provided by review creators to provide more context of the review to admins. Supports $select.
     */
    @SerializedName(value = "descriptionForAdmins", alternate = {"DescriptionForAdmins"})
    @Expose
	@Nullable
    public String descriptionForAdmins;

    /**
     * The Description For Reviewers.
     * Description provided  by review creators to provide more context of the review to reviewers. Reviewers will see this description in the email sent to them requesting their review. Email notifications support up to 256 characters. Supports $select.
     */
    @SerializedName(value = "descriptionForReviewers", alternate = {"DescriptionForReviewers"})
    @Expose
	@Nullable
    public String descriptionForReviewers;

    /**
     * The Display Name.
     * Name of the access review series. Supports $select and $orderBy. Required on create.
     */
    @SerializedName(value = "displayName", alternate = {"DisplayName"})
    @Expose
	@Nullable
    public String displayName;

    /**
     * The Fallback Reviewers.
     * This collection of reviewer scopes is used to define the list of fallback reviewers. These fallback reviewers will be notified to take action if no users are found from the list of reviewers specified. This could occur when either the group owner is specified as the reviewer but the group owner does not exist, or manager is specified as reviewer but a user's manager does not exist. See accessReviewReviewerScope. Replaces backupReviewers. Supports $select. NOTE: The value of this property will be ignored if fallback reviewers are assigned through the stageSettings property.
     */
    @SerializedName(value = "fallbackReviewers", alternate = {"FallbackReviewers"})
    @Expose
	@Nullable
    public java.util.List<AccessReviewReviewerScope> fallbackReviewers;

    /**
     * The Instance Enumeration Scope.
     * This property is required when scoping a review to guest users' access across all Microsoft 365 groups and determines which Microsoft 365 groups are reviewed. Each group will become a unique accessReviewInstance of the access review series.  For supported scopes, see accessReviewScope. Supports $select. For examples of options for configuring instanceEnumerationScope, see Configure the scope of your access review definition using the Microsoft Graph API.
     */
    @SerializedName(value = "instanceEnumerationScope", alternate = {"InstanceEnumerationScope"})
    @Expose
	@Nullable
    public AccessReviewScope instanceEnumerationScope;

    /**
     * The Last Modified Date Time.
     * Timestamp when the access review series was last modified. Supports $select. Read-only.
     */
    @SerializedName(value = "lastModifiedDateTime", alternate = {"LastModifiedDateTime"})
    @Expose
	@Nullable
    public java.time.OffsetDateTime lastModifiedDateTime;

    /**
     * The Reviewers.
     * This collection of access review scopes is used to define who are the reviewers. The reviewers property is only updatable if individual users are assigned as reviewers. Required on create. Supports $select. For examples of options for assigning reviewers, see Assign reviewers to your access review definition using the Microsoft Graph API. NOTE: The value of this property will be ignored if reviewers are assigned through the stageSettings property.
     */
    @SerializedName(value = "reviewers", alternate = {"Reviewers"})
    @Expose
	@Nullable
    public java.util.List<AccessReviewReviewerScope> reviewers;

    /**
     * The Scope.
     * Defines the entities whose access is reviewed. For supported scopes, see accessReviewScope. Required on create. Supports $select and $filter (contains only). For examples of options for configuring scope, see Configure the scope of your access review definition using the Microsoft Graph API.
     */
    @SerializedName(value = "scope", alternate = {"Scope"})
    @Expose
	@Nullable
    public AccessReviewScope scope;

    /**
     * The Settings.
     * The settings for an access review series, see type definition below. Supports $select. Required on create.
     */
    @SerializedName(value = "settings", alternate = {"Settings"})
    @Expose
	@Nullable
    public AccessReviewScheduleSettings settings;

    /**
     * The Stage Settings.
     * Required only for a multi-stage access review to define the stages and their settings. You can break down each review instance into up to three sequential stages, where each stage can have a different set of reviewers, fallback reviewers, and settings. Stages will be created sequentially based on the dependsOn property. Optional.  When this property is defined, its settings are used instead of the corresponding settings in the accessReviewScheduleDefinition object and its settings, reviewers, and fallbackReviewers properties.
     */
    @SerializedName(value = "stageSettings", alternate = {"StageSettings"})
    @Expose
	@Nullable
    public java.util.List<AccessReviewStageSettings> stageSettings;

    /**
     * The Status.
     * This read-only field specifies the status of an access review. The typical states include Initializing, NotStarted, Starting, InProgress, Completing, Completed, AutoReviewing, and AutoReviewed.  Supports $select, $orderby, and $filter (eq only). Read-only.
     */
    @SerializedName(value = "status", alternate = {"Status"})
    @Expose
	@Nullable
    public String status;

    /**
     * The Instances.
     * If the accessReviewScheduleDefinition is a recurring access review, instances represent each recurrence. A review that does not recur will have exactly one instance. Instances also represent each unique resource under review in the accessReviewScheduleDefinition. If a review has multiple resources and multiple instances, each resource will have a unique instance for each recurrence.
     */
    @SerializedName(value = "instances", alternate = {"Instances"})
    @Expose
	@Nullable
    public com.microsoft.graph.requests.AccessReviewInstanceCollectionPage instances;

    /**
     * Sets the raw JSON object
     *
     * @param serializer the serializer
     * @param json the JSON object to set this object to
     */
    public void setRawObject(@Nonnull final ISerializer serializer, @Nonnull final JsonObject json) {

        if (json.has("instances")) {
            instances = serializer.deserializeObject(json.get("instances"), com.microsoft.graph.requests.AccessReviewInstanceCollectionPage.class);
        }
    }
}


text:
import os
import csv
import operator

import numpy as np
import pandas as pd
import theano
from sklearn.cross_validation import train_test_split

from fuel import config
from fuel.transformers import Transformer
from foxhound.utils import shuffle
from pycocotools.coco import COCO
from config import COCO_DIR, SBU_DIR, FLICKR8K_DIR, FLICKR30K_DIR

def coco(mode="dev", n_captions=1, test_size=None):
    """loads coco data into train and test features and targets.
    mode = 'dev' is used for development (quick load of subset)
    """
    # train_fns
    dataType='train2014'
    train_fns = os.listdir("%s/features/%s"%(COCO_DIR, dataType))

    # reduce it to a dev set
    if mode == "dev":
        train_fns = shuffle(train_fns)[:256]
    trX, trY = loadFeaturesTargets(train_fns, dataType, n_captions)

    # val_fns
    dataType='val2014'
    test_fns = os.listdir("%s/features/%s"%(COCO_DIR, dataType))

    # reduce it to a dev set
    if mode == "dev":
        test_fns = shuffle(test_fns)[:128]

    if test_size:
        test_fns = shuffle(test_fns)[:test_size]

    teX, teY = loadFeaturesTargets(test_fns, dataType, n_captions)

    return trX, teX, trY, teY

def sbu(mode="dev", n_sbu=None, test_size=None):
    """loads sbu data into train and test features and targets.
    mode = 'dev' is used for development (quick load of subset)
    """
    if mode == 'dev':
        n_sbu = 256
        test_size = 128

    sbuX, sbuY, _ = sbuXYFilenames(n_sbu)
    return train_test_split(sbuX, sbuY, test_size=test_size)

def flickrXYFilenames(n_examples=None, dataType='8k'):
    if dataType == '8k':
        FLICKR_DIR = FLICKR8K_DIR
    else:
        FLICKR_DIR = FLICKR30K_DIR
    feature_path = os.path.join(FLICKR_DIR, "features")
    caption_path = os.path.join(FLICKR_DIR, "annotations/tokens.txt")

    f = open(caption_path, 'r')
    lines = f.read().splitlines()

    data_dict = {}

    def parse(line):
        split = line.split('#')
        img = split[0]
        caption_ugly = split[1:]
        if isinstance(caption_ugly, list):
            caption_ugly = ' '.join(caption_ugly)
        i, caption = caption_ugly.split('\t')
        handful = data_dict.get(img, [])
        handful.append(caption)
        data_dict[img] = handful

    print("Parsing flickr%s captions..." % dataType)
    for i, line in enumerate(lines):
        parse(line)

    fns, Y = zip(*data_dict.items())
    X = []
    successes = []

    print("Loading flickr%s features..." % dataType)
    for i in range(len(fns)):
        fn = fns[i]
        try:
            name = fn.split('.')[0]
            X.append(np.load(os.path.join(feature_path, "%s.npy" % name)))
            successes.append(i)
        except Exception, e:
            continue

    # get only the successful funs
    if successes:
        Y = operator.itemgetter(*successes)(Y)
        fns = operator.itemgetter(*successes)(fns)

    return X, Y, fns

def sbuXYFilenames(n_examples=None):
    """
    n_examples to try to load.  It might not load all of them
    """
    sbu_feature_path = os.path.join(SBU_DIR, "features")
    sbu_caption_path = os.path.join(SBU_DIR, "SBU_captioned_photo_dataset_captions.txt")
    fns = os.listdir(sbu_feature_path)
    if n_examples:
        fns = fns[:n_examples]

    print "Reading SBU captions"
    f = open(sbu_caption_path, 'rb')
    captions = f.read().splitlines()
    f.close()

    X, Y = [], []
    successes = []

    print "Loading in SBU Features"
    for i in range(len(fns)):
        fn = fns[i]
        try:
            # fn should be SBU_%d
            index = int(fn[4:].split(".")[0])
            X.append(np.load(os.path.join(sbu_feature_path, fn)))
            Y.append([captions[index]])
            successes.append(i)
        except:
            continue

    # get only the successful fns
    fns = operator.itemgetter(*successes)(fns)
    print "SBU Done!"

    return X, Y, fns

def cocoXYFilenames(n_captions=5, dataType='val2014'):
    """Helps when you are evaluating and want the filenames
    associated with the features and target variables

    Parameters
    ----------
    n_captions: integer
        how many captions to load for the image

    dataType: 'val2014' or 'train2014'

    Returns
    -------
    X: the features
    Y: the targets
    filenames: the filenames corresponding to each
    """
    fns = os.listdir("%s/features/%s"%(COCO_DIR, dataType))
    fns = shuffle(fns)
    X, Y = loadFeaturesTargets(fns, dataType, n_captions)

    return X, Y, fns

def loadFeaturesTargets(fns, dataType, n_captions=1):
    """
    Note: filenames should come from the same type of dataType.

    filenames from val2014, for example, should have dataType val2014
    Parameters
    ----------
    fns: filenames, strings

    dataType: string folder, i.e. train2014, val2014

    n_captions: int, number of captions for each image to load

    Returns
    -------
    X: list of im_vects
        1st list length = len(fns)
        vectors are shape (4096, )

    Y: list of list of captions.
        1st list length = len(fns)
        sublist length = n_captions
    """
    annFile = '%s/annotations/captions_%s.json'%(COCO_DIR,dataType)
    caps=COCO(annFile)

    X = []
    Y = []

    for fn in fns:
        # Features
        x = np.load('%s/features/%s/%s'%(COCO_DIR, dataType, fn))

        # Targets
        annIds = caps.getAnnIds(imgIds=getImageId(fn));
        anns = caps.loadAnns(annIds)

        # sample n_captions per image
        anns = shuffle(anns)
        captions = [getCaption(anns[i]) for i in range(n_captions)]

        X.append(x)
        Y.append(captions)

    return X, Y

def getImageId(fn):
    """Filename to image id

    Parameters
    ----------
    fn: a string
        filename of the COCO dataset.

        example:
        COCO_val2014_000000581929.npy

    Returns
    imageId: an int
    """
    return int(fn.split("_")[-1].split('.')[0])

def getCaption(ann):
    """gets Caption from the COCO annotation object

    Parameters
    ----------
    ann: list of annotation objects
    """
    return str(ann["caption"])

def fillOutFilenames(filenames, n_captions):
    new_fns = []
    for fn in filenames:
        new_fns.extend([fn for i in range(n_captions)])
    return new_fns

# Foxhound + Fuel
class FoxyDataStream(object):
    """FoxyDataStream attempts to merge the gap between fuel DataStreams and
    Foxhound iterators.

    The place we will be doing this merge is in the blocks MainLoop. Inserting
    a FoxyDataStream() in place of a DataStream.default_stream()
    will suffice.

    (Note)
    These are broken down into the following common areas
    - dataset which has (features, targets) or (X, Y)
    - iteration_scheme (sequential vs shuffling, batch_size)
    - transforms

    Parameters
    ----------
    data: tuple of X, Y

    sources: tuple of sourcenameX, sourcenameY

    iterator: a Foxhound iterator.  The use is jank right now, but always use
        trXt and trYt as the X and Y transforms respectively
    """

    def __init__(self, data, sources, make_iterator, iteration_scheme=None):
        self.data = data
        self.sources = sources
        self.iterator = make_iterator
        # self.iterator_prototype = make_iterator
        self.iteration_scheme = iteration_scheme # Compatibility with the blocks mainloop

    def get_epoch_iterator(self, as_dict=False):

        # iterator = self.iterator_prototype(None)
        # print iterator
        for datamb in self.iterator.iterXY(*self.data):
            yield dict(zip(self.sources, datamb)) if as_dict else datamb

class FoxyIterationScheme(object):
    """mimics like a Fox a fuel iteration scheme

    Important Attributes
    --------------------
    num_batches: int

    OR

    num_examples: int

    batch_size: int
    """
    def __init__(self, examples, batch_size):
        self.num_examples = examples
        self.batch_size = batch_size

class GloveTransformer(Transformer):
    glove_folder = "glove"
    vector_dim = 0

    def __init__(self, glove_file, data_stream, vectorizer):
        super(GloveTransformer, self).__init__(data_stream)
        dir_path = os.path.join(config.data_path, self.glove_folder)
        data_path = os.path.join(dir_path, glove_file)
        raw = pd.read_csv(data_path, header=None, sep=' ', quoting=csv.QUOTE_NONE, nrows=50000)
        #raw = pd.read_csv(data_path, nrows=400, header=None, sep=' ', quoting=csv.QUOTE_NONE)
        keys = raw[0].values
        self.vectors = raw[range(1, len(raw.columns))].values.astype(theano.config.floatX)
        self.vector_dim = self.vectors.shape[1]

        # lookup will have (key, val) -> (word-string, row index in self.vectors)
        row_indexes = range(self.vectors.shape[0])
        self.lookup = dict(zip(keys, row_indexes))
        self.reverse_lookup = dict(zip(row_indexes, keys))
        self.vectorizer = vectorizer

    def get_data(self, request=None):
        if request is not None:
            raise ValueError

        image_reps, codes = next(self.child_epoch_iterator)

        def process_tokens(tokens):
            output = np.random.rand(len(tokens), self.vector_dim)
            for i,t in enumerate(tokens):
                word = self.vectorizer.decoder[t]
                if word in self.lookup:
                    output[i, :] = self.vectors[self.lookup[word]]
                # else t is UNK so we leave the output alone
            return output

        word_reps = np.asarray(
              [process_tokens(tokens) for tokens in codes.T]
            , dtype=theano.config.floatX)

        return image_reps, word_reps

class ShuffleBatch(Transformer):
    """Shuffle the Batch, helpful when generating contrastive examples"""
    def __init__(self, data_stream):
        super(ShuffleBatch, self).__init__(data_stream)

    def get_data(self, request=None):
        if request is not None:
            raise ValueError
        data = next(self.child_epoch_iterator)
        return shuffle(*data)


text:
package org.apache.wicket.security.examples.components.navigation;

import java.util.Arrays;
import java.util.List;

import org.apache.wicket.AttributeModifier;
import org.apache.wicket.Page;
import org.apache.wicket.markup.ComponentTag;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.Model;
import org.apache.wicket.security.checks.LinkSecurityCheck;
import org.apache.wicket.security.components.markup.html.links.SecureBookmarkablePageLink;

/**
 * Simple container to display some menu buttons.
 *
 * @author marrink
 *
 */
public abstract class ButtonContainer extends Panel
{
	private static final long serialVersionUID = 1L;

	/**
	 * The buttons.
	 */
	protected Integer[] BUTTONS;

	/**
	 * Names for the buttons.
	 */
	protected String[] NAMES;

	/**
	 * The destination for the button clicks.
	 */
	protected List<Class< ? extends Page>> PAGES;

	/**
	 *
	 * Construct.
	 *
	 * @param id
	 * @param selectedButton
	 *            one of BUTTON_....
	 */
	public ButtonContainer(String id, final Integer selectedButton)
	{
		super(id);
		setupButtons();
		setRenderBodyOnly(true);
		ListView<Integer> buttons = new ListView<Integer>("buttons", Arrays.asList(BUTTONS))
		{
			private static final long serialVersionUID = 1L;

			@Override
			protected void populateItem(ListItem<Integer> item)
			{
				Integer button = item.getModelObject();
				SecureBookmarkablePageLink<Void> link =
					new SecureBookmarkablePageLink<Void>("button", PAGES.get(button.intValue()))
					{
						private static final long serialVersionUID = 1L;

						/**
						 * Overrides default behavior purely for the sake of the
						 * stylesheet. The wicket default already does a good job in
						 * disabling the links
						 *
						 * @see org.apache.wicket.markup.html.link.AbstractLink#disableLink(org.apache.wicket.markup.ComponentTag)
						 */
						@Override
						protected void disableLink(final ComponentTag tag)
						{
							// if the tag is an anchor proper
							if (tag.getName().equalsIgnoreCase("a")
								|| tag.getName().equalsIgnoreCase("link")
								|| tag.getName().equalsIgnoreCase("area"))
							{
								// Remove any href from the old link
								tag.remove("href");

								tag.put("onclick", "return false;");
								tag.put("id", "disabledButton");
							}
							// if the tag is a button or input
							else if ("button".equalsIgnoreCase(tag.getName())
								|| "input".equalsIgnoreCase(tag.getName()))
							{
								tag.put("disabled", "disabled");
							}
						}
					};
				// always render the buttons unless the link itself does not
				// have enough rights
				((LinkSecurityCheck) link.getSecurityCheck()).setUseAlternativeRenderCheck(true);
				link.add(new Label("title", NAMES[button.intValue()]).setRenderBodyOnly(true));
				item.add(link);
				// stylesheet stuff
				if (selectedButton.equals(button))
				{
					link.add(new AttributeModifier("id", true, new Model<String>("activeButton")));
				}
				item.setRenderBodyOnly(true);
			}
		};
		add(buttons);
	}

	/**
	 * Allows subclasses to setup the buttons.
	 */
	protected abstract void setupButtons();
}


text:
require 'delegate'

module MescalCli
  class Config < Delegator
    def self.load(file)
      Config.new(MultiJson.load(open(file).read))
    end

    def initialize(obj)
      super
      @delegate_obj = obj
    end

    def __getobj__
      @delegate_obj
    end

    def __setobj__(obj)
      @delegate_obj = obj
    end
  end
end


text:
<!DOCTYPE html>

	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width">
	<title>SparkMonitor JavaScript Documentation Index</title>

	<link type="text/css" rel="stylesheet" href="styles/sunlight.default.css">

	<link type="text/css" rel="stylesheet" href="styles/site.lumen.css">

		SparkMonitor JavaScript Documentation
		<button class="navbar-toggle" type="button" data-toggle="collapse" data-target="#topNavigation">

        </button>

				Modules

CellMonitor

SparkMonitor

TaskChart

Timeline

currentcell

module

taskdetails

				Classes

SparkMonitor~SparkMonitor

CellMonitor~CellMonitor

TaskChart~TaskChart

Timeline~Timeline

                <form class="navbar-form" role="search">

                        <input type="text" class="form-control" placeholder="Search" name="q" id="search-input">

                            <button class="btn btn-default" id="search-submit"></button>

                </form>

            <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Search results

            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

	Documentation generated by JSDoc 3.5.4

		on 2017-08-27T18:34:47+05:30

	using the DocStrap template.


text:
var autobahn = require('./../index.js');
var testutil = require('./testutil.js');

exports.testPubsubPublisherDiscloseMe = function (testcase) {

   testcase.expect(1);

   var test = new testutil.Testlog("test/test_pubsub_publisher_disclose_me.txt");

   var dl = testutil.connect_n(2);

   autobahn.when.all(dl).then(
      function (res) {
         test.log("all sessions connected");

         var session1 = res[0];
         var session2 = res[1];

         var counter = 0;

         // cleans up after test
         function onTestFinished() {
               session1.leave();
               session2.leave();

               var chk = test.check()
               testcase.ok(!chk, chk);
               testcase.done();
         }

         // Case 1: "session.publisher_disclose_me" unset
         //
         // Expected:
         //    - no publisher ID given for call without "disclose_me" set
         //    - no publisher ID given for call without "disclose_me" set to "false"
         //    - publisher ID given for call without "disclose_me" set to "true"
         function case1 () {

            test.log("");
            test.log("Case 1: 'session.publisher_disclose_me' unset");
            test.log("=============================================");

            var counter = 0;

            function onevent1 (args, kwargs, details) {

               var publisher_disclosed = details.publisher === undefined ? false : true;
               test.log("Publisher disclosed:", publisher_disclosed);

               counter += 1;
               if (counter === 3) {
                  test.log("");
                  test.log("");

                  case2();

               }
            }

            session1.subscribe("com.myapp.topic1", onevent1);

            // No explicit setting of 'publisher_disclose_me'
            session2.publish("com.myapp.topic1"); // false
            session2.publish("com.myapp.topic1", [], {}, { disclose_me: false}); // false
            session2.publish("com.myapp.topic1", [], {}, { disclose_me: true}); // true

         }

         // Case 2: "session.publisher_disclose_me" set to "false"
         //
         // Expected:
         //    - no publisher ID given for call without "disclose_me" set
         //    - no publisher ID given for call without "disclose_me" set to "false"
         //    - publisher ID given for call without "disclose_me" set to "true"
         function case2 () {

            test.log("");
            test.log("Case 2: 'session.publisher_disclose_me' set to 'false'");
            test.log("======================================================");

            var counter = 0;

            function onevent2 (args, kwargs, details) {

               var publisher_disclosed = details.publisher === undefined ? false : true;
               test.log("Publisher disclosed:", publisher_disclosed);

               counter += 1;
               if (counter === 3) {
                  test.log("");
                  test.log("");

                  case3();

               }
            }

            session1.subscribe("com.myapp.topic2", onevent2);

            session2.publisher_disclose_me = false;

            session2.publish("com.myapp.topic2"); // false
            session2.publish("com.myapp.topic2", [], {}, { disclose_me: false}); // false
            session2.publish("com.myapp.topic2", [], {}, { disclose_me: true}); // true

         }

         // Case 3: "session.publisher_disclose_me" set to "true"
         //
         // Expected:
         //    - publisher ID given for call without "disclose_me" set
         //    - no publisher ID given for call without "disclose_me" set to "false"
         //    - publisher ID given for call without "disclose_me" set to "true"
         function case3 () {

            test.log("");
            test.log("Case 3: 'session.publisher_disclose_me' set to 'true'");
            test.log("=====================================================");

            var counter = 0;

            function onevent3 (args, kwargs, details) {

               var publisher_disclosed = details.publisher === undefined ? false : true;
               test.log("Publisher disclosed:", publisher_disclosed);

               counter += 1;
               if (counter === 3) {
                  test.log("");
                  test.log("");

                  onTestFinished();

               }
            }

            session1.subscribe("com.myapp.topic3", onevent3);

            session2.publisher_disclose_me = true;

            session2.publish("com.myapp.topic3"); // true
            session2.publish("com.myapp.topic3", [], {}, { disclose_me: false}); // false
            session2.publish("com.myapp.topic3", [], {}, { disclose_me: true}); // true

         }

         case1();

      },
      function (err) {
         test.log(err);
      }
   );
}


text:
<?xml version="1.0" encoding="UTF-8"?>

<faces-config
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd"
    version="2.0">

    <navigation-rule>

   <navigation-case>
    		<from-outcome>login</from-outcome>
    		<to-view-id>/login.jsf</to-view-id>
    		<redirect></redirect>
    	</navigation-case>

    <navigation-case>
    		<from-outcome>index</from-outcome>
    		<to-view-id>/index.jsf</to-view-id>
    		<redirect></redirect>
    	</navigation-case>

    <!-- cadastros -->

    	<navigation-case>
    		<from-outcome>cliente</from-outcome>
    		<to-view-id>/cadastros/cliente/cliente.jsf</to-view-id>
    		<redirect></redirect>
    	</navigation-case>

    	<navigation-case>
    		<from-outcome>fornecedor</from-outcome>
    		<to-view-id>/cadastros/fornecedor/fornecedor.jsf</to-view-id>
    		<redirect></redirect>
    	</navigation-case>

    	<navigation-case>
    		<from-outcome>contaBancaria</from-outcome>
    		<to-view-id>/cadastros/contaBancaria/contaBancaria.jsf</to-view-id>
    		<redirect></redirect>
    	</navigation-case>

    	<navigation-case>
    		<from-outcome>grupoProduto</from-outcome>
    		<to-view-id>/cadastros/grupoProduto/grupoProduto.jsf</to-view-id>
    		<redirect></redirect>
    	</navigation-case>

    	<navigation-case>
    		<from-outcome>produto</from-outcome>
    		<to-view-id>/cadastros/produto/produto.jsf</to-view-id>
    		<redirect></redirect>
    	</navigation-case>

    	<navigation-case>
    		<from-outcome>usuario</from-outcome>
    		<to-view-id>/cadastros/usuario/usuario.jsf</to-view-id>
    		<redirect></redirect>
    	</navigation-case>

    	<navigation-case>
    		<from-outcome>contaGerencial</from-outcome>
    		<to-view-id>/cadastros/contaGerencial/contaGerencial.jsf</to-view-id>
    		<redirect></redirect>
    	</navigation-case>

    	<navigation-case>
    		<from-outcome>tipoDocumento</from-outcome>
    		<to-view-id>/cadastros/tipoDocumento/tipoDocumento.jsf</to-view-id>
    		<redirect></redirect>
    	</navigation-case>

    	<navigation-case>
    		<from-outcome>chequesEmitidos</from-outcome>
    		<to-view-id>/cadastros/chequesEmitidos/chequesEmitidos.jsf</to-view-id>
    		<redirect></redirect>
    	</navigation-case>

    	<navigation-case>
    		<from-outcome>chequesPredatados</from-outcome>
    		<to-view-id>/cadastros/chequesPredatados/chequesPredatados.jsf</to-view-id>
    		<redirect></redirect>
    	</navigation-case>

    	<navigation-case>
    		<from-outcome>estoque</from-outcome>
    		<to-view-id>/cadastros/estoque/estoque.jsf</to-view-id>
    		<redirect></redirect>
    	</navigation-case>

    	<navigation-case>
    		<from-outcome>historicoMovProduto</from-outcome>
    		<to-view-id>/cadastros/estoque/historicoMovimentacao.jsf</to-view-id>
    		<redirect></redirect>
    	</navigation-case>

    	<navigation-case>
    		<from-outcome>lancaCaixa</from-outcome>
    		<to-view-id>/cadastros/lancaCaixa/lancaCaixa.jsf</to-view-id>
    		<redirect></redirect>
    	</navigation-case>

    	<navigation-case>
    		<from-outcome>lancaBanco</from-outcome>
    		<to-view-id>/cadastros/lancaBanco/lancaBanco.jsf</to-view-id>
    		<redirect></redirect>
    	</navigation-case>

    	<navigation-case>
    		<from-outcome>estornarFechamentoCaixa</from-outcome>
    		<to-view-id>/cadastros/lancaCaixa/estornaFechamento.jsf</to-view-id>
    		<redirect></redirect>
    	</navigation-case>

    	<navigation-case>
    		<from-outcome>estornarFechamentoBanco</from-outcome>
    		<to-view-id>/cadastros/lancaBanco/estornaFechamento.jsf</to-view-id>
    		<redirect></redirect>
    	</navigation-case>

    	<navigation-case>
    		<from-outcome>contasReceber</from-outcome>
    		<to-view-id>/cadastros/contasReceber/contasReceber.jsf</to-view-id>
    		<redirect></redirect>
    	</navigation-case>

    	<navigation-case>
    		<from-outcome>contasPagar</from-outcome>
    		<to-view-id>/cadastros/contasPagar/contasPagar.jsf</to-view-id>
    		<redirect></redirect>
    	</navigation-case>

    	<navigation-case>
    		<from-outcome>editarRecebimento</from-outcome>
    		<to-view-id>/cadastros/contasReceber/editar.jsf</to-view-id>
    		<redirect></redirect>
    	</navigation-case>

    	<navigation-case>
    		<from-outcome>editarPagamento</from-outcome>
    		<to-view-id>/cadastros/contasPagar/editar.jsf</to-view-id>
    		<redirect></redirect>
    	</navigation-case>

    	  <!-- listagem -->
    	  <navigation-case>
    	  	<from-outcome>listagemCliente</from-outcome>
    	  	<to-view-id>/cadastros/cliente/listagem/listagemCliente.jsf</to-view-id>
    	  	<redirect></redirect>
    	  </navigation-case>

    	  <navigation-case>
    	  	<from-outcome>listagemFornecedor</from-outcome>
    	  	<to-view-id>/cadastros/fornecedor/listagem/listagemFornecedor.jsf</to-view-id>
    	  	<redirect></redirect>
    	  </navigation-case>

    	   <navigation-case>
    	  	<from-outcome>listagemContaBancaria</from-outcome>
    	  	<to-view-id>/cadastros/contaBancaria/listagem/listagemContaBancaria.jsf</to-view-id>
    	  	<redirect></redirect>
    	  </navigation-case>

    	  <navigation-case>
    	  	<from-outcome>listagemGrupoProduto</from-outcome>
    	  	<to-view-id>/cadastros/grupoProduto/listagem/listagemGrupoProduto.jsf</to-view-id>
    	  	<redirect></redirect>
    	  </navigation-case>

    	   <navigation-case>
    	  	<from-outcome>listagemProduto</from-outcome>
    	  	<to-view-id>/cadastros/produto/listagem/listagemProduto.jsf</to-view-id>
    	  	<redirect></redirect>
    	  </navigation-case>

    	  <navigation-case>
    	  	<from-outcome>listagemUsuario</from-outcome>
    	  	<to-view-id>/cadastros/usuario/listagem/listagemUsuario.jsf</to-view-id>
    	  	<redirect></redirect>
    	  </navigation-case>

    	  <navigation-case>
    	  	<from-outcome>listagemContaGerencial</from-outcome>
    	  	<to-view-id>/cadastros/contaGerencial/listagem/listagemContaGerencial.jsf</to-view-id>
    	  	<redirect></redirect>
    	  </navigation-case>

    	  <navigation-case>
    	  	<from-outcome>listagemTipoDocumento</from-outcome>
    	  	<to-view-id>/cadastros/tipoDocumento/listagem/listagemTipoDocumento.jsf</to-view-id>
    	  	<redirect></redirect>
    	  </navigation-case>

    	   <navigation-case>
    	  	<from-outcome>listagemChequesEmitidos</from-outcome>
    	  	<to-view-id>/cadastros/chequesEmitidos/listagem/listagemChequesEmitidos.jsf</to-view-id>
    	  	<redirect></redirect>
    	  </navigation-case>

    	   <navigation-case>
    	  	<from-outcome>listagemChequesPredatados</from-outcome>
    	  	<to-view-id>/cadastros/chequesPredatados/listagem/listagemChequesPredatados.jsf</to-view-id>
    	  	<redirect></redirect>
    	  </navigation-case>

    	    <navigation-case>
    	  	<from-outcome>listagemEstoque</from-outcome>
    	  	<to-view-id>/cadastros/estoque/listagem/listagemEstoque.jsf</to-view-id>
    	  	<redirect></redirect>
    	  </navigation-case>

    	   <navigation-case>
    	  	<from-outcome>listagemContasReceber</from-outcome>
    	  	<to-view-id>/cadastros/contasReceber/listagem/listagemContasReceber.jsf</to-view-id>
    	  	<redirect></redirect>
    	  </navigation-case>

    	  <navigation-case>
    	  	<from-outcome>listagemContasPagar</from-outcome>
    	  	<to-view-id>/cadastros/contasPagar/listagem/listagemContasPagar.jsf</to-view-id>
    	  	<redirect></redirect>
    	  </navigation-case>

    </navigation-rule>

</faces-config>


text:
require 'test_helper'

module Dyalikeblags
  class PostTest < ActiveSupport::TestCase
    # test "the truth" do
    #   assert true
    # end
  end
end


text:
define([
    'underscore',
    'backbone'
], function (_, Backbone) {
    var WizardView = Backbone.View.extend({
        render: function () {
            var wizardTempl = contrail.getTemplate4Id("sm-wizard-view-template"),
                viewConfig = this.attributes.viewConfig,
                elId = this.attributes.elementId,
                validation = this.attributes.validation,
                lockEditingByDefault = this.attributes.lockEditingByDefault,
                self = this,
                childViewObj, childElId, steps;

            this.$el.html(wizardTempl({viewConfig: viewConfig, elementId: elId}));
            steps = viewConfig['steps'];

            $.each(steps, function(stepKey, stepValue){

                self.model.showErrorAttr(stepValue.elementId, false);
                if(stepValue.onInitRender == true) {
                    stepValue.onInitWizard = function(params) {
                        smwu.renderView4Config($("#" + stepValue.elementId), self.model, stepValue, validation, lockEditingByDefault);
                    }
                }
                else {
                    stepValue.onInitFromNext = function (params) {
                        smwu.renderView4Config($("#" + stepValue.elementId), self.model, stepValue, validation, lockEditingByDefault);
                    }
                }
            });

            this.$el.find("#" + elId).contrailWizard({
                headerTag: "h2",
                bodyTag: "section",
                transitionEffect: "slideLeft",
                titleTemplate: '#index# #title#',
                steps: steps,
                params: {
                    model: this.model
                }
            });

            this.$el.parents('.modal-body').css({'padding': '0'});
        }
    });

    return WizardView;
});


text:
package com.github.lukaspili.architectmapdemo.di;

import com.github.lukaspili.architectmapdemo.mvp.presenter.HomePresenter;

import autodagger.AutoComponent;

/**
 * @author Lukasz Piliszczuk - lukasz.pili@gmail.com
 */
@AutoComponent(
        dependencies = HomePresenter.class,
        includes = AutoComponentDependencies.class
)
public @interface FromHomeAutoComponent {
}


text:
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "content/common/gpu/gpu_memory_manager.h"

#include <algorithm>

#include "base/bind.h"
#include "base/command_line.h"
#include "base/debug/trace_event.h"
#include "base/message_loop.h"
#include "base/process_util.h"
#include "base/string_number_conversions.h"
#include "content/common/gpu/gpu_channel_manager.h"
#include "content/common/gpu/gpu_memory_allocation.h"
#include "content/common/gpu/gpu_memory_manager_client.h"
#include "content/common/gpu/gpu_memory_tracking.h"
#include "content/common/gpu/gpu_memory_uma_stats.h"
#include "content/common/gpu/gpu_messages.h"
#include "gpu/command_buffer/service/gpu_switches.h"

namespace content {
namespace {

const int kDelayedScheduleManageTimeoutMs = 67;

const uint64 kBytesAllocatedUnmanagedStep = 16 * 1024 * 1024;

void TrackValueChanged(uint64 old_size, uint64 new_size, uint64* total_size) {
  DCHECK(new_size > old_size || *total_size >= (old_size - new_size));
  *total_size += (new_size - old_size);
}

template<typename T>
T RoundUp(T n, T mul) {
  return ((n + mul - 1) / mul) * mul;
}

template<typename T>
T RoundDown(T n, T mul) {
  return (n / mul) * mul;
}

}

GpuMemoryManager::GpuMemoryManager(
    GpuChannelManager* channel_manager,
    uint64 max_surfaces_with_frontbuffer_soft_limit)
    : channel_manager_(channel_manager),
      manage_immediate_scheduled_(false),
      max_surfaces_with_frontbuffer_soft_limit_(
          max_surfaces_with_frontbuffer_soft_limit),
      bytes_available_gpu_memory_(0),
      bytes_available_gpu_memory_overridden_(false),
      bytes_minimum_per_client_(0),
      bytes_default_per_client_(0),
      bytes_allocated_managed_current_(0),
      bytes_allocated_managed_visible_(0),
      bytes_allocated_managed_nonvisible_(0),
      bytes_allocated_unmanaged_current_(0),
      bytes_allocated_historical_max_(0),
      bytes_allocated_unmanaged_high_(0),
      bytes_allocated_unmanaged_low_(0),
      bytes_unmanaged_limit_step_(kBytesAllocatedUnmanagedStep),
      disable_schedule_manage_(false)
{
  CommandLine* command_line = CommandLine::ForCurrentProcess();

#if defined(OS_ANDROID)
  bytes_default_per_client_ = 32 * 1024 * 1024;
  bytes_minimum_per_client_ = 32 * 1024 * 1024;
#else
  bytes_default_per_client_ = 64 * 1024 * 1024;
  bytes_minimum_per_client_ = 64 * 1024 * 1024;
#endif

  if (command_line->HasSwitch(switches::kForceGpuMemAvailableMb)) {
    base::StringToUint64(
        command_line->GetSwitchValueASCII(switches::kForceGpuMemAvailableMb),
        &bytes_available_gpu_memory_);
    bytes_available_gpu_memory_ *= 1024 * 1024;
    bytes_available_gpu_memory_overridden_ = true;
  } else
    bytes_available_gpu_memory_ = GetDefaultAvailableGpuMemory();
}

GpuMemoryManager::~GpuMemoryManager() {
  DCHECK(tracking_groups_.empty());
  DCHECK(clients_visible_mru_.empty());
  DCHECK(clients_nonvisible_mru_.empty());
  DCHECK(clients_nonsurface_.empty());
  DCHECK(!bytes_allocated_managed_current_);
  DCHECK(!bytes_allocated_unmanaged_current_);
  DCHECK(!bytes_allocated_managed_visible_);
  DCHECK(!bytes_allocated_managed_nonvisible_);
}

uint64 GpuMemoryManager::GetAvailableGpuMemory() const {
  // Allow unmanaged allocations to over-subscribe by at most (high_ - low_)
  // before restricting managed (compositor) memory based on unmanaged usage.
  if (bytes_allocated_unmanaged_low_ > bytes_available_gpu_memory_)
    return 0;
  return bytes_available_gpu_memory_ - bytes_allocated_unmanaged_low_;
}

uint64 GpuMemoryManager::GetDefaultAvailableGpuMemory() const {
#if defined(OS_ANDROID)
  return 32 * 1024 * 1024;
#elif defined(OS_CHROMEOS)
  return 1024 * 1024 * 1024;
#else
  return 256 * 1024 * 1024;
#endif
}

uint64 GpuMemoryManager::GetMaximumTotalGpuMemory() const {
#if defined(OS_ANDROID)
  return 256 * 1024 * 1024;
#else
  return 1024 * 1024 * 1024;
#endif
}

uint64 GpuMemoryManager::GetMaximumClientAllocation() const {
#if defined(OS_ANDROID) || defined(OS_CHROMEOS)
  return bytes_available_gpu_memory_;
#else
  // This is to avoid allowing a single page on to use a full 256MB of memory
  // (the current total limit). Long-scroll pages will hit this limit,
  // resulting in instability on some platforms (e.g, issue 141377).
  return bytes_available_gpu_memory_ / 2;
#endif
}

uint64 GpuMemoryManager::CalcAvailableFromGpuTotal(uint64 total_gpu_memory) {
#if defined(OS_ANDROID)
  // We don't need to reduce the total on Android, since
  // the total is an estimate to begin with.
  return total_gpu_memory;
#else
  // Allow Chrome to use 75% of total GPU memory, or all-but-64MB of GPU
  // memory, whichever is less.
  return std::min(3 * total_gpu_memory / 4, total_gpu_memory - 64*1024*1024);
#endif
}

void GpuMemoryManager::UpdateAvailableGpuMemory() {
  // If the amount of video memory to use was specified at the command
  // line, never change it.
  if (bytes_available_gpu_memory_overridden_)
    return;

  // On non-Android, we use an operating system query when possible.
  // We do not have a reliable concept of multiple GPUs existing in
  // a system, so just be safe and go with the minimum encountered.
  uint64 bytes_min = 0;

  // Only use the clients that are visible, because otherwise the set of clients
  // we are querying could become extremely large.
  for (ClientStateList::const_iterator it = clients_visible_mru_.begin();
      it != clients_visible_mru_.end();
      ++it) {
    const GpuMemoryManagerClientState* client_state = *it;
    if (!client_state->has_surface_)
      continue;
    if (!client_state->visible_)
      continue;

    uint64 bytes = 0;
    if (client_state->client_->GetTotalGpuMemory(&bytes)) {
      if (!bytes_min || bytes < bytes_min)
        bytes_min = bytes;
    }
  }

  if (!bytes_min)
    return;

  bytes_available_gpu_memory_ = CalcAvailableFromGpuTotal(bytes_min);

  // Never go below the default allocation
  bytes_available_gpu_memory_ = std::max(bytes_available_gpu_memory_,
                                         GetDefaultAvailableGpuMemory());

  // Never go above the maximum.
  bytes_available_gpu_memory_ = std::min(bytes_available_gpu_memory_,
                                         GetMaximumTotalGpuMemory());
}

void GpuMemoryManager::UpdateUnmanagedMemoryLimits() {
  // Set the limit to be [current_, current_ + step_ / 4), with the endpoints
  // of the intervals rounded down and up to the nearest step_, to avoid
  // thrashing the interval.
  bytes_allocated_unmanaged_high_ = RoundUp(
      bytes_allocated_unmanaged_current_ + bytes_unmanaged_limit_step_ / 4,
      bytes_unmanaged_limit_step_);
  bytes_allocated_unmanaged_low_ = RoundDown(
      bytes_allocated_unmanaged_current_,
      bytes_unmanaged_limit_step_);
}

void GpuMemoryManager::ScheduleManage(
    ScheduleManageTime schedule_manage_time) {
  if (disable_schedule_manage_)
    return;
  if (manage_immediate_scheduled_)
    return;
  if (schedule_manage_time == kScheduleManageNow) {
    MessageLoop::current()->PostTask(
      FROM_HERE,
      base::Bind(&GpuMemoryManager::Manage, AsWeakPtr()));
    manage_immediate_scheduled_ = true;
    if (!delayed_manage_callback_.IsCancelled())
      delayed_manage_callback_.Cancel();
  } else {
    if (!delayed_manage_callback_.IsCancelled())
      return;
    delayed_manage_callback_.Reset(base::Bind(&GpuMemoryManager::Manage,
                                              AsWeakPtr()));
    MessageLoop::current()->PostDelayedTask(
      FROM_HERE,
      delayed_manage_callback_.callback(),
      base::TimeDelta::FromMilliseconds(kDelayedScheduleManageTimeoutMs));
  }
}

void GpuMemoryManager::TrackMemoryAllocatedChange(
    GpuMemoryTrackingGroup* tracking_group,
    uint64 old_size,
    uint64 new_size,
    gpu::gles2::MemoryTracker::Pool tracking_pool) {
  TrackValueChanged(old_size, new_size, &tracking_group->size_);
  switch (tracking_pool) {
    case gpu::gles2::MemoryTracker::kManaged:
      TrackValueChanged(old_size, new_size, &bytes_allocated_managed_current_);
      break;
    case gpu::gles2::MemoryTracker::kUnmanaged:
      TrackValueChanged(old_size,
                        new_size,
                        &bytes_allocated_unmanaged_current_);
      break;
    default:
      NOTREACHED();
      break;
  }
  if (new_size != old_size) {
    TRACE_COUNTER1("gpu",
                   "GpuMemoryUsage",
                   GetCurrentUsage());
  }

  // If we've gone past our current limit on unmanaged memory, schedule a
  // re-manage to take int account the unmanaged memory.
  if (bytes_allocated_unmanaged_current_ >= bytes_allocated_unmanaged_high_)
    ScheduleManage(kScheduleManageNow);
  if (bytes_allocated_unmanaged_current_ < bytes_allocated_unmanaged_low_)
    ScheduleManage(kScheduleManageLater);

  if (GetCurrentUsage() > bytes_allocated_historical_max_) {
      bytes_allocated_historical_max_ = GetCurrentUsage();
      // If we're blowing into new memory usage territory, spam the browser
      // process with the most up-to-date information about our memory usage.
      SendUmaStatsToBrowser();
  }
}

bool GpuMemoryManager::EnsureGPUMemoryAvailable(uint64 /* size_needed */) {
  // TODO: Check if there is enough space. Lose contexts until there is.
  return true;
}

GpuMemoryManagerClientState* GpuMemoryManager::CreateClientState(
    GpuMemoryManagerClient* client,
    bool has_surface,
    bool visible) {
  TrackingGroupMap::iterator tracking_group_it =
      tracking_groups_.find(client->GetMemoryTracker());
  DCHECK(tracking_group_it != tracking_groups_.end());
  GpuMemoryTrackingGroup* tracking_group = tracking_group_it->second;

  GpuMemoryManagerClientState* client_state = new GpuMemoryManagerClientState(
      this, client, tracking_group, has_surface, visible);
  TrackValueChanged(0, client_state->managed_memory_stats_.bytes_allocated,
                    client_state->visible_ ?
                        &bytes_allocated_managed_visible_ :
                        &bytes_allocated_managed_nonvisible_);
  AddClientToList(client_state);
  ScheduleManage(kScheduleManageNow);
  return client_state;
}

void GpuMemoryManager::OnDestroyClientState(
    GpuMemoryManagerClientState* client_state) {
  RemoveClientFromList(client_state);
  TrackValueChanged(client_state->managed_memory_stats_.bytes_allocated, 0,
                    client_state->visible_ ?
                        &bytes_allocated_managed_visible_ :
                        &bytes_allocated_managed_nonvisible_);
  ScheduleManage(kScheduleManageLater);
}

void GpuMemoryManager::SetClientStateVisible(
    GpuMemoryManagerClientState* client_state, bool visible) {
  DCHECK(client_state->has_surface_);
  if (client_state->visible_ == visible)
    return;

  RemoveClientFromList(client_state);
  client_state->visible_ = visible;
  AddClientToList(client_state);

  TrackValueChanged(client_state->managed_memory_stats_.bytes_allocated, 0,
                    client_state->visible_ ?
                        &bytes_allocated_managed_nonvisible_ :
                        &bytes_allocated_managed_visible_);
  TrackValueChanged(0, client_state->managed_memory_stats_.bytes_allocated,
                    client_state->visible_ ?
                        &bytes_allocated_managed_visible_ :
                        &bytes_allocated_managed_nonvisible_);
  ScheduleManage(visible ? kScheduleManageNow : kScheduleManageLater);
}

void GpuMemoryManager::SetClientStateManagedMemoryStats(
    GpuMemoryManagerClientState* client_state,
    const GpuManagedMemoryStats& stats)
{
  TrackValueChanged(client_state->managed_memory_stats_.bytes_allocated,
                    stats.bytes_allocated,
                    client_state->visible_ ?
                        &bytes_allocated_managed_visible_ :
                        &bytes_allocated_managed_nonvisible_);
  client_state->managed_memory_stats_ = stats;

  // If this is the first time that stats have been received for this
  // client, use them immediately.
  if (!client_state->managed_memory_stats_received_) {
    client_state->managed_memory_stats_received_ = true;
    ScheduleManage(kScheduleManageNow);
    return;
  }

  // If these statistics sit outside of the range that we used in our
  // computation of memory allocations then recompute the allocations.
  if (client_state->managed_memory_stats_.bytes_nice_to_have >
      client_state->bytes_nicetohave_limit_high_) {
    ScheduleManage(kScheduleManageNow);
  } else if (client_state->managed_memory_stats_.bytes_nice_to_have <
             client_state->bytes_nicetohave_limit_low_) {
    ScheduleManage(kScheduleManageLater);
  }
}

GpuMemoryTrackingGroup* GpuMemoryManager::CreateTrackingGroup(
    base::ProcessId pid, gpu::gles2::MemoryTracker* memory_tracker) {
  GpuMemoryTrackingGroup* tracking_group = new GpuMemoryTrackingGroup(
      pid, memory_tracker, this);
  DCHECK(!tracking_groups_.count(tracking_group->GetMemoryTracker()));
  tracking_groups_.insert(std::make_pair(tracking_group->GetMemoryTracker(),
                                         tracking_group));
  return tracking_group;
}

void GpuMemoryManager::OnDestroyTrackingGroup(
    GpuMemoryTrackingGroup* tracking_group) {
  DCHECK(tracking_groups_.count(tracking_group->GetMemoryTracker()));
  tracking_groups_.erase(tracking_group->GetMemoryTracker());
}

void GpuMemoryManager::GetVideoMemoryUsageStats(
    GPUVideoMemoryUsageStats* video_memory_usage_stats) const {
  // For each context group, assign its memory usage to its PID
  video_memory_usage_stats->process_map.clear();
  for (TrackingGroupMap::const_iterator i =
       tracking_groups_.begin(); i != tracking_groups_.end(); ++i) {
    const GpuMemoryTrackingGroup* tracking_group = i->second;
    video_memory_usage_stats->process_map[
        tracking_group->GetPid()].video_memory += tracking_group->GetSize();
  }

  // Assign the total across all processes in the GPU process
  video_memory_usage_stats->process_map[
      base::GetCurrentProcId()].video_memory = GetCurrentUsage();
  video_memory_usage_stats->process_map[
      base::GetCurrentProcId()].has_duplicates = true;

  video_memory_usage_stats->bytes_allocated = GetCurrentUsage();
  video_memory_usage_stats->bytes_allocated_historical_max =
      bytes_allocated_historical_max_;
}

void GpuMemoryManager::Manage() {
  manage_immediate_scheduled_ = false;
  delayed_manage_callback_.Cancel();

  // Update the amount of GPU memory available on the system.
  UpdateAvailableGpuMemory();

  // Update the limit on unmanaged memory.
  UpdateUnmanagedMemoryLimits();

  // Determine which clients are "hibernated" (which determines the
  // distribution of frontbuffers and memory among clients that don't have
  // surfaces).
  SetClientsHibernatedState();

  // Assign memory allocations to clients that have surfaces.
  AssignSurfacesAllocations();

  // Assign memory allocations to clients that don't have surfaces.
  AssignNonSurfacesAllocations();

  SendUmaStatsToBrowser();
}

// static
uint64 GpuMemoryManager::ComputeCap(
    std::vector<uint64> bytes, uint64 bytes_sum_limit)
{
  size_t bytes_size = bytes.size();
  uint64 bytes_sum = 0;

  if (bytes_size == 0)
    return std::numeric_limits<uint64>::max();

  // Sort and add up all entries
  std::sort(bytes.begin(), bytes.end());
  for (size_t i = 0; i < bytes_size; ++i)
    bytes_sum += bytes[i];

  // As we go through the below loop, let bytes_partial_sum be the
  // sum of bytes[0] + ... + bytes[bytes_size - i - 1]
  uint64 bytes_partial_sum = bytes_sum;

  // Try using each entry as a cap, and see where we get cut off.
  for (size_t i = 0; i < bytes_size; ++i) {
    // Try limiting cap to bytes[bytes_size - i - 1]
    uint64 test_cap = bytes[bytes_size - i - 1];
    uint64 bytes_sum_with_test_cap = i * test_cap + bytes_partial_sum;

    // If that fits, raise test_cap to give an even distribution to the
    // last i entries.
    if (bytes_sum_with_test_cap <= bytes_sum_limit) {
      if (i == 0)
        return std::numeric_limits<uint64>::max();
      else
        return test_cap + (bytes_sum_limit - bytes_sum_with_test_cap) / i;
    } else {
      bytes_partial_sum -= test_cap;
    }
  }

  // If we got here, then we can't fully accommodate any of the clients,
  // so distribute bytes_sum_limit evenly.
  return bytes_sum_limit / bytes_size;
}

uint64 GpuMemoryManager::ComputeClientAllocationWhenVisible(
    GpuMemoryManagerClientState* client_state,
    uint64 bytes_above_required_cap,
    uint64 bytes_above_minimum_cap,
    uint64 bytes_overall_cap) {
  GpuManagedMemoryStats* stats = &client_state->managed_memory_stats_;

  if (!client_state->managed_memory_stats_received_)
    return GetDefaultClientAllocation();

  uint64 bytes_required = 9 * stats->bytes_required / 8;
  bytes_required = std::min(bytes_required, GetMaximumClientAllocation());
  bytes_required = std::max(bytes_required, GetMinimumClientAllocation());

  uint64 bytes_nicetohave = 4 * stats->bytes_nice_to_have / 3;
  bytes_nicetohave = std::min(bytes_nicetohave, GetMaximumClientAllocation());
  bytes_nicetohave = std::max(bytes_nicetohave, GetMinimumClientAllocation());
  bytes_nicetohave = std::max(bytes_nicetohave, bytes_required);

  uint64 allocation = GetMinimumClientAllocation();
  allocation += std::min(bytes_required - GetMinimumClientAllocation(),
                         bytes_above_minimum_cap);
  allocation += std::min(bytes_nicetohave - bytes_required,
                         bytes_above_required_cap);
  allocation = std::min(allocation,
                        bytes_overall_cap);
  return allocation;
}

uint64 GpuMemoryManager::ComputeClientAllocationWhenNonvisible(
    GpuMemoryManagerClientState* client_state) {

  if (!client_state->managed_memory_stats_received_)
    return 0;

  return 9 * client_state->managed_memory_stats_.bytes_required / 8;
}

void GpuMemoryManager::ComputeVisibleSurfacesAllocations() {
  uint64 bytes_available_total = GetAvailableGpuMemory();
  uint64 bytes_above_required_cap = std::numeric_limits<uint64>::max();
  uint64 bytes_above_minimum_cap = std::numeric_limits<uint64>::max();
  uint64 bytes_overall_cap_visible = GetMaximumClientAllocation();

  // Compute memory usage at three levels
  // - painting everything that is nicetohave for visible clients
  // - painting only what that is visible
  // - giving every client the minimum allocation
  uint64 bytes_nicetohave_visible = 0;
  uint64 bytes_required_visible = 0;
  uint64 bytes_minimum_visible = 0;
  for (ClientStateList::const_iterator it = clients_visible_mru_.begin();
       it != clients_visible_mru_.end();
       ++it) {
    GpuMemoryManagerClientState* client_state = *it;
    client_state->bytes_allocation_ideal_nicetohave_ =
        ComputeClientAllocationWhenVisible(
            client_state,
            bytes_above_required_cap,
            bytes_above_minimum_cap,
            bytes_overall_cap_visible);
    client_state->bytes_allocation_ideal_required_ =
        ComputeClientAllocationWhenVisible(
            client_state,
            0,
            bytes_above_minimum_cap,
            bytes_overall_cap_visible);
    client_state->bytes_allocation_ideal_minimum_ =
        ComputeClientAllocationWhenVisible(
            client_state,
            0,
            0,
            bytes_overall_cap_visible);

    bytes_nicetohave_visible +=
        client_state->bytes_allocation_ideal_nicetohave_;
    bytes_required_visible +=
        client_state->bytes_allocation_ideal_required_;
    bytes_minimum_visible +=
        client_state->bytes_allocation_ideal_minimum_;
  }

  // Determine which of those three points we can satisfy, and limit
  // bytes_above_required_cap and bytes_above_minimum_cap to not go
  // over the limit.
  if (bytes_minimum_visible > bytes_available_total) {
    bytes_above_required_cap = 0;
    bytes_above_minimum_cap = 0;
  } else if (bytes_required_visible > bytes_available_total) {
    std::vector<uint64> bytes_to_fit;
    for (ClientStateList::const_iterator it = clients_visible_mru_.begin();
         it != clients_visible_mru_.end();
         ++it) {
      GpuMemoryManagerClientState* client_state = *it;
      bytes_to_fit.push_back(client_state->bytes_allocation_ideal_required_ -
                             client_state->bytes_allocation_ideal_minimum_);
    }
    bytes_above_required_cap = 0;
    bytes_above_minimum_cap = ComputeCap(
        bytes_to_fit, bytes_available_total - bytes_minimum_visible);
  } else if (bytes_nicetohave_visible > bytes_available_total) {
    std::vector<uint64> bytes_to_fit;
    for (ClientStateList::const_iterator it = clients_visible_mru_.begin();
         it != clients_visible_mru_.end();
         ++it) {
      GpuMemoryManagerClientState* client_state = *it;
      bytes_to_fit.push_back(client_state->bytes_allocation_ideal_nicetohave_ -
                             client_state->bytes_allocation_ideal_required_);
    }
    bytes_above_required_cap = ComputeCap(
        bytes_to_fit, bytes_available_total - bytes_required_visible);
    bytes_above_minimum_cap = std::numeric_limits<uint64>::max();
  }

  // Given those computed limits, set the actual memory allocations for the
  // visible clients, tracking the largest allocation and the total allocation
  // for future use.
  uint64 bytes_allocated_visible = 0;
  uint64 bytes_allocated_max_client_allocation = 0;
  for (ClientStateList::const_iterator it = clients_visible_mru_.begin();
       it != clients_visible_mru_.end();
       ++it) {
    GpuMemoryManagerClientState* client_state = *it;
    client_state->bytes_allocation_when_visible_ =
        ComputeClientAllocationWhenVisible(
            client_state,
            bytes_above_required_cap,
            bytes_above_minimum_cap,
            bytes_overall_cap_visible);
    bytes_allocated_visible += client_state->bytes_allocation_when_visible_;
    bytes_allocated_max_client_allocation = std::max(
        bytes_allocated_max_client_allocation,
        client_state->bytes_allocation_when_visible_);
  }

  // Set the limit for nonvisible clients for when they become visible.
  // Use the same formula, with a lowered overall cap to in case any of the
  // currently-nonvisible clients are much more resource-intensive than any
  // of the existing clients.
  uint64 bytes_overall_cap_nonvisible = bytes_allocated_max_client_allocation;
  if (bytes_available_total > bytes_allocated_visible) {
    bytes_overall_cap_nonvisible +=
        bytes_available_total - bytes_allocated_visible;
  }
  bytes_overall_cap_nonvisible = std::min(bytes_overall_cap_nonvisible,
                                          GetMaximumClientAllocation());
  for (ClientStateList::const_iterator it = clients_nonvisible_mru_.begin();
       it != clients_nonvisible_mru_.end();
       ++it) {
    GpuMemoryManagerClientState* client_state = *it;
    client_state->bytes_allocation_when_visible_ =
        ComputeClientAllocationWhenVisible(
            client_state,
            bytes_above_required_cap,
            bytes_above_minimum_cap,
            bytes_overall_cap_nonvisible);
  }
}

void GpuMemoryManager::ComputeNonvisibleSurfacesAllocations() {
  uint64 bytes_allocated_visible = 0;
  for (ClientStateList::const_iterator it = clients_visible_mru_.begin();
       it != clients_visible_mru_.end();
       ++it) {
    GpuMemoryManagerClientState* client_state = *it;
    bytes_allocated_visible += client_state->bytes_allocation_when_visible_;
  }

  // Allow up to 1/4 of the memory that was available for visible clients to
  // go to nonvisible clients.
  uint64 bytes_available_total = GetAvailableGpuMemory();
  uint64 bytes_available_nonvisible = 0;
  uint64 bytes_allocated_nonvisible = 0;
  if (bytes_available_total > bytes_allocated_visible) {
    bytes_available_nonvisible = std::min(
        bytes_available_total / 4,
        bytes_available_total - bytes_allocated_visible);
  }

  // On Android, always discard everything that is nonvisible.
#if defined(OS_ANDROID)
  bytes_available_nonvisible = 0;
#endif

  // Determine which now-visible clients should keep their contents when
  // they are made nonvisible.
  for (ClientStateList::const_iterator it = clients_visible_mru_.begin();
       it != clients_visible_mru_.end();
       ++it) {
    GpuMemoryManagerClientState* client_state = *it;

    // Compute the amount of space available have for this renderer when it is
    // nonvisible. Do not count this client's allocation while visible against
    // the nonvisible clients' allocation total.
    uint64 bytes_available_nonvisible_adjusted = std::min(
        bytes_available_nonvisible +
            client_state->bytes_allocation_when_visible_ / 4,
        bytes_available_total / 4);

    // Allow this client to keep its contents if they fit in the allocation.
    client_state->bytes_allocation_when_nonvisible_ =
        ComputeClientAllocationWhenNonvisible(client_state);
    if (client_state->bytes_allocation_when_nonvisible_ >
        bytes_available_nonvisible_adjusted)
      client_state->bytes_allocation_when_nonvisible_ = 0;
  }

  // Compute which currently nonvisible clients should keep their contents.
  for (ClientStateList::const_iterator it = clients_nonvisible_mru_.begin();
       it != clients_nonvisible_mru_.end();
       ++it) {
    GpuMemoryManagerClientState* client_state = *it;

    // If this client is nonvisible and has already had its contents discarded,
    // don't re-generate the contents until the client becomes visible again.
    if (!client_state->bytes_allocation_when_nonvisible_)
      continue;

    client_state->bytes_allocation_when_nonvisible_ =
        ComputeClientAllocationWhenNonvisible(client_state);

    // Take into account all more recently used nonvisible clients, and only if
    // this client still fits, all it to keep its contents.
    if (bytes_allocated_nonvisible +
        client_state->bytes_allocation_when_nonvisible_ >
        bytes_available_nonvisible) {
      client_state->bytes_allocation_when_nonvisible_ = 0;
    }
    bytes_allocated_nonvisible +=
        client_state->bytes_allocation_when_nonvisible_;
  }
}

void GpuMemoryManager::DistributeRemainingMemoryToVisibleSurfaces() {
  uint64 bytes_available_total = GetAvailableGpuMemory();
  uint64 bytes_allocated_total = 0;

  for (ClientStateList::const_iterator it = clients_visible_mru_.begin();
       it != clients_visible_mru_.end();
       ++it) {
    GpuMemoryManagerClientState* client_state = *it;
    bytes_allocated_total += client_state->bytes_allocation_when_visible_;
  }
  for (ClientStateList::const_iterator it = clients_nonvisible_mru_.begin();
       it != clients_nonvisible_mru_.end();
       ++it) {
    GpuMemoryManagerClientState* client_state = *it;
    bytes_allocated_total += client_state->bytes_allocation_when_nonvisible_;
  }

  if (bytes_allocated_total >= bytes_available_total)
    return;

  std::vector<uint64> bytes_extra_requests;
  for (ClientStateList::const_iterator it = clients_visible_mru_.begin();
       it != clients_visible_mru_.end();
       ++it) {
    GpuMemoryManagerClientState* client_state = *it;
    CHECK(GetMaximumClientAllocation() >=
          client_state->bytes_allocation_when_visible_);
    uint64 bytes_extra = GetMaximumClientAllocation() -
                         client_state->bytes_allocation_when_visible_;
    bytes_extra_requests.push_back(bytes_extra);
  }
  uint64 bytes_extra_cap = ComputeCap(
      bytes_extra_requests, bytes_available_total - bytes_allocated_total);
  for (ClientStateList::const_iterator it = clients_visible_mru_.begin();
       it != clients_visible_mru_.end();
       ++it) {
    GpuMemoryManagerClientState* client_state = *it;
    uint64 bytes_extra = GetMaximumClientAllocation() -
                         client_state->bytes_allocation_when_visible_;
    client_state->bytes_allocation_when_visible_ += std::min(
        bytes_extra, bytes_extra_cap);
  }
}

void GpuMemoryManager::AssignSurfacesAllocations() {
  // Compute allocation when for all clients.
  ComputeVisibleSurfacesAllocations();
  ComputeNonvisibleSurfacesAllocations();

  // Distribute the remaining memory to visible clients.
  DistributeRemainingMemoryToVisibleSurfaces();

  // Send that allocation to the clients.
  ClientStateList clients = clients_visible_mru_;
  clients.insert(clients.end(),
                 clients_nonvisible_mru_.begin(),
                 clients_nonvisible_mru_.end());
  for (ClientStateList::const_iterator it = clients.begin();
       it != clients.end();
       ++it) {
    GpuMemoryManagerClientState* client_state = *it;

    // Re-assign memory limits to this client when its "nice to have" bucket
    // grows or shrinks by 1/4.
    client_state->bytes_nicetohave_limit_high_ =
        5 * client_state->managed_memory_stats_.bytes_nice_to_have / 4;
    client_state->bytes_nicetohave_limit_low_ =
        3 * client_state->managed_memory_stats_.bytes_nice_to_have / 4;

    // Populate and send the allocation to the client
    GpuMemoryAllocation allocation;

    allocation.browser_allocation.suggest_have_frontbuffer =
        !client_state->hibernated_;

    allocation.renderer_allocation.bytes_limit_when_visible =
        client_state->bytes_allocation_when_visible_;
    // Use a more conservative memory allocation policy on Mac because the
    // platform is unstable when under memory pressure.
    // http://crbug.com/141377
    allocation.renderer_allocation.priority_cutoff_when_visible =
#if defined(OS_MACOSX)
        GpuMemoryAllocationForRenderer::kPriorityCutoffAllowNiceToHave;
#else
        GpuMemoryAllocationForRenderer::kPriorityCutoffAllowEverything;
#endif

    allocation.renderer_allocation.bytes_limit_when_not_visible =
        client_state->bytes_allocation_when_nonvisible_;
    allocation.renderer_allocation.priority_cutoff_when_not_visible =
        GpuMemoryAllocationForRenderer::kPriorityCutoffAllowOnlyRequired;

    client_state->client_->SetMemoryAllocation(allocation);
  }
}

void GpuMemoryManager::AssignNonSurfacesAllocations() {
  for (ClientStateList::const_iterator it = clients_nonsurface_.begin();
       it != clients_nonsurface_.end();
       ++it) {
    GpuMemoryManagerClientState* client_state = *it;
    GpuMemoryAllocation allocation;

    if (!client_state->hibernated_) {
      allocation.renderer_allocation.bytes_limit_when_visible =
          GetMinimumClientAllocation();
      allocation.renderer_allocation.priority_cutoff_when_visible =
          GpuMemoryAllocationForRenderer::kPriorityCutoffAllowEverything;
    }

    client_state->client_->SetMemoryAllocation(allocation);
  }
}

void GpuMemoryManager::SetClientsHibernatedState() const {
  // Re-set all tracking groups as being hibernated.
  for (TrackingGroupMap::const_iterator it = tracking_groups_.begin();
       it != tracking_groups_.end();
       ++it) {
    GpuMemoryTrackingGroup* tracking_group = it->second;
    tracking_group->hibernated_ = true;
  }
  // All clients with surfaces that are visible are non-hibernated.
  uint64 non_hibernated_clients = 0;
  for (ClientStateList::const_iterator it = clients_visible_mru_.begin();
       it != clients_visible_mru_.end();
       ++it) {
    GpuMemoryManagerClientState* client_state = *it;
    client_state->hibernated_ = false;
    client_state->tracking_group_->hibernated_ = false;
    non_hibernated_clients++;
  }
  // Then an additional few clients with surfaces are non-hibernated too, up to
  // a fixed limit.
  for (ClientStateList::const_iterator it = clients_nonvisible_mru_.begin();
       it != clients_nonvisible_mru_.end();
       ++it) {
    GpuMemoryManagerClientState* client_state = *it;
    if (non_hibernated_clients < max_surfaces_with_frontbuffer_soft_limit_) {
      client_state->hibernated_ = false;
      client_state->tracking_group_->hibernated_ = false;
      non_hibernated_clients++;
    } else {
      client_state->hibernated_ = true;
    }
  }
  // Clients that don't have surfaces are non-hibernated if they are
  // in a GL share group with a non-hibernated surface.
  for (ClientStateList::const_iterator it = clients_nonsurface_.begin();
       it != clients_nonsurface_.end();
       ++it) {
    GpuMemoryManagerClientState* client_state = *it;
    client_state->hibernated_ = client_state->tracking_group_->hibernated_;
  }
}

void GpuMemoryManager::SendUmaStatsToBrowser() {
  if (!channel_manager_)
    return;
  GPUMemoryUmaStats params;
  params.bytes_allocated_current = GetCurrentUsage();
  params.bytes_allocated_max = bytes_allocated_historical_max_;
  params.bytes_limit = bytes_available_gpu_memory_;
  params.client_count = clients_visible_mru_.size() +
                        clients_nonvisible_mru_.size() +
                        clients_nonsurface_.size();
  params.context_group_count = tracking_groups_.size();
  channel_manager_->Send(new GpuHostMsg_GpuMemoryUmaStats(params));
}

GpuMemoryManager::ClientStateList* GpuMemoryManager::GetClientList(
    GpuMemoryManagerClientState* client_state) {
  if (client_state->has_surface_) {
    if (client_state->visible_)
      return &clients_visible_mru_;
    else
      return &clients_nonvisible_mru_;
  }
  return &clients_nonsurface_;
}

void GpuMemoryManager::AddClientToList(
    GpuMemoryManagerClientState* client_state) {
  DCHECK(!client_state->list_iterator_valid_);
  ClientStateList* client_list = GetClientList(client_state);
  client_state->list_iterator_ = client_list->insert(
      client_list->begin(), client_state);
  client_state->list_iterator_valid_ = true;
}

void GpuMemoryManager::RemoveClientFromList(
    GpuMemoryManagerClientState* client_state) {
  DCHECK(client_state->list_iterator_valid_);
  ClientStateList* client_list = GetClientList(client_state);
  client_list->erase(client_state->list_iterator_);
  client_state->list_iterator_valid_ = false;
}

}  // namespace content


text:
/* isatty.c */

/* Dumb implementation so programs will at least run.  */

#include <sys/stat.h>

int
isatty (int fd)
{

  return 1;
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>HorizontalListView.RunningOutOfDataListener</title>
<meta name="date" content="2014-09-12">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

您的浏览器已禁用 JavaScript。

跳过导航链接

概览

程序包

类

使用

树

已过时

索引

帮助

上一个类

下一个类

框架

无框架

所有类

概要:

嵌套 |

字段 |

构造器 |

方法

详细资料:

字段 |

构造器 |

方法

org.kymjs.aframe.ui.widget

接口 HorizontalListView.RunningOutOfDataListener

封闭类:

HorizontalListView

public static interface HorizontalListView.RunningOutOfDataListener

This listener is used to allow notification when the HorizontalListView
 is running low on data to display.

方法概要

All Methods Instance Methods Abstract Methods

限定符和类型
方法和说明

void
onRunningOutOfData()

Called when the HorizontalListView is running out of data and has
 reached at least the provided threshold.

方法详细资料

onRunningOutOfData

void onRunningOutOfData()

Called when the HorizontalListView is running out of data and has
 reached at least the provided threshold.

跳过导航链接

概览

程序包

类

使用

树

已过时

索引

帮助

上一个类

下一个类

框架

无框架

所有类

概要:

嵌套 |

字段 |

构造器 |

方法

详细资料:

字段 |

构造器 |

方法


text:
// -----------------------------------------------------------------------
// <copyright file="StringExtension.cs" company="YamNet">
//   Copyright (c) 2013 YamNet contributors
// </copyright>
// -----------------------------------------------------------------------

namespace YamNet.Client
{
    using System;

    /// <summary>
    /// The string extension methods.
    /// </summary>
    public static class StringExtension
    {
        /// <summary>
        /// Checks whether the supplied string is a valid URI.
        /// </summary>
        /// <param name="value">The value.</param>
        /// <param name="uriKind">The uri kind.</param>
        /// <returns>The <see cref="bool"/>.</returns>
        public static bool IsUri(this string value, UriKind uriKind = UriKind.Absolute)
        {
            return
                !string.IsNullOrWhiteSpace(value)
                && Uri.IsWellFormedUriString(value, uriKind);
        }

        /// <summary>
        /// Convert the string to a valid URI.
        /// </summary>
        /// <param name="value">The value.</param>
        /// <param name="uriKind">The uri kind.</param>
        /// <returns>The <see cref="Uri"/>, or null if it is invalid URI.</returns>
        public static Uri ToUri(this string value, UriKind uriKind = UriKind.Absolute)
        {
            return
                (string.IsNullOrWhiteSpace(value) || !Uri.IsWellFormedUriString(value, uriKind))
                    ? null
                    : new Uri(value, uriKind);
        }
    }
}


text:
'''
Problem 7
28 December 2001

By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.

What is the 10 001st prime number?

----------------------------------------------------------
Created on 25.01.2012

@author: ahallmann
'''
import unittest
import timeit
from problem003 import generate_primes

def prime_at(nr):
    prime_nr = 1
    for prime in generate_primes():
        if prime_nr == nr:
            return prime
        prime_nr += 1

class Test(unittest.TestCase):
    def test_simple1(self):
        self.assertEqual(2, prime_at(1))
    def test_simple2(self):
        self.assertEqual(3, prime_at(2))
    def test_sample(self):
        self.assertEqual(13, prime_at(6))
    def test_answer(self):
        self.assertEqual(104743, prime_at(10001))

# -----------------------------------------

def run():
    return prime_at(10001)

if __name__ == '__main__':
    unittest.main()

if __name__ == '__main__':
    t = timeit.Timer("run()", "from __main__ import run")
    count = 10000
    print str(t.timeit(count)) + " seconds for " + str(count) + " runs"


text:
<?php
// This file is part of Book module for Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

defined('MOODLE_INTERNAL') || die;

/**
 * Migrate book files stored in moddata folders.
 *
 * Please note it was a big mistake to store the files there in the first place!
 *
 * @param stdClass $book
 * @param stdClass $context
 * @param string $path
 * @return void
 */
function mod_book_migrate_moddata_dir_to_legacy($book, $context, $path) {
    global $OUTPUT, $CFG;

    $base = "$CFG->dataroot/$book->course/$CFG->moddata/book/$book->id";
    $fulldir = $base.$path;

    if (!is_dir($fulldir)) {
        // does not exist
        return;
    }

    $fs      = get_file_storage();
    $items   = new DirectoryIterator($fulldir);

    foreach ($items as $item) {
        if ($item->isDot()) {
            unset($item); // release file handle
            continue;
        }

        if ($item->isLink()) {
            // do not follow symlinks - they were never supported in moddata, sorry
            unset($item); // release file handle
            continue;
        }

        if ($item->isFile()) {
            if (!$item->isReadable()) {
                echo $OUTPUT->notification(" File not readable, skipping: ".$fulldir.$item->getFilename());
                unset($item); // release file handle
                continue;
            }

            $filepath = clean_param("/$CFG->moddata/book/$book->id".$path, PARAM_PATH);
            $filename = clean_param($item->getFilename(), PARAM_FILE);

            if ($filename === '') {
                // unsupported chars, sorry
                unset($item); // release file handle
                continue;
            }

            if (textlib::strlen($filepath) > 255) {
                echo $OUTPUT->notification(" File path longer than 255 chars, skipping: ".$fulldir.$item->getFilename());
                unset($item); // release file handle
                continue;
            }

            if (!$fs->file_exists($context->id, 'course', 'legacy', '0', $filepath, $filename)) {
                $file_record = array('contextid'=>$context->id, 'component'=>'course', 'filearea'=>'legacy', 'itemid'=>0, 'filepath'=>$filepath, 'filename'=>$filename,
                                     'timecreated'=>$item->getCTime(), 'timemodified'=>$item->getMTime());
                $fs->create_file_from_pathname($file_record, $fulldir.$item->getFilename());
            }
            $oldpathname = $fulldir.$item->getFilename();
            unset($item); // release file handle
            @unlink($oldpathname);

        } else {
            // migrate recursively all subdirectories
            $oldpathname = $base.$item->getFilename().'/';
            $subpath     = $path.$item->getFilename().'/';
            unset($item);  // release file handle
            mod_book_migrate_moddata_dir_to_legacy($book, $context, $subpath);
            @rmdir($oldpathname); // deletes dir if empty
        }
    }
    unset($items); // release file handles
}

/**
 * Migrate legacy files in intro and chapters
 * @return void
 */
function mod_book_migrate_all_areas() {
    global $DB;

    $rsbooks = $DB->get_recordset('book');
    foreach($rsbooks as $book) {
        upgrade_set_timeout(360); // set up timeout, may also abort execution
        $cm = get_coursemodule_from_instance('book', $book->id);
        $context = context_module::instance($cm->id);
        mod_book_migrate_area($book, 'intro', 'book', $book->course, $context, 'mod_book', 'intro', 0);

        $rschapters = $DB->get_recordset('book_chapters', array('bookid'=>$book->id));
        foreach ($rschapters as $chapter) {
            mod_book_migrate_area($chapter, 'content', 'book_chapters', $book->course, $context, 'mod_book', 'chapter', $chapter->id);
        }
        $rschapters->close();
    }
    $rsbooks->close();
}

/**
 * Migrate one area, this should be probably part of moodle core...
 *
 * @param stdClass $record object to migrate files (book, chapter)
 * @param string $field field in the record we are going to migrate
 * @param string $table DB table containing the information to migrate
 * @param int $courseid id of the course the book module belongs to
 * @param context_module $context context of the book module
 * @param string $component component to be used for the migrated files
 * @param string $filearea filearea to be used for the migrated files
 * @param int $itemid id to be used for the migrated files
 * @return void
 */
function mod_book_migrate_area($record, $field, $table, $courseid, $context, $component, $filearea, $itemid) {
    global $CFG, $DB;

    $fs = get_file_storage();

    foreach(array(get_site()->id, $courseid) as $cid) {
        $matches = null;
        $ooldcontext = context_course::instance($cid);
        if (preg_match_all("|$CFG->wwwroot/file.php(\?file=)?/$cid(/[^\s'\"&\?#]+)|", $record->$field, $matches)) {
            $file_record = array('contextid'=>$context->id, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid);
            foreach ($matches[2] as $i=>$filepath) {
                if (!$file = $fs->get_file_by_hash(sha1("/$ooldcontext->id/course/legacy/0".$filepath))) {
                    continue;
                }
                try {
                    if (!$newfile = $fs->get_file_by_hash(sha1("/$context->id/$component/$filearea/$itemid".$filepath))) {
                        $fs->create_file_from_storedfile($file_record, $file);
                    }
                    $record->$field = str_replace($matches[0][$i], '@@PLUGINFILE@@'.$filepath, $record->$field);
                } catch (Exception $ex) {
                    // ignore problems
                }
                $DB->set_field($table, $field, $record->$field, array('id'=>$record->id));
            }
        }
    }
}