text:
<?php

namespace Mcms\Core\Services\ItemConnector;

use Mcms\Core\Exceptions\InvalidItemConnectorException;
use Illuminate\Support\Collection;
use Validator;

class ConnectorInstance
{
    /**
     * @var
     */
    public $name;
    /**
     * @var
     */
    public $connector;

    /**
     * ConnectorInstance constructor.
     * @param $connector
     */
    public function __construct(array $connector)
    {
        $check = Validator::make($connector, [
            'name' => 'required',
            'connector' => 'required'
        ]);

        if ($check->fails()){
            throw new InvalidItemConnectorException($check->messages());
        }

        $this->name = $connector['name'];
        $this->type = (isset($connector['type'])) ? $connector['type'] : 'generic';
        $this->order = (isset($connector['connector']['order'])) ? $connector['connector']['order'] : 0;
        $this->connector = $connector['connector'];

        /**
         * Do some validation
         */
        return new Collection($connector);
    }
}


text:
namespace autofill {

// Interface for form-filling implementations that fill a single field at a
// time, such as Autocomplete or merchant promo codes.
class SingleFieldFormFiller {
 public:
  // Interface to be implemented by classes that want to fetch autocomplete
  // suggestions.
  class SuggestionsHandler {
   public:
    virtual ~SuggestionsHandler() = default;

    // Function that will be called-back once SingleFieldFormFiller gets the
    // corresponding response from the DB.
    // |query_id| is the value given by the implementor when
    // OnGetSingleFieldSuggestions was called (it is not the DB query ID).
    // |suggestions| is the list of fetched suggestions.
    virtual void OnSuggestionsReturned(
        int query_id,
        bool autoselect_first_suggestion,
        const std::vector<Suggestion>& suggestions) = 0;
  };

  SingleFieldFormFiller();
  virtual ~SingleFieldFormFiller();
  SingleFieldFormFiller(const SingleFieldFormFiller&) = delete;
  SingleFieldFormFiller& operator=(const SingleFieldFormFiller&) = delete;

  // Gets suggestions for a given field. In the case of Autocomplete, this is
  // through a DB query, though it could be different for other fill types.
  // |query_id| is given by the client as context.
  // |is_autocomplete_enabled| is to determine if the feature is enable for the
  // requestor's context (e.g. Android WebViews have different contexts).
  // |name| is the name of the field.
  // |prefix| is the field's value.
  // |form_control_type| is the field's control type.
  // |handler| is weak pointer to the requestor, which we will call back once we
  // receive the response. There can only be one pending query per |handler|,
  // hence this function will cancel the previous pending query if it hadn't
  // already been resolved, at which point no method of the handler will be
  // called.
  virtual void OnGetSingleFieldSuggestions(
      int query_id,
      bool is_autocomplete_enabled,
      bool autoselect_first_suggestion,
      const std::u16string& name,
      const std::u16string& prefix,
      const std::string& form_control_type,
      base::WeakPtr<SuggestionsHandler> handler) = 0;

  // Runs when a form is going to be submitted. In the case of Autocomplete, it
  // saves the given input from the |form| as new or updated Autocomplete
  // entries, which can then be served in the future as suggestions. This update
  // is dependent on whether we are running in incognito and if Autocomplete is
  // enabled or not.
  virtual void OnWillSubmitForm(const FormData& form,
                                bool is_autocomplete_enabled) = 0;

  // Cancels the currently pending WebDataService queries associated with the
  // given |handler|.
  virtual void CancelPendingQueries(const SuggestionsHandler* handler) = 0;

  // If applicable, removes the currently-selected suggestion from the database.
  virtual void OnRemoveCurrentSingleFieldSuggestion(
      const std::u16string& field_name,
      const std::u16string& value) = 0;

  // Invoked when the user selects |value| in the list of suggestions. For
  // Autocomplete, this function logs the DaysSinceLastUse of the Autocomplete
  // entry associated with |value|.
  virtual void OnSingleFieldSuggestionSelected(const std::u16string& value) = 0;
};

}  // namespace autofill

#endif  // COMPONENTS_AUTOFILL_CORE_BROWSER_SINGLE_FIELD_FORM_FILLER_H_

redpajama_set_name: RedPajamaGithub


text:
package net.javacrumbs.springws.test.template;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

import javax.xml.transform.Source;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import net.javacrumbs.springws.test.util.DefaultXmlUtil;
import net.javacrumbs.springws.test.util.XmlUtil;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
import org.springframework.ws.WebServiceMessage;
import org.springframework.xml.transform.ResourceSource;
import org.w3c.dom.Document;

/**
 * Evaluates XSLT template.
 * @author Lukas Krecan
 *
 */
public class XsltTemplateProcessor implements TemplateProcessor {

	private static final String XSL_NAMESPACE = "http://www.w3.org/1999/XSL/Transform";

	private final Log logger = LogFactory.getLog(getClass());

	private XmlUtil xmlUtil = DefaultXmlUtil.getInstance();

	public Resource processTemplate(Resource resource, WebServiceMessage message) throws IOException {
		if (resource!=null)
		{
			if (isTemplate(resource))
			{
				return transform(resource, message);
			}
			else
			{
				return resource;
			}
		}
		else
		{
			return null;
		}
	}

	protected boolean isTemplate(Resource resource) throws IOException {
		Document document = loadDocument(resource);
		return XSL_NAMESPACE.equals(document.getFirstChild().getNamespaceURI());
	}

	protected Document loadDocument(Resource resource) throws IOException {
		return getXmlUtil().loadDocument(resource);
	}

	protected Resource transform(Resource resource, WebServiceMessage message) throws IOException {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		Source envelopeSource = message!=null?getXmlUtil().getEnvelopeSource(message):new DOMSource();
		getXmlUtil().transform(new ResourceSource(resource), envelopeSource, new StreamResult(baos));
		if (logger.isDebugEnabled())
		{
			logger.debug("Transformation result:\n"+new String(baos.toByteArray(),"UTF-8"));
		}
		return new ByteArrayResource(baos.toByteArray());
	}

	public XmlUtil getXmlUtil() {
		return xmlUtil;
	}

	public void setXmlUtil(XmlUtil xmlUtil) {
		this.xmlUtil = xmlUtil;
	}

}


text:
class incompleteBasis : public nodalBasis {
private:
    const nodalBasis *completeBasis;
    const polynomialBasis *polyBasis;
    fullMatrix<double> coefficients;

public:
    incompleteBasis(){};
    incompleteBasis(int tag);
    ~incompleteBasis();

    virtual int getNumShapeFunctions() const { return points.size1(); }

    virtual void f(double u, double v, double w, double *sf) const;
    virtual void f(const fullMatrix<double> &coord, fullMatrix<double> &sf) const;
    virtual void df(const fullMatrix<double> &coord,
                    fullMatrix<double> &dfm) const;
    virtual void df(double u, double v, double w, double grads[][3]) const;
    virtual void ddf(double u, double v, double w, double hess[][3][3]) const;
    virtual void dddf(double u, double v, double w,
                      double third[][3][3][3]) const;

private:
    void _computeCoefficientsTriangle();
};

#endif


text:
package graphql.execution;

import graphql.GraphQLError;
import graphql.language.FragmentDefinition;
import graphql.language.OperationDefinition;
import graphql.schema.GraphQLSchema;

import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;

public class ExecutionContext {

    private final GraphQLSchema graphQLSchema;
    private final ExecutionId executionId;
    private final ExecutionStrategy queryStrategy;
    private final ExecutionStrategy mutationStrategy;
    private final Map<String, FragmentDefinition> fragmentsByName;
    private final OperationDefinition operationDefinition;
    private final Map<String, Object> variables;
    private final Object root;
    private final List<GraphQLError> errors = new CopyOnWriteArrayList<GraphQLError>();

    public ExecutionContext(ExecutionId executionId, GraphQLSchema graphQLSchema, ExecutionStrategy queryStrategy, ExecutionStrategy mutationStrategy, Map<String, FragmentDefinition> fragmentsByName, OperationDefinition operationDefinition, Map<String, Object> variables, Object root) {
        this.graphQLSchema = graphQLSchema;
        this.executionId = executionId;
        this.queryStrategy = queryStrategy;
        this.mutationStrategy = mutationStrategy;
        this.fragmentsByName = fragmentsByName;
        this.operationDefinition = operationDefinition;
        this.variables = variables;
        this.root = root;
    }

    public ExecutionId getExecutionId() {
        return executionId;
    }

    public GraphQLSchema getGraphQLSchema() {
        return graphQLSchema;
    }

    public Map<String, FragmentDefinition> getFragmentsByName() {
        return fragmentsByName;
    }

    public OperationDefinition getOperationDefinition() {
        return operationDefinition;
    }

    public Map<String, Object> getVariables() {
        return variables;
    }

    public <T> T getRoot() {
        //noinspection unchecked
        return (T) root;
    }

    public FragmentDefinition getFragment(String name) {
        return fragmentsByName.get(name);
    }

    public void addError(GraphQLError error) {
        this.errors.add(error);
    }

    public List<GraphQLError> getErrors() {
        return errors;
    }

    public ExecutionStrategy getQueryStrategy() {
        return queryStrategy;
    }

    public ExecutionStrategy getMutationStrategy() {
        return mutationStrategy;
    }
}


text:
package com.android.tools.idea.gradle.facet;

import com.android.tools.idea.startup.AndroidStudioSpecificInitializer;
import com.intellij.facet.FacetConfiguration;
import com.intellij.facet.ui.FacetEditorContext;
import com.intellij.facet.ui.FacetEditorTab;
import com.intellij.facet.ui.FacetValidatorsManager;
import com.intellij.openapi.util.InvalidDataException;
import com.intellij.openapi.util.WriteExternalException;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.util.xmlb.XmlSerializer;
import org.jdom.Element;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;

/**
 * Configuration options for the Android-Gradle facet. In Android Studio, these options cannot be directly changed by users.
 */
public class AndroidGradleFacetConfiguration implements FacetConfiguration {
  @NonNls public String GRADLE_PROJECT_PATH;

  @NotNull
  @Override
  public FacetEditorTab[] createEditorTabs(FacetEditorContext editorContext,
                                           FacetValidatorsManager validatorsManager) {
    if (!AndroidStudioSpecificInitializer.isAndroidStudio() && StringUtil.isNotEmpty(GRADLE_PROJECT_PATH)) {
      // IntelliJ only
      return new FacetEditorTab[]{new AndroidGradleFacetEditorTab(editorContext.getProject(), GRADLE_PROJECT_PATH)};
    }
    return new FacetEditorTab[0];
  }

  @Override
  public void readExternal(Element element) throws InvalidDataException {
    XmlSerializer.deserializeInto(this, element);
  }

  @Override
  public void writeExternal(Element element) throws WriteExternalException {
    XmlSerializer.serializeInto(this, element);
  }
}


text:
dlfcn-win32 [![Build status](https://ci.appveyor.com/api/projects/status/celmbkqj0k41fk04/branch/master?svg=true)](https://ci.appveyor.com/project/dlfcn-win32/dlfcn-win32/branch/master)
===========

dlfcn-win32 is an implementation of dlfcn for Windows.

dlfcn is a set of functions that allows runtime dynamic library loading. It is
standardized in the POSIX. Windows also provide similar routines, but not in a
POSIX-compatible way. This library attempts to implement a wrapper around the
Windows functions to make programs written for POSIX that use dlfcn work in
Windows without any modifications.

It follows the standard as described here:

http://www.opengroup.org/onlinepubs/009695399/basedefs/dlfcn.h.html
http://www.opengroup.org/onlinepubs/009695399/functions/dlerror.html
http://www.opengroup.org/onlinepubs/009695399/functions/dlsym.html
http://www.opengroup.org/onlinepubs/009695399/functions/dlclose.html
http://www.opengroup.org/onlinepubs/009695399/functions/dlopen.html

Using This Library
------------------

### Using CMake
Once the library has been installed, add to your project `CMakeLists.txt` :
~~~
...
find_package(dlfcn-win32 REQUIRED)
...
target_link_libraries(<target> dlfcn-win32::dl)
...
~~~
If you want to use this library in a cross-platform project, a convenient way
to proceed is to define the CMake variable [`CMAKE_DL_LIBS`](https://cmake.org/cmake/help/latest/variable/CMAKE_DL_LIBS.html)
(that is normally empty on Windows) and then use it for linking:
~~~
...
if (WIN32)
  find_package(dlfcn-win32 REQUIRED)
  set(CMAKE_DL_LIBS dlfcn-win32::dl)
endif ()
...
target_link_libraries(<target> ${CMAKE_DL_LIBS})
...
~~~

When cross-compiling you might want to set CMAKE_CROSSCOMPILING_EMULATOR to the path of wine to run tests.

Author
------

Written by Ramiro Polla in 2007.
Maintained by Tiancheng "Timothy" Gu from 2013.

License
-------

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.


text: Dispute dispute = Dispute.Fetch(dispute_href);


text:
package net.mindengine.jeremy.tests;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.mindengine.jeremy.exceptions.DeserializationException;
import net.mindengine.jeremy.exceptions.SerializationException;
import net.mindengine.jeremy.messaging.LanguageHandler;
import net.mindengine.jeremy.messaging.json.DefaultJsonLanguageHandler;
import net.mindengine.jeremy.objects.SerialObject;
import net.mindengine.jeremy.tests.mocks.HttpRequestMock;

import org.junit.Test;

public class RequestResponseHandlerUnitTest {

    public Long sampleMethod(String arg1, Integer arg2, Integer[]arg3) {
        return 123L;
    }

    @Test
    public void jsonSerializationForSimpleMethodArgumentsShouldWork() throws SerializationException {
        LanguageHandler handler = new DefaultJsonLanguageHandler();

        assertEquals("\"string text\"", handler.serializeResponse("string text"));
        assertEquals("132", handler.serializeResponse((Integer)132));
        assertEquals("[3,4,1]", handler.serializeResponse(new Integer[]{3,4,1}));
    }

    /**
     * Just a sample method so it could be used in unit test for testing deserialization
     */
    public void testMethod(SerialObject object) {

    }

    @Test
    public void jsonSerializationDeserializationForComplexObjectShouldWork() throws SerializationException, IOException, URISyntaxException, SecurityException, DeserializationException, NoSuchMethodException {
        SerialObject obj = new SerialObject();
        Date date = new Date(1319180501953L);
        obj.setDate(date);
        obj.setDoubleField(12.3);
        obj.setFloatField(23.1f);

        List<SerialObject> list =new LinkedList<SerialObject>();
        list.add(new SerialObject("obj1"));
        list.add(new SerialObject("obj2"));
        list.add(new SerialObject("obj3"));
        obj.setListOfObjects(list);

        obj.setLongField(45L);

        Map<String, SerialObject> map = new HashMap<String, SerialObject>();
        map.put("obj1", new SerialObject("map_object1"));
        map.put("obj2", new SerialObject("map_object2"));
        obj.setMapOfObjects(map);

        obj.setNestedObject(new SerialObject("Nested object"));
        obj.setStringField("object");
        LanguageHandler handler = new DefaultJsonLanguageHandler();
        String serialized = handler.serializeResponse(obj);

        HttpServletRequest request = new HttpRequestMock();
        ((HttpRequestMock)request).putParameter("arg0", serialized);

        SerialObject objDes = (SerialObject) handler.deserializeObject(serialized, SerialObject.class);

        assertNotNull(objDes);

        assertEquals(1319180501953L, objDes.getDate().getTime());
        assertEquals((Double)12.3, objDes.getDoubleField());
        assertEquals((Float)23.1f, objDes.getFloatField());
        assertEquals((int)3, objDes.getListOfObjects().size());
        assertEquals("obj1", objDes.getListOfObjects().get(0).getStringField());
        assertNull(objDes.getListOfObjects().get(0).getDoubleField());
        assertEquals("obj2", objDes.getListOfObjects().get(1).getStringField());
        assertNull(objDes.getListOfObjects().get(1).getDoubleField());
        assertEquals("obj3", objDes.getListOfObjects().get(2).getStringField());
        assertNull(objDes.getListOfObjects().get(2).getDoubleField());

        assertEquals((Long)45L, objDes.getLongField());

        assertEquals("map_object1", objDes.getMapOfObjects().get("obj1").getStringField());
        assertEquals("map_object2", objDes.getMapOfObjects().get("obj2").getStringField());

        assertEquals("Nested object", objDes.getNestedObject().getStringField());
        assertEquals("object", objDes.getStringField());
    }
}


text: body,input,select,textarea{font-size:12pt}


text:
package com.hekta.chdynmap.abstraction.bukkit;

import com.hekta.chdynmap.abstraction.MCDynmapIcon;
import com.hekta.chdynmap.abstraction.enums.MCDynmapIconSize;
import com.hekta.chdynmap.abstraction.enums.bukkit.BukkitMCDynmapIconSize;
import com.laytonsmith.abstraction.Implementation;
import com.laytonsmith.annotations.abstraction;
import java.io.InputStream;
import org.dynmap.markers.MarkerIcon;

/**
 *
 * @author Hekta
 */
@abstraction(type = Implementation.Type.BUKKIT)
public class BukkitMCDynmapIcon implements MCDynmapIcon {

	private final MarkerIcon _icon;

	public BukkitMCDynmapIcon(MarkerIcon icon) {
		_icon = icon;
	}

	public BukkitMCDynmapIcon(Object object) {
		this((MarkerIcon) object);
	}

	@Override
	public MarkerIcon getHandle() {
		return _icon;
	}

	@Override
	public String getId() {
		return _icon.getMarkerIconID();
	}

	@Override
	public String getLabel() {
		return _icon.getMarkerIconLabel();
	}

	@Override
	public void setLabel(String label) {
		_icon.setMarkerIconLabel(label);
	}

	@Override
	public void setImage(InputStream image) {
		_icon.setMarkerIconImage(image);
	}

	@Override
	public void delete() {
		_icon.deleteIcon();
	}

	@Override
	public boolean isBuiltIn() {
		return _icon.isBuiltIn();
	}

	@Override
	public MCDynmapIconSize getSize() {
		return BukkitMCDynmapIconSize.getConvertor().getAbstractedEnum(_icon.getMarkerIconSize());
	}
}


text:
import unittest
import os
import tempfile
import cv2
import shutil
import numpy as np
from PIL import Image

import paddle
from paddle.vision import image_load, set_image_backend
from paddle.vision.datasets import DatasetFolder
from paddle.vision.transforms import transforms
import paddle.vision.transforms.functional as F

class TestTransformsCV2(unittest.TestCase):
    def setUp(self):
        self.backend = self.get_backend()
        set_image_backend(self.backend)
        self.data_dir = tempfile.mkdtemp()
        for i in range(2):
            sub_dir = os.path.join(self.data_dir, 'class_' + str(i))
            if not os.path.exists(sub_dir):
                os.makedirs(sub_dir)
            for j in range(2):
                if j == 0:
                    fake_img = (np.random.random((280, 350, 3)) * 255).astype(
                        'uint8'
                    )
                else:
                    fake_img = (np.random.random((400, 300, 3)) * 255).astype(
                        'uint8'
                    )
                cv2.imwrite(os.path.join(sub_dir, str(j) + '.jpg'), fake_img)

    def get_backend(self):
        return 'cv2'

    def create_image(self, shape):
        if self.backend == 'cv2':
            return (np.random.rand(*shape) * 255).astype('uint8')
        elif self.backend == 'pil':
            return Image.fromarray(
                (np.random.rand(*shape) * 255).astype('uint8')
            )

    def get_shape(self, img):
        if isinstance(img, paddle.Tensor):
            return img.shape

        elif self.backend == 'pil':
            return np.array(img).shape

        return img.shape

    def tearDown(self):
        shutil.rmtree(self.data_dir)

    def do_transform(self, trans):
        dataset_folder = DatasetFolder(self.data_dir, transform=trans)

        for _ in dataset_folder:
            pass

    def test_trans_all(self):
        normalize = transforms.Normalize(
            mean=[123.675, 116.28, 103.53],
            std=[58.395, 57.120, 57.375],
        )
        trans = transforms.Compose(
            [
                transforms.RandomResizedCrop(224),
                transforms.ColorJitter(
                    brightness=0.4, contrast=0.4, saturation=0.4, hue=0.4
                ),
                transforms.RandomHorizontalFlip(),
                transforms.Transpose(),
                normalize,
            ]
        )

        self.do_transform(trans)

    def test_normalize(self):
        normalize = transforms.Normalize(mean=0.5, std=0.5)
        trans = transforms.Compose([transforms.Transpose(), normalize])
        self.do_transform(trans)

    def test_trans_resize(self):
        trans = transforms.Compose(
            [
                transforms.Resize(300),
                transforms.RandomResizedCrop((280, 280)),
                transforms.Resize(280),
                transforms.Resize((256, 200)),
                transforms.Resize((180, 160)),
                transforms.CenterCrop(128),
                transforms.CenterCrop((128, 128)),
            ]
        )
        self.do_transform(trans)

    def test_flip(self):
        trans = transforms.Compose(
            [
                transforms.RandomHorizontalFlip(1.0),
                transforms.RandomHorizontalFlip(0.0),
                transforms.RandomVerticalFlip(0.0),
                transforms.RandomVerticalFlip(1.0),
            ]
        )
        self.do_transform(trans)

    def test_color_jitter(self):
        trans = transforms.Compose(
            [
                transforms.BrightnessTransform(0.0),
                transforms.HueTransform(0.0),
                transforms.SaturationTransform(0.0),
                transforms.ContrastTransform(0.0),
            ]
        )
        self.do_transform(trans)

    def test_affine(self):
        trans = transforms.Compose(
            [
                transforms.RandomAffine(90),
                transforms.RandomAffine([-10, 10], translate=[0.1, 0.3]),
                transforms.RandomAffine(
                    45, translate=[0.2, 0.2], scale=[0.2, 0.5]
                ),
                transforms.RandomAffine(
                    10, translate=[0.2, 0.2], scale=[0.5, 0.5], shear=[-10, 10]
                ),
                transforms.RandomAffine(
                    10,
                    translate=[0.5, 0.3],
                    scale=[0.7, 1.3],
                    shear=[-10, 10, 20, 40],
                ),
                transforms.RandomAffine(
                    10,
                    translate=[0.5, 0.3],
                    scale=[0.7, 1.3],
                    shear=[-10, 10, 20, 40],
                    interpolation='bilinear',
                ),
                transforms.RandomAffine(
                    10,
                    translate=[0.5, 0.3],
                    scale=[0.7, 1.3],
                    shear=[-10, 10, 20, 40],
                    interpolation='bilinear',
                    fill=114,
                ),
                transforms.RandomAffine(
                    10,
                    translate=[0.5, 0.3],
                    scale=[0.7, 1.3],
                    shear=[-10, 10, 20, 40],
                    interpolation='bilinear',
                    fill=114,
                    center=(60, 80),
                ),
            ]
        )
        self.do_transform(trans)

    def test_rotate(self):
        trans = transforms.Compose(
            [
                transforms.RandomRotation(90),
                transforms.RandomRotation([-10, 10]),
                transforms.RandomRotation(45, expand=True),
                transforms.RandomRotation(10, expand=True, center=(60, 80)),
            ]
        )
        self.do_transform(trans)

    def test_perspective(self):
        trans = transforms.Compose(
            [
                transforms.RandomPerspective(prob=1.0),
                transforms.RandomPerspective(prob=1.0, distortion_scale=0.9),
            ]
        )
        self.do_transform(trans)

    def test_pad(self):
        trans = transforms.Compose([transforms.Pad(2)])
        self.do_transform(trans)

        fake_img = self.create_image((200, 150, 3))
        trans_pad = transforms.Pad(10)
        fake_img_padded = trans_pad(fake_img)
        np.testing.assert_equal(self.get_shape(fake_img_padded), (220, 170, 3))
        trans_pad1 = transforms.Pad([1, 2])
        trans_pad2 = transforms.Pad([1, 2, 3, 4])
        img = trans_pad1(fake_img)
        img = trans_pad2(img)

    def test_random_crop(self):
        trans = transforms.Compose(
            [
                transforms.RandomCrop(200),
                transforms.RandomCrop((140, 160)),
            ]
        )
        self.do_transform(trans)

        trans_random_crop1 = transforms.RandomCrop(224)
        trans_random_crop2 = transforms.RandomCrop((140, 160))

        fake_img = self.create_image((500, 400, 3))
        fake_img_crop1 = trans_random_crop1(fake_img)
        fake_img_crop2 = trans_random_crop2(fake_img_crop1)

        np.testing.assert_equal(self.get_shape(fake_img_crop1), (224, 224, 3))

        np.testing.assert_equal(self.get_shape(fake_img_crop2), (140, 160, 3))

        trans_random_crop_same = transforms.RandomCrop((140, 160))
        img = trans_random_crop_same(fake_img_crop2)

        trans_random_crop_bigger = transforms.RandomCrop(
            (180, 200), pad_if_needed=True
        )
        img = trans_random_crop_bigger(img)

        trans_random_crop_pad = transforms.RandomCrop((224, 256), 2, True)
        img = trans_random_crop_pad(img)

    def test_erase(self):
        trans = transforms.Compose(
            [
                transforms.RandomErasing(),
                transforms.RandomErasing(value="random"),
            ]
        )
        self.do_transform(trans)

    def test_grayscale(self):
        trans = transforms.Compose([transforms.Grayscale()])
        self.do_transform(trans)

        trans_gray = transforms.Grayscale()
        fake_img = self.create_image((500, 400, 3))
        fake_img_gray = trans_gray(fake_img)

        np.testing.assert_equal(self.get_shape(fake_img_gray)[0], 500)
        np.testing.assert_equal(self.get_shape(fake_img_gray)[1], 400)

        trans_gray3 = transforms.Grayscale(3)
        fake_img = self.create_image((500, 400, 3))
        fake_img_gray = trans_gray3(fake_img)

    def test_tranpose(self):
        trans = transforms.Compose([transforms.Transpose()])
        self.do_transform(trans)

        fake_img = self.create_image((50, 100, 3))
        converted_img = trans(fake_img)

        np.testing.assert_equal(self.get_shape(converted_img), (3, 50, 100))

    def test_to_tensor(self):
        trans = transforms.Compose([transforms.ToTensor()])
        fake_img = self.create_image((50, 100, 3))

        tensor = trans(fake_img)

        assert isinstance(tensor, paddle.Tensor)
        np.testing.assert_equal(tensor.shape, (3, 50, 100))

    def test_keys(self):
        fake_img1 = self.create_image((200, 150, 3))
        fake_img2 = self.create_image((200, 150, 3))
        trans_pad = transforms.Pad(10, keys=("image",))
        fake_img_padded = trans_pad((fake_img1, fake_img2))

    def test_exception(self):
        trans = transforms.Compose([transforms.Resize(-1)])

        trans_batch = transforms.Compose([transforms.Resize(-1)])

        with self.assertRaises(Exception):
            self.do_transform(trans)

        with self.assertRaises(Exception):
            self.do_transform(trans_batch)

        with self.assertRaises(ValueError):
            transforms.ContrastTransform(-1.0)

        with self.assertRaises(ValueError):
            transforms.SaturationTransform(-1.0),

        with self.assertRaises(ValueError):
            transforms.HueTransform(-1.0)

        with self.assertRaises(ValueError):
            transforms.BrightnessTransform(-1.0)

        with self.assertRaises(ValueError):
            transforms.Pad([1.0, 2.0, 3.0])

        with self.assertRaises(TypeError):
            fake_img = self.create_image((100, 120, 3))
            F.pad(fake_img, '1')

        with self.assertRaises(TypeError):
            fake_img = self.create_image((100, 120, 3))
            F.pad(fake_img, 1, {})

        with self.assertRaises(TypeError):
            fake_img = self.create_image((100, 120, 3))
            F.pad(fake_img, 1, padding_mode=-1)

        with self.assertRaises(ValueError):
            fake_img = self.create_image((100, 120, 3))
            F.pad(fake_img, [1.0, 2.0, 3.0])

        with self.assertRaises(TypeError):
            tensor_img = paddle.rand((3, 100, 100))
            F.pad(tensor_img, '1')

        with self.assertRaises(TypeError):
            tensor_img = paddle.rand((3, 100, 100))
            F.pad(tensor_img, 1, {})

        with self.assertRaises(TypeError):
            tensor_img = paddle.rand((3, 100, 100))
            F.pad(tensor_img, 1, padding_mode=-1)

        with self.assertRaises(ValueError):
            tensor_img = paddle.rand((3, 100, 100))
            F.pad(tensor_img, [1.0, 2.0, 3.0])

        with self.assertRaises(ValueError):
            transforms.RandomAffine(-10)

        with self.assertRaises(ValueError):
            transforms.RandomAffine([-30, 60], translate=[2, 2])

        with self.assertRaises(ValueError):
            transforms.RandomAffine(10, translate=[0.2, 0.2], scale=[1, 2, 3]),

        with self.assertRaises(ValueError):
            transforms.RandomAffine(
                10, translate=[0.2, 0.2], scale=[0.5, 0.5], shear=[1, 2, 3]
            ),

        with self.assertRaises(ValueError):
            transforms.RandomAffine(
                10,
                translate=[0.5, 0.3],
                scale=[0.7, 1.3],
                shear=[-10, 10, 0, 20, 40],
            )

        with self.assertRaises(ValueError):
            transforms.RandomAffine(
                10,
                translate=[0.5, 0.3],
                scale=[0.7, 1.3],
                shear=[-10, 10, 20, 40],
                fill=114,
                center=(1, 2, 3),
            )

        with self.assertRaises(ValueError):
            transforms.RandomRotation(-2)

        with self.assertRaises(ValueError):
            transforms.RandomRotation([1, 2, 3])

        with self.assertRaises(ValueError):
            trans_gray = transforms.Grayscale(5)
            fake_img = self.create_image((100, 120, 3))
            trans_gray(fake_img)

        with self.assertRaises(TypeError):
            transform = transforms.RandomResizedCrop(64)
            transform(1)

        with self.assertRaises(ValueError):
            transform = transforms.BrightnessTransform([-0.1, -0.2])

        with self.assertRaises(TypeError):
            transform = transforms.BrightnessTransform('0.1')

        with self.assertRaises(ValueError):
            transform = transforms.BrightnessTransform('0.1', keys=1)

        with self.assertRaises(NotImplementedError):
            transform = transforms.BrightnessTransform('0.1', keys='a')

        with self.assertRaises(Exception):
            transform = transforms.RandomErasing(scale=0.5)

        with self.assertRaises(Exception):
            transform = transforms.RandomErasing(ratio=0.8)

        with self.assertRaises(Exception):
            transform = transforms.RandomErasing(scale=(10, 0.4))

        with self.assertRaises(Exception):
            transform = transforms.RandomErasing(ratio=(3.3, 0.3))

        with self.assertRaises(Exception):
            transform = transforms.RandomErasing(prob=1.5)

        with self.assertRaises(Exception):
            transform = transforms.RandomErasing(value="0")

    def test_info(self):
        str(transforms.Compose([transforms.Resize((224, 224))]))
        str(transforms.Compose([transforms.Resize((224, 224))]))

class TestTransformsPIL(TestTransformsCV2):
    def get_backend(self):
        return 'pil'

class TestTransformsTensor(TestTransformsCV2):
    def get_backend(self):
        return 'tensor'

    def create_image(self, shape):
        return paddle.to_tensor(np.random.rand(*shape)).transpose(
            (2, 0, 1)
        )  # hwc->chw

    def do_transform(self, trans):
        trans.transforms.insert(0, transforms.ToTensor(data_format='CHW'))
        trans.transforms.append(transforms.Transpose(order=(1, 2, 0)))
        dataset_folder = DatasetFolder(self.data_dir, transform=trans)
        for _ in dataset_folder:
            pass

    def test_trans_all(self):
        normalize = transforms.Normalize(
            mean=[123.675, 116.28, 103.53],
            std=[58.395, 57.120, 57.375],
        )
        trans = transforms.Compose(
            [
                transforms.RandomResizedCrop(224),
                transforms.RandomHorizontalFlip(),
                normalize,
            ]
        )
        self.do_transform(trans)

    def test_grayscale(self):
        trans = transforms.Compose([transforms.Grayscale()])
        self.do_transform(trans)

        trans_gray = transforms.Grayscale()
        fake_img = self.create_image((500, 400, 3))
        fake_img_gray = trans_gray(fake_img)

        np.testing.assert_equal(self.get_shape(fake_img_gray)[1], 500)
        np.testing.assert_equal(self.get_shape(fake_img_gray)[2], 400)

        trans_gray3 = transforms.Grayscale(3)
        fake_img = self.create_image((500, 400, 3))
        fake_img_gray = trans_gray3(fake_img)

    def test_normalize(self):
        normalize = transforms.Normalize(mean=0.5, std=0.5)
        trans = transforms.Compose([normalize])
        self.do_transform(trans)

    def test_color_jitter(self):
        trans = transforms.Compose([transforms.ColorJitter(1.1, 2.2, 0.8, 0.1)])
        self.do_transform(trans)

        color_jitter_trans = transforms.ColorJitter(1.2, 0.2, 0.5, 0.2)
        batch_input = paddle.rand((2, 3, 4, 4), dtype=paddle.float32)
        result = color_jitter_trans(batch_input)

    def test_perspective(self):
        trans = transforms.RandomPerspective(prob=1.0, distortion_scale=0.7)
        batch_input = paddle.rand((2, 3, 4, 4), dtype=paddle.float32)
        result = trans(batch_input)

    def test_affine(self):
        trans = transforms.RandomAffine(15, translate=[0.1, 0.1])
        batch_input = paddle.rand((2, 3, 4, 4), dtype=paddle.float32)
        result = trans(batch_input)

    def test_pad(self):
        trans = transforms.Compose([transforms.Pad(2)])
        self.do_transform(trans)

        fake_img = self.create_image((200, 150, 3))
        trans_pad = transforms.Compose([transforms.Pad(10)])
        fake_img_padded = trans_pad(fake_img)
        np.testing.assert_equal(self.get_shape(fake_img_padded), (3, 220, 170))
        trans_pad1 = transforms.Pad([1, 2])
        trans_pad2 = transforms.Pad([1, 2, 3, 4])
        trans_pad4 = transforms.Pad(1, padding_mode='edge')
        img = trans_pad1(fake_img)
        img = trans_pad2(img)
        img = trans_pad4(img)

    def test_random_crop(self):
        trans = transforms.Compose(
            [
                transforms.RandomCrop(200),
                transforms.RandomCrop((140, 160)),
            ]
        )
        self.do_transform(trans)

        trans_random_crop1 = transforms.RandomCrop(224)
        trans_random_crop2 = transforms.RandomCrop((140, 160))

        fake_img = self.create_image((500, 400, 3))
        fake_img_crop1 = trans_random_crop1(fake_img)
        fake_img_crop2 = trans_random_crop2(fake_img_crop1)

        np.testing.assert_equal(self.get_shape(fake_img_crop1), (3, 224, 224))

        np.testing.assert_equal(self.get_shape(fake_img_crop2), (3, 140, 160))

        trans_random_crop_same = transforms.RandomCrop((140, 160))
        img = trans_random_crop_same(fake_img_crop2)

        trans_random_crop_bigger = transforms.RandomCrop(
            (180, 200), pad_if_needed=True
        )
        img = trans_random_crop_bigger(img)

        trans_random_crop_pad = transforms.RandomCrop((224, 256), 2, True)
        img = trans_random_crop_pad(img)

    def test_erase(self):
        trans = transforms.Compose(
            [
                transforms.RandomErasing(value=(0.5,)),
                transforms.RandomErasing(value="random"),
            ]
        )
        self.do_transform(trans)

        erase_trans = transforms.RandomErasing(value=(0.5, 0.2, 0.01))
        batch_input = paddle.rand((2, 3, 4, 4), dtype=paddle.float32)
        result = erase_trans(batch_input)

    def test_exception(self):
        trans = transforms.Compose([transforms.Resize(-1)])

        trans_batch = transforms.Compose([transforms.Resize(-1)])

        with self.assertRaises(Exception):
            self.do_transform(trans)

        with self.assertRaises(Exception):
            self.do_transform(trans_batch)

        with self.assertRaises(ValueError):
            transforms.Pad([1.0, 2.0, 3.0])

        with self.assertRaises(TypeError):
            fake_img = self.create_image((100, 120, 3))
            F.pad(fake_img, '1')

        with self.assertRaises(TypeError):
            fake_img = self.create_image((100, 120, 3))
            F.pad(fake_img, 1, {})

        with self.assertRaises(TypeError):
            fake_img = self.create_image((100, 120, 3))
            F.pad(fake_img, 1, padding_mode=-1)

        with self.assertRaises(ValueError):
            fake_img = self.create_image((100, 120, 3))
            F.pad(fake_img, [1.0, 2.0, 3.0])

        with self.assertRaises(TypeError):
            tensor_img = paddle.rand((3, 100, 100))
            F.pad(tensor_img, '1')

        with self.assertRaises(TypeError):
            tensor_img = paddle.rand((3, 100, 100))
            F.pad(tensor_img, 1, {})

        with self.assertRaises(TypeError):
            tensor_img = paddle.rand((3, 100, 100))
            F.pad(tensor_img, 1, padding_mode=-1)

        with self.assertRaises(ValueError):
            tensor_img = paddle.rand((3, 100, 100))
            F.pad(tensor_img, [1.0, 2.0, 3.0])

        with self.assertRaises(ValueError):
            transforms.RandomAffine(-10)

        with self.assertRaises(ValueError):
            transforms.RandomAffine([-30, 60], translate=[2, 2])

        with self.assertRaises(ValueError):
            transforms.RandomAffine(10, translate=[0.2, 0.2], scale=[-2, -1]),

        with self.assertRaises(ValueError):
            transforms.RandomAffine(10, translate=[0.2, 0.2], scale=[1, 2, 3]),

        with self.assertRaises(ValueError):
            transforms.RandomAffine(
                10, translate=[0.2, 0.2], scale=[0.5, 0.5], shear=[1, 2, 3]
            ),

        with self.assertRaises(ValueError):
            transforms.RandomAffine(
                10,
                translate=[0.5, 0.3],
                scale=[0.7, 1.3],
                shear=[-10, 10, 0, 20, 40],
            )

        with self.assertRaises(ValueError):
            transforms.RandomRotation(-2)

        with self.assertRaises(ValueError):
            transforms.RandomRotation([1, 2, 3])

        with self.assertRaises(ValueError):
            trans_gray = transforms.Grayscale(5)
            fake_img = self.create_image((100, 120, 3))
            trans_gray(fake_img)

        with self.assertRaises(TypeError):
            transform = transforms.RandomResizedCrop(64)
            transform(1)

    test_color_jitter = None

class TestFunctional(unittest.TestCase):
    def test_errors(self):
        with self.assertRaises(TypeError):
            F.to_tensor(1)

        with self.assertRaises(ValueError):
            fake_img = Image.fromarray(
                (np.random.rand(28, 28, 3) * 255).astype('uint8')
            )
            F.to_tensor(fake_img, data_format=1)

        with self.assertRaises(ValueError):
            fake_img = paddle.rand((3, 100, 100))
            F.pad(fake_img, 1, padding_mode='symmetric')

        with self.assertRaises(TypeError):
            fake_img = paddle.rand((3, 100, 100))
            F.resize(fake_img, {1: 1})

        with self.assertRaises(TypeError):
            fake_img = Image.fromarray(
                (np.random.rand(28, 28, 3) * 255).astype('uint8')
            )
            F.resize(fake_img, '1')

        with self.assertRaises(TypeError):
            F.resize(1, 1)

        with self.assertRaises(TypeError):
            F.pad(1, 1)

        with self.assertRaises(TypeError):
            F.crop(1, 1, 1, 1, 1)

        with self.assertRaises(TypeError):
            F.hflip(1)

        with self.assertRaises(TypeError):
            F.vflip(1)

        with self.assertRaises(TypeError):
            F.adjust_brightness(1, 0.1)

        with self.assertRaises(TypeError):
            F.adjust_contrast(1, 0.1)

        with self.assertRaises(TypeError):
            F.adjust_hue(1, 0.1)

        with self.assertRaises(TypeError):
            F.adjust_saturation(1, 0.1)

        with self.assertRaises(TypeError):
            F.affine('45')

        with self.assertRaises(TypeError):
            F.affine(45, translate=0.3)

        with self.assertRaises(TypeError):
            F.affine(45, translate=[0.2, 0.2, 0.3])

        with self.assertRaises(TypeError):
            F.affine(45, translate=[0.2, 0.2], scale=-0.5)

        with self.assertRaises(TypeError):
            F.affine(45, translate=[0.2, 0.2], scale=0.5, shear=10)

        with self.assertRaises(TypeError):
            F.affine(45, translate=[0.2, 0.2], scale=0.5, shear=[-10, 0, 10])

        with self.assertRaises(TypeError):
            F.affine(
                45,
                translate=[0.2, 0.2],
                scale=0.5,
                shear=[-10, 10],
                interpolation=2,
            )

        with self.assertRaises(TypeError):
            F.affine(
                45, translate=[0.2, 0.2], scale=0.5, shear=[-10, 10], center=0
            )

        with self.assertRaises(TypeError):
            F.rotate(1, 0.1)

        with self.assertRaises(TypeError):
            F.to_grayscale(1)

        with self.assertRaises(ValueError):
            set_image_backend(1)

        with self.assertRaises(ValueError):
            image_load('tmp.jpg', backend=1)

    def test_normalize(self):
        np_img = (np.random.rand(28, 24, 3) * 255).astype('uint8')
        pil_img = Image.fromarray(np_img)
        tensor_img = F.to_tensor(pil_img)
        tensor_img_hwc = F.to_tensor(pil_img, data_format='HWC') * 255

        mean = [0.5, 0.5, 0.5]
        std = [0.5, 0.5, 0.5]

        normalized_img = F.normalize(tensor_img, mean, std)
        normalized_img_tensor = F.normalize(
            tensor_img_hwc, mean, std, data_format='HWC'
        )

        normalized_img_pil = F.normalize(pil_img, mean, std, data_format='HWC')
        normalized_img_np = F.normalize(
            np_img, mean, std, data_format='HWC', to_rgb=False
        )

        np.testing.assert_almost_equal(
            np.array(normalized_img_pil), normalized_img_np
        )
        np.testing.assert_almost_equal(
            normalized_img_tensor.numpy(), normalized_img_np, decimal=4
        )

    def test_center_crop(self):
        np_img = (np.random.rand(28, 24, 3) * 255).astype('uint8')
        pil_img = Image.fromarray(np_img)
        tensor_img = F.to_tensor(pil_img, data_format='CHW') * 255

        np_cropped_img = F.center_crop(np_img, 4)
        pil_cropped_img = F.center_crop(pil_img, 4)
        tensor_cropped_img = F.center_crop(tensor_img, 4)

        np.testing.assert_almost_equal(
            np_cropped_img, np.array(pil_cropped_img)
        )
        np.testing.assert_almost_equal(
            np_cropped_img,
            tensor_cropped_img.numpy().transpose((1, 2, 0)),
            decimal=4,
        )

    def test_color_jitter_sub_function(self):
        np.random.seed(555)
        np_img = (np.random.rand(28, 28, 3) * 255).astype('uint8')
        pil_img = Image.fromarray(np_img)
        tensor_img = F.to_tensor(np_img)
        np_img = pil_img

        np_img_gray = (np.random.rand(28, 28, 1) * 255).astype('uint8')
        tensor_img_gray = F.to_tensor(np_img_gray)

        places = ['cpu']
        if paddle.device.is_compiled_with_cuda():
            places.append('gpu')

        def test_adjust_brightness(np_img, tensor_img):
            result_cv2 = np.array(F.adjust_brightness(np_img, 1.2))
            result_tensor = F.adjust_brightness(tensor_img, 1.2).numpy()
            result_tensor = np.transpose(result_tensor * 255, (1, 2, 0)).astype(
                'uint8'
            )
            np.testing.assert_equal(result_cv2, result_tensor)

        # For adjust_contrast / adjust_saturation / adjust_hue the implement is kind
        # of different between PIL and Tensor. So the results can not equal exactly.

        def test_adjust_contrast(np_img, tensor_img):
            result_pil = np.array(F.adjust_contrast(np_img, 0.36))
            result_tensor = F.adjust_contrast(tensor_img, 0.36).numpy()
            result_tensor = np.transpose(result_tensor * 255, (1, 2, 0))
            diff = np.max(np.abs(result_tensor - result_pil))
            self.assertTrue(diff < 1.1)

        def test_adjust_saturation(np_img, tensor_img):
            result_pil = np.array(F.adjust_saturation(np_img, 1.0))
            result_tensor = F.adjust_saturation(tensor_img, 1.0).numpy()
            result_tensor = np.transpose(result_tensor * 255.0, (1, 2, 0))
            diff = np.max(np.abs(result_tensor - result_pil))
            self.assertTrue(diff < 1.1)

        def test_adjust_hue(np_img, tensor_img):
            result_pil = np.array(F.adjust_hue(np_img, 0.45))
            result_tensor = F.adjust_hue(tensor_img, 0.45).numpy()
            result_tensor = np.transpose(result_tensor * 255, (1, 2, 0))
            diff = np.max(np.abs(result_tensor - result_pil))
            self.assertTrue(diff <= 16.0)

        for place in places:
            paddle.set_device(place)

            test_adjust_brightness(np_img, tensor_img)
            test_adjust_contrast(np_img, tensor_img)
            test_adjust_saturation(np_img, tensor_img)
            test_adjust_hue(np_img, tensor_img)

    def test_pad(self):
        np_img = (np.random.rand(28, 24, 3) * 255).astype('uint8')
        pil_img = Image.fromarray(np_img)
        tensor_img = F.to_tensor(pil_img, 'CHW') * 255

        np_padded_img = F.pad(np_img, [1, 2], padding_mode='reflect')
        pil_padded_img = F.pad(pil_img, [1, 2], padding_mode='reflect')
        tensor_padded_img = F.pad(tensor_img, [1, 2], padding_mode='reflect')

        np.testing.assert_almost_equal(np_padded_img, np.array(pil_padded_img))
        np.testing.assert_almost_equal(
            np_padded_img,
            tensor_padded_img.numpy().transpose((1, 2, 0)),
            decimal=3,
        )

        tensor_padded_img = F.pad(tensor_img, 1, padding_mode='reflect')
        tensor_padded_img = F.pad(
            tensor_img, [1, 2, 1, 2], padding_mode='reflect'
        )

        pil_p_img = pil_img.convert('P')
        pil_padded_img = F.pad(pil_p_img, [1, 2])
        pil_padded_img = F.pad(pil_p_img, [1, 2], padding_mode='reflect')

    def test_resize(self):
        np_img = (np.zeros([28, 24, 3]) * 255).astype('uint8')
        pil_img = Image.fromarray(np_img)
        tensor_img = F.to_tensor(pil_img, 'CHW') * 255

        np_reseized_img = F.resize(np_img, 40)
        pil_reseized_img = F.resize(pil_img, 40)
        tensor_reseized_img = F.resize(tensor_img, 40)
        tensor_reseized_img2 = F.resize(tensor_img, (46, 40))

        np.testing.assert_almost_equal(
            np_reseized_img, np.array(pil_reseized_img)
        )
        np.testing.assert_almost_equal(
            np_reseized_img,
            tensor_reseized_img.numpy().transpose((1, 2, 0)),
            decimal=3,
        )
        np.testing.assert_almost_equal(
            np_reseized_img,
            tensor_reseized_img2.numpy().transpose((1, 2, 0)),
            decimal=3,
        )

        gray_img = (np.zeros([28, 32])).astype('uint8')
        gray_resize_img = F.resize(gray_img, 40)

    def test_to_tensor(self):
        np_img = (np.random.rand(28, 28) * 255).astype('uint8')
        pil_img = Image.fromarray(np_img)

        np_tensor = F.to_tensor(np_img, data_format='HWC')
        pil_tensor = F.to_tensor(pil_img, data_format='HWC')

        np.testing.assert_allclose(np_tensor.numpy(), pil_tensor.numpy())

        # test float dtype
        float_img = np.random.rand(28, 28)
        float_tensor = F.to_tensor(float_img)

        pil_img = Image.fromarray(np_img).convert('I')
        pil_tensor = F.to_tensor(pil_img)

        pil_img = Image.fromarray(np_img).convert('I;16')
        pil_tensor = F.to_tensor(pil_img)

        pil_img = Image.fromarray(np_img).convert('F')
        pil_tensor = F.to_tensor(pil_img)

        pil_img = Image.fromarray(np_img).convert('1')
        pil_tensor = F.to_tensor(pil_img)

        pil_img = Image.fromarray(np_img).convert('YCbCr')
        pil_tensor = F.to_tensor(pil_img)

    def test_erase(self):
        np_img = (np.random.rand(28, 28, 3) * 255).astype('uint8')
        pil_img = Image.fromarray(np_img).convert('RGB')

        expected = np_img.copy()
        expected[10:15, 10:15, :] = 0

        F.erase(np_img, 10, 10, 5, 5, 0, inplace=True)
        np.testing.assert_equal(np_img, expected)

        pil_result = F.erase(pil_img, 10, 10, 5, 5, 0)
        np.testing.assert_equal(np.array(pil_result), expected)

        np_data = np.random.rand(3, 28, 28).astype('float32')
        places = ['cpu']
        if paddle.device.is_compiled_with_cuda():
            places.append('gpu')
        for place in places:
            paddle.set_device(place)
            tensor_img = paddle.to_tensor(np_data)
            expected_tensor = tensor_img.clone()
            expected_tensor[:, 10:15, 10:15] = paddle.to_tensor([0.88])

            tensor_result = F.erase(
                tensor_img, 10, 10, 5, 5, paddle.to_tensor([0.88])
            )
            np.testing.assert_equal(
                tensor_result.numpy(), expected_tensor.numpy()
            )

    def test_erase_backward(self):
        img = paddle.randn((3, 14, 14), dtype=np.float32)
        img.stop_gradient = False
        erased = F.erase(
            img, 3, 3, 5, 5, paddle.ones((1, 1, 1), dtype='float32')
        )
        loss = erased.sum()
        loss.backward()

        expected_grad = np.ones((3, 14, 14), dtype=np.float32)
        expected_grad[:, 3:8, 3:8] = 0.0
        np.testing.assert_equal(img.grad.numpy(), expected_grad)

    def test_image_load(self):
        fake_img = Image.fromarray(
            (np.random.random((32, 32, 3)) * 255).astype('uint8')
        )

        temp_dir = tempfile.TemporaryDirectory()
        path = os.path.join(temp_dir.name, 'temp.jpg')
        fake_img.save(path)

        set_image_backend('pil')

        pil_img = image_load(path).convert('RGB')

        print(type(pil_img))

        set_image_backend('cv2')

        np_img = image_load(path)

        temp_dir.cleanup()

    def test_affine(self):
        np_img = (np.random.rand(32, 26, 3) * 255).astype('uint8')
        pil_img = Image.fromarray(np_img).convert('RGB')
        tensor_img = F.to_tensor(pil_img, data_format='CHW') * 255

        np.testing.assert_almost_equal(
            np_img, tensor_img.transpose((1, 2, 0)), decimal=4
        )

        np_affined_img = F.affine(
            np_img, 45, translate=[0.2, 0.2], scale=0.5, shear=[-10, 10]
        )
        pil_affined_img = F.affine(
            pil_img, 45, translate=[0.2, 0.2], scale=0.5, shear=[-10, 10]
        )
        tensor_affined_img = F.affine(
            tensor_img, 45, translate=[0.2, 0.2], scale=0.5, shear=[-10, 10]
        )

        np.testing.assert_equal(
            np_affined_img.shape, np.array(pil_affined_img).shape
        )
        np.testing.assert_equal(
            np_affined_img.shape, tensor_affined_img.transpose((1, 2, 0)).shape
        )

        np.testing.assert_almost_equal(
            np.array(pil_affined_img),
            tensor_affined_img.numpy().transpose((1, 2, 0)),
            decimal=4,
        )

    def test_rotate(self):
        np_img = (np.random.rand(28, 28, 3) * 255).astype('uint8')
        pil_img = Image.fromarray(np_img).convert('RGB')
        rotated_np_img = F.rotate(np_img, 80, expand=True)
        rotated_pil_img = F.rotate(pil_img, 80, expand=True)

        tensor_img = F.to_tensor(pil_img, 'CHW')

        rotated_tensor_img1 = F.rotate(tensor_img, 80, expand=True)

        rotated_tensor_img2 = F.rotate(
            tensor_img,
            80,
            interpolation='bilinear',
            center=(10, 10),
            expand=False,
        )

        np.testing.assert_equal(
            rotated_np_img.shape, np.array(rotated_pil_img).shape
        )
        np.testing.assert_equal(
            rotated_np_img.shape, rotated_tensor_img1.transpose((1, 2, 0)).shape
        )

    def test_rotate1(self):
        np_img = (np.random.rand(28, 28, 3) * 255).astype('uint8')
        pil_img = Image.fromarray(np_img).convert('RGB')

        rotated_np_img = F.rotate(
            np_img, 80, expand=True, center=[0, 0], fill=[0, 0, 0]
        )
        rotated_pil_img = F.rotate(
            pil_img, 80, expand=True, center=[0, 0], fill=[0, 0, 0]
        )

        np.testing.assert_equal(
            rotated_np_img.shape, np.array(rotated_pil_img).shape
        )

    def test_perspective(self):
        np_img = (np.random.rand(32, 26, 3) * 255).astype('uint8')
        pil_img = Image.fromarray(np_img).convert('RGB')
        tensor_img = F.to_tensor(pil_img, data_format='CHW') * 255

        np.testing.assert_almost_equal(
            np_img, tensor_img.transpose((1, 2, 0)), decimal=4
        )

        startpoints = [[0, 0], [13, 0], [13, 15], [0, 15]]
        endpoints = [[3, 2], [12, 3], [10, 14], [2, 15]]

        np_perspectived_img = F.perspective(np_img, startpoints, endpoints)
        pil_perspectived_img = F.perspective(pil_img, startpoints, endpoints)
        tensor_perspectived_img = F.perspective(
            tensor_img, startpoints, endpoints
        )

        np.testing.assert_equal(
            np_perspectived_img.shape, np.array(pil_perspectived_img).shape
        )
        np.testing.assert_equal(
            np_perspectived_img.shape,
            tensor_perspectived_img.transpose((1, 2, 0)).shape,
        )

        result_pil = np.array(pil_perspectived_img)
        result_tensor = (
            tensor_perspectived_img.numpy().transpose((1, 2, 0)).astype('uint8')
        )
        num_diff_pixels = (result_pil != result_tensor).sum() / 3.0
        ratio_diff_pixels = (
            num_diff_pixels / result_tensor.shape[0] / result_tensor.shape[1]
        )
        # Tolerance : less than 6% of different pixels
        assert ratio_diff_pixels < 0.06

    def test_batch_input(self):
        paddle.seed(777)
        batch_tensor = paddle.rand((2, 3, 8, 8), dtype=paddle.float32)

        def test_erase(batch_tensor):
            input1, input2 = paddle.unbind(batch_tensor, axis=0)
            target_result = paddle.stack(
                [
                    F.erase(input1, 1, 1, 2, 2, 0.5),
                    F.erase(input2, 1, 1, 2, 2, 0.5),
                ]
            )

            batch_result = F.erase(batch_tensor, 1, 1, 2, 2, 0.5)

            return paddle.allclose(batch_result, target_result)

        self.assertTrue(test_erase(batch_tensor))

        def test_affine(batch_tensor):
            input1, input2 = paddle.unbind(batch_tensor, axis=0)
            target_result = paddle.stack(
                [
                    F.affine(
                        input1,
                        45,
                        translate=[0.2, 0.2],
                        scale=0.5,
                        shear=[-10, 10],
                    ),
                    F.affine(
                        input2,
                        45,
                        translate=[0.2, 0.2],
                        scale=0.5,
                        shear=[-10, 10],
                    ),
                ]
            )
            batch_result = F.affine(
                batch_tensor,
                45,
                translate=[0.2, 0.2],
                scale=0.5,
                shear=[-10, 10],
            )

            return paddle.allclose(batch_result, target_result)

        self.assertTrue(test_affine(batch_tensor))

        def test_perspective(batch_tensor):
            input1, input2 = paddle.unbind(batch_tensor, axis=0)
            startpoints = [[0, 0], [3, 0], [4, 5], [6, 7]]
            endpoints = [[0, 1], [3, 1], [4, 4], [5, 7]]
            target_result = paddle.stack(
                [
                    F.perspective(input1, startpoints, endpoints),
                    F.perspective(input2, startpoints, endpoints),
                ]
            )

            batch_result = F.perspective(batch_tensor, startpoints, endpoints)

            return paddle.allclose(batch_result, target_result)

        self.assertTrue(test_perspective(batch_tensor))

        def test_adjust_brightness(batch_tensor):
            input1, input2 = paddle.unbind(batch_tensor, axis=0)
            target_result = paddle.stack(
                [
                    F.adjust_brightness(input1, 2.1),
                    F.adjust_brightness(input2, 2.1),
                ]
            )

            batch_result = F.adjust_brightness(batch_tensor, 2.1)

            return paddle.allclose(batch_result, target_result)

        self.assertTrue(test_adjust_brightness(batch_tensor))

        def test_adjust_contrast(batch_tensor):
            input1, input2 = paddle.unbind(batch_tensor, axis=0)
            target_result = paddle.stack(
                [F.adjust_contrast(input1, 0.3), F.adjust_contrast(input2, 0.3)]
            )

            batch_result = F.adjust_contrast(batch_tensor, 0.3)

            return paddle.allclose(batch_result, target_result)

        self.assertTrue(test_adjust_contrast(batch_tensor))

        def test_adjust_saturation(batch_tensor):
            input1, input2 = paddle.unbind(batch_tensor, axis=0)
            target_result = paddle.stack(
                [
                    F.adjust_saturation(input1, 1.1),
                    F.adjust_saturation(input2, 1.1),
                ]
            )

            batch_result = F.adjust_saturation(batch_tensor, 1.1)

            return paddle.allclose(batch_result, target_result)

        self.assertTrue(test_adjust_saturation(batch_tensor))

        def test_adjust_hue(batch_tensor):
            input1, input2 = paddle.unbind(batch_tensor, axis=0)
            target_result = paddle.stack(
                [F.adjust_hue(input1, -0.2), F.adjust_hue(input2, -0.2)]
            )

            batch_result = F.adjust_hue(batch_tensor, -0.2)

            return paddle.allclose(batch_result, target_result)

        self.assertTrue(test_adjust_hue(batch_tensor))

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


text:
import Sector from './lib/Sector';
import SectorManager from './lib/SectorManager';

export {
  Sector,
  SectorManager
};


text:
namespace RWEST.Nexus.MDM.Contracts
{
    using System.Runtime.Serialization;
    using System.Xml.Serialization;

    [DataContract(Namespace = "http://schemas.rwe.com/nexus")]
    [XmlType(Namespace = "http://schemas.rwe.com/nexus")]
    public class InstrumentTypeExceptionDetails
    {
        [DataMember(Order = 1)]
        [XmlElement]
        public string Name { get; set; }

        [DataMember(Order = 2)]
        [XmlElement]
        public EntityId ProductType { get; set; }

        [DataMember(Order = 3)]
        [XmlElement]
        public EntityId Broker { get; set; }

        [DataMember(Order = 4)]
        [XmlElement]
        public EntityId CommodityInstrumentType { get; set; }

        [DataMember(Order = 5)]
        [XmlElement]
        public string InstrumentSubType { get; set; }
    }
}


text:
"""
Exception definitions.
"""

class CommandError(Exception):
    pass

class ValidationError(Exception):
    pass

class AuthorizationFailure(Exception):
    pass

class NoTokenLookupException(Exception):
    """This form of authentication does not support looking up
       endpoints from an existing token."""
    pass

class EndpointNotFound(Exception):
    """Could not find Service or Region in Service Catalog."""
    pass

class EmptyCatalog(Exception):
    """ The service catalog is empty. """
    pass

class NoUniqueMatch(Exception):
    """Unable to find unique resource"""
    pass

class ClientException(Exception):
    """
    The base exception class for all exceptions this library raises.
    """
    def __init__(self, code, message=None, details=None):
        self.code = code
        self.message = message or self.__class__.message
        self.details = details

    def __str__(self):
        return "%s (HTTP %s)" % (self.message, self.code)

class BadRequest(ClientException):
    """
    HTTP 400 - Bad request: you sent some malformed data.
    """
    http_status = 400
    message = "Bad request"

class Unauthorized(ClientException):
    """
    HTTP 401 - Unauthorized: bad credentials.
    """
    http_status = 401
    message = "Unauthorized"

class Forbidden(ClientException):
    """
    HTTP 403 - Forbidden: your credentials don't give you access to this
    resource.
    """
    http_status = 403
    message = "Forbidden"

class NotFound(ClientException):
    """
    HTTP 404 - Not found
    """
    http_status = 404
    message = "Not found"

class MethodNotAllowed(ClientException):
    """
    HTTP 405 - Method not allowed
    """
    http_status = 405
    message = "Method not allowed"

class Conflict(ClientException):
    """
    HTTP 409 - Conflict
    """
    http_status = 409
    message = "Conflict"

class OverLimit(ClientException):
    """
    HTTP 413 - Over limit: you're over the API limits for this time period.
    """
    http_status = 413
    message = "Over limit"

# NotImplemented is a python keyword.
class HTTPNotImplemented(ClientException):
    """
    HTTP 501 - Not Implemented: the server does not support this operation.
    """
    http_status = 501
    message = "Not Implemented"

class ServiceUnavailable(ClientException):
    """
    HTTP 503 - Service Unavailable: The server is currently unavailable.
    """
    http_status = 503
    message = "Service Unavailable"

# In Python 2.4 Exception is old-style and thus doesn't have a __subclasses__()
# so we can do this:
#     _code_map = dict((c.http_status, c)
#                      for c in ClientException.__subclasses__())
#
# Instead, we have to hardcode it:
_code_map = dict((c.http_status, c) for c in [BadRequest,
                                              Unauthorized,
                                              Forbidden,
                                              NotFound,
                                              MethodNotAllowed,
                                              Conflict,
                                              OverLimit,
                                              HTTPNotImplemented,
                                              ServiceUnavailable])

def from_response(response, body):
    """
    Return an instance of an ClientException or subclass
    based on an requests response.

    Usage::

        resp = requests.request(...)
        if resp.status_code != 200:
            raise exception_from_response(resp, resp.text)
    """
    cls = _code_map.get(response.status_code, ClientException)
    if body:
        if hasattr(body, 'keys'):
            error = body[body.keys()[0]]
            message = error.get('message', None)
            details = error.get('details', None)
        else:
            # If we didn't get back a properly formed error message we
            # probably couldn't communicate with Keystone at all.
            message = "Unable to communicate with identity service: %s." % body
            details = None
        return cls(code=response.status_code, message=message, details=details)
    else:
        return cls(code=response.status_code)


text:
package xyz.openmodloader.gradle.util.delayed;

import xyz.openmodloader.gradle.ModGradleExtension;

public interface IDelayed<T> {
    T get(ModGradleExtension extension);
}


text: AD_EXPORT dispatch_time_t ADDispatchTimeSinceNow( NSTimeInterval time_interval_ );


text:
package za.org.grassroot.integration;

import com.amazonaws.AmazonServiceException;
import com.amazonaws.SdkClientException;
import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder;
import com.amazonaws.services.dynamodbv2.document.DynamoDB;
import com.amazonaws.services.dynamodbv2.document.Index;
import com.amazonaws.services.dynamodbv2.document.Item;
import com.amazonaws.services.dynamodbv2.document.Table;
import com.amazonaws.services.dynamodbv2.document.spec.QuerySpec;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import za.org.grassroot.core.domain.User;
import za.org.grassroot.core.domain.livewire.LiveWireAlert;
import za.org.grassroot.core.domain.media.MediaFileRecord;
import za.org.grassroot.core.domain.media.MediaFunction;
import za.org.grassroot.core.repository.MediaFileRecordRepository;
import za.org.grassroot.core.repository.UserRepository;
import za.org.grassroot.integration.storage.StorageBroker;

import javax.annotation.PostConstruct;
import java.time.Instant;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Service
public class MediaFileBrokerImpl implements MediaFileBroker {

    private static final Logger logger = LoggerFactory.getLogger(MediaFileBrokerImpl.class);

    @Value("${grassroot.task.images.bucket:null}")
    private String taskImagesBucket;

    @Value("${grassroot.livewire.media.bucket:grassroot-livewire-media}")
    private String liveWireMediaBucket;

    @Value("${grassroot.media.default.bucket:null}")
    private String defaultMediaBucket;

    @Value("${grassroot.campaign.media.enabled:false}")
    public boolean campaignMediaEnabled; // i.e., if we have these recorded in NoSQL table (over time will migrate all media to that pattern)

    private final StorageBroker storageBroker;
    private final UserRepository userRepository;
    private final MediaFileRecordRepository recordRepository;

    private AmazonDynamoDB dynamoDBClient;

    public MediaFileBrokerImpl(StorageBroker storageBroker, UserRepository userRepository, MediaFileRecordRepository recordRepository) {
        this.storageBroker = storageBroker;
        this.userRepository = userRepository;
        this.recordRepository = recordRepository;
    }

    @PostConstruct
    public void init() {
        if (campaignMediaEnabled) {
            dynamoDBClient = AmazonDynamoDBClientBuilder.standard()
                    .withRegion(Regions.EU_WEST_1)
                    .withCredentials(new ProfileCredentialsProvider("default")).build();
        }
    }

    @Override
    @Transactional(readOnly = true)
    public MediaFileRecord load(String uid) {
        return recordRepository.findOneByUid(uid);
    }

    @Override
    @Transactional(readOnly = true)
    public MediaFileRecord load(MediaFunction function, String imageKey) {
        return recordRepository.findByBucketAndKey(getBucketForFunction(function), imageKey);
    }

    @Override
    public boolean doesFileExist(MediaFunction function, String imageKey) {
        return imageKey != null && recordRepository.findByBucketAndKey(getBucketForFunction(function), imageKey) != null;
    }

    @Override
    @Transactional
    public String storeFile(MultipartFile file, MediaFunction function, String mimeType, String imageKey, String fileName) {
        String bucket = getBucketForFunction(Objects.requireNonNull(function));

        logger.info("storing a file, with function {}, bucket {}, content type: {}, passed mime type: {}, file name: {}, original name: {}",
                function, bucket, file.getContentType(), mimeType, fileName, file.getOriginalFilename());

        MediaFileRecord record = recordRepository.findByBucketAndKey(bucket, imageKey);
        String contentType = StringUtils.isEmpty(mimeType) ? file.getContentType() : mimeType;
        String nameToUse = StringUtils.isEmpty(fileName) ? file.getOriginalFilename() : fileName;
        if (record == null)
            record = new MediaFileRecord(bucket, contentType, imageKey, nameToUse, null);

        boolean fileStored = false;
        try {
            fileStored = storageBroker.storeMedia(record, file);
        } catch (SdkClientException e){
            logger.error("AWS SDK exception storing file ...",e.getMessage());
        }

        if (fileStored) {
            logger.info("media record stored and has mime type");
            record = recordRepository.save(record);
            return record.getUid();
        } else {
            logger.error("Error storing media file, returning null");
            return null;
        }
    }

    @Override
    @Transactional
    public String recordFile(String userUid, String bucket, String mimeType, String imageKey, String fileName) {
        logger.info("Storing a file with bucket {}, key {}, mime type {}", bucket, imageKey, mimeType);
        MediaFileRecord record = new MediaFileRecord(bucket, mimeType, imageKey, fileName, userUid);
        record.setStoredTime(Instant.now());
        record = recordRepository.save(record);
        return record.getUid();
    }

    @Override
    @Transactional
    public void deleteFile(LiveWireAlert liveWireAlert, String imageKey, MediaFunction function){
        String bucket = getBucketForFunction(Objects.requireNonNull(function));
        MediaFileRecord record = recordRepository.findByBucketAndKey(bucket, imageKey);
        liveWireAlert.getMediaFiles().remove(record);
    }

    @Override
    public String getBucketForFunction(MediaFunction function) {
        switch (function) {
            case TASK_IMAGE:
                return taskImagesBucket;
            case LIVEWIRE_MEDIA:
                return liveWireMediaBucket;
            case USER_PROFILE_IMAGE:
                return defaultMediaBucket;
            case BROADCAST_IMAGE:
                return defaultMediaBucket;
            case CAMPAIGN_IMAGE:
                return defaultMediaBucket;
            default:
                return defaultMediaBucket;
        }
    }

    @Override
    public List<MediaFileRecord> fetchInboundMediaRecordsForCampaign(String campaignUid) {
        if (!campaignMediaEnabled) {
            logger.info("Campaign media not enabled, returning empty list");
            return new ArrayList<>();
        }

        logger.info("Fetching campaign media records, for campaign id: {}", campaignUid);
        DynamoDB dynamoDB = new DynamoDB(dynamoDBClient);
        Table mediaFileTable = dynamoDB.getTable("inbound_media_file_records");
        Index timeSortedIndex = mediaFileTable.getIndex("assoc_entity_id-stored_timestamp-index");

        Map<String, Object> valueMap = new HashMap<>();
        valueMap.put(":id", campaignUid);

        QuerySpec querySpec = new QuerySpec()
                .withKeyConditionExpression("assoc_entity_id = :id")
                .withValueMap(valueMap)
                .withScanIndexForward(false);

        try {
            Iterator<Item> outcome = timeSortedIndex.query(querySpec).iterator();
            List<MediaFileRecord> records = new ArrayList<>();
            while (outcome.hasNext()) {
                Item item = outcome.next();
                final String submittingUserUid = item.getString("submitting_user_id");
                final String key = item.getString("folder") + "/" + item.getString("media_file_id");
                logger.info("Converting media file with key {}, submitted by user with uid: {}", key, submittingUserUid);

                MediaFileRecord record = new MediaFileRecord(
                        item.getString("bucket"),
                        item.getString("media_type"),
                        key,
                        item.getString("media_file_id"),
                        submittingUserUid);

                record.setStoredTime(Instant.ofEpochMilli(item.getLong("stored_timestamp")));
                record.setPreSignedUrl(storageBroker.getPresignedUrl(item.getString("bucket"), key));

                // when we start having large numbers of submissions this will get non-performant, so fix it then
                if (!StringUtils.isEmpty(submittingUserUid)) {
                    User submittingUser = userRepository.findOneByUid(submittingUserUid); // todo: watch this and use projection if gets slow
                    record.setCreatedByUserName(submittingUser != null ? submittingUser.getName() : null);
                }

                logger.info("Converted DynamoDB record to: {}", record);
                records.add(record);
            }
            return records;
        } catch (AmazonServiceException e) {
            logger.error("Error retrieving media files! Error: ", e);
            return new ArrayList<>();
        }
    }

}


text:
import { validators, widgets } from '../index';

const showName = widgets.TextBuilder.setLabel('Show Name');

const firstEpisodeDate = widgets.TextBuilder
  .setValidation('BirthdateValidation', validators.date.birthdate)
  .setLabel('Date of Birth');

const genre = widgets.TextBuilder
  .setLabel('Genre')
  .makeOptional();

export default widgets.StructBuilder
  .setField('showName', showName)
  .setField('firstEpisodeDate', firstEpisodeDate)
  .setField('genre', genre)
  .setColumns(2);


text: Credit credit = new Credit(credit_href);


text:
<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "cuenta_presupuestaria".
 *
 * @property integer $id
 * @property string $cuenta
 * @property string $nombre
 *
 * @property PartidaPartida[] $partidaPartidas
 */
class CuentaPresupuestaria extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'cuenta_presupuestaria';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['cuenta', 'nombre'], 'required'],
            [['cuenta'], 'string', 'max' => 1],
            [['nombre'], 'string', 'max' => 15]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'cuenta' => 'Cuenta',
            'nombre' => 'Nombre',
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getPartidaPartidas()
    {
        return $this->hasMany(PartidaPartida::className(), ['cuenta' => 'id']);
    }
}


text:
Application

Help

Help Videos

                    <h12 class="col-md-4"> </h12>

Map - Basemaps

This video describes how to choose different basemaps.

Play

Map - Layers

This video describes how to interact with map layers and layer visibility.

Play

Parking Themes

This video describes how to navigate around the parking themes and parking inspector.

Play

Map - Utilities

This video describes how to navigate across the map as well as of printing capabilities.

Play

Parking Data

This video describes how to view and download Parking Data.

Play