text:
/*
 * Created on May 26, 2005 TODO To change the template for this generated file go to Window -
 * Preferences - Java - Code Style - Code Templates
 */

package org.owasp.webgoat.plugin;

import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.encoding.XMLType;
import org.apache.ecs.Element;
import org.apache.ecs.ElementContainer;
import org.apache.ecs.html.A;
import org.apache.ecs.html.BR;
import org.apache.ecs.html.Input;
import org.apache.ecs.html.Option;
import org.apache.ecs.html.P;
import org.apache.ecs.html.Select;
import org.apache.ecs.html.TD;
import org.apache.ecs.html.TR;
import org.apache.ecs.html.Table;
import org.owasp.webgoat.lessons.Category;
import org.owasp.webgoat.lessons.LessonAdapter;
import org.owasp.webgoat.session.DatabaseUtilities;
import org.owasp.webgoat.session.ECSFactory;
import org.owasp.webgoat.session.WebSession;
import org.owasp.webgoat.session.WebgoatContext;

import javax.xml.namespace.QName;
import javax.xml.rpc.ParameterMode;
import javax.xml.rpc.ServiceException;
import java.rmi.RemoteException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/***************************************************************************************************
 *
 *
 * This file is part of WebGoat, an Open Web Application Security Project utility. For details,
 * please see http://www.owasp.org/
 *
 * Copyright (c) 2002 - 20014 Bruce Mayhew
 *
 * This program 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 2 of the
 * License, or (at your option) any later version.
 *
 * This program 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 this program; if
 * not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
 * 02111-1307, USA.
 *
 * Getting Source ==============
 *
 * Source for this application is maintained at https://github.com/WebGoat/WebGoat, a repository for free software
 * projects.
 *
 * For details, please see http://webgoat.github.io
 *
 * @author asmolen
 *
 *         TODO To change the template for this generated type comment go to Window - Preferences -
 *         Java - Code Style - Code Templates
 */
public class WSDLScanning extends LessonAdapter
{

    static boolean completed = false;

    static boolean beenRestartedYet = false;

    public final static String firstName = "getFirstName";

    public final static String lastName = "getLastName";

    public final static String loginCount = "getLoginCount";

    public final static String ccNumber = "getCreditCard";

    private static WebgoatContext webgoatContext;

    /**
     * We maintain a static reference to WebgoatContext, since this class is also automatically
     * instantiated by the Axis web services module, which does not call setWebgoatContext()
     * (non-Javadoc)
     *
     * @see org.owasp.webgoat.lessons.AbstractLesson#setWebgoatContext(org.owasp.webgoat.session.WebgoatContext)
     */
    @Override
    public void setWebgoatContext(WebgoatContext webgoatContext)
    {
        WSDLScanning.webgoatContext = webgoatContext;
    }

    @Override
    public WebgoatContext getWebgoatContext()
    {
        return WSDLScanning.webgoatContext;
    }

    protected Category getDefaultCategory()
    {
        return Category.WEB_SERVICES;
    }

    protected List<String> getHints(WebSession s)
    {
        List<String> hints = new ArrayList<String>();
        hints.add("Try connecting to the WSDL with a browser or Web Service tool.");
        hints.add("Sometimes the WSDL will define methods that are not available through a web API. "
                + "Try to find operations that are in the WSDL, but not part of this API");
        hints.add("The URL for the web service is: http://localhost/webgoat/services/WSDLScanning <br>"
                + "The WSDL can usually be viewed by adding a ?WSDL on the end of the request.");
        hints.add("Look in the WSDL for the getCreditCard operation and insert the field in an intercepted request.");
        return hints;
    }

    private final static Integer DEFAULT_RANKING = new Integer(120);

    protected Integer getDefaultRanking()
    {
        return DEFAULT_RANKING;
    }

    public String getTitle()
    {
        return "WSDL Scanning";
    }

    public Object accessWGService(WebSession s, String serv, int port, String proc, String parameterName, Object parameterValue)
    {
        String targetNamespace = "WebGoat";
        try
        {
            QName serviceName = new QName(targetNamespace, serv);
            QName operationName = new QName(targetNamespace, proc);
            Service service = new Service();
            Call call = (Call) service.createCall();
            call.setOperationName(operationName);
            call.addParameter(parameterName, serviceName, ParameterMode.INOUT);
            call.setReturnType(XMLType.XSD_STRING);
            call.setUsername("guest");
            call.setPassword("guest");
            call.setTargetEndpointAddress("http://localhost:" + port + "/" + s.getRequest().getContextPath() + "/services/" + serv);
            Object result = call.invoke(new Object[] { parameterValue });
            return result;
        } catch (RemoteException e)
        {
            e.printStackTrace();
        } catch (ServiceException e)
        {
            e.printStackTrace();
        } catch (Exception e)
        {
            e.printStackTrace();
        }
        return null;
    }

    protected Element createContent(WebSession s)
    {
        ElementContainer ec = new ElementContainer();

        Table t1 = new Table().setCellSpacing(0).setCellPadding(2);

        if (s.isColor())
        {
            t1.setBorder(1);
        }
        TR tr = new TR();
        tr.addElement(new TD("Enter your account number: "));
        tr.addElement(new TD(new Input(Input.TEXT, "id", "101")));
        t1.addElement(tr);

        tr = new TR();
        tr.addElement(new TD("Select the fields to return: "));
        tr.addElement(new TD(new Select("field").setMultiple(true).addElement(
                                                                                new Option(firstName)
                                                                                .addElement("First Name"))
                .addElement(new Option(lastName).addElement("Last Name"))
                .addElement(new Option(loginCount).addElement("Login Count"))));
        t1.addElement(tr);

        tr = new TR();
        Element b = ECSFactory.makeButton("Submit");
        tr.addElement(new TD(b).setAlign("CENTER").setColSpan(2));
        t1.addElement(tr);

        ec.addElement(t1);

        try
        {
            String[] fields = s.getParser().getParameterValues("field");
            int id = s.getParser().getIntParameter("id");

            Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(1);

            if (s.isColor())
            {
                t.setBorder(1);
            }
            TR header = new TR();
            TR results = new TR();
            int port = s.getRequest().getServerPort();
            for (int i = 0; i < fields.length; i++)
            {
                header.addElement(new TD().addElement(fields[i]));
                results.addElement(new TD().addElement((String) accessWGService(s, "WSDLScanning", port, fields[i],
                                                                                "acct_num", new Integer(id))));
            }
            if (fields.length == 0)
            {
                s.setMessage("Please select a value to return.");
            }
            t.addElement(header);
            t.addElement(results);
            ec.addElement(new P().addElement(t));
        } catch (Exception e)
        {

        }
        try
        {
            A a = new A("services/WSDLScanning?WSDL", "WebGoat WSDL File");
            ec.addElement(new P()
                    .addElement("View the web services definition language (WSDL) to see the complete API:"));
            ec.addElement(new BR());
            ec.addElement(a);
            // getLessonTracker( s ).setCompleted( completed );

            if (completed && !getLessonTracker(s).getCompleted() && !beenRestartedYet)
            {
                makeSuccess(s);
                beenRestartedYet = true;
            }
            else if (completed && !getLessonTracker(s).getCompleted() && beenRestartedYet)
            {
                completed = false;
                beenRestartedYet = false;
            }

            // accessWGService("WSDLScanning", "getCreditCard", "acct_num", new Integer(101));
        } catch (Exception e)
        {
            s.setMessage("Error generating " + this.getClass().getName());
            e.printStackTrace();
        }
        return (ec);
    }

    public String getResults(int id, String field)
    {
        try
        {
            Connection connection = DatabaseUtilities.getConnection("guest", getWebgoatContext());
            PreparedStatement ps = connection.prepareStatement("SELECT * FROM user_data WHERE userid = ?");
            ps.setInt(1, id);
            try
            {
                ResultSet results = ps.executeQuery();
                if ((results != null) && (results.next() == true)) { return results.getString(field); }
            } catch (SQLException sqle)
            {
            }
        } catch (Exception e)
        {
        }
        return null;
    }

    public String getCreditCard(int id)
    {
        String result = getResults(id, "cc_number");
        if (result != null)
        {
            completed = true;
            return result;
        }
        return null;
    }

    public String getFirstName(int id)
    {
        String result = getResults(id, "first_name");
        if (result != null) { return result; }
        return null;
    }

    public String getLastName(int id)
    {
        String result = getResults(id, "last_name");
        if (result != null) { return result; }
        return null;
    }

    public String getLoginCount(int id)
    {
        String result = getResults(id, "login_count");
        if (result != null) { return result; }
        return null;
    }

}


text:
using Arch.CFramework.AppInternals;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using Arch.CFramework.AppInternals.Components;
using System.Web;
using System.IO;
using System.Threading;
using Arch.CFX.Test.Common;

namespace Arch.CFramework.AppInternals.Test
{

    ///
    ///This is a test class for MenusContainerTest and is intended
    ///to contain all MenusContainerTest Unit Tests
    ///
    [TestClass()]
    public class MenusContainerTest
    {

        private TestContext testContextInstance;

        ///
        ///Gets or sets the test context which provides
        ///information about and functionality for the current test run.
        ///
        public TestContext TestContext
        {
            get
            {
                return testContextInstance;
            }
            set
            {
                testContextInstance = value;
            }
        }

        #region Additional test attributes
        //
        //You can use the following additional attributes as you write your tests:
        //
        //Use ClassInitialize to run code before running the first test in the class
        [ClassInitialize()]
        public static void MyClassInitialize(TestContext testContext)
        {

        }
        //
        //Use ClassCleanup to run code after all tests in a class have run
        [ClassCleanup()]
        public static void MyClassCleanup()
        {

        }
        //
        //Use TestInitialize to run code before running each test
        //[TestInitialize()]
        //public void MyTestInitialize()
        //{
        //}
        //
        //Use TestCleanup to run code after each test has run
        //[TestCleanup()]
        //public void MyTestCleanup()
        //{
        //}
        //
        #endregion

        ///
        ///A test for MenusContainer Constructor
        ///
        [TestMethod()]
        [DeploymentItem("Arch.CFramework.AppInternals.dll")]
        public void MenusContainerConstructorTest()
        {
            MenusContainer_Accessor target = new MenusContainer_Accessor();
            Assert.IsTrue(true);
        }

        ///
        ///A test for GetMenus
        ///
        [TestMethod()]
        public void GetMenusTest()
        {
            MenusContainer_Accessor target = new MenusContainer_Accessor(); // TODO: Initialize to an appropriate value
            ComponentCollection expected = null; // TODO: Initialize to an appropriate value
            ComponentCollection actual;
            //HttpRequest request = new HttpRequest("~/", "http://localhost/test/appinternals/configurations/beans/appsettingsbean", "action=view");

            //HttpResponse response = new HttpResponse(new StringWriter());
            //HttpContext context = new HttpContext(request, response);

            Thread.GetDomain().SetData(".appPath", AppDomain.CurrentDomain.BaseDirectory);
            Thread.GetDomain().SetData(".appVPath", "/");
            Thread.GetDomain().SetData(".appDomain", "*");
            TextWriter tw = new StringWriter();
            TestWorkerRequest wr = new TestWorkerRequest("/test/appinternals/configurations/beans/appsettingsbean", "", tw);
            wr.SetRemoteAddress("127.0.0.1");
            HttpContext.Current = new HttpContext(wr);

           // HttpContext.Current = context;
            actual = target.GetMenus();
            Assert.AreNotEqual(expected, actual);
            Assert.IsTrue(actual.Components.Count==6);
        }

        ///
        ///A test for SetMenus
        ///
        [TestMethod()]
        [DeploymentItem("Arch.CFramework.AppInternals.dll")]
        public void SetMenusTest()
        {
            MenusContainer_Accessor target = new MenusContainer_Accessor(); // TODO: Initialize to an appropriate value
            ComponentCollection expected = null; // TODO: Initialize to an appropriate value
            ComponentCollection actual;
            //HttpRequest request = new HttpRequest("~/", "http://localhost/test/appinternals/configurations/beans/appsettingsbean", "action=view");

            //HttpResponse response = new HttpResponse(new StringWriter());
            //HttpContext context = new HttpContext(request, response);
            //HttpContext.Current = context;

            Thread.GetDomain().SetData(".appPath", AppDomain.CurrentDomain.BaseDirectory);
            Thread.GetDomain().SetData(".appVPath", "/");
            Thread.GetDomain().SetData(".appDomain", "*");
            TextWriter tw = new StringWriter();
            TestWorkerRequest wr = new TestWorkerRequest("/test/appinternals/configurations/beans/appsettingsbean", "", tw);
            wr.SetRemoteAddress("127.0.0.1");
            HttpContext.Current = new HttpContext(wr);

            actual = target.SetMenus();
            Assert.AreNotEqual(expected, actual);
            Assert.IsTrue(actual.Components.Count == 6);
        }

        ///
        ///A test for Current
        ///
        [TestMethod()]
        public void CurrentTest()
        {
            MenusContainer actual;
            actual = MenusContainer.Current;
            Assert.IsNotNull(actual);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package customresourcedefinition

import (
	"context"
	"fmt"

	"k8s.io/apiextensions-apiserver/pkg/apis/apiextensions"
	"k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/validation"
	apiequality "k8s.io/apimachinery/pkg/api/equality"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/fields"
	"k8s.io/apimachinery/pkg/labels"
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/apimachinery/pkg/runtime/schema"
	"k8s.io/apimachinery/pkg/util/validation/field"
	genericapirequest "k8s.io/apiserver/pkg/endpoints/request"
	"k8s.io/apiserver/pkg/registry/generic"
	"k8s.io/apiserver/pkg/storage"
	"k8s.io/apiserver/pkg/storage/names"
	"sigs.k8s.io/structured-merge-diff/v4/fieldpath"
)

// strategy implements behavior for CustomResources.
type strategy struct {
	runtime.ObjectTyper
	names.NameGenerator
}

func NewStrategy(typer runtime.ObjectTyper) strategy {
	return strategy{typer, names.SimpleNameGenerator}
}

func (strategy) NamespaceScoped() bool {
	return false
}

// GetResetFields returns the set of fields that get reset by the strategy
// and should not be modified by the user.
func (strategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set {
	fields := map[fieldpath.APIVersion]*fieldpath.Set{
		"apiextensions.k8s.io/v1": fieldpath.NewSet(
			fieldpath.MakePathOrDie("status"),
		),
		"apiextensions.k8s.io/v1beta1": fieldpath.NewSet(
			fieldpath.MakePathOrDie("status"),
		),
	}

	return fields
}

// PrepareForCreate clears the status of a CustomResourceDefinition before creation.
func (strategy) PrepareForCreate(ctx context.Context, obj runtime.Object) {
	crd := obj.(*apiextensions.CustomResourceDefinition)
	crd.Status = apiextensions.CustomResourceDefinitionStatus{}
	crd.Generation = 1

	for _, v := range crd.Spec.Versions {
		if v.Storage {
			if !apiextensions.IsStoredVersion(crd, v.Name) {
				crd.Status.StoredVersions = append(crd.Status.StoredVersions, v.Name)
			}
			break
		}
	}
}

// PrepareForUpdate clears fields that are not allowed to be set by end users on update.
func (strategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {
	newCRD := obj.(*apiextensions.CustomResourceDefinition)
	oldCRD := old.(*apiextensions.CustomResourceDefinition)
	newCRD.Status = oldCRD.Status

	// Any changes to the spec increment the generation number, any changes to the
	// status should reflect the generation number of the corresponding object. We push
	// the burden of managing the status onto the clients because we can't (in general)
	// know here what version of spec the writer of the status has seen. It may seem like
	// we can at first -- since obj contains spec -- but in the future we will probably make
	// status its own object, and even if we don't, writes may be the result of a
	// read-update-write loop, so the contents of spec may not actually be the spec that
	// the controller has *seen*.
	if !apiequality.Semantic.DeepEqual(oldCRD.Spec, newCRD.Spec) {
		newCRD.Generation = oldCRD.Generation + 1
	}

	for _, v := range newCRD.Spec.Versions {
		if v.Storage {
			if !apiextensions.IsStoredVersion(newCRD, v.Name) {
				newCRD.Status.StoredVersions = append(newCRD.Status.StoredVersions, v.Name)
			}
			break
		}
	}
}

// Validate validates a new CustomResourceDefinition.
func (strategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList {
	var groupVersion schema.GroupVersion
	if requestInfo, found := genericapirequest.RequestInfoFrom(ctx); found {
		groupVersion = schema.GroupVersion{Group: requestInfo.APIGroup, Version: requestInfo.APIVersion}
	}

	return validation.ValidateCustomResourceDefinition(obj.(*apiextensions.CustomResourceDefinition), groupVersion)
}

// AllowCreateOnUpdate is false for CustomResourceDefinition; this means a POST is
// needed to create one.
func (strategy) AllowCreateOnUpdate() bool {
	return false
}

// AllowUnconditionalUpdate is the default update policy for CustomResourceDefinition objects.
func (strategy) AllowUnconditionalUpdate() bool {
	return false
}

// Canonicalize normalizes the object after validation.
func (strategy) Canonicalize(obj runtime.Object) {
}

// ValidateUpdate is the default update validation for an end user updating status.
func (strategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {
	var groupVersion schema.GroupVersion
	if requestInfo, found := genericapirequest.RequestInfoFrom(ctx); found {
		groupVersion = schema.GroupVersion{Group: requestInfo.APIGroup, Version: requestInfo.APIVersion}
	}

	return validation.ValidateCustomResourceDefinitionUpdate(obj.(*apiextensions.CustomResourceDefinition), old.(*apiextensions.CustomResourceDefinition), groupVersion)
}

type statusStrategy struct {
	runtime.ObjectTyper
	names.NameGenerator
}

func NewStatusStrategy(typer runtime.ObjectTyper) statusStrategy {
	return statusStrategy{typer, names.SimpleNameGenerator}
}

func (statusStrategy) NamespaceScoped() bool {
	return false
}

// GetResetFields returns the set of fields that get reset by the strategy
// and should not be modified by the user.
func (statusStrategy) GetResetFields() map[fieldpath.APIVersion]*fieldpath.Set {
	fields := map[fieldpath.APIVersion]*fieldpath.Set{
		"apiextensions.k8s.io/v1": fieldpath.NewSet(
			fieldpath.MakePathOrDie("metadata"),
			fieldpath.MakePathOrDie("spec"),
		),
		"apiextensions.k8s.io/v1beta1": fieldpath.NewSet(
			fieldpath.MakePathOrDie("metadata"),
			fieldpath.MakePathOrDie("spec"),
		),
	}

	return fields
}

func (statusStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {
	newObj := obj.(*apiextensions.CustomResourceDefinition)
	oldObj := old.(*apiextensions.CustomResourceDefinition)
	newObj.Spec = oldObj.Spec

	// Status updates are for only for updating status, not objectmeta.
	metav1.ResetObjectMetaForStatus(&newObj.ObjectMeta, &newObj.ObjectMeta)
}

func (statusStrategy) AllowCreateOnUpdate() bool {
	return false
}

func (statusStrategy) AllowUnconditionalUpdate() bool {
	return false
}

func (statusStrategy) Canonicalize(obj runtime.Object) {
}

func (statusStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {
	return validation.ValidateUpdateCustomResourceDefinitionStatus(obj.(*apiextensions.CustomResourceDefinition), old.(*apiextensions.CustomResourceDefinition))
}

// GetAttrs returns labels and fields of a given object for filtering purposes.
func GetAttrs(obj runtime.Object) (labels.Set, fields.Set, error) {
	apiserver, ok := obj.(*apiextensions.CustomResourceDefinition)
	if !ok {
		return nil, nil, fmt.Errorf("given object is not a CustomResourceDefinition")
	}
	return labels.Set(apiserver.ObjectMeta.Labels), CustomResourceDefinitionToSelectableFields(apiserver), nil
}

// MatchCustomResourceDefinition is the filter used by the generic etcd backend to watch events
// from etcd to clients of the apiserver only interested in specific labels/fields.
func MatchCustomResourceDefinition(label labels.Selector, field fields.Selector) storage.SelectionPredicate {
	return storage.SelectionPredicate{
		Label:    label,
		Field:    field,
		GetAttrs: GetAttrs,
	}
}

// CustomResourceDefinitionToSelectableFields returns a field set that represents the object.
func CustomResourceDefinitionToSelectableFields(obj *apiextensions.CustomResourceDefinition) fields.Set {
	return generic.ObjectMetaFieldsSet(&obj.ObjectMeta, true)
}


text:
// Copyright 2020 The Oppia Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * @fileoverview Controller for customize interaction modal.
 */

import { SubtitledHtml } from
  'domain/exploration/subtitled-html.model';
import { SubtitledUnicode } from
  'domain/exploration/SubtitledUnicodeObjectFactory';
import { Schema } from 'services/schema-default-value.service';
import { SchemaConstants } from
  'components/forms/schema-based-editors/schema.constants';

require(
  'components/common-layout-directives/common-elements/' +
  'confirm-or-cancel-modal.controller.ts');
require(
  'components/state-editor/state-editor-properties-services/' +
  'state-customization-args.service.ts');
require(
  'components/state-editor/state-editor-properties-services/' +
  'state-editor.service.ts');
require(
  'components/state-editor/state-editor-properties-services/' +
  'state-interaction-id.service.ts');
require(
  'components/state-editor/state-editor-properties-services/' +
  'state-next-content-id-index.service');
require('domain/exploration/InteractionObjectFactory.ts');
require('domain/utilities/url-interpolation.service.ts');
require(
  'pages/exploration-editor-page/editor-tab/services/' +
  'interaction-details-cache.service.ts');
require(
  'pages/exploration-editor-page/services/editor-first-time-events.service.ts');
require('services/context.service');

angular.module('oppia').controller('CustomizeInteractionModalController', [
  '$controller', '$injector', '$scope', '$uibModal', '$uibModalInstance',
  'ContextService', 'EditorFirstTimeEventsService',
  'InteractionDetailsCacheService', 'InteractionObjectFactory',
  'StateCustomizationArgsService', 'StateEditorService',
  'StateInteractionIdService', 'StateNextContentIdIndexService',
  'UrlInterpolationService',
  'showMarkAllAudioAsNeedingUpdateModalIfRequired',
  'ALLOWED_EXPLORATION_IN_STORY_INTERACTION_CATEGORIES',
  'ALLOWED_INTERACTION_CATEGORIES',
  'ALLOWED_QUESTION_INTERACTION_CATEGORIES',
  'COMPONENT_NAME_INTERACTION_CUSTOMIZATION_ARGS',
  'INTERACTION_SPECS',
  function(
      $controller, $injector, $scope, $uibModal, $uibModalInstance,
      ContextService, EditorFirstTimeEventsService,
      InteractionDetailsCacheService, InteractionObjectFactory,
      StateCustomizationArgsService, StateEditorService,
      StateInteractionIdService, StateNextContentIdIndexService,
      UrlInterpolationService,
      showMarkAllAudioAsNeedingUpdateModalIfRequired,
      ALLOWED_EXPLORATION_IN_STORY_INTERACTION_CATEGORIES,
      ALLOWED_INTERACTION_CATEGORIES,
      ALLOWED_QUESTION_INTERACTION_CATEGORIES,
      COMPONENT_NAME_INTERACTION_CUSTOMIZATION_ARGS,
      INTERACTION_SPECS) {
    $controller('ConfirmOrCancelModalController', {
      $scope: $scope,
      $uibModalInstance: $uibModalInstance
    });
    EditorFirstTimeEventsService
      .registerFirstClickAddInteractionEvent();

    // This binds the services to the HTML template, so that
    // their displayed values can be used in the HTML.
    $scope.StateInteractionIdService = StateInteractionIdService;
    $scope.StateCustomizationArgsService = StateCustomizationArgsService;
    $scope.getInteractionThumbnailImageUrl = function(interactionId) {
      return UrlInterpolationService.getInteractionThumbnailImageUrl(
        interactionId);
    };

    $scope.INTERACTION_SPECS = INTERACTION_SPECS;

    if (StateEditorService.isInQuestionMode()) {
      $scope.ALLOWED_INTERACTION_CATEGORIES = (
        ALLOWED_QUESTION_INTERACTION_CATEGORIES);
    } else if (ContextService.isExplorationLinkedToStory()) {
      $scope.ALLOWED_INTERACTION_CATEGORIES = (
        ALLOWED_EXPLORATION_IN_STORY_INTERACTION_CATEGORIES);
    } else {
      $scope.ALLOWED_INTERACTION_CATEGORIES = (
        ALLOWED_INTERACTION_CATEGORIES);
    }

    if (StateInteractionIdService.savedMemento) {
      $scope.customizationModalReopened = true;
      var interactionSpec = INTERACTION_SPECS[
        StateInteractionIdService.savedMemento];
      $scope.customizationArgSpecs = interactionSpec.customization_arg_specs;

      StateInteractionIdService.displayed = angular.copy(
        StateInteractionIdService.savedMemento);
      StateCustomizationArgsService.displayed = (
        StateCustomizationArgsService.savedMemento);

      // Ensure that StateCustomizationArgsService.displayed is
      // fully populated.
      for (var i = 0; i < $scope.customizationArgSpecs.length; i++) {
        var argName = $scope.customizationArgSpecs[i].name;
        if (
          !StateCustomizationArgsService.savedMemento.hasOwnProperty(argName)
        ) {
          throw new Error(
            `Interaction is missing customization argument ${argName}`);
        }
      }

      StateCustomizationArgsService.onSchemaBasedFormsShown.emit();
      $scope.form = {};
      $scope.hasCustomizationArgs = (
        StateCustomizationArgsService.displayed &&
        Object.keys(StateCustomizationArgsService.displayed).length > 0
      );
    }

    $scope.getCustomizationArgsWarningsList = function() {
      var validationServiceName =
        INTERACTION_SPECS[
          $scope.StateInteractionIdService.displayed].id +
        'ValidationService';
      var validationService = $injector.get(validationServiceName);
      var warningsList = validationService.getCustomizationArgsWarnings(
        StateCustomizationArgsService.displayed);
      return warningsList;
    };

    $scope.getCustomizationArgsWarningMessage = function() {
      var warningsList = (
        $scope.getCustomizationArgsWarningsList());
      var warningMessage = '';
      if (warningsList.length !== 0) {
        warningMessage = warningsList[0].message;
      }
      return warningMessage;
    };

    $scope.onChangeInteractionId = function(newInteractionId) {
      EditorFirstTimeEventsService
        .registerFirstSelectInteractionTypeEvent();

      var interactionSpec = INTERACTION_SPECS[newInteractionId];
      $scope.customizationArgSpecs = (
        interactionSpec.customization_arg_specs);

      StateInteractionIdService.displayed = newInteractionId;
      StateCustomizationArgsService.displayed = {};
      if (
        InteractionDetailsCacheService.contains(
          newInteractionId)) {
        StateCustomizationArgsService.displayed = (
          InteractionDetailsCacheService.get(
            newInteractionId).customization);
      } else {
        const customizationArgsBackendDict = {};
        $scope.customizationArgSpecs.forEach(function(caSpec) {
          customizationArgsBackendDict[caSpec.name] = {
            value: caSpec.default_value
          };
        });

        StateCustomizationArgsService.displayed = (
          InteractionObjectFactory.convertFromCustomizationArgsBackendDict(
            newInteractionId,
            customizationArgsBackendDict
          )
        );
      }

      if (Object.keys(
        StateCustomizationArgsService.displayed).length === 0) {
        $scope.save();
        $scope.hasCustomizationArgs = false;
      } else {
        $scope.hasCustomizationArgs = true;
      }

      StateCustomizationArgsService.onSchemaBasedFormsShown.emit();
      $scope.form = {};
    };

    $scope.returnToInteractionSelector = function() {
      InteractionDetailsCacheService.set(
        StateInteractionIdService.displayed,
        StateCustomizationArgsService.displayed);

      StateInteractionIdService.displayed = null;
      StateCustomizationArgsService.displayed = {};
    };

    $scope.isSaveInteractionButtonEnabled = function() {
      return !!(
        $scope.hasCustomizationArgs &&
        $scope.StateInteractionIdService.displayed &&
        $scope.form.schemaForm.$valid &&
        ($scope.getCustomizationArgsWarningsList().length === 0));
    };

    $scope.getSaveInteractionButtonTooltip = function() {
      if (!$scope.hasCustomizationArgs) {
        return 'No customization arguments';
      }
      if (!$scope.StateInteractionIdService.displayed) {
        return 'No interaction being displayed';
      }

      var warningsList =
        $scope.getCustomizationArgsWarningsList();
      var warningMessages = warningsList.map(function(warning) {
        return warning.message;
      });

      if (warningMessages.length === 0) {
        if ($scope.form.schemaForm.$invalid) {
          return 'Some of the form entries are invalid.';
        } else {
          return '';
        }
      } else {
        return warningMessages.join(' ');
      }
    };

    $scope.cancelWithConfirm = function() {
      // Do nothing if the confirmation modal is already open.
      if ($('.modal-title').text().includes('Confirmation Required')) {
        return;
      }
      $uibModal.open({
        template: require(
          'pages/exploration-editor-page/modal-templates/' +
          'confirm-leave-modal.template.html'),
        backdrop: 'static',
        keyboard: false,
        controller: 'ConfirmOrCancelModalController'
      }).result.then(function() {
        $scope.cancel();
      }, function() {
        // Note to developers:
        // This callback is triggered when the Cancel button is clicked.
        // No further action is needed.
      });
    };

    /**
     * The default values of SubtitledHtml and SubtitledUnicode objects in the
     * customization arguments have a null content_id. This function populates
     * these null content_id's with a content_id generated from traversing the
     * schema and with next content id index, ensuring a unique content_id.
     */
    $scope.populateNullContentIds = function() {
      const interactionId = $scope.StateInteractionIdService.displayed;

      let traverseSchemaAndAssignContentIds = (
          value: Object | Object[],
          schema: Schema,
          contentIdPrefix: string,
      ): void => {
        const schemaIsSubtitledHtml = (
          schema.type === SchemaConstants.SCHEMA_TYPE_CUSTOM &&
          schema.obj_type === SchemaConstants.SCHEMA_OBJ_TYPE_SUBTITLED_HTML);
        const schemaIsSubtitledUnicode = (
          schema.type === SchemaConstants.SCHEMA_TYPE_CUSTOM &&
          schema.obj_type === SchemaConstants.SCHEMA_OBJ_TYPE_SUBTITLED_UNICODE
        );

        if (schemaIsSubtitledHtml || schemaIsSubtitledUnicode) {
          if ((value as SubtitledHtml|SubtitledUnicode).contentId === null) {
            (value as SubtitledHtml|SubtitledUnicode).contentId = (
              `${contentIdPrefix}_${StateNextContentIdIndexService.displayed}`
            );
            StateNextContentIdIndexService.displayed += 1;
          }
        } else if (schema.type === SchemaConstants.SCHEMA_KEY_LIST) {
          for (
            let i = 0;
            i < (value as Object[]).length;
            i++
          ) {
            traverseSchemaAndAssignContentIds(
              value[i],
              schema.items as Schema,
              `${contentIdPrefix}`);
          }
        } else if (schema.type === SchemaConstants.SCHEMA_TYPE_DICT) {
          schema.properties.forEach(property => {
            const name = property.name;
            traverseSchemaAndAssignContentIds(
              value[name],
              property.schema,
              `${contentIdPrefix}_${name}`);
          });
        }
      };

      const caSpecs = INTERACTION_SPECS[interactionId].customization_arg_specs;
      const caValues = StateCustomizationArgsService.displayed;
      for (const caSpec of caSpecs) {
        const name = caSpec.name;
        if (caValues.hasOwnProperty(name)) {
          traverseSchemaAndAssignContentIds(
            caValues[name].value,
            caSpec.schema,
            `${COMPONENT_NAME_INTERACTION_CUSTOMIZATION_ARGS}_${name}`);
        }
      }
    };

    /**
     * Extracts a mapping of content ids to the html or unicode content found
     * in the customization arguments.
     * @returns {Object} A Mapping of content ids (string) to content (string).
     */
    $scope.getContentIdToContent = function() {
      const interactionId = $scope.StateInteractionIdService.displayed;
      const contentIdToContent = {};

      let traverseSchemaAndCollectContent = (
          value: Object | Object[],
          schema: Schema
      ): void => {
        const schemaIsSubtitledHtml = (
          schema.type === SchemaConstants.SCHEMA_TYPE_CUSTOM &&
          schema.obj_type === SchemaConstants.SCHEMA_OBJ_TYPE_SUBTITLED_HTML);
        const schemaIsSubtitledUnicode = (
          schema.type === SchemaConstants.SCHEMA_TYPE_CUSTOM &&
          schema.obj_type === SchemaConstants.SCHEMA_OBJ_TYPE_SUBTITLED_UNICODE
        );

        if (schemaIsSubtitledHtml) {
          const subtitledHtmlValue = value as SubtitledHtml;
          contentIdToContent[
            subtitledHtmlValue.contentId
          ] = subtitledHtmlValue.html;
        } else if (schemaIsSubtitledUnicode) {
          const subtitledUnicodeValue = value as SubtitledUnicode;
          contentIdToContent[
            subtitledUnicodeValue.contentId
          ] = subtitledUnicodeValue.unicode;
        } else if (schema.type === SchemaConstants.SCHEMA_KEY_LIST) {
          for (let i = 0; i < (value as Object[]).length; i++) {
            traverseSchemaAndCollectContent(value[i], schema.items as Schema);
          }
        } else if (schema.type === SchemaConstants.SCHEMA_TYPE_DICT) {
          schema.properties.forEach(property => {
            const name = property.name;
            traverseSchemaAndCollectContent(value[name], property.schema);
          });
        }
      };

      const caSpecs = INTERACTION_SPECS[interactionId].customization_arg_specs;
      const caValues = StateCustomizationArgsService.displayed;
      for (const caSpec of caSpecs) {
        const name = caSpec.name;
        if (caValues.hasOwnProperty(name)) {
          traverseSchemaAndCollectContent(caValues[name].value, caSpec.schema);
        }
      }

      return contentIdToContent;
    };

    $scope.save = function() {
      const updatedContentIdToContent = $scope.getContentIdToContent(
        StateCustomizationArgsService.displayed);
      const contentIdsWithModifiedContent = [];
      Object.keys($scope.originalContentIdToContent).forEach(contentId => {
        if (
          $scope.originalContentIdToContent.hasOwnProperty(contentId) &&
          updatedContentIdToContent.hasOwnProperty(contentId) &&
          ($scope.originalContentIdToContent[contentId] !==
            updatedContentIdToContent[contentId])
        ) {
          contentIdsWithModifiedContent.push(contentId);
        }
      });
      showMarkAllAudioAsNeedingUpdateModalIfRequired(
        contentIdsWithModifiedContent);

      $scope.populateNullContentIds();
      EditorFirstTimeEventsService.registerFirstSaveInteractionEvent();
      $uibModalInstance.close();
    };

    $scope.getHyphenatedLowercaseCategoryName = function(categoryName) {
      return categoryName && categoryName.replace(/\s/g, '-').toLowerCase();
    };

    $scope.init = function() {
      $scope.originalContentIdToContent = {};
      if (StateInteractionIdService.savedMemento) {
        // We track the original html or unicode for each content id so that we
        // can detect changes in $scope.save().
        $scope.originalContentIdToContent = $scope.getContentIdToContent(
          StateCustomizationArgsService.displayed);
      }
      $scope.explorationIsLinkedToStory = (
        ContextService.isExplorationLinkedToStory());
    };

    $scope.init();
  }
]);


text:
local BaseObj = class("BaseObj",function()
    return display.newNode()
end)

function BaseObj:ctor()
	self.info = {}
	self.info.node = nil  --所在四叉树节点
	self.info.lastIndex = 0  --上一帧所在节点的象限
	self.info.nowIndex = 0  --当前帧所在节点的象限
end

function BaseObj:getInfo()
	return self.info
end

function BaseObj:getRect()
	return cc.rect(0,0,0,0)
end

function BaseObj:setNode(node)
	self.info.node = node
end

return BaseObj


text:
local Workbook = require "xlsxwriter.workbook"

local workbook  = Workbook:new("test_print_options01.xlsx")
local worksheet = workbook:add_worksheet()

worksheet:hide_gridlines(0)
worksheet:write_string("A1", "Foo")

workbook:close()


text:
package net.antonywarner.guava.eventbus.annotations;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import com.google.common.eventbus.EventBus;

/**
 * Declares that the return value of a method invocation should be posted to an {@link EventBus}
 *
 * @author Antony Warner
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Publish {

}


text:
from rqt_gui_py.plugin import Plugin
from python_qt_binding.QtGui import (QAction, QIcon, QMenu, QWidget,
                                     QPainter, QColor, QFont, QBrush,
                                     QPen)
from python_qt_binding.QtCore import Qt, QTimer, qWarning, Slot, QEvent
from threading import Lock
import rospy
import python_qt_binding.QtCore as QtCore
from std_msgs.msg import Bool, Time
import math

class DRCEnvironmentViewer(Plugin):
    def __init__(self, context):
        super(DRCEnvironmentViewer, self).__init__(context)
        self.setObjectName("DRCEnvironmentViewer")
        self._widget = DRCEnvironmentViewerWidget()
        context.add_widget(self._widget)

class DRCEnvironmentViewerWidget(QWidget):
    _SMILEY = ":)"
    _FROWN = ":("
    _OK_COLOR = QColor("#18FFFF")
    _DISABLED_COLOR = QColor("#BDBDBD")
    _BLACKOUT_COLOR = QColor("#F44336")
    def __init__(self):
        self.lock = Lock()
        super(DRCEnvironmentViewerWidget, self).__init__()
        self.is_disabled = False
        self.is_blackout = False
        self.next_whiteout_time = rospy.Time.now()
        self.blackout_time = rospy.Time.now()
        self.event = None
        self.sub_is_disabled = rospy.Subscriber("/drc_2015_environment/is_disabled",
                                                Bool, self.isDisabledCallback)
        self.sub_is_blackout = rospy.Subscriber("/drc_2015_environment/is_blackout",
                                                Bool, self.isBlackoutCallback)
        self.sub_next_whiteout_time = rospy.Subscriber("/drc_2015_environment/next_whiteout_time",
                                                       Time, self.nextWhiteoutTimeCallback)
        self._update_plot_timer = QTimer(self)
        self._update_plot_timer.timeout.connect(self.redraw)
        self._update_plot_timer.start(1000 / 15)
    def isDisabledCallback(self, msg):
        with self.lock:
            self.is_disabled = msg.data
    def isBlackoutCallback(self, msg):
        with self.lock:
            if not self.is_blackout and msg.data:
                self.blackout_time = rospy.Time.now()
            self.is_blackout = msg.data
    def nextWhiteoutTimeCallback(self, msg):
        with self.lock:
            self.next_whiteout_time = msg.data
    def redraw(self):
        self.update()
        # if self.event:
        #     self.paintEvent(self.event)
    def paintEvent(self, event):
        with self.lock:
            self.event = event
            rect = event.rect()
            qp = QPainter()
            qp.begin(self)
            radius = min(rect.width(), rect.height()) - 50
            qp.setFont(QFont('Helvetica', 100))
            qp.setPen(QPen(QBrush(QColor(255, 255, 255)), 20))

            if self.is_disabled:
                qp.fillRect(rect, self._DISABLED_COLOR)
                qp.drawText(rect, QtCore.Qt.AlignCenter, self._FROWN)
            elif self.is_blackout:
                qp.fillRect(rect, self._BLACKOUT_COLOR)
                qp.drawText(rect, QtCore.Qt.AlignCenter, self._FROWN)
                time_diff = (self.next_whiteout_time - rospy.Time.now()).to_sec()
                if time_diff < 0:
                    time_diff = 0
                time_ratio = time_diff / (self.next_whiteout_time - self.blackout_time).to_sec()
                qp.setFont(QFont('Helvetica', 30))
                qp.drawText(0, rect.height() - 150, rect.width(), 150, QtCore.Qt.AlignCenter, "%.1f sec" % time_diff)
                # 0-360
                if time_ratio > 0:
                    rad = int(math.fmod(time_ratio * 360 + 90*16, 360) * 16)
                    qp.drawArc((rect.width() - radius) / 2, (rect.height() - radius) / 2, radius, radius, 90*16, rad)
            else:
                qp.fillRect(rect, self._OK_COLOR)
                qp.drawText(rect, QtCore.Qt.AlignCenter, self._SMILEY)
            qp.end()


text:
<?php

namespace Mesd\Jasper\ReportBundle\DependencyInjection;

use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;

class Configuration implements ConfigurationInterface
{
    public function getConfigTreeBuilder()
    {
        $builder = new TreeBuilder();

        $builder->root('mesd_jasper_report')
            ->addDefaultsIfNotSet()
            ->children()
                ->scalarNode('default_folder')->defaultValue('/reports')->end()
                ->scalarNode('version')->defaultValue('5.5.0')->end()
                ->arrayNode('connection')
                    ->addDefaultsIfNotSet()
                    ->children()
                        ->scalarNode('username')->defaultValue('please_change')->end()
                        ->scalarNode('password')->defaultValue('please_change')->end()
                        ->scalarNode('host')->defaultValue('please_change')->end()
                        ->scalarNode('port')->defaultValue('8080')->end()
                    ->end()
                ->end()
                ->arrayNode('folder_cache')
                    ->addDefaultsIfNotSet()
                    ->children()
                        ->booleanNode('use_cache')->defaultTrue()->end()
                        ->scalarNode('cache_dir')->defaultValue('../app/cache/jasper_resource_list/')->end()
                        ->scalarNode('cache_timeout')->defaultValue(30)->end()
                    ->end()
                ->end()
                ->arrayNode('report_cache')
                    ->addDefaultsIfNotSet()
                    ->children()
                        ->booleanNode('use_cache')->defaultTrue()->end()
                        ->scalarNode('cache_dir')->defaultValue('../report-store/reports/')->end()
                    ->end()
                ->end()
                ->arrayNode('display')
                    ->addDefaultsIfNotSet()
                    ->children()
                        ->scalarNode('default_export_route')->defaultValue('MesdJasperReportBundle_export_cached_report')->end()
                    ->end()
                ->end()
                ->arrayNode('report_loader')
                    ->addDefaultsIfNotSet()
                    ->children()
                        ->scalarNode('default_page')->defaultValue(1)->end()
                        ->scalarNode('default_attach_asset_url')->defaultTrue()->end()
                        ->scalarNode('default_asset_route')->defaultValue('MesdJasperReportBundle_render_cached_asset')->end()
                    ->end()
                ->end()
                ->arrayNode('report_history')
                    ->addDefaultsIfNotSet()
                    ->children()
                        ->scalarNode('entity_manager')->defaultValue('default')->end()
                    ->end()
                ->end()
                ->scalarNode('options_handler')->defaultValue('mesd.jasper.report.default_options_handler')->end()
                ->scalarNode('forms_handler')->defaultValue('mesd.jasper.report.default_options_handler')->end()
                ->scalarNode('default_input_options_source')->defaultValue('Fallback')->end()
                ->arrayNode('report_security')
                    ->addDefaultsIfNotSet()
                    ->children()
                        ->scalarNode('use_security')->defaultTrue()->end()
                        ->scalarNode('max_level_set_at_default')->defaultTrue()->end()
                        ->scalarNode('security_file')->defaultValue('/config/report_security.yml')->end()
                        ->arrayNode('default_roles')
                            ->defaultValue(array('ROLE_USER', 'ROLE_ADMIN', 'ROLE_SUPERADMIN'))
                            ->prototype('scalar')
                            ->end()
                        ->end()
                    ->end()
                ->end()
            ->end()
        ;
        return $builder;
    }
}


text:
define('async-not-index@0.1.0/lib/relative.js', [], function(require, exports, module){
    module.exports = function(n){
        return n + 1;
    };
});


text:
package org.atlasapi.generation.output;

import java.util.Set;

import org.atlasapi.generation.model.FieldInfo;
import org.atlasapi.generation.model.JsonType;
import org.atlasapi.generation.model.ModelClassInfo;
import org.atlasapi.generation.model.ModelMethodInfo;
import org.atlasapi.generation.model.ModelTypeInfo;

import com.google.common.collect.ImmutableSet;

public class ModelClassInfoSourceGenerator
        extends AbstractSourceGenerator<ModelTypeInfo, ModelMethodInfo> {

    @Override
    public Set<Class<?>> importedClasses() {
        return ImmutableSet.<Class<?>>builder()
                .add(Set.class)
                .add(ImmutableSet.class)
                .add(ModelClassInfo.class)
                .add(FieldInfo.class)
                .add(JsonType.class)
                .build();
    }

    @Override
    public Class<?> inheritedInterfaceName() {
        return ModelClassInfo.class;
    }

    @Override
    public String setName() {
        return "fields";
    }

    @Override
    public Class<?> setType() {
        return FieldInfo.class;
    }

    // TODO fix this and tidy it up (remove all these ghastly tabs, for one thing)
    // need to define boundaries between this and where it's used more clearly
    // can the logic that parses params from methods/types be pulled out from the source creation code?
    // if so, what's the intermediate form?
    @Override
    public String setElementFromMethod(ModelMethodInfo method, String indent) {
        StringBuilder setElement = new StringBuilder();

        setElement.append(indent);
        setElement.append("FieldInfo.builder()\n");

        setElement.append(createBuilderMethod(
                indent + TAB,
                "withName",
                addQuotesToString(method.name())
        ));
        setElement.append(createBuilderMethod(
                indent + TAB,
                "withDescription",
                addQuotesToString(method.description())
        ));
        setElement.append(createBuilderMethod(
                indent + TAB,
                "withType",
                addQuotesToString(method.type())
        ));
        setElement.append(createBuilderMethod(
                indent + TAB,
                "withIsMultiple",
                method.isMultiple().toString()
        ));
        setElement.append(createBuilderMethod(
                indent + TAB,
                "withIsModelType",
                method.isModelType().toString()
        ));
        setElement.append(createBuilderMethod(
                indent + TAB,
                "withJsonType",
                "JsonType." + method.jsonType().name()
        ));

        setElement.append(indent + TAB);
        setElement.append(".build()");

        return setElement.toString();
    }

    private String createBuilderMethod(String whitespace, String methodName, String paramValue) {
        return new StringBuilder()
                .append(whitespace)
                .append(".")
                .append(methodName)
                .append("(")
                .append(paramValue)
                .append(")\n")
                .toString();
    }

    @Override
    public String generateTypeBasedFields(ModelTypeInfo typeInfo) {
        return new StringBuilder()
                .append(formatOverriddenMethod("key", "String", typeInfo.key()))
                .append(NEWLINE)
                .append(formatOverriddenMethod("description", "String", typeInfo.description()))
                .append(NEWLINE)
                .append(formatOverriddenMethod("describedType", "Class<?>", typeInfo.parsedClass()))
                .toString();
    }
}


text:
#include <aws/rekognition/model/SegmentTypeInfo.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Utils::Json;
using namespace Aws::Utils;

namespace Aws
{
namespace Rekognition
{
namespace Model
{

SegmentTypeInfo::SegmentTypeInfo() :
    m_type(SegmentType::NOT_SET),
    m_typeHasBeenSet(false),
    m_modelVersionHasBeenSet(false)
{
}

SegmentTypeInfo::SegmentTypeInfo(JsonView jsonValue) :
    m_type(SegmentType::NOT_SET),
    m_typeHasBeenSet(false),
    m_modelVersionHasBeenSet(false)
{
  *this = jsonValue;
}

SegmentTypeInfo& SegmentTypeInfo::operator =(JsonView jsonValue)
{
  if(jsonValue.ValueExists("Type"))
  {
    m_type = SegmentTypeMapper::GetSegmentTypeForName(jsonValue.GetString("Type"));

    m_typeHasBeenSet = true;
  }

  if(jsonValue.ValueExists("ModelVersion"))
  {
    m_modelVersion = jsonValue.GetString("ModelVersion");

    m_modelVersionHasBeenSet = true;
  }

  return *this;
}

JsonValue SegmentTypeInfo::Jsonize() const
{
  JsonValue payload;

  if(m_typeHasBeenSet)
  {
   payload.WithString("Type", SegmentTypeMapper::GetNameForSegmentType(m_type));
  }

  if(m_modelVersionHasBeenSet)
  {
   payload.WithString("ModelVersion", m_modelVersion);

  }

  return payload;
}

} // namespace Model
} // namespace Rekognition
} // namespace Aws


text:
const dateFormat = require('dateformat');
const { OperationResult } = require('./operation_result');

let now = dateFormat(Date.now(), 'isoUtcDateTime');

function getPreFabResult() {
    let result = new OperationResult('bagging', 'bagger');
    result.started = now;
    result.completed = now;
    result.filepath = "/path/to/file.txt";
    result.filesize = 8800;
    result.fileMtime = now;
    result.remoteURL = 'https://aptrust.org';
    result.remoteChecksum = '12345678';
    result.info = 'Ned Flanders';
    result.warning = 'Come out, Neville.';
    result.error = 'There was no error.';
    result.attempt = 1;
    return result;
}

test('Constructor sets expected properties', () => {
    let result = new OperationResult('bagging', 'bagger');
    expect(result.operation).toEqual('bagging');
    expect(result.provider).toEqual('bagger');
    expect(result.attempt).toEqual(0);
    expect(result.errors).not.toBeNull();
    expect(result.errors.length).toEqual(0);
});

test('reset()', () => {
    let result = getPreFabResult();
    result.reset();

    expect(result.operation).toEqual('bagging');
    expect(result.provider).toEqual('bagger');
    expect(result.attempt).toEqual(1);
    expect(result.started).toBeNull();
    expect(result.completed).toBeNull();
    // No started/completed timestamps
    expect(result.succeeded()).toBe(false);
    expect(result.filesize).toEqual(0);
    expect(result.fileMtime).toBeNull();
    expect(result.remoteURL).toBeNull();
    expect(result.remoteChecksum).toBeNull();
    expect(result.info).toBeNull();
    expect(result.warning).toBeNull();
    expect(result.errors).not.toBeNull();
    expect(result.errors.length).toEqual(0);
});

test('start()', () => {
    let result = getPreFabResult();
    result.started = null;

    // Start should set started, increment attempt, and clear
    // most other attributes.
    result.start();
    expect(result.operation).toEqual('bagging');
    expect(result.provider).toEqual('bagger');
    expect(result.attempt).toEqual(2);
    expect(result.started).not.toBeNull();
    expect(result.completed).toBeNull();
    // No started/completed timestamps
    expect(result.succeeded()).toBe(false);
    expect(result.filesize).toEqual(0);
    expect(result.fileMtime).toBeNull();
    expect(result.remoteURL).toBeNull();
    expect(result.remoteChecksum).toBeNull();
    expect(result.info).toBeNull();
    expect(result.warning).toBeNull();
    expect(result.errors).not.toBeNull();
    expect(result.errors.length).toEqual(0);
});

test('finish()', () => {
    let result = new OperationResult('bagging', 'bagger');
    result.start();
    result.finish();
    expect(result.completed).not.toBeNull();
    expect(result.succeeded()).toBe(true);
    expect(result.errors.length).toEqual(0);

    result.finish('No friggin way, Mister Lahey!');
    expect(result.completed).not.toBeNull();
    expect(result.succeeded()).toBe(false);
    expect(result.errors.length).toEqual(1);
    expect(result.errors).toContain('No friggin way, Mister Lahey!');

    // Should be able to finish with an array of errors.
    // Add three new ones to the one above.
    result.finish(['No friggin way, Mister Lahey!',
                   'Step away from the cat, Bubbles.',
                   'Take those grow lights out of my trailer, Ricky.']);
    expect(result.errors.length).toEqual(4);
});

test('first and last error', () => {
    let result = new OperationResult('bagging', 'bagger');
    expect(result.firstError()).not.toBeDefined();
    expect(result.lastError()).not.toBeDefined();

    result.errors.push('Rickey and Bubbles, get in the car.');
    result.errors.push('No friggin way, Mister Lahey!');
    expect(result.firstError()).toEqual('Rickey and Bubbles, get in the car.');
    expect(result.lastError()).toEqual('No friggin way, Mister Lahey!');
});

test('succeeded()', () => {
    let result = new OperationResult('bagging', 'bagger');
    result.attempt = 0;
    result.started = null;
    result.completed = null;
    result.errors = ['Oopsie!'];

    // No success conditions fulfilled.
    expect(result.succeeded()).toBe(false);

    // Attempted, but no start or completion time.
    result.attempt = 1;
    expect(result.succeeded()).toBe(false);

    // Not yet completed.
    result.started = new Date('2019-02-28T14:57:00');
    expect(result.succeeded()).toBe(false);

    // Has completed time, but still has errors.
    result.completed = new Date('2019-02-28T14:59:00');
    expect(result.succeeded()).toBe(false);

    // Attempted, started, completed, and no errors = success.
    result.errors = [];
    expect(result.succeeded()).toBe(true);
});

test('inflateFrom()', () => {
    let data = {
        operation: 'abc',
        provider: 'xyz'
    };
    let result = OperationResult.inflateFrom(data);

    // Should copy data attributes
    expect(result.operation).toEqual(data.operation);
    expect(result.provider).toEqual(data.provider);

    // Methods should be defined
    expect(typeof result.lastError).toEqual('function');
    expect(typeof result.succeeded).toEqual('function');
});

test('firstError()', () => {
    let result = new OperationResult('bagging', 'bagger');
    expect(result.firstError()).not.toBeDefined();
    result.errors = ['Err1', 'Err2'];
    expect(result.firstError()).toEqual('Err1');
})

test('hasErrors()', () => {
    let result = new OperationResult('bagging', 'bagger');
    expect(result.hasErrors()).toBe(false);
    result.errors = ['Err1'];
    expect(result.hasErrors()).toBe(true);
})


text:
class CreateVideos < ActiveRecord::Migration
  def change
    create_table :videos do |t|
      t.string :url
      t.string :title
      t.text :description
      t.string :tags, array: true

      t.timestamps null: false
    end
  end
end


text: docker run --rm -it root bash


text:
from __future__ import absolute_import
from __future__ import unicode_literals

from six import text_type as str

from yelp.obj.response_object import ResponseObject

class Attribute(ResponseObject):

    _schema = {"name": str, "value": str}


text:
import {Component} from '@angular/core';

@Component({
  selector: 'app',
  styleUrls: ['./app.component.scss'],
  templateUrl: './app.component.html',
})
export class AppComponent {
}


text:
class PostgresqlAT10 < Formula
  desc "Object-relational database system"
  homepage "https://www.postgresql.org/"
  url "https://ftp.postgresql.org/pub/source/v10.22/postgresql-10.22.tar.bz2"
  sha256 "955977555c69df1a64f44b81d4a1987eb74abbd1870579f5ad9d946133dd8e4d"
  license "PostgreSQL"
  revision 3

  livecheck do
    url "https://ftp.postgresql.org/pub/source/"
    regex(%r{href=["']?v?(10(?:\.\d+)+)/?["' >]}i)
  end

  bottle do
    sha256 arm64_ventura:  "12a23aa3da4c20fe27d7d2cf7e68a31f8072b8e5e1356e95e0918d7d528a6faa"
    sha256 arm64_monterey: "95ff39fa2a308b2ba32569df5da563911664d447ab160cf9e7a4e0dc81cd46c1"
    sha256 arm64_big_sur:  "ce82c9858b89a210fe816495af9072c57e4a2102007dbd481bb6055ac3ab37a5"
    sha256 ventura:        "e192b534805c7bc6d03af8e3bbfbd5bccdac4f33a1901dfddc0f5532ea125458"
    sha256 monterey:       "56d578ffafd4651d48ea24c65c2821d5eab5c4308dc83ec0b13a7aa069a8dfe1"
    sha256 big_sur:        "0709771101fc5c98748b905b4687b19275fa196169a12f2b882ba4c14fc0668e"
    sha256 catalina:       "a8fdf9b8cc39eb124cf9006ba21d13b9b47aea401f4916a9159db27877029bdc"
    sha256 x86_64_linux:   "ba4d03256d2b7217953fa653505d053f12d71af9291f3b6adb16bc0a5a665b4f"
  end

  keg_only :versioned_formula

  # https://www.postgresql.org/support/versioning/
  deprecate! date: "2022-11-10", because: :unsupported

  depends_on "pkg-config" => :build
  depends_on "icu4c"
  depends_on "openssl@1.1"
  depends_on "readline"

  uses_from_macos "krb5"
  uses_from_macos "libxslt"
  uses_from_macos "openldap"
  uses_from_macos "perl"

  on_linux do
    depends_on "linux-pam"
    depends_on "util-linux"
  end

  def install
    ENV.prepend "LDFLAGS", "-L#{Formula["openssl@1.1"].opt_lib} -L#{Formula["readline"].opt_lib}"
    ENV.prepend "CPPFLAGS", "-I#{Formula["openssl@1.1"].opt_include} -I#{Formula["readline"].opt_include}"

    args = %W[
      --disable-debug
      --prefix=#{prefix}
      --datadir=#{pkgshare}
      --libdir=#{lib}
      --sysconfdir=#{etc}
      --docdir=#{doc}
      --enable-thread-safety
      --with-gssapi
      --with-icu
      --with-ldap
      --with-libxml
      --with-libxslt
      --with-openssl
      --with-pam
      --with-perl
      --with-uuid=e2fs
    ]
    if OS.mac?
      args += %w[
        --with-bonjour
        --with-tcl
      ]
    end

    # PostgreSQL by default uses xcodebuild internally to determine this,
    # which does not work on CLT-only installs.
    args << "PG_SYSROOT=#{MacOS.sdk_path}" if MacOS.sdk_root_needed?

    system "./configure", *args
    system "make"

    #  pkglibdir=#{lib}/postgresql
    dirs = %W[datadir=#{pkgshare} libdir=#{lib} pkglibdir=#{lib}]

    # Temporarily disable building/installing the documentation.
    # Postgresql seems to "know" the build system has been altered and
    # tries to regenerate the documentation when using `install-world`.
    # This results in the build failing:
    #  `ERROR: `osx' is missing on your system.`
    # Attempting to fix that by adding a dependency on `open-sp` doesn't
    # work and the build errors out on generating the documentation, so
    # for now let's simply omit it so we can package Postgresql for Mojave.
    if OS.mac?
      if DevelopmentTools.clang_build_version >= 1000
        system "make", "all"
        system "make", "-C", "contrib", "install", "all", *dirs
        system "make", "install", "all", *dirs
      else
        system "make", "install-world", *dirs
      end
    else
      system "make", "all"
      system "make", "-C", "contrib", "install", "all", *dirs
      system "make", "install", "all", *dirs
      inreplace lib/"pgxs/src/Makefile.global",
                "LD = #{HOMEBREW_PREFIX}/Homebrew/Library/Homebrew/shims/linux/super/ld",
                "LD = #{HOMEBREW_PREFIX}/bin/ld"
    end
  end

  def post_install
    (var/"log").mkpath
    postgresql_datadir.mkpath

    # Don't initialize database, it clashes when testing other PostgreSQL versions.
    return if ENV["HOMEBREW_GITHUB_ACTIONS"]

    system "#{bin}/initdb", "--locale=C", "-E", "UTF-8", postgresql_datadir unless pg_version_exists?
  end

  def postgresql_datadir
    var/name
  end

  def postgresql_log_path
    var/"log/#{name}.log"
  end

  def pg_version_exists?
    (postgresql_datadir/"PG_VERSION").exist?
  end

  def caveats
    <<~EOS
      This formula has created a default database cluster with:
        initdb --locale=C -E UTF-8 #{postgresql_datadir}
      For more details, read:
        https://www.postgresql.org/docs/#{version.major}/app-initdb.html
    EOS
  end

  service do
    run [opt_bin/"postgres", "-D", var/"postgresql@10"]
    keep_alive true
    log_path var/"log/postgresql@10.log"
    error_log_path var/"log/postgresql@10.log"
    working_dir HOMEBREW_PREFIX
  end

  test do
    system "#{bin}/initdb", testpath/"test" unless ENV["HOMEBREW_GITHUB_ACTIONS"]
    assert_equal pkgshare.to_s, shell_output("#{bin}/pg_config --sharedir").chomp
    assert_equal lib.to_s, shell_output("#{bin}/pg_config --libdir").chomp
    assert_equal lib.to_s, shell_output("#{bin}/pg_config --pkglibdir").chomp
  end
end


text:
var Waterline = require('../../lib/waterline'),
    assert = require('assert');

describe('Waterline Collection', function() {
  var User, status = 0;

  before(function(done) {

    var adapter_1 = {
      identity: 'foo',
      registerConnection: function(connection, collections, cb) {
        status++;
        cb();
      }
    };

    var adapter_2 = {
      identity: 'bar',
      registerConnection: function(connection, collections, cb) {
        status++;
        cb();
      }
    };

    var Model = Waterline.Collection.extend({
      attributes: {},
      connection: ['my_foo', 'my_bar'],
      tableName: 'tests'
    });

    var waterline = new Waterline();
    waterline.loadCollection(Model);

    var connections = {
      'my_foo': {
        adapter: 'foo'
      },
      'my_bar': {
        adapter: 'bar'
      }
    };

    waterline.initialize({ adapters: { 'foo': adapter_1, 'bar': adapter_2 }, connections: connections }, function(err, colls) {
      if(err) return done(err);
      User = colls.collections.tests;
      done();
    });
  });

  describe('multiple adapters', function() {

    it('should call registerCollection on all adapters', function() {
      assert(status == 2);
    });

  });
});


text:
r"""Experimental Keras MNIST Example.

To test on CPU:
    python mnist.py --use_tpu=False [--fake_data=true]

To test on TPU:
    python mnist.py --use_tpu=True [--tpu=$TPU_NAME]
"""

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

# Standard Imports
from absl import app
from absl import flags
import numpy as np
import tensorflow.compat.v1 as tf
from tensorflow.contrib import cluster_resolver as contrib_cluster_resolver
from tensorflow.contrib import distribute as contrib_distribute

# TODO(sourabhbajaj): Remove the need for this flag.
flags.DEFINE_bool('use_tpu', True,
                  'Ignored: preserved for backward compatibility.')
flags.DEFINE_string('tpu', '', 'Name of the TPU to use.')
flags.DEFINE_string(
    'model_dir', None,
    ('The directory where the model and training/evaluation summaries '
     'are stored. If unset, no summaries will be stored.'))

flags.DEFINE_bool('fake_data', False, 'Use fake data to test functionality.')

# Batch size should satify two properties to be able to run in cloud:
# num_eval_samples % batch_size == 0
# batch_size % 8 == 0
BATCH_SIZE = 200
NUM_CLASSES = 10
EPOCHS = 15

# input image dimensions
IMG_ROWS, IMG_COLS = 28, 28

FLAGS = flags.FLAGS

def mnist_model(input_shape):
  """Creates a MNIST model."""
  model = tf.keras.models.Sequential()
  model.add(
      tf.keras.layers.Conv2D(
          32, kernel_size=(3, 3), activation='relu', input_shape=input_shape))
  model.add(tf.keras.layers.Conv2D(64, (3, 3), activation='relu'))
  model.add(tf.keras.layers.MaxPooling2D(pool_size=(2, 2)))
  model.add(tf.keras.layers.Dropout(0.25))
  model.add(tf.keras.layers.Flatten())
  model.add(tf.keras.layers.Dense(128, activation='relu'))
  model.add(tf.keras.layers.Dropout(0.5))
  model.add(tf.keras.layers.Dense(NUM_CLASSES, activation='softmax'))
  return model

def run():
  """Run the model training and return evaluation output."""
  resolver = contrib_cluster_resolver.TPUClusterResolver(tpu=FLAGS.tpu)
  contrib_distribute.initialize_tpu_system(resolver)
  strategy = contrib_distribute.TPUStrategy(resolver, steps_per_run=100)

  if FLAGS.fake_data:
    print('Using fake data')
    x_train = np.random.random((BATCH_SIZE, IMG_ROWS, IMG_COLS))
    y_train = np.zeros([BATCH_SIZE, 1], dtype=np.int32)
    x_test, y_test = x_train, y_train
  else:
    # the data, split between train and test sets
    print('Using real data')
    (x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()

  x_train = x_train.reshape(x_train.shape[0], IMG_ROWS, IMG_COLS, 1)
  x_test = x_test.reshape(x_test.shape[0], IMG_ROWS, IMG_COLS, 1)
  input_shape = (IMG_ROWS, IMG_COLS, 1)

  x_train = x_train.astype('float32')
  x_test = x_test.astype('float32')
  x_train /= 255
  x_test /= 255
  print('x_train shape:', x_train.shape)
  print(x_train.shape[0], 'train samples')
  print(x_test.shape[0], 'test samples')

  # convert class vectors to binary class matrices
  y_train = tf.keras.utils.to_categorical(y_train, NUM_CLASSES)
  y_test = tf.keras.utils.to_categorical(y_test, NUM_CLASSES)
  with strategy.scope():
    model = mnist_model(input_shape)
    model.compile(
        loss=tf.keras.losses.categorical_crossentropy,
        optimizer=tf.train.GradientDescentOptimizer(learning_rate=0.05),
        metrics=['accuracy'])

  callbacks = []
  if FLAGS.model_dir:
    callbacks = [tf.keras.callbacks.TensorBoard(log_dir=FLAGS.model_dir)]

  model.fit(
      x_train,
      y_train,
      batch_size=BATCH_SIZE,
      callbacks=callbacks,
      epochs=EPOCHS,
      verbose=1,
      validation_data=(x_test, y_test))
  return model.evaluate(x_test, y_test, batch_size=BATCH_SIZE, verbose=1)

def main(unused_dev):
  score = run()
  print('Loss for final step: %s;' % score[0])
  print('Accuracy: %s;' % score[1])

if __name__ == '__main__':
  tf.logging.set_verbosity(tf.logging.INFO)
  app.run(main)


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

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<title>LCD Library: /Users/fmalpartida/development/ardWorkspace/LiquidCrystal_I2C/LiquiCrystal_I2C/FastIO.h Source File</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css"/>

LCD Library 1.2.0

LCD Library - LCD control class hierarchy library. Drop in replacement for the LiquidCrystal Library.

Main Page

Classes

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

File List

File Members

/Users/fmalpartida/development/ardWorkspace/LiquidCrystal_I2C/LiquiCrystal_I2C/FastIO.h

Go to the documentation of this file.

00001 // ---------------------------------------------------------------------------
00002 // Created by Florian Fida on 20/01/12
00003 // Copyright 2012 - Under creative commons license 3.0:
00004 //        Attribution-ShareAlike CC BY-SA
00005 //        http://creativecommons.org/licenses/by-sa/3.0/
00006 //
00007 // This software is furnished "as is", without technical support, and with no
00008 // warranty, express or implied, as to its usefulness for any purpose.
00009 // ---------------------------------------------------------------------------
00010 // fio_shiftOut1 functions are based on Shif1 protocol developed by Roman Black
00011 // (http://www.romanblack.com/shift1.htm)
00012 //
00013 // Thread Safe: No
00014 // Extendable: Yes
00015 //
00016 // @file FastIO.h
00017 // This file implements basic fast IO routines.
00018 //
00019 // @brief
00020 //
00021 // @version API 1.0.0
00022 //
00023 // @author Florian Fida -
00024 //
00025 // @todo:
00026 //  support chipkit:
00027 // (https://github.com/chipKIT32/chipKIT32-MAX/blob/master/hardware/pic32/
00028 //   cores/pic32/wiring_digital.c)
00029 // ---------------------------------------------------------------------------
00030 #ifndef FAST_IO_H
00031 #define FAST_IO_H
00032
00033 #if (ARDUINO <  100)
00034 #include <WProgram.h>
00035 #else
00036 #include <Arduino.h>
00037 #endif
00038
00039 #include <pins_arduino.h> // pleasing sanguino core
00040 #include <inttypes.h>
00041 #include <util/delay.h>
00042
00048 #ifndef __AVR__
00049 #define FIO_FALLBACK
00050 #endif
00051
00052 // PUBLIC CONSTANTS DEFINITIONS
00053 // ---------------------------------------------------------------------------
00059 #define SKIP 0x23
00060
00061 // PUBLIC TYPE DEFINITIONS
00062 // ---------------------------------------------------------------------------
00063 typedef uint8_t fio_bit;
00064
00065
00066 #ifndef FIO_FALLBACK
00067 typedef volatile uint8_t * fio_register;
00068 #else
00069 // remove volatile to give optimizer a chance
00070 typedef uint8_t fio_register;
00071 #endif
00072
00080 fio_register fio_pinToOutputRegister(uint8_t pin, uint8_t initial_state = LOW);
00081
00089 fio_register fio_pinToInputRegister(uint8_t pin);
00090
00098 fio_bit fio_pinToBit(uint8_t pin);
00099
00100
00110 // __attribute__ ((always_inline)) /* let the optimizer decide that for now */
00111 void fio_digitalWrite ( fio_register pinRegister, fio_bit pinBit, uint8_t value );
00112
00119 #ifndef FIO_FALLBACK
00120 #define fio_digitalWrite_LOW(reg,bit) *reg &= ~bit
00121 #define fio_digitalWrite_HIGH(reg,bit) *reg |= bit
00122 #define fio_digitalWrite_SWITCH(reg,bit) *reg ^= bit
00123 #define fio_digitalWrite_SWITCHTO(reg,bit,val) fio_digitalWrite_SWITCH(reg,bit)
00124 #else
00125 // reg -> dummy NULL, bit -> pin
00126 #define fio_digitalWrite_HIGH(reg,bit) digitalWrite(bit,HIGH)
00127 #define fio_digitalWrite_LOW(reg,bit) digitalWrite(bit,LOW)
00128 #define fio_digitalWrite_SWITCH(reg,bit) digitalWrite(bit, !digitalRead(bit))
00129 #define fio_digitalWrite_SWITCHTO(reg,bit,val) digitalWrite(bit,val);
00130 #endif
00131
00141 int fio_digitalRead ( fio_register pinRegister, fio_bit pinBit );
00142
00154 void fio_shiftOut( fio_register dataRegister, fio_bit dataBit, fio_register clockRegister,
00155                    fio_bit clockBit, uint8_t value, uint8_t bitOrder );
00156
00167 void fio_shiftOut(fio_register dataRegister, fio_bit dataBit, fio_register clockRegister, fio_bit clockBit);
00168
00177 void fio_shiftOut1(fio_register shift1Register, fio_bit shift1Bit, uint8_t value, boolean noLatch = false);
00185 void fio_shiftOut1(uint8_t pin, uint8_t value, boolean noLatch = false);
00193 void fio_shiftOut1_init(fio_register shift1Register, fio_bit shift1Bit);
00200 void fio_shiftOut1_init(uint8_t pin);
00201
00202 #endif // FAST_IO_H

 All Classes Files Functions Variables Typedefs Defines

<address class="footer">Generated on Tue Feb 28 2012 19:52:02 for LCD Library by

 1.7.4 </address>


text: yes = do mapM print a; return b


text:
$packageName = "{{PackageName}}"
$unzipLoc = "$(Split-Path -parent $MyInvocation.MyCommand.Definition)"
$url = "{{DownloadUrlx64}}"
$checksum = "{{Checksum}}"
$checksumType = 'sha1'

Install-ChocolateyZipPackage -PackageName "$packageName" -Url "$url" -UnzipLocation "$unzipLoc" -Url64bit "$url64" -Checksum "$checksum" -ChecksumType "$checksumType"


text:
#ifndef Common_rtCore_Texture_h
#define Common_rtCore_Texture_h

namespace rtCore
{
  class Texture
  {
  public:

  private:
  };
}

#endif // Common_rtCore_Texture_h


text:
<!DOCTYPE html>

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Exploring Attributions in the What-If Tool</title>

        <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
    <link rel="stylesheet" href="/what-if-tool/assets/css/material.min.css">
    <link rel="stylesheet" href="/what-if-tool/assets/css/material-components-web.min.css">
    <link href="https://fonts.googleapis.com/css?family=Open+Sans:400,400italic,500,500italic,700,700italic" rel="stylesheet" type="text/css">
    <link href="https://fonts.googleapis.com/css?family=Manrope:400,400italic,500,500italic,700,700italic" rel="stylesheet" type="text/css">

    <link href='/what-if-tool/assets/css/new.css' rel='stylesheet' type='text/css'>
    <link rel="icon" href="/what-if-tool/assets/images/favicon.png" type="image/png"/>

          What-If Tool

            GET STARTED
            TUTORIALS
            DEMOS
            FAQs
            GET INVOLVED
            GITHUB

        What-If Tool

          GET STARTED
          TUTORIALS
          DEMOS
          FAQs
          GET INVOLVED
          GITHUB

  Learn > Conducting Analysis in the What-If Tool > Exploring Attributions

Exploring Attributions in the What-If Tool

Exploring feature attributions is a great way to understand what features a model is relying on when making a prediction. Many techniques exist to get feature attributions from a model's predictions, such as LIME, integrated gradients, and shapley values. WIT allows users to consume feature attributions from any technique along with model predictions, and then uses those attributions to enhance its visualizations.

The feature attributions can be provided to WIT in one of two ways:

Through a Cloud AI Platform model that has explanations enabled. Details on setting up WIT for a Cloud AI Platform model can be found in the Getting Started in Notebooks tutorial.

Through a custom prediction function that returns feature attributions for each prediction, in addition to the standard prediction results. This can be done for WIT in either TensorBoard or notebooks. See the tutorial on custom prediction functions in WIT for details on how to set this up. The user defines how the attributions are calculated and WIT then takes those attributions and adds them to its visualizations.

Attribution Visualizations

When attributions are returned along with predictions, new visualizations are enabled in WIT. When selecting a datapoint, the Datapoint Editor will do three things with the attribution information:

Features in the datapoint will be sorted by their attribution values, with the features with the highest attributions being at the top of the list. This sort order can be changed by a dropdown at the top of the Datapoint Editor.

The exact attribution values for each feature will be listed next to each feature value.

The feature values will have their background colored by their feature attribution scores, to allow at-a-glance understanding of the individual feature attributions.

Attribution values in the Datapoint Editor.

Additionally, the feature attribution values can be used in the datapoints visualization, as a way to organize the datapoints, using those values to control scatter plot axes, datapoint binning, or datapoint coloring.

Exploring an age-prediction regression model. Scatter plots of age versus predicted age for a test dataset, faceted into two plots by how important the "hours per week" feature was to each prediction.

In the "Performance" tab, in addition to the standard metrics that are calculated and shown, there will be a table of mean feature attributions across the entire dataset, sorted with the highest-attributed feature at the top. If you slice a dataset in this tab, each slice will have its own mean attributions table. This table uses the same color scale as the attribution value-based background colors in the Datapoint Editor. You can also use the feature attributions as a dimension to slice your dataset on in this tab, such as slicing the dataset into those with high attribution on a specific feature, versus those with low attribution on that feature, in order to compare the performance metrics on those two slices.

Mean attribution tables in the Performance tab for a regression model.

Attribution-based Counterfactuals

When attributions are provided to WIT, its counterfactual-generating capabilities are enhanced. In addition to being able to find nearest counterfactuals through datapoint feature value similarity, you can find nearest counterfactuals through attribution similarity. Switching to using attribution-based distance is controlled by a dropdown in the counterfactual controls area in the Vizualize module in the Datapoint Editor tab.

When finding nearest counterfactuals by attribution distance, WIT calculates the distance between two datapoints based on the difference in attribution values for each feature of a datapoint, instead of the difference in feature values. This gives you another way to explore the decision boundary of a model for a given datapoint, based purely on attributions from whatever methodology you are using to calculate feature-wise attributions.

Finding the closest counterfactual datapoint based on feature attributions as opposed to feature values.

time to read

15 minutes

use with

Classification models
Multi-class models
Regression models

before you begin

Have a trained model with logic that returns predictions and feature attributions and test dataset for analyzing.

related demos

Regression Model: UCI Census Age Prediction

takeaways

Learn how to analyze feature attributions in the What-If Tool.

what-if questions

How do I view feature attributions in the What-If Tool?

            The What-If Tool is being actively developed and documentation is likely to change as we improve the tool. We want to hear from you! Leave us a note, feedback, or suggestion on our community group.

Google Research

Get Involved

Github


text:
html {
	overflow-y: scroll;
}

.grid a {
	display: block;
	position: relative;
	background: #bbbbbb;
}

.grid a .dim {
	display: block;
	position: absolute;
	background: #ffffff;
	opacity: 0.3;
	top: 0;
	right: 0;
	bottom: 0;
	left: 0;

	-webkit-backface-visibility: hidden;
	-moz-backface-visibility:    hidden;
	-ms-backface-visibility:     hidden;
	backface-visibility:         hidden;

	-webkit-transition: opacity 300ms linear;
	-moz-transition:    opacity 300ms linear;
	-ms-transition:     opacity 300ms linear;
	-o-transition:      opacity 300ms linear;
	transition:         opacity 300ms linear;
}
.grid a:hover .dim {
	opacity: 0;

	-webkit-transition: opacity 300ms linear;
	-moz-transition:    opacity 300ms linear;
	-ms-transition:     opacity 300ms linear;
	-o-transition:      opacity 300ms linear;
	transition:         opacity 300ms linear;
}

.grid a .title {
	display: block;
	position: absolute;
	background: #000000;
	opacity: 0.2;
	right: 0;
	bottom: 0;
	left: 0;
	margin: 5px;
	border-radius: 0;
	text-align: center;
	white-space: normal;

	-webkit-transition: opacity 300ms linear;
	-moz-transition:    opacity 300ms linear;
	-ms-transition:     opacity 300ms linear;
	-o-transition:      opacity 300ms linear;
	transition:         opacity 300ms linear;
}
.grid a:hover .title {
	opacity: 0.5;

	-webkit-transition: opacity 300ms linear;
	-moz-transition:    opacity 300ms linear;
	-ms-transition:     opacity 300ms linear;
	-o-transition:      opacity 300ms linear;
	transition:         opacity 300ms linear;
}

.fullimagecontainer img {
	margin: 0 auto;
}

.breadcrumb {
	padding: 8px 15px;
	margin-bottom: 20px;
	list-style: none;
	background-color: #f5f5f5;
	border-radius: 0;
}

.page-header {
	margin: 20px 0 20px;
}

.page-footer {
	padding-top: 9px;
	margin: 20px 0 20px;
	border-top: 1px solid #eeeeee;
}

.navigation {
	margin-bottom: 10px;
}

.social {
	padding-top: 9px;
	margin: 20px 0 0;
	border-top: 1px solid #eeeeee;
	height: 29px;
}

.social_links {
	display: inline-block;
	height: 20px;
}
.social_links img {
	vertical-align: baseline;
}

.fb_likes {
	width: 140px;
}

.twitter-share-button {
	width: 90px !important;
}

.comments {
	padding-top: 9px;
	margin: 9px 0 20px;
	border-top: 1px solid #eeeeee;
}

.comments .fb_iframe_widget,
.comments .fb_iframe_widget span,
.comments .fb_iframe_widget iframe[style] {
	width: 100% !important;
}

.fb_btns {
	padding-top: 9px;
	margin: 6px 0 0;
	border-top: 1px solid #eeeeee;
}

#loader.loading {
	background: url('../img/load.gif') no-repeat center center;
}

#loader.loaderror {
	background: url('../img/loaderror.gif') no-repeat center center;
}

.fullimage {
	width: 100%;
	/*min-height: 50px;*/
}

.img-full-height {
	max-height: 100%;
}

.img-description {
	padding: 8px 15px;
	margin-top: 10px;
	background-color: #f5f5f5;
}

.alert {
	padding: 15px;
	margin-bottom: 10px;
	border: 0;
	border-radius: 0;
}
.alert-dismissable .close {
	position: inherit;
}

@media (max-width:991px){
	.grid a .dim {
		opacity: 0;
	}
	.grid a .title {
		opacity: 0.5;
	}
}


text:
Previous: Mathematical Function Probes, Up: Internal Probes   [Contents][Index]

36.3 Non-local Goto Probes

These probes are used to signal calls to setjmp, sigsetjmp,
longjmp or siglongjmp.

Probe: setjmp (void *<var>$arg1</var>, int <var>$arg2</var>, void *<var>$arg3</var>)

This probe is triggered whenever setjmp or sigsetjmp is
called.  Argument <var>$arg1</var> is a pointer to the jmp_buf
passed as the first argument of setjmp or sigsetjmp,
<var>$arg2</var> is the second argument of sigsetjmp or zero if this
is a call to setjmp and <var>$arg3</var> is a pointer to the return
address that will be stored in the jmp_buf.

Probe: longjmp (void *<var>$arg1</var>, int <var>$arg2</var>, void *<var>$arg3</var>)

This probe is triggered whenever longjmp or siglongjmp
is called.  Argument <var>$arg1</var> is a pointer to the jmp_buf
passed as the first argument of longjmp or siglongjmp,
<var>$arg2</var> is the return value passed as the second argument of
longjmp or siglongjmp and <var>$arg3</var> is a pointer to
the return address longjmp or siglongjmp will return to.

The longjmp probe is triggered at a point where the registers
have not yet been restored to the values in the jmp_buf and
unwinding will show a call stack including the caller of
longjmp or siglongjmp.

Probe: longjmp_target (void *<var>$arg1</var>, int <var>$arg2</var>, void *<var>$arg3</var>)

This probe is triggered under the same conditions and with the same
arguments as the longjmp probe.

The longjmp_target probe is triggered at a point where the
registers have been restored to the values in the jmp_buf and
unwinding will show a call stack including the caller of setjmp
or sigsetjmp.


text:
package de.zalando.refugees.web.rest;

import com.codahale.metrics.annotation.Timed;
import de.zalando.refugees.domain.Authority;
import de.zalando.refugees.domain.User;
import de.zalando.refugees.repository.AuthorityRepository;
import de.zalando.refugees.repository.UserRepository;
import de.zalando.refugees.security.AuthoritiesConstants;
import de.zalando.refugees.service.MailService;
import de.zalando.refugees.service.UserService;
import de.zalando.refugees.web.rest.dto.ManagedUserDTO;
import de.zalando.refugees.web.rest.dto.UserDTO;
import de.zalando.refugees.web.rest.util.HeaderUtil;
import de.zalando.refugees.web.rest.util.PaginationUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.annotation.Secured;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.inject.Inject;
import java.net.URI;
import java.net.URISyntaxException;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

/**
 * REST controller for managing users.
 *
 *
This class accesses the User entity, and needs to fetch its collection of authorities.

 *

 * For a normal use-case, it would be better to have an eager relationship between User and Authority,
 * and send everything to the client side: there would be no DTO, a lot less code, and an outer-join
 * which would be good for performance.
 *

 *

 * We use a DTO for 3 reasons:
 *

 *
We want to keep a lazy association between the user and the authorities, because people will
 * quite often do relationships with the user, and we don't want them to get the authorities all
 * the time for nothing (for performance reasons). This is the #1 goal: we should not impact our users'
 * application because of this use-case.

 *
 Not having an outer join causes n+1 requests to the database. This is not a real issue as
 * we have by default a second-level cache. This means on the first HTTP call we do the n+1 requests,
 * but then all authorities come from the cache, so in fact it's much better than doing an outer join
 * (which will get lots of data from the database, for each HTTP call).

 *
 As this manages users, for security reasons, we'd rather have a DTO layer.

 *

 *
Another option would be to have a specific JPA entity graph to handle this case.

 */
@RestController
@RequestMapping("/api")
public class UserResource {

    private final Logger log = LoggerFactory.getLogger(UserResource.class);

    @Inject
    private UserRepository userRepository;

    @Inject
    private MailService mailService;

    @Inject
    private AuthorityRepository authorityRepository;

    @Inject
    private UserService userService;

    /**
     * POST  /users -> Creates a new user.
     *

     * Creates a new user if the login and email are not already used, and sends an
     * mail with an activation link.
     * The user needs to be activated on creation.
     *

     */
    @RequestMapping(value = "/users",
        method = RequestMethod.POST,
        produces = MediaType.APPLICATION_JSON_VALUE)
    @Timed
    @Secured(AuthoritiesConstants.ADMIN)
    public ResponseEntity<?> createUser(@RequestBody ManagedUserDTO managedUserDTO, HttpServletRequest request) throws URISyntaxException {
        log.debug("REST request to save User : {}", managedUserDTO);
        if (userRepository.findOneByLogin(managedUserDTO.getLogin()).isPresent()) {
            return ResponseEntity.badRequest()
                .headers(HeaderUtil.createFailureAlert("user-management", "userexists", "Login already in use"))
                .body(null);
        } else if (userRepository.findOneByEmail(managedUserDTO.getEmail()).isPresent()) {
            return ResponseEntity.badRequest()
                .headers(HeaderUtil.createFailureAlert("user-management", "emailexists", "Email already in use"))
                .body(null);
        } else {
            User newUser = userService.createUser(managedUserDTO);
            String baseUrl = request.getScheme() + // "http"
            "://" +                                // "://"
            request.getServerName() +              // "myhost"
            ":" +                                  // ":"
            request.getServerPort() +              // "80"
            request.getContextPath();              // "/myContextPath" or "" if deployed in root context
            mailService.sendCreationEmail(newUser, baseUrl);
            return ResponseEntity.created(new URI("/api/users/" + newUser.getLogin()))
                .headers(HeaderUtil.createAlert( "user-management.created", newUser.getLogin()))
                .body(newUser);
        }
    }

    /**
     * PUT  /users -> Updates an existing User.
     */
    @RequestMapping(value = "/users",
        method = RequestMethod.PUT,
        produces = MediaType.APPLICATION_JSON_VALUE)
    @Timed
    @Transactional
    @Secured(AuthoritiesConstants.ADMIN)
    public ResponseEntity<ManagedUserDTO> updateUser(@RequestBody ManagedUserDTO managedUserDTO) throws URISyntaxException {
        log.debug("REST request to update User : {}", managedUserDTO);
        Optional<User> existingUser = userRepository.findOneByEmail(managedUserDTO.getEmail());
        if (existingUser.isPresent() && (!existingUser.get().getId().equals(managedUserDTO.getId()))) {
            return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert("user-management", "emailexists", "E-mail already in use")).body(null);
        }
        existingUser = userRepository.findOneByLogin(managedUserDTO.getLogin());
        if (existingUser.isPresent() && (!existingUser.get().getId().equals(managedUserDTO.getId()))) {
            return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert("user-management", "userexists", "Login already in use")).body(null);
        }
        return userRepository
            .findOneById(managedUserDTO.getId())
            .map(user -> {
                user.setLogin(managedUserDTO.getLogin());
                user.setFirstName(managedUserDTO.getFirstName());
                user.setLastName(managedUserDTO.getLastName());
                user.setEmail(managedUserDTO.getEmail());
                user.setActivated(managedUserDTO.isActivated());
                user.setLangKey(managedUserDTO.getLangKey());
                Set<Authority> authorities = user.getAuthorities();
                authorities.clear();
                managedUserDTO.getAuthorities().stream().forEach(
                    authority -> authorities.add(authorityRepository.findOne(authority))
                );
                return ResponseEntity.ok()
                    .headers(HeaderUtil.createAlert("user-management.updated", managedUserDTO.getLogin()))
                    .body(new ManagedUserDTO(userRepository
                        .findOne(managedUserDTO.getId())));
            })
            .orElseGet(() -> new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR));

    }

    /**
     * GET  /users -> get all users.
     */
    @RequestMapping(value = "/users",
        method = RequestMethod.GET,
        produces = MediaType.APPLICATION_JSON_VALUE)
    @Timed
    @Transactional(readOnly = true)
    public ResponseEntity<List<ManagedUserDTO>> getAllUsers(Pageable pageable)
        throws URISyntaxException {
        Page<User> page = userRepository.findAll(pageable);
        List<ManagedUserDTO> managedUserDTOs = page.getContent().stream()
            .map(user -> new ManagedUserDTO(user))
            .collect(Collectors.toList());
        HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/users");
        return new ResponseEntity<>(managedUserDTOs, headers, HttpStatus.OK);
    }

    /**
     * GET  /users/:login -> get the "login" user.
     */
    @RequestMapping(value = "/users/{login:[_'.@a-z0-9-]+}",
        method = RequestMethod.GET,
        produces = MediaType.APPLICATION_JSON_VALUE)
    @Timed
    public ResponseEntity<ManagedUserDTO> getUser(@PathVariable String login) {
        log.debug("REST request to get User : {}", login);
        return userService.getUserWithAuthoritiesByLogin(login)
                .map(ManagedUserDTO::new)
                .map(managedUserDTO -> new ResponseEntity<>(managedUserDTO, HttpStatus.OK))
                .orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));
    }
    /**
     * DELETE  USER :login -> delete the "login" User.
     */
    @RequestMapping(value = "/users/{login}",
        method = RequestMethod.DELETE,
        produces = MediaType.APPLICATION_JSON_VALUE)
    @Timed
    @Secured(AuthoritiesConstants.ADMIN)
    public ResponseEntity<Void> deleteUser(@PathVariable String login) {
        log.debug("REST request to delete User: {}", login);
        userService.deleteUserInformation(login);
        return ResponseEntity.ok().headers(HeaderUtil.createAlert( "user-management.deleted", login)).build();
    }
}