text:
``iostream``
--------
``iostream`` is the library you use to do input and output.

The most important parts to us this week are ``cin`` and ``cout``.

``cin`` is used for
keyboard input
and ``cout`` is used for
character output.

Your first program
----
```c++
#include <iostream>
using namespace std;

int main() {
    cout << "Hello world!" << endl;
    return 0;
}
```

The first line of code enables
input and output

The second line is magic.
Ignore it for now.

The fourth line of code contains the main function.
This is the entry point for every c++ program you will ever create.

The fifth line prints "Hello world!" to the user's screen.

The sixth line stops the execution of this function, and says that everything went ok (the value 0).

Exercise 1
---
Write a story!

Get into groups, and spend 10-15 minutes creating a story.

* What do we see when we're introduced to the world?
* Who's around?
* Why are things the way they are?

Make sure to leave holes in the story for character names, special objects, and the like.
Then, write a program asking the user for this information!
Use that information to tell the story you've come up with.

Make sure no single line of code is longer than 80 characters!
Also, some output formatting would be nice.
Start a new line after every sentence!

If you want a challenge, start a new line every 80 *output* characters
(notice that output characters don't necessarily line up with the code).

Exercise 2
---
Show me your ascii art!

Google "ascii art" and find some pieces that you think are aesthetically pleasing.
Then, write a program to print those out!

Exercise 3 (optional)
---
Write an interactive story!

You can use your story from exercise 1, and modify it a little.
If you don't want to do that, spend 10-15 minutes coming up with a new setting.

Next, come up with 10 decisions our main character has to make.

After you have the questions, put them code.
The answers (for simplicity) should be binary;
there are only 2 answers per question.

Also, you don't need to create a branching story tree!
If the player answers incorrectly, end the story.
I can provide an example of how to code that on the board.

This activity involves material from chapter 3 (branches)!
Don't attempt it unless you're comfortable with going ahead.

Quiz!
---
[quiz01](https://docs.google.com/a/ucr.edu/forms/d/e/1FAIpQLScjKZR7DzYmg73RwV3DSFHXtk6p0OPZ_9Kq6d-zv9x22c96Og/viewform)

Answers
---
The answers to the blank sections above are in white.
Highlight them to reveal the answers!
Make sure you at least attempt an answer first!


text:
.. class:: carbond.security.HttpBasicAuthenticator
    :heading:

.. |br| raw:: html

   <br />

=======================================
carbond.security.HttpBasicAuthenticator
=======================================
*extends* :class:`~carbond.security.Authenticator`

An authenticator for the Basic HTTP Authenitcation Scheme.

Instance Properties
-------------------

.. class:: carbond.security.HttpBasicAuthenticator
    :noindex:
    :hidden:

    .. attribute:: passwordField

       :type: string
       :required:

       Name of the field that contains the password in the database.

    .. attribute:: passwordHashFn

       :type: string | function
       :default: ``noop``

       Either a string representing a :class:`~carbond.security.Hasher` (possible values are *noop*, *sha256*, and *bcrypt*), an instance of :class:`~carbond.security.Hasher` or a constructor function for a :class:`~carbond.security.Hasher`.

    .. attribute:: usernameField

       :type: string
       :required:

       Name of the field that contains the username in the database.

Abstract Methods
----------------

.. class:: carbond.security.HttpBasicAuthenticator
    :noindex:
    :hidden:

    .. function:: findUser(username)

        :param username: The username sent by the client.
        :type username: string
        :throws: Error If the usernameField or passwordField are undefined.

        Find a user matching a username. Must be implemented by subcalsses.

    .. function:: getAuthenticationHeaders()

        :inheritedFrom: :class:`~carbond.security.Authenticator`
        :returns: An array of strings representing request headers.
        :rtype: string[]

        Gets the names of the request headers where authentication details can be found. Should be implemented by subclasses, for example: :attr:`~carbond.security.ApiKeyAuthenticator`. Must be implemented by subclasses which use headers other than the Authorization header. Otherwise the custom headers will be blocked by the Service.

Methods
-------

.. class:: carbond.security.HttpBasicAuthenticator
    :noindex:
    :hidden:

    .. function:: authenticate(req)

        :param req: The current request
        :type req: Request
        :throws: HttpErrors.Unauthorized If credentials weren't validated
        :returns: An object representing the user. Undefined if no credentials are found on the request.
        :rtype: Object | undefined

        Authenticates a request using HTTP Baisc. Returns a user object that matches the username and password sent with the request. If no user matching the username and password is found, throws a 401 Unauthorized error.

    .. function:: getService()

        :inheritedFrom: :class:`~carbond.security.Authenticator`
        :returns: The parent Service
        :rtype: :class:`~carbond.Service`

        A getter for the parent Service

    .. function:: initialize(service)

        :inheritedFrom: :class:`~carbond.security.Authenticator`
        :param service: The parent Service
        :type service: :class:`~carbond.Service`
        :rtype: undefined

        Initializes the authenticator. Called by :class:`~carbond.Service.start` on the parent Service and sets `this.service` to the parent Service.

    .. function:: throwUnauthenticated(msg)

        :inheritedFrom: :class:`~carbond.security.Authenticator`
        :param msg: The message returned with the 401 error.
        :type msg: string
        :throws: HttpErrors.Unauthorized
        :rtype: undefined

        Throws a 401 Unauthorized Error.

    .. function:: validateCreds(username, password)

        :param username: username from the HTTP request
        :type username: string
        :param password: password from the HTTP request
        :type password: string
        :throws: Service.errors.InternalServerError 500 Internal Server Error
        :returns: Object representing the user if a user matching the username and password is found. Otherwise returns undefined.
        :rtype: Object | undefined

        Finds a user matching a username and password. The password is checked using the hash function.

redpajama_set_name: RedPajamaGithub


text:
layout: post
title: Application Routes with onePK and the Need for Better Libraries
tags: onepk
---

It's been some time since I wrote about Cisco's onePK.  In this post, I'll look at some of the good and the bad of onePK and also show an example of how to add a route to a device running onePK to help make a few points along the way.

### The Bad

I've never heard anyone speak positively about onePK and I'm not sure I 100% agree, but I'll save the positivity for the next section.  onePK is a thick Software Development Kit (SDK).  If you are a network engineer looking to learn to program from the ground up, it may NOT be the BEST place to start.  That said, if you are looking to learn about object oriented programming, listener APIs, etc., and can spare some time, it's a great place to start.  If you're already a developer, it probably won't be much different compared to learning any other SDK.

Another thing to be weary of is that onePK was not intended to be a configuration API.  I voiced my [opinion](https://communities.cisco.com/thread/41789) on this already and I do think things are headed in the right direction, but it always helps knowing the history.  Initially, it was about dynamic configurations.  This means that if the onePK app disconnected from a device, all configs that the app provisioned would be de-commissioned.  Not cool.

Lastly, if you are going to use onePK don't forget to cross check SDK support with platform support.  There is not 100% uniformity, but hey, you may not need it anyway given what you are trying to accomplish.

### Adding a Route the onePK Way

You can easily see the complexity here.  Look at all of the modules required for what "should" be a simple task.

![onepk-1](/img/one1.png)

The following picture shows the process to create and send the route to a device.  The screen shot shows it in a function that I created to simplify the process and you'll see that more in the next section, but you get the idea.  15 commands to add a route seems like it's a few too many.  What do you think?

![onepk-2](/img/one2.png)

### The Good

Cisco DevNet offers an all-in-one onePK virtual machine.  You can download a virtual machine that has a 3 node virtual router topology that has Java/C/Python onePK libraries pre-installed.  Each router, of course, supports onePK.  The VM also has all of the onePK documentation bookmarked in a FireFox browser.  This is real.  It exists today.  It is one of the best learning VMs I've seen for network programming.  So, to those who want to wait for VIRL to start programming, keep waiting.  I do think it's the better option, but at the end of the day, if you are just looking to understand the basics of working with an API, it does not matter and this is a real solid choice.  For this reason, I think onePK is just fine.  While challenging, you'll learn quite a bit and then be able to recognize when you work with more consumable APIs like Cisco NX-API or Arista eAPI.

### Adding a route my way

After abstracting out the creation and deployment of a route into its own function, all you need to do is create a single variable (Python dictionary) and store the data about the route you want to add.  Then call the addRoute() function by sending it two arguments: (1) the device object which should be of type NetworkElement and (2) the route in the form of a Python dictionary.

![onepk-3](/img/one3.png)

This isn't showing the details of the Device module, but that's something I also created to simplify setting up devices in onePK.

### Consumable Libraries

As you can see, we need more "widgets" like addRoute() and Device().  These are just two quick examples, but if consumable libraries were out there, it would increase the rate of adoption and learning.  The best example of a comprehensive consumable library is from Juniper.  The [Juniper PyEZ](https://techwiki.juniper.net/Automation_Scripting/010_Getting_Started_and_Reference/Junos_PyEZ) library abstracts away having to know anything about the Juniper underlying Netconf/XML interface.

There is no reason libraries can't be created to ease consumption of the "off the shelf" APIs and libraries from every vendor.  In the meantime, we can all keep creating small modules ("widgets") like this to make our lives easier.

FYI to the vendors: This is not just a onePK thing.  We need more consumable libraries all around.  As new vendors emerge and incumbents come out with APIs, please think through who your target audience is and how you will help them consume your API.

Thanks,
Jason

Twitter: @jedelman8


text:
package org.springframework.boot.actuate.autoconfigure.cloudfoundry;

import org.junit.Test;

import org.springframework.boot.actuate.autoconfigure.cloudfoundry.CloudFoundryAuthorizationException.Reason;
import org.springframework.http.HttpStatus;

import static org.assertj.core.api.Assertions.assertThat;

/**
 * Tests for {@link CloudFoundryAuthorizationException}.
 *
 * @author Madhura Bhave
 */
public class CloudFoundryAuthorizationExceptionTests {

	@Test
	public void statusCodeForInvalidTokenReasonShouldBe401() {
		assertThat(createException(Reason.INVALID_TOKEN).getStatusCode())
				.isEqualTo(HttpStatus.UNAUTHORIZED);
	}

	@Test
	public void statusCodeForInvalidIssuerReasonShouldBe401() {
		assertThat(createException(Reason.INVALID_ISSUER).getStatusCode())
				.isEqualTo(HttpStatus.UNAUTHORIZED);
	}

	@Test
	public void statusCodeForInvalidAudienceReasonShouldBe401() {
		assertThat(createException(Reason.INVALID_AUDIENCE).getStatusCode())
				.isEqualTo(HttpStatus.UNAUTHORIZED);
	}

	@Test
	public void statusCodeForInvalidSignatureReasonShouldBe401() {
		assertThat(createException(Reason.INVALID_SIGNATURE).getStatusCode())
				.isEqualTo(HttpStatus.UNAUTHORIZED);
	}

	@Test
	public void statusCodeForMissingAuthorizationReasonShouldBe401() {
		assertThat(createException(Reason.MISSING_AUTHORIZATION).getStatusCode())
				.isEqualTo(HttpStatus.UNAUTHORIZED);
	}

	@Test
	public void statusCodeForUnsupportedSignatureAlgorithmReasonShouldBe401() {
		assertThat(createException(Reason.UNSUPPORTED_TOKEN_SIGNING_ALGORITHM)
				.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED);
	}

	@Test
	public void statusCodeForTokenExpiredReasonShouldBe401() {
		assertThat(createException(Reason.TOKEN_EXPIRED).getStatusCode())
				.isEqualTo(HttpStatus.UNAUTHORIZED);
	}

	@Test
	public void statusCodeForAccessDeniedReasonShouldBe403() {
		assertThat(createException(Reason.ACCESS_DENIED).getStatusCode())
				.isEqualTo(HttpStatus.FORBIDDEN);
	}

	@Test
	public void statusCodeForServiceUnavailableReasonShouldBe503() {
		assertThat(createException(Reason.SERVICE_UNAVAILABLE).getStatusCode())
				.isEqualTo(HttpStatus.SERVICE_UNAVAILABLE);
	}

	private CloudFoundryAuthorizationException createException(Reason reason) {
		return new CloudFoundryAuthorizationException(reason, "message");
	}

}


text:
#ifndef _TASK_SWITCHING_AMD64_H
#define _TASK_SWITCHING_AMD64_H
#include <stdint.h>

#include <onyx/fpu.h>
#include <onyx/registers.h>
#include <onyx/scheduler.h>

#define THREAD_RUNNABLE        0
#define THREAD_INTERRUPTIBLE   1
#define THREAD_SLEEPING        2
#define THREAD_IDLE            3
#define THREAD_DEAD            4
#define THREAD_UNINTERRUPTIBLE 5
#define THREAD_STOPPED         6

#endif


text:
#include "paddle/fluid/framework/tensor_util.h"

#include <algorithm>
#include <limits>
#include <memory>
#include <string>
#include <utility>
#include <vector>

#include "paddle/fluid/framework/convert_utils.h"
#include "paddle/fluid/framework/data_type.h"
#include "paddle/fluid/platform/complex.h"
#include "paddle/fluid/platform/profiler/event_tracing.h"
#include "paddle/phi/core/dense_tensor.h"

#ifdef PADDLE_WITH_MKLDNN
#include "dnnl_debug.h"  // NOLINT
#endif

namespace paddle {
namespace framework {

template <typename TENSOR>
void TensorCopyImpl(const TENSOR& src,
                    const platform::Place& dst_place,
                    const platform::DeviceContext& ctx,
                    TENSOR* dst) {
  if (&src == dst) {
    auto src_copy = src;
    TensorCopyImpl(src_copy, dst_place, ctx, dst);
    return;
  }

  VLOG(3) << "TensorCopy " << src.dims() << " from " << src.place() << " to "
          << dst_place;
  src.check_memory_size();
  dst->Resize(src.dims());
  dst->set_layout(src.layout());
  auto src_place = src.place();
  auto src_ptr = src.data();
#ifdef PADDLE_WITH_MKLDNN
  dst->set_mem_desc(src.mem_desc());
  // oneDNN tensors due to padding may be of bigger size
  // than numel()*size(type())
  auto dst_ptr =
      src.layout() == DataLayout::ONEDNN
          ? dst->mutable_data(dst_place, src.dtype(), src.memory_size())
          : dst->mutable_data(dst_place, src.dtype());
#else
  auto dst_ptr = dst->mutable_data(dst_place, src.dtype());
#endif
  dst->set_layout(src.layout());
  if (src_ptr == dst_ptr && src_place == dst_place) {
    VLOG(3) << "Skip copy the same data async from " << src_place << " to "
            << dst_place;
    return;
  }
  VLOG(4) << "src:" << src_ptr << ", dst:" << dst_ptr;

#ifdef PADDLE_WITH_MKLDNN
  auto size = src.layout() == DataLayout::ONEDNN
                  ? src.memory_size()
                  : src.numel() * framework::DataTypeSize(src.dtype());
#else
  auto size = src.numel() * framework::DataTypeSize(src.dtype());
#endif

  if (platform::is_cpu_place(src_place) && platform::is_cpu_place(dst_place)) {
    memory::Copy(dst_place, dst_ptr, src_place, src_ptr, size);
  }
#ifdef PADDLE_WITH_CUSTOM_DEVICE
  else if (platform::is_custom_place(src_place) &&  // NOLINT
           platform::is_cpu_place(dst_place)) {
    auto stream =
        reinterpret_cast<const platform::CustomDeviceContext&>(ctx).stream();
    memory::Copy(dst_place, dst_ptr, src_place, src_ptr, size, stream);
  } else if (platform::is_cpu_place(src_place) &&  // NOLINT
             platform::is_custom_place(dst_place)) {
    auto stream =
        reinterpret_cast<const platform::CustomDeviceContext&>(ctx).stream();
    memory::Copy(dst_place, dst_ptr, src_place, src_ptr, size, stream);
  } else if (platform::is_custom_place(src_place) &&  // NOLINT
             platform::is_custom_place(dst_place)) {
    if (src_ptr == dst_ptr) {
      VLOG(3) << "Skip copy the same data async from " << src_place << " to "
              << dst_place;
      return;
    }
    auto stream =
        reinterpret_cast<const platform::CustomDeviceContext&>(ctx).stream();
    memory::Copy(dst_place, dst_ptr, src_place, src_ptr, size, stream);
  }
#endif
#ifdef PADDLE_WITH_XPU
  else if (platform::is_xpu_place(src_place) &&  // NOLINT
           platform::is_cpu_place(dst_place)) {
    memory::Copy(dst_place, dst_ptr, src_place, src_ptr, size);
  } else if (platform::is_cpu_place(src_place) &&
             platform::is_xpu_place(dst_place)) {
    memory::Copy(dst_place, dst_ptr, src_place, src_ptr, size);
  } else if (platform::is_xpu_place(src_place) &&
             platform::is_xpu_place(dst_place)) {
    if (src_ptr == dst_ptr) {
      VLOG(3) << "Skip copy the same data async from " << src_place << " to "
              << dst_place;
      return;
    }
    memory::Copy(dst_place, dst_ptr, src_place, src_ptr, size);
  } else {
    PADDLE_THROW(platform::errors::Unimplemented(
        "Copy from %s to %s is not supported.", src_place, dst_place));
  }
#endif
#ifdef PADDLE_WITH_ASCEND_CL
  // TODO(zhiqiu): handle different condition like CUDA code below
  else if (platform::is_npu_place(src_place) &&  // NOLINT
           platform::is_cpu_place(dst_place)) {
    auto stream =
        reinterpret_cast<const platform::NPUDeviceContext&>(ctx).stream();
    memory::Copy(dst_place, dst_ptr, src_place, src_ptr, size, stream);
  }
  else if (platform::is_cpu_place(src_place) &&  // NOLINT
           platform::is_npu_place(dst_place)) {
    //  1. cpu tensor -> npu pinned tensor
    platform::NPUPinnedPlace npu_pinned_place;
    phi::DenseTensor npu_pinned_tensor;
    npu_pinned_tensor.Resize(src.dims());
    auto npu_pinned_ptr =
        npu_pinned_tensor.mutable_data(npu_pinned_place, src.dtype());
    memory::Copy(npu_pinned_place, npu_pinned_ptr, src_place, src_ptr, size);

    //  2. async copy npu pinned tensor -> npu tensor
    memory::Copy(
        dst_place,
        dst_ptr,
        npu_pinned_place,
        npu_pinned_ptr,
        size,
        reinterpret_cast<const platform::NPUDeviceContext&>(ctx).stream());

    //  3. record event
    auto npu_pinned_allocator =
        static_cast<paddle::memory::allocation::NPUPinnedAllocator*>(
            paddle::memory::allocation::AllocatorFacade::Instance()
                .GetAllocator(npu_pinned_place)
                .get());
    phi::Allocation* allocation = npu_pinned_tensor.Holder().get();
    npu_pinned_allocator->RecordEvent(
        allocation,
        reinterpret_cast<const platform::NPUDeviceContext&>(ctx).stream());
  }
  else if (platform::is_npu_place(src_place) &&  // NOLINT
           platform::is_npu_place(dst_place)) {
    if (src_ptr == dst_ptr) {
      VLOG(3) << "Skip copy the same data async from " << src_place << " to "
              << dst_place;
      return;
    }
    auto stream =
        reinterpret_cast<const platform::NPUDeviceContext&>(ctx).stream();
    memory::Copy(dst_place, dst_ptr, src_place, src_ptr, size, stream);
  }
  else if (platform::is_npu_pinned_place(src_place) &&  // NOLINT
           platform::is_npu_place(dst_place)) {         /* npu_pinned->npu */
    auto src_npu_pinned_place = src_place;
    auto dst_npu_place = dst_place;
    auto ctx_place = ctx.GetPlace();
    PADDLE_ENFORCE_EQ(
        platform::is_npu_place(ctx_place),
        true,
        platform::errors::PreconditionNotMet(
            "Device context place mismatch. When copying phi::DenseTensor "
            "data from NPU Pinned memory to NPU memory, current "
            "device context place should be NPU."));
    auto ctx_npu_place = ctx_place;
    PADDLE_ENFORCE_EQ(dst_npu_place,
                      ctx_npu_place,
                      platform::errors::PreconditionNotMet(
                          "The target NPU device and current device context do "
                          "not match. The target NPU device number is %d, but "
                          "device context NPU number is %d.",
                          dst_npu_place.device,
                          ctx_npu_place.device));
    auto stream =
        reinterpret_cast<const platform::NPUDeviceContext&>(ctx).stream();
    memory::Copy(
        dst_npu_place, dst_ptr, src_npu_pinned_place, src_ptr, size, stream);
  }
  else if (platform::is_npu_place(src_place) &&        // NOLINT
           platform::is_npu_pinned_place(dst_place)) { /* npu->npu_pinned */
    auto src_npu_place = src_place;
    auto dst_npu_pinned_place = dst_place;
    auto ctx_place = ctx.GetPlace();
    PADDLE_ENFORCE_EQ(
        platform::is_npu_place(ctx_place),
        true,
        platform::errors::PreconditionNotMet(
            "Device context place mismatch. When copying phi::DenseTensor "
            "data from NPU memory to NPU Pinned memory, current "
            "device context place should be NPU."));
    auto ctx_npu_place = ctx_place;
    PADDLE_ENFORCE_EQ(src_place,
                      ctx_npu_place,
                      platform::errors::PreconditionNotMet(
                          "The source NPU device and current device context do "
                          "not match. The source NPU device number is %d, but "
                          "device context NPU number is %d.",
                          src_npu_place.device,
                          ctx_npu_place.device));
    auto stream =
        reinterpret_cast<const platform::NPUDeviceContext&>(ctx).stream();
    memory::Copy(
        dst_npu_pinned_place, dst_ptr, src_npu_place, src_ptr, size, stream);
  }
  else {  // NOLINT
    PADDLE_THROW(platform::errors::Unimplemented(
        "Copy from %s to %s is not supported.", src_place, dst_place));
  }
#endif
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
  else if (platform::is_cuda_pinned_place(src_place) &&  // NOLINT
           platform::is_cuda_pinned_place(dst_place)) {
    memory::Copy(dst_place, dst_ptr, src_place, src_ptr, size);
  }
  else if (platform::is_cuda_pinned_place(src_place) &&  // NOLINT
           platform::is_cpu_place(dst_place)) {
    memory::Copy(dst_place, dst_ptr, src_place, src_ptr, size);
  }
  else if (platform::is_cpu_place(src_place) &&  // NOLINT
           platform::is_cuda_pinned_place(dst_place)) {
    memory::Copy(dst_place, dst_ptr, src_place, src_ptr, size);
  }
  else if (platform::is_gpu_place(src_place) &&  // NOLINT
           platform::is_cpu_place(dst_place)) {
    auto src_gpu_place = src_place;
    auto dst_cpu_place = dst_place;
    auto ctx_place = ctx.GetPlace();
    PADDLE_ENFORCE_EQ(
        platform::is_gpu_place(ctx_place),
        true,
        platform::errors::PreconditionNotMet(
            "Context place error, excepted GPUPlace, but actually %s.",
            ctx_place));
    auto ctx_gpu_place = ctx_place;
    PADDLE_ENFORCE_EQ(src_gpu_place,
                      ctx_gpu_place,
                      platform::errors::Unavailable(
                          "Source place and context place do not match, source "
                          "place is %s, context place is %s.",
                          src_gpu_place,
                          ctx_gpu_place));
    auto stream = reinterpret_cast<const phi::GPUContext&>(ctx).stream();
    memory::Copy(dst_cpu_place, dst_ptr, src_gpu_place, src_ptr, size, stream);
  }
  else if (platform::is_cpu_place(src_place) &&  // NOLINT
           platform::is_gpu_place(dst_place)) {
    auto src_cpu_place = src_place;
    auto dst_gpu_place = dst_place;
    auto ctx_place = ctx.GetPlace();
    PADDLE_ENFORCE_EQ(
        platform::is_gpu_place(ctx_place),
        true,
        platform::errors::PreconditionNotMet(
            "Context place error, excepted GPUPlace, but actually %s.",
            ctx_place));
    auto ctx_gpu_place = ctx_place;
    PADDLE_ENFORCE_EQ(dst_gpu_place,
                      ctx_gpu_place,
                      platform::errors::Unavailable(
                          "Destination place and context place do not match, "
                          "destination place is %s, context place is %s.",
                          dst_gpu_place,
                          ctx_gpu_place));
    auto stream = reinterpret_cast<const phi::GPUContext&>(ctx).stream();
    memory::Copy(dst_gpu_place, dst_ptr, src_cpu_place, src_ptr, size, stream);
  }
  else if (platform::is_gpu_place(src_place) &&  // NOLINT
           platform::is_cuda_pinned_place(dst_place)) {
    auto src_gpu_place = src_place;
    auto dst_cuda_pinned_place = dst_place;
    auto ctx_place = ctx.GetPlace();
    PADDLE_ENFORCE_EQ(
        platform::is_gpu_place(ctx_place),
        true,
        platform::errors::PreconditionNotMet(
            "Device context place mismatch. When copying phi::DenseTensor "
            "data from GPU memory to CUDA Pinned memory, current "
            "device context place should be GPU."));
    auto ctx_gpu_place = ctx_place;
    PADDLE_ENFORCE_EQ(src_gpu_place,
                      ctx_gpu_place,
                      platform::errors::PreconditionNotMet(
                          "The source GPU device and current device context do "
                          "not match. The source GPU device number is %d, but "
                          "device context GPU number is %d.",
                          src_gpu_place.device,
                          ctx_gpu_place.device));
    auto stream = reinterpret_cast<const phi::GPUContext&>(ctx).stream();
    memory::Copy(
        dst_cuda_pinned_place, dst_ptr, src_gpu_place, src_ptr, size, stream);
  }
  else if (platform::is_cuda_pinned_place(src_place) &&  // NOLINT
           platform::is_gpu_place(dst_place)) {
    auto src_cuda_pinned_place = src_place;
    auto dst_gpu_place = dst_place;
    auto ctx_place = ctx.GetPlace();
    PADDLE_ENFORCE_EQ(
        platform::is_gpu_place(ctx_place),
        true,
        platform::errors::PreconditionNotMet(
            "Device context place mismatch. When copying phi::DenseTensor "
            "data from CUDA Pinned memory to GPU memory, current "
            "device context place should be GPU."));
    auto ctx_gpu_place = ctx_place;
    PADDLE_ENFORCE_EQ(dst_gpu_place,
                      ctx_gpu_place,
                      platform::errors::PreconditionNotMet(
                          "The target GPU device and current device context do "
                          "not match. The target GPU device number is %d, but "
                          "device context GPU number is %d.",
                          dst_gpu_place.device,
                          ctx_gpu_place.device));
    auto stream = reinterpret_cast<const phi::GPUContext&>(ctx).stream();
    memory::Copy(
        dst_gpu_place, dst_ptr, src_cuda_pinned_place, src_ptr, size, stream);
  }
  else if (platform::is_gpu_place(src_place) &&  // NOLINT
           platform::is_gpu_place(dst_place)) {
    auto src_gpu_place = src_place;
    auto dst_gpu_place = dst_place;
    auto ctx_place = ctx.GetPlace();
    PADDLE_ENFORCE_EQ(
        platform::is_gpu_place(ctx_place),
        true,
        platform::errors::PreconditionNotMet(
            "Context place error, excepted GPUPlace, but actually %s.",
            ctx_place));
    auto stream = reinterpret_cast<const phi::GPUContext&>(ctx).stream();
    if (platform::is_same_place(src_place, dst_place)) {
      memory::Copy(
          dst_gpu_place, dst_ptr, src_gpu_place, src_ptr, size, stream);
    } else {
      if (platform::is_same_place(ctx_place, src_place)) {
        memory::Copy(
            dst_gpu_place, dst_ptr, src_gpu_place, src_ptr, size, stream);
        platform::DeviceContextPool::Instance().Get(src.place())->Wait();
      } else if (platform::is_same_place(ctx_place, dst_place)) {
        platform::DeviceContextPool::Instance().Get(src.place())->Wait();
        memory::Copy(
            dst_gpu_place, dst_ptr, src_gpu_place, src_ptr, size, stream);
      } else {
        PADDLE_THROW(platform::errors::Unavailable(
            "Context place dose not match the source and destination place."));
      }
    }
  }
  else {  // NOLINT
    PADDLE_THROW(platform::errors::Unimplemented(
        "Copying from %s to %s is not supported.", src_place, dst_place));
  }
#endif
#ifdef PADDLE_WITH_MLU
  else if (platform::is_mlu_place(src_place) &&  // NOLINT
           platform::is_cpu_place(dst_place)) {
    auto src_mlu_place = src_place;
    auto dst_cpu_place = dst_place;
    auto stream =
        reinterpret_cast<const platform::MLUDeviceContext&>(ctx).stream();
    memory::Copy(dst_cpu_place, dst_ptr, src_mlu_place, src_ptr, size, stream);
  }
  else if (platform::is_cpu_place(src_place) &&  // NOLINT
           platform::is_mlu_place(dst_place)) {
    auto src_cpu_place = src_place;
    auto dst_mlu_place = dst_place;
    auto stream =
        reinterpret_cast<const platform::MLUDeviceContext&>(ctx).stream();
    memory::Copy(dst_mlu_place, dst_ptr, src_cpu_place, src_ptr, size, stream);
  }
  else if (platform::is_mlu_place(src_place) &&  // NOLINT
           platform::is_mlu_place(dst_place)) {
    auto src_mlu_place = src_place;
    auto dst_mlu_place = dst_place;
    auto stream =
        reinterpret_cast<const platform::MLUDeviceContext&>(ctx).stream();
    memory::Copy(dst_mlu_place, dst_ptr, src_mlu_place, src_ptr, size, stream);
  }
  else {  // NOLINT
    PADDLE_THROW(platform::errors::Unimplemented(
        "Copying from %s to %s is not supported.", src_place, dst_place));
  }
#endif
#ifdef PADDLE_WITH_IPU
  else if (platform::is_ipu_place(src_place) &&  // NOLINT
           platform::is_cpu_place(dst_place)) {
    memory::Copy(dst_place, dst_ptr, src_place, src_ptr, size);
  }
  else if (platform::is_cpu_place(src_place) &&  // NOLINT
           platform::is_ipu_place(dst_place)) {
    memory::Copy(dst_place, dst_ptr, src_place, src_ptr, size);
  }
  else if (platform::is_ipu_place(src_place) &&  // NOLINT
           platform::is_ipu_place(dst_place)) {
    if (src_ptr == dst_ptr) {
      VLOG(3) << "Skip copy the same data sync from " << src_place << " to "
              << dst_place;
      return;
    }
    memory::Copy(dst_place, dst_ptr, src_place, src_ptr, size);
  }
  else {  // NOLINT
    PADDLE_THROW(platform::errors::Unimplemented(
        "Copying from %s to %s is not supported.", src_place, dst_place));
  }
#endif
}

template <typename TENSOR>
void TensorCopyImpl(const TENSOR& src,
                    const platform::Place& dst_place,
                    TENSOR* dst) {
  platform::DeviceContextPool& pool = platform::DeviceContextPool::Instance();
  const platform::DeviceContext* dev_ctx;
  if (platform::is_gpu_place(dst_place) || platform::is_npu_place(dst_place) ||
      platform::is_mlu_place(dst_place) ||
      platform::is_custom_place(dst_place)) {
    dev_ctx = pool.Get(dst_place);
  } else {
    dev_ctx = pool.Get(src.place());
  }
  TensorCopyImpl(src, dst_place, *dev_ctx, dst);
}

void TensorCopy(const phi::DenseTensor& src,
                const platform::Place& dst_place,
                phi::DenseTensor* dst) {
  TensorCopyImpl<phi::DenseTensor>(src, dst_place, dst);
}
void TensorCopy(const phi::DenseTensor& src,
                const platform::Place& dst_place,
                const platform::DeviceContext& ctx,
                phi::DenseTensor* dst) {
  TensorCopyImpl<phi::DenseTensor>(src, dst_place, ctx, dst);
}

void TensorCopySync(const phi::DenseTensor& src,
                    const platform::Place& dst_place,
                    phi::DenseTensor* dst) {
  if (&src == dst) {
    auto src_copy = src;
    TensorCopySync(src_copy, dst_place, dst);
    return;
  }

  VLOG(3) << "TensorCopySync " << src.dims() << " from " << src.place()
          << " to " << dst_place;
  src.check_memory_size();
  dst->Resize(src.dims());
  dst->set_layout(src.layout());
#ifdef PADDLE_WITH_MKLDNN
  if (src.layout() == DataLayout::ONEDNN) {
    dst->set_mem_desc(src.mem_desc());
  }
#endif
  auto src_place = src.place();
  auto src_ptr = src.data();
  auto dst_ptr = dst->mutable_data(dst_place, src.dtype());
  VLOG(4) << "src:" << src_ptr << ", dst:" << dst_ptr;

  if (src_ptr == dst_ptr && src_place == dst_place) {
    VLOG(3) << "Skip copy the same data from " << src_place << " to "
            << dst_place;
    return;
  }

  auto size = src.numel() * framework::DataTypeSize(src.dtype());
  if (platform::is_cpu_place(src_place) && platform::is_cpu_place(dst_place)) {
    memory::Copy(dst_place, dst_ptr, src_place, src_ptr, size);
  }
#ifdef PADDLE_WITH_CUSTOM_DEVICE
  else if (platform::is_custom_place(src_place) &&  // NOLINT
           platform::is_cpu_place(dst_place)) {     /* custom_device -> cpu*/
    memory::Copy(dst_place, dst_ptr, src_place, src_ptr, size, nullptr);
  }                                                // NOLINT
  else if (platform::is_cpu_place(src_place) &&    // NOLINT
           platform::is_custom_place(dst_place)) { /* cpu -> custom_device*/
    memory::Copy(dst_place, dst_ptr, src_place, src_ptr, size, nullptr);
  }                                                 // NOLINT
  else if (platform::is_custom_place(src_place) &&  // NOLINT
           platform::is_custom_place(
               dst_place)) { /* custom_device -> custom_device*/
    if (src_ptr == dst_ptr) {
      VLOG(3) << "Skip copy the same data sync from " << src_place << " to "
              << dst_place;
      return;
    }
    memory::Copy(dst_place, dst_ptr, src_place, src_ptr, size, nullptr);
  }
#endif
#ifdef PADDLE_WITH_XPU
  else if (platform::is_xpu_place(src_place) &&  // NOLINT
           platform::is_cpu_place(dst_place)) {
    memory::Copy(dst_place, dst_ptr, src_place, src_ptr, size);
  }                                              // NOLINT
  else if (platform::is_cpu_place(src_place) &&  // NOLINT
           platform::is_xpu_place(dst_place)) {
    memory::Copy(dst_place, dst_ptr, src_place, src_ptr, size);
  }                                              // NOLINT
  else if (platform::is_xpu_place(src_place) &&  // NOLINT
           platform::is_xpu_place(dst_place)) {
    if (src_ptr == dst_ptr) {
      VLOG(3) << "Skip copy the same data async from " << src_place << " to "
              << dst_place;
      return;
    }
    memory::Copy(dst_place, dst_ptr, src_place, src_ptr, size);
    platform::XPUPlace xpu_dst_place = dst_place;
    platform::XPUPlace xpu_src_place = src_place;
    if (xpu_dst_place.device == xpu_src_place.device) {
      auto xpu_ctx = platform::DeviceContextPool::Instance().Get(xpu_dst_place);
      xpu_ctx->Wait();
    }
  }       // NOLINT
  else {  // NOLINT
    PADDLE_THROW(platform::errors::Unimplemented(
        "Copy from %s to %s is not supported.", src_place, dst_place));
  }
#endif
#ifdef PADDLE_WITH_ASCEND_CL
  else if (platform::is_npu_place(src_place) &&  // NOLINT
           platform::is_cpu_place(dst_place)) {  /* npu -> cpu*/
    memory::Copy(dst_place, dst_ptr, src_place, src_ptr, size, nullptr);
  }
  else if (platform::is_cpu_place(src_place) &&  // NOLINT
           platform::is_npu_place(dst_place)) {  /* cpu -> npu*/
    memory::Copy(dst_place, dst_ptr, src_place, src_ptr, size, nullptr);
  }
  else if (platform::is_npu_place(src_place) &&  // NOLINT
           platform::is_npu_place(dst_place)) {  /* npu -> npu*/
    if (src_ptr == dst_ptr) {
      VLOG(3) << "Skip copy the same data sync from " << src_place << " to "
              << dst_place;
      return;
    }
    memory::Copy(dst_place, dst_ptr, src_place, src_ptr, size, nullptr);
  }
  else {  // NOLINT
    PADDLE_THROW(platform::errors::Unimplemented(
        "Copy from %s to %s is not supported.", src_place, dst_place));
  }
#endif
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
  else if (platform::is_cuda_pinned_place(src_place) &&  // NOLINT
           platform::is_cuda_pinned_place(dst_place)) {
    memory::Copy(dst_place, dst_ptr, src_place, src_ptr, size);
  }
  else if (platform::is_cuda_pinned_place(src_place) &&  // NOLINT
           platform::is_cpu_place(dst_place)) {
    memory::Copy(dst_place, dst_ptr, src_place, src_ptr, size);
  }
  else if (platform::is_cpu_place(src_place) &&  // NOLINT
           platform::is_cuda_pinned_place(dst_place)) {
    memory::Copy(dst_place, dst_ptr, src_place, src_ptr, size);
  }
  else if (platform::is_gpu_place(src_place) &&  // NOLINT
           platform::is_cuda_pinned_place(dst_place)) {
    memory::Copy(dst_place, dst_ptr, src_place, src_ptr, size, nullptr);
  }
  else if (platform::is_gpu_place(src_place) &&  // NOLINT
           platform::is_cpu_place(dst_place)) {
    auto src_gpu_place = src_place;
    auto dst_cpu_place = dst_place;
    memory::Copy(dst_cpu_place, dst_ptr, src_gpu_place, src_ptr, size, nullptr);
  }
  else if (platform::is_cpu_place(src_place) &&  // NOLINT
           platform::is_gpu_place(dst_place)) {
    auto src_cpu_place = src_place;
    auto dst_gpu_place = dst_place;
    memory::Copy(dst_gpu_place, dst_ptr, src_cpu_place, src_ptr, size, nullptr);
  }
  else if (platform::is_gpu_place(src_place) &&  // NOLINT
           platform::is_gpu_place(dst_place)) {
    auto src_gpu_place = src_place;
    auto dst_gpu_place = dst_place;
    memory::Copy(dst_gpu_place, dst_ptr, src_gpu_place, src_ptr, size, nullptr);
  }
  else if (platform::is_cuda_pinned_place(src_place) &&  // NOLINT
           platform::is_gpu_place(dst_place)) {
    auto src_pinned_place = src_place;
    auto dst_gpu_place = dst_place;
    memory::Copy(
        dst_gpu_place, dst_ptr, src_pinned_place, src_ptr, size, nullptr);
  }
  else {  // NOLINT
    PADDLE_THROW(platform::errors::Unimplemented(
        "Copy from %s to %s is not supported.", src_place, dst_place));
  }
#endif
#ifdef PADDLE_WITH_MLU
  else if (platform::is_mlu_place(src_place) &&  // NOLINT
           platform::is_cpu_place(dst_place)) {
    memory::Copy(dst_place, dst_ptr, src_place, src_ptr, size, nullptr);
  }
  else if (platform::is_cpu_place(src_place) &&  // NOLINT
           platform::is_mlu_place(dst_place)) {
    memory::Copy(dst_place, dst_ptr, src_place, src_ptr, size, nullptr);
  }
  else if (platform::is_mlu_place(src_place) &&  // NOLINT
           platform::is_mlu_place(dst_place)) {
    if (src_ptr == dst_ptr) {
      VLOG(3) << "Skip copy the same data async from " << src_place << " to "
              << dst_place;
      return;
    }
    memory::Copy(dst_place, dst_ptr, src_place, src_ptr, size, nullptr);
  }
  else {  // NOLINT
    PADDLE_THROW(platform::errors::Unimplemented(
        "Copy from %s to %s is not supported.", src_place, dst_place));
  }
#endif
#ifdef PADDLE_WITH_IPU
  else if (platform::is_ipu_place(src_place) &&  // NOLINT
           platform::is_cpu_place(dst_place)) {
    memory::Copy(dst_place, dst_ptr, src_place, src_ptr, size);
  }
  else if (platform::is_cpu_place(src_place) &&  // NOLINT
           platform::is_ipu_place(dst_place)) {
    memory::Copy(dst_place, dst_ptr, src_place, src_ptr, size);
  }
  else if (platform::is_ipu_place(src_place) &&  // NOLINT
           platform::is_ipu_place(dst_place)) {
    if (src_ptr == dst_ptr) {
      VLOG(3) << "Skip copy the same data sync from " << src_place << " to "
              << dst_place;
      return;
    }
    memory::Copy(dst_place, dst_ptr, src_place, src_ptr, size);
  }
  else {  // NOLINT
    PADDLE_THROW(platform::errors::Unimplemented(
        "Copy from %s to %s is not supported.", src_place, dst_place));
  }
#endif
}

void TensorToStream(std::ostream& os,
                    const phi::DenseTensor& tensor,
                    const platform::DeviceContext& dev_ctx) {
  {  // the 1st field, uint32_t version
    constexpr uint32_t version = 0;
    os.write(reinterpret_cast<const char*>(&version), sizeof(version));
  }
  {  // the 2nd field, tensor description
     // int32_t  size
     // void*    protobuf message
    proto::VarType::TensorDesc desc;
    desc.set_data_type(framework::TransToProtoVarType(tensor.dtype()));
    auto dims = phi::vectorize(tensor.dims());
    auto* pb_dims = desc.mutable_dims();
    pb_dims->Resize(static_cast<int>(dims.size()), 0);
    std::copy(dims.begin(), dims.end(), pb_dims->begin());
    int32_t size = desc.ByteSize();
    os.write(reinterpret_cast<const char*>(&size), sizeof(size));
    auto out = desc.SerializeAsString();
    os.write(out.data(), size);
  }
  {  // the 3rd field, tensor data
    uint64_t size = tensor.numel() * framework::DataTypeSize(tensor.dtype());

    auto* data_ptr = tensor.data();
    PADDLE_ENFORCE_LT(size,
                      (std::numeric_limits<std::streamsize>::max)(),
                      platform::errors::ResourceExhausted(
                          "tensor size %d overflow when writing tensor", size));
    if (platform::is_gpu_place(tensor.place())) {
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
      constexpr size_t kBufSize = 1024 * 1024 * 64;  // 64MB
      std::unique_ptr<char[]> buf(new char[kBufSize]);
      auto& gpu_dev_ctx = static_cast<const phi::GPUContext&>(dev_ctx);
      platform::CPUPlace cpu;
      uintptr_t data = reinterpret_cast<uintptr_t>(data_ptr);
      while (size != 0) {
        size_t size_to_write = std::min(kBufSize, static_cast<size_t>(size));
        memory::Copy(cpu,
                     buf.get(),
                     tensor.place(),
                     reinterpret_cast<const void*>(data),
                     size_to_write,
                     gpu_dev_ctx.stream());
        gpu_dev_ctx.Wait();
        os.write(buf.get(), size_to_write);
        data += size_to_write;
        size -= size_to_write;
      }
#else
      PADDLE_THROW(platform::errors::Unimplemented(
          "CUDAPlace is not supported when not compiled with CUDA"));
#endif
    } else if (platform::is_xpu_place(tensor.place())) {
#ifdef PADDLE_WITH_XPU
      constexpr size_t kBufSize = 1024 * 1024 * 64;  // 64MB
      std::unique_ptr<char[]> buf(new char[kBufSize]);
      auto& xpu_dev_ctx =
          static_cast<const platform::XPUDeviceContext&>(dev_ctx);
      platform::CPUPlace cpu;
      uintptr_t data = reinterpret_cast<uintptr_t>(data_ptr);
      while (size != 0) {
        size_t size_to_write = std::min(kBufSize, static_cast<size_t>(size));
        memory::Copy(cpu,
                     buf.get(),
                     tensor.place(),
                     reinterpret_cast<const void*>(data),
                     size_to_write);
        xpu_dev_ctx.Wait();
        os.write(buf.get(), size_to_write);
        data += size_to_write;
        size -= size_to_write;
      }
#else
      PADDLE_THROW(platform::errors::Unimplemented(
          "XPUPlace is not supported when not compiled with XPU"));
#endif
    } else if (platform::is_mlu_place(tensor.place())) {
#ifdef PADDLE_WITH_MLU
      constexpr size_t kBufSize = 1024 * 1024 * 64;  // 64MB
      std::unique_ptr<char[]> buf(new char[kBufSize]);
      auto& mlu_dev_ctx =
          static_cast<const platform::MLUDeviceContext&>(dev_ctx);
      platform::CPUPlace cpu;
      uintptr_t data = reinterpret_cast<uintptr_t>(data_ptr);
      while (size != 0) {
        size_t size_to_write = std::min(kBufSize, static_cast<size_t>(size));
        memory::Copy(cpu,
                     buf.get(),
                     tensor.place(),
                     reinterpret_cast<const void*>(data),
                     size_to_write,
                     mlu_dev_ctx.stream());
        mlu_dev_ctx.Wait();
        os.write(buf.get(), size_to_write);
        data += size_to_write;
        size -= size_to_write;
      }
#else
      PADDLE_THROW(platform::errors::Unimplemented(
          "MLUPlace is not supported when not compiled with MLU"));
#endif
    } else if (platform::is_npu_place(tensor.place())) {
#ifdef PADDLE_WITH_ASCEND_CL
      constexpr size_t kBufSize = 1024 * 1024 * 64;  // 64MB
      std::unique_ptr<char[]> buf(new char[kBufSize]);
      auto& npu_dev_ctx =
          static_cast<const platform::NPUDeviceContext&>(dev_ctx);
      platform::CPUPlace cpu;
      uintptr_t data = reinterpret_cast<uintptr_t>(data_ptr);
      while (size != 0) {
        size_t size_to_write = std::min(kBufSize, static_cast<size_t>(size));
        memory::Copy(cpu,
                     buf.get(),
                     tensor.place(),
                     reinterpret_cast<const void*>(data),
                     size_to_write,
                     npu_dev_ctx.stream());
        npu_dev_ctx.Wait();
        os.write(buf.get(), size_to_write);
        data += size_to_write;
        size -= size_to_write;
      }
#else
      PADDLE_THROW(platform::errors::Unimplemented(
          "NPUPlace is not supported when not compiled with NPU"));
#endif
    } else if (platform::is_custom_place(tensor.place())) {
#ifdef PADDLE_WITH_CUSTOM_DEVICE
      constexpr size_t kBufSize = 1024 * 1024 * 64;  // 64MB
      std::unique_ptr<char[]> buf(new char[kBufSize]);
      auto& custom_device_context =
          static_cast<const platform::CustomDeviceContext&>(dev_ctx);
      platform::CPUPlace cpu;
      uintptr_t data = reinterpret_cast<uintptr_t>(data_ptr);
      while (size != 0) {
        size_t size_to_write = std::min(kBufSize, static_cast<size_t>(size));
        memory::Copy(cpu,
                     buf.get(),
                     tensor.place(),
                     reinterpret_cast<const void*>(data),
                     size_to_write,
                     custom_device_context.stream());
        custom_device_context.Wait();
        os.write(buf.get(), size_to_write);
        data += size_to_write;
        size -= size_to_write;
      }
#else
      PADDLE_THROW(platform::errors::Unimplemented(
          "CustomPlace is not supported when not compiled with "
          "CustomDevice"));
#endif
    } else {
      os.write(static_cast<const char*>(data_ptr),
               static_cast<std::streamsize>(size));
    }
  }
}

struct DeserializedDataFunctor {
  DeserializedDataFunctor(void** buf,
                          phi::DenseTensor* tensor,
                          const platform::Place& place)
      : buf_(buf), tensor_(tensor), place_(place) {}

  template <typename T>
  void apply() {
    *buf_ = tensor_->mutable_data<T>(place_);
  }

  void** buf_;
  phi::DenseTensor* tensor_;
  platform::Place place_;
};

void TensorFromStream(std::istream& is,
                      phi::DenseTensor* tensor,
                      const platform::DeviceContext& dev_ctx,
                      const size_t& seek,
                      const std::vector<int64_t>& shape) {
  uint32_t version;
  is.read(reinterpret_cast<char*>(&version), sizeof(version));

  PADDLE_ENFORCE_EQ(
      version,
      0U,
      platform::errors::InvalidArgument(
          "tensor version %u is not supported, Only version 0 is supported",
          version));

  proto::VarType::TensorDesc desc;
  {  // int32_t size
    // proto buffer
    int32_t size;
    is.read(reinterpret_cast<char*>(&size), sizeof(size));
    std::unique_ptr<char[]> buf(new char[size]);
    is.read(reinterpret_cast<char*>(buf.get()), size);
    PADDLE_ENFORCE_EQ(
        desc.ParseFromArray(buf.get(), size),
        true,
        platform::errors::InvalidArgument("Cannot parse tensor desc"));
  }
  {  // read tensor
    tensor->Resize(phi::make_ddim(shape));
    size_t seekg = seek * framework::SizeOfType(desc.data_type());
    is.seekg(seekg, is.cur);

    void* buf;
    phi::CPUContext ctx;
    size_t size = tensor->numel() * framework::SizeOfType(desc.data_type());
    if (platform::is_gpu_place(dev_ctx.GetPlace()) ||
        platform::is_xpu_place(dev_ctx.GetPlace()) ||
        platform::is_mlu_place(dev_ctx.GetPlace()) ||
        platform::is_npu_place(dev_ctx.GetPlace()) ||
        platform::is_custom_place(dev_ctx.GetPlace())) {
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP) || \
    defined(PADDLE_WITH_XPU) || defined(PADDLE_WITH_MLU) ||  \
    defined(PADDLE_WITH_ASCEND_CL) || defined(PADDLE_WITH_CUSTOM_DEVICE)
      phi::DenseTensor cpu_tensor;
      cpu_tensor.Resize(phi::make_ddim(shape));
      framework::VisitDataType(
          desc.data_type(),
          DeserializedDataFunctor(&buf, &cpu_tensor, ctx.GetPlace()));
      is.read(static_cast<char*>(buf), size);
      auto dst_place = dev_ctx.GetPlace();
      framework::TensorCopy(cpu_tensor, dst_place, dev_ctx, tensor);
      if (platform::is_npu_place(dev_ctx.GetPlace()) ||
          platform::is_custom_place(dev_ctx.GetPlace())) {
        dev_ctx.Wait();
      }
#else
      if (platform::is_gpu_place(dev_ctx.GetPlace())) {
        PADDLE_THROW(platform::errors::Unimplemented(
            "CUDAPlace is not supported when not compiled with CUDA"));
      } else if (platform::is_xpu_place(dev_ctx.GetPlace())) {
        PADDLE_THROW(platform::errors::Unimplemented(
            "XPUPlace is not supported when not compiled with XPU"));
      } else if (platform::is_mlu_place(dev_ctx.GetPlace())) {
        PADDLE_THROW(platform::errors::Unimplemented(
            "MLUPlace is not supported when not compiled with MLU"));
      } else {
        PADDLE_THROW(platform::errors::Unimplemented(
            "NPUPlace is not supported when not compiled with NPU"));
      }
#endif
    } else {
      framework::VisitDataType(
          desc.data_type(),
          DeserializedDataFunctor(&buf, tensor, ctx.GetPlace()));
      is.read(static_cast<char*>(buf), size);
    }
  }
}

void TensorFromStream(std::istream& is,
                      phi::DenseTensor* tensor,
                      const platform::DeviceContext& dev_ctx) {
  uint32_t version;
  is.read(reinterpret_cast<char*>(&version), sizeof(version));
  PADDLE_ENFORCE_EQ(
      version,
      0U,
      platform::errors::InvalidArgument(
          "tensor version %u is not supported, Only version 0 is supported",
          version));
  proto::VarType::TensorDesc desc;
  {  // int32_t size
     // proto buffer
    int32_t size = -1;
    is.read(reinterpret_cast<char*>(&size), sizeof(size));
    PADDLE_ENFORCE_EQ(
        is.good(),
        true,
        platform::errors::Unavailable("Cannot read tensor desc size"));
    PADDLE_ENFORCE_GE(size,
                      0,
                      platform::errors::InvalidArgument(
                          "phi::DenseTensor desc size should >= 0"));
    std::unique_ptr<char[]> buf(new char[size]);
    is.read(reinterpret_cast<char*>(buf.get()), size);
    PADDLE_ENFORCE_EQ(
        desc.ParseFromArray(buf.get(), size),
        true,
        platform::errors::InvalidArgument("Cannot parse tensor desc"));
  }
  {  // read tensor
    std::vector<int64_t> dims;
    dims.reserve(static_cast<size_t>(desc.dims().size()));
    std::copy(desc.dims().begin(), desc.dims().end(), std::back_inserter(dims));
    tensor->Resize(phi::make_ddim(dims));
    void* buf;
    phi::CPUContext ctx;
    size_t size = tensor->numel() * framework::SizeOfType(desc.data_type());
    if (platform::is_gpu_place(dev_ctx.GetPlace()) ||
        platform::is_xpu_place(dev_ctx.GetPlace()) ||
        platform::is_mlu_place(dev_ctx.GetPlace()) ||
        platform::is_npu_place(dev_ctx.GetPlace()) ||
        platform::is_custom_place(dev_ctx.GetPlace())) {
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP) || \
    defined(PADDLE_WITH_XPU) || defined(PADDLE_WITH_MLU) ||  \
    defined(PADDLE_WITH_ASCEND_CL) || defined(PADDLE_WITH_CUSTOM_DEVICE)
      phi::DenseTensor cpu_tensor;
      cpu_tensor.Resize(phi::make_ddim(dims));
      framework::VisitDataType(
          desc.data_type(),
          DeserializedDataFunctor(&buf, &cpu_tensor, ctx.GetPlace()));
      is.read(static_cast<char*>(buf), size);
      auto dst_place = dev_ctx.GetPlace();
      framework::TensorCopy(cpu_tensor, dst_place, dev_ctx, tensor);
      if (platform::is_npu_place(dev_ctx.GetPlace()) ||
          platform::is_custom_place(dev_ctx.GetPlace())) {
        dev_ctx.Wait();
      }
#else
      if (platform::is_gpu_place(dev_ctx.GetPlace())) {
        PADDLE_THROW(platform::errors::Unimplemented(
            "CUDAPlace is not supported when not compiled with CUDA"));
      } else if (platform::is_xpu_place(dev_ctx.GetPlace())) {
        PADDLE_THROW(platform::errors::Unimplemented(
            "XPUPlace is not supported when not compiled with XPU"));
      } else if (platform::is_mlu_place(dev_ctx.GetPlace())) {
        PADDLE_THROW(platform::errors::Unimplemented(
            "MLUPlace is not supported when not compiled with MLU"));
      } else if (platform::is_npu_place(dev_ctx.GetPlace())) {
        PADDLE_THROW(platform::errors::Unimplemented(
            "NPUPlace is not supported when not compiled with NPU"));
      } else {
        PADDLE_THROW(platform::errors::Unimplemented(
            "CutomPlace is not supported when not compiled with CustomDevice"));
      }
#endif
    } else {
      framework::VisitDataType(
          desc.data_type(),
          DeserializedDataFunctor(&buf, tensor, ctx.GetPlace()));
      is.read(static_cast<char*>(buf), size);
    }
  }
}

// get tensor data point by DLDataType
void* GetDstPtrByDLDataType(DLDataType type,
                            phi::DenseTensor* dst,
                            const platform::Place& dst_place) {
  // vector types not currently supported
  PADDLE_ENFORCE_LE(type.lanes,
                    1,
                    platform::errors::Unimplemented(
                        "Vector type is not supported currently."));

  switch (type.bits) {
    case 8:
      if (type.code == kDLInt)
        return static_cast<void*>(dst->mutable_data<int8_t>(dst_place));
      if (type.code == kDLUInt)
        return static_cast<void*>(dst->mutable_data<uint8_t>(dst_place));
      PADDLE_THROW(platform::errors::Unimplemented(
          "DLDataType code <%d> is illegal when DLDataType.bits is <%d>.",
          type.code,
          type.bits));
    case 16:
      if (type.code == kDLInt)
        return static_cast<void*>(dst->mutable_data<int16_t>(dst_place));
      if (type.code == kDLFloat)
        return static_cast<void*>(
            dst->mutable_data<paddle::platform::float16>(dst_place));
      if (type.code == kDLBfloat)
        return static_cast<void*>(
            dst->mutable_data<paddle::platform::bfloat16>(dst_place));
      PADDLE_THROW(platform::errors::Unimplemented(
          "DLDataType code <%d> is illegal when DLDataType.bits is <%d>.",
          type.code,
          type.bits));
    case 32:
      if (type.code == kDLInt)
        return static_cast<void*>(dst->mutable_data<int32_t>(dst_place));
      if (type.code == kDLFloat)
        return static_cast<void*>(dst->mutable_data<float>(dst_place));
      PADDLE_THROW(platform::errors::Unimplemented(
          "DLDataType code <%d> is illegal when DLDataType.bits is <%d>.",
          type.code,
          type.bits));
    case 64:
      if (type.code == kDLInt)
        return static_cast<void*>(dst->mutable_data<int64_t>(dst_place));
      if (type.code == kDLFloat)
        return static_cast<void*>(dst->mutable_data<double>(dst_place));
      if (type.code == kDLComplex)
        return static_cast<void*>(
            dst->mutable_data<paddle::platform::complex<float>>(dst_place));
      PADDLE_THROW(platform::errors::Unimplemented(
          "DLDataType code <%d> is illegal when DLDataType.bits is <%d>.",
          type.code,
          type.bits));
    case 128:
      if (type.code == kDLComplex)
        return static_cast<void*>(
            dst->mutable_data<paddle::platform::complex<double>>(dst_place));
      PADDLE_THROW(platform::errors::Unimplemented(
          "DLDataType code <%d> is illegal when DLDataType.bits is <%d>.",
          type.code,
          type.bits));
    default:
      PADDLE_THROW(platform::errors::Unimplemented(
          "Unsupported DLDataType.bits %d.", type.bits));
  }
}

void TensorFromDLPack(const ::DLTensor& dl_tensor, phi::DenseTensor* dst) {
  platform::CPUPlace dst_place = platform::CPUPlace();
  platform::CPUPlace src_place = platform::CPUPlace();

  std::vector<int64_t> vec;
  std::copy(dl_tensor.shape,
            dl_tensor.shape + dl_tensor.ndim,
            std::back_inserter(vec));

  framework::DDim vddim = phi::make_ddim(vec);

  dst->Resize(vddim);
  ::DLDataType type = dl_tensor.dtype;
  void* dst_ptr = GetDstPtrByDLDataType(type, dst, dst_place);

  auto src_ptr = static_cast<const void*>(dl_tensor.data);
  auto size = phi::product(vddim) * type.bits / 8;

  if (dl_tensor.device.device_type == kDLCPU) {
    memory::Copy(dst_place, dst_ptr, src_place, src_ptr, size);
  }
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
  if (dl_tensor.device.device_type == kDLGPU) {
    platform::CUDAPlace dst_place =
        platform::CUDAPlace(dl_tensor.device.device_id);
    platform::CUDAPlace src_place =
        platform::CUDAPlace(dl_tensor.device.device_id);
    dst_ptr = GetDstPtrByDLDataType(type, dst, dst_place);
    auto* ctx = platform::DeviceContextPool::Instance().GetByPlace(dst_place);
    memory::Copy(dst_place,
                 dst_ptr,
                 src_place,
                 src_ptr,
                 size,
                 reinterpret_cast<const phi::GPUContext&>(*ctx).stream());
  }
#endif
#ifdef PADDLE_WITH_XPU
  PADDLE_THROW(platform::errors::Unimplemented("XPUPlace is not supported"));
#endif
}

void TensorFromDLPack(const DLManagedTensor* src, phi::DenseTensor* dst) {
  std::vector<int64_t> vec;
  std::copy(src->dl_tensor.shape,
            src->dl_tensor.shape + src->dl_tensor.ndim,
            std::back_inserter(vec));

  framework::DDim vddim = phi::make_ddim(vec);
  dst->Resize(vddim);
  ::DLDataType type = src->dl_tensor.dtype;

  auto src_ptr = static_cast<const void*>(src->dl_tensor.data);
  auto size = phi::product(vddim) * type.bits / 8;

  if (src->dl_tensor.device.device_type == kDLCPU) {
    platform::CPUPlace dst_place = platform::CPUPlace();
    platform::CPUPlace src_place = platform::CPUPlace();
    void* dst_ptr = GetDstPtrByDLDataType(type, dst, dst_place);
    memory::Copy(dst_place, dst_ptr, src_place, src_ptr, size);
  }
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
  if (src->dl_tensor.device.device_type == kDLGPU) {
    platform::CUDAPlace dst_place =
        platform::CUDAPlace(src->dl_tensor.device.device_id);
    platform::CUDAPlace src_place =
        platform::CUDAPlace(src->dl_tensor.device.device_id);
    void* dst_ptr = GetDstPtrByDLDataType(type, dst, dst_place);
    auto* ctx = platform::DeviceContextPool::Instance().GetByPlace(dst_place);
    // Fix copy by share allocation.
    memory::Copy(dst_place,
                 dst_ptr,
                 src_place,
                 src_ptr,
                 size,
                 reinterpret_cast<const phi::GPUContext&>(*ctx).stream());
  }
#endif
  src->deleter(const_cast<DLManagedTensor*>(src));
#ifdef PADDLE_WITH_XPU
  PADDLE_THROW(platform::errors::Unimplemented("XPUPlace is not supported"));
#endif
}

template <typename T>
std::string format_tensor(const phi::DenseTensor& tensor) {
  // TODO(zhiqiu): use the print option to format tensor.
  return "NOT IMPLEMENTED";
}

template <typename T>
std::ostream& print_tensor(std::ostream& os, const phi::DenseTensor& tensor) {
  auto inspect = tensor.data<T>();
  auto element_num = tensor.numel();

  os << "  - data: [";
  // Note: int8_t && uint8_t is typedf of char, ostream unable to print properly
  if (typeid(int8_t) == typeid(T) || typeid(uint8_t) == typeid(T)) {
    if (element_num > 0) {
      os << signed(inspect[0]);
      for (int j = 1; j < element_num; ++j) {
        os << " " << signed(inspect[j]);
      }
    }
  } else {
    if (element_num > 0) {
      os << inspect[0];
      for (int j = 1; j < element_num; ++j) {
        os << " " << inspect[j];
      }
    }
  }
  os << "]";
  return os;
}

template <>
std::ostream& print_tensor<paddle::platform::complex<float>>(
    std::ostream& os, const phi::DenseTensor& tensor) {
  auto inspect = tensor.data<paddle::platform::complex<float>>();
  auto element_num = tensor.numel();

  os << "  - data: [";
  if (element_num > 0) {
    os << signed(inspect[0].real) << "+" << signed(inspect[0].imag) << "j";
    for (int j = 1; j < element_num; ++j) {
      os << " " << signed(inspect[j].real) << "+" << signed(inspect[j].imag)
         << "j";
    }
  }
  os << "]";
  return os;
}

template <>
std::ostream& print_tensor<paddle::platform::complex<double>>(
    std::ostream& os, const phi::DenseTensor& tensor) {
  auto inspect = tensor.data<paddle::platform::complex<double>>();
  auto element_num = tensor.numel();

  os << "  - data: [";
  if (element_num > 0) {
    os << signed(inspect[0].real) << "+" << signed(inspect[0].imag) << "j";
    for (int j = 1; j < element_num; ++j) {
      os << " " << signed(inspect[j].real) << "+" << signed(inspect[j].imag)
         << "j";
    }
  }
  os << "]";
  return os;
}

std::ostream& operator<<(std::ostream& os, const LoD& lod) {
  // NOTE(xiongkun):
  // https://stackoverflow.com/questions/5195512/namespaces-and-operator-resolution
  // if we don't redefine, the operator << of phi / framework LoD is not found.
  paddle::string::operator<<(os, lod);
  return os;
}

}  // namespace framework
}  // namespace paddle

namespace phi {

std::ostream& operator<<(std::ostream& os, const LoD& lod) {
  paddle::string::operator<<(os, lod);
  return os;
}

std::ostream& operator<<(std::ostream& os, const phi::DenseTensor& t) {
  if (t.lod().size() > 0) {
    os << "  - lod: " << t.lod() << "\n";
  }

  os << "  - place: " << t.place() << "\n";
  os << "  - shape: [" << t.dims() << "]\n";
  os << "  - layout: " << phi::DataLayoutToString(t.layout()) << "\n";

  DenseTensor tensor;
  tensor.Resize(t.dims());
  if (paddle::platform::is_cpu_place(t.place())) {
    tensor.ShareDataWith(t);
  } else {
    paddle::platform::CPUPlace place;
    paddle::framework::TensorCopy(t, place, &tensor);
    paddle::platform::DeviceContextPool& pool =
        paddle::platform::DeviceContextPool::Instance();
    auto& dev_ctx = *pool.Get(t.place());
    dev_ctx.Wait();
  }

#define PrintTensorCallback(cpp_type, proto_type)                 \
  do {                                                            \
    if (paddle::framework::TransToProtoVarType(tensor.dtype()) == \
        proto_type) {                                             \
      os << "  - dtype: " << proto_type << "\n";                  \
      paddle::framework::print_tensor<cpp_type>(os, tensor);      \
      return os;                                                  \
    }                                                             \
  } while (0)

  _ForEachDataType_(PrintTensorCallback);
  VLOG(1) << "PrintVar: unrecognized data type:" << t.type();
  return os;
}
}  // namespace phi


text:
import {h, Component} from 'preact';
import WithData from 'components/WithData';
import List from 'components/List';

import {memory, network} from 'api/list';
import {RetrieveList} from 'api/types';
import {LIST_TYPES, List as ListType, ListPage, UUID} from '@kristoferbaxter/hn-api';

interface Props {
  matches: any;
  type: LIST_TYPES;
}
interface State {
  uuid: UUID;
}
export default class extends Component<Props, State> {
  render({matches, type}: Props, {uuid}: State): JSX.Element {
    const values: RetrieveList = {
      page: Number(matches.page || 1),
      type,
      uuid,
    };

    return (
      <WithData
        memory={memory}
        network={network}
        values={values}
        handleUUIDChange={this.handleUUIDChange}
        render={this.ListViewWithData}
      />
    );
  }

  private ListViewWithData = (data: ListType & ListPage): JSX.Element => {
    return <List data={data} />;
  };
  private handleUUIDChange = (uuid: UUID): void => {
    this.state.uuid = uuid;
  };
}


text:
<?php

namespace ZeDoctrineExtensions;

/**
 * Get the Database custome DQL functions
 *
 * Get the name=>class of the custome DQL functions.
 *
 * @category    ZeDoctrineExtensions
 * @package     ZeDoctrineExtensions
 * @license     http://www.opensource.org/licenses/mit-license.html  MIT License
 * @author      Mohammad ZeinEddin <mohammad@zeineddin.name>
 */

class Utils
{
    public static function getOracleDQLFunctions()
    {
        return array(
            'datetime_functions' => array(
                'Nvl2' => 'ZeDoctrineExtensions\Query\Oracle\Nvl2',
                'Nvl' => 'ZeDoctrineExtensions\Query\Oracle\Nvl',
                'Translate' => 'ZeDoctrineExtensions\Query\Oracle\Translate',
                'ToDate' => 'ZeDoctrineExtensions\Query\Oracle\ToDate',
                'TruncDate' => 'ZeDoctrineExtensions\Query\Oracle\TruncDate',
                'Extract' => 'ZeDoctrineExtensions\Query\Oracle\Extract',
                'Listagg' => 'ZeDoctrineExtensions\Query\Oracle\Listagg',
            ),
            'string_functions' => array(),
            'numeric_functions' => array(
                'ToChar' => 'ZeDoctrineExtensions\Query\Oracle\ToChar',
            ),
        );
    }

    public static function getMySQLDQLFunctions()
    {
        return array(
            'datetime_functions' => array(
                'Date' => 'ZeDoctrineExtensions\Query\MySQL\Date',
                'DateFormat' => 'ZeDoctrineExtensions\Query\MySQL\DateFormat',
                'SecToTime' => 'ZeDoctrineExtensions\Query\MySQL\SecToTime',
                'TimeDiff' => 'ZeDoctrineExtensions\Query\MySQL\TimeDiff',
                'TimeToSec' => 'ZeDoctrineExtensions\Query\MySQL\TimeToSec',
                'StrToDate' => 'ZeDoctrineExtensions\Query\MySQL\StrToDate',
                'Extract' => 'ZeDoctrineExtensions\Query\MySQL\Extract',
                'GroupConcat' => 'ZeDoctrineExtensions\Query\MySQL\GroupConcat',
            ),
            'string_functions' => array(
                'IfNull' => 'ZeDoctrineExtensions\Query\MySQL\IfNull',
                'NullIf' => 'ZeDoctrineExtensions\Query\MySQL\NullIf',
            ),
            'numeric_functions' => array(),
        );
    }
}


text:
     ////   ///   /// ///
   //////  ////   // ////  ////
 /// ////  ////  //  ////  ////
///  //// /////  //        ///
///  //// ///// //  //// //////
//   /// /////  //  ////  ////
 // //// ///// //  ////  ////
    /////////////  ////  ////
    ////////////   ///   ///
    ///// /////   ////  ////
    ///// /////   //// ///// //
    ////  ////    /// ///// //
   ///// /////   ////////////
   ////  ////     ////  ////

// The Web framework with class.

// ~~~~~~~~~~~~~~~~~~~~~~~~~~ //

// Copyright (c) 2013 Adam R. Nelson
//
// 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.

package com.sector91.wit.css;

public enum WhiteSpace implements CssEnum<WhiteSpace> {
  NORMAL   ("normal"),
  PRE      ("pre"),
  NOWRAP   ("nowrap"),
  PRE_WRAP ("pre-wrap"),
  PRE_LINE ("pre-line");

  private final String token;

  private WhiteSpace(String token) {
    this.token = token;
  }

  @Override public String token() {
    return token;
  }

  @Override public String toString() {
    return token;
  }
}


text:
package featurescomparison.workingwithheadersandbody.extractmessagebody.java;

import org.apache.poi.hsmf.MAPIMessage;

public class ApacheMsgBody
{
	public static void main(String[] args) throws Exception
	{
		String dataPath = "src/featurescomparison/workingwithheadersandbody/extractmessagebody/data/";

		MAPIMessage msg = new MAPIMessage(dataPath + "message.msg");

		double startTime = System.nanoTime();

		String messageTextBody = msg.getTextBody();

		System.out.println("Text Body:"+ messageTextBody);
	}
}


text:
<?php
session_start();
session_regenerate_id();
include('../models/conn.php');
include('../models/workshop.php');
include('../models/user.php');
include('../models/userWorkshop.php');
include('../models/profile.php');
include('../models/userActivity.php');

$session = getProfile();

if( (session_id()  || isset($_SESSION)) && isset($_SESSION['id']) && $session[3] == 0){
    // IF it is logged
    ?>

    <?php include('header.php'); ?>

        <?php include('navbar.php'); ?>

Login successfull

Login failed

Registration successfull

Registration failed

Registration failed User alredy existed

                  Registro

Registrar Empleado

Registrar Alumno

                  Taller / Actividades

Registrar Taller

Registrar Actividad

Eliminar Taller

Eliminar Actividad

                  Registro Taller/Actividad

Registrar Alumno a Taller

Registrar Madre a Actividad

                  Becas

Registrar Beca a alumno

                  Editar

Editar Alumno

Editar Madre

                              <form id="registerScholarship">

 Registrar Beca

                                      Usuario
                                      <input id="usuario_id" class="form-control"
                                             placeholder="Usuario" style="min-width: 200px;">
                                      <input id="uuid_selected" class="hidden"
                                             placeholder="Matricula" style="min-width: 200px;">

                                      Fecha de Inicio
                                      <input type="date" class="form-control" id="fecha_inicio"
                                             required placeholder="Fecha de Inicio">

                                      Fecha de Término
                                      <input type="date" class="form-control" id="fecha_termino"
                                             required placeholder="Fecha de Término">

                                  <button type="submit" class="btn btn-lg btn-primary
                        btn-block">Registro</button>
                              </form>

Bienvenido al menu de Admin!

                  <form id="registrarEmpleado">

 Registrar empleado

                              Nombre de usuario
                              <input type="text" class="form-control" id="emailRegister" required autofocus placeholder="Nombre de usuario">

                              Nombre
                              <input type="name" class="form-control" id="fName" required placeholder="Nombre">

                              Apellido
                              <input type="name" class="form-control" id="lName" required placeholder="Apellido">

                              Contraseña
                              <input type="password" class="form-control" id="passwordRegister" required placeholder="Contraseña">

                              Confirmar Contraseña
                              <input type="password" class="form-control" id="confirmRegister" required placeholder="Contraseña">

                              Tipo de empleado
                              <select class="form-control" id="tipoEmpleado">
                                  <option id="0">Trabajadora Social (Admin)</option>
                                  <option id="1">Psicologo</option>
                                  <option id="2" disabled>Promotor deportivo</option>
                                  <option id="3" disabled>Supervisor de operaciones</option>
                                  <option id="4" disabled>Terapeuta</option>
                              </select>

                          <button type="submit" class="btn btn-lg btn-primary btn-block">Registrar Empleado</button>

                  </form>

                  <form id="registrarAlumno">

 Registrar alumno

                              Matricula
                              <input type="text" class="form-control" id="matricula" required autofocus placeholder="######">

                              Nombre
                              <input type="name" class="form-control" id="fName1" required placeholder="Nombre">

                              Apellido
                              <input type="name" class="form-control" id="lName1" required placeholder="Apellido">

                              Tipo
                              <select class="form-control" id="tipoSelec">
                                  <option>Estudiante</option>
                                  <option>Madre</option>
                              </select>

                                  <?php
                                    $mothers = indexMother();

                                  echo " Madre";
                                  echo "<select class=\"form-control\" id=\"madre\">";
                                  echo "<option data-id='-1'>Ninguna</option>";

                                  for($i = 0; $i < count($mothers); $i++){
                                      echo "<option data-id='".$mothers[$i][0]."'>".$mothers[$i][2]." ".$mothers[$i][3]."</option>";
                                  }

                                  echo "</select>";

                                  ?>

                          <button type="submit" class="btn btn-lg btn-primary btn-block">Registrar Alumno</button>

                  </form>

                  <form id="registrarActividad">

 Registrar Actividad

                              Nombre
                              <input type="text" class="form-control" id="nombreActividad" required autofocus placeholder="Nombre de la actividad">

                              Profesor
                              <input type="text" class="form-control" id="profesorActividad" required autofocus placeholder="Profesor de la actividad">

                              Cantidad de sesiones
                              <input type="number" class="form-control" id="cantSesionesActividad" required placeholder="15">

                          <button type="submit" class="btn btn-lg btn-primary btn-block">Registrar Actividad</button>

                  </form>

                  <form id="registrarTaller">

 Registrar taller

                              Nombre
                              <input type="text" class="form-control" id="nombreTaller" required autofocus placeholder="Nombre del taller">

                              Profesor
                              <input type="text" class="form-control" id="profesorTaller" required autofocus placeholder="Profesor del taller">

                              Cantidad de evaluaciones
                              <input type="number" class="form-control" id="cantEvals" required placeholder="3">

                              Cantidad de sesiones
                              <input type="number" class="form-control" id="cantSesiones" required placeholder="15">

                          <button type="submit" class="btn btn-lg btn-primary btn-block">Registrar Taller</button>

                  </form>

                              Seleccione Actividad

                              <select class="form-control" id="activitiesMadresRegistrar">
                                  <?php
                                  $activities = getActivities();
                                  $idDefault = $activities[0][0];
                                  for($i = 0; $i < count($activities); $i++){
                                      echo "<option id='". $activities[$i][0] ."' >" . $activities[$i][1] . "</option>";
                                  }
                                  ?>
                              </select>

Matricula

Nombre

Remover

                                    <?php

                                    $indexUser = getUsersInActivity($idDefault);
                                    for($i = 0; $i < count($indexUser); $i++){
                                        echo  "
";
                                        echo "
" . $indexUser[$i][1] . "
	";
                                        echo "
" . $indexUser[$i][2] . " " . $indexUser[$i][3] . "
	";
                                        echo "
<button type='button' data-studentuuid='". $indexUser[$i][0] . "'";
                                        echo "data-workshopuuid='". $idDefault . "'  class='remover-usuario-activity btn btn-danger'>Remover</button>
	";
                                        echo "
";
                                    }

                                    ?>

Agregar

Matricula

Nombre

                                    <?php

                                    $userNotInActivity = getUsersNotInActivity($idDefault);

                                    for($i = 0; $i < count($userNotInActivity); $i++){
                                        echo  "
";
                                        echo "
<button type='button' data-studentuuid='". $userNotInActivity[$i][0] . "'";
                                        echo "data-workshopuuid='". $idDefault . "'  class='agregar-usuario-activity btn btn-success'>Agregar</button>
	";
                                        echo "
" . $userNotInActivity[$i][1] . "
	";
                                        echo "
" . $userNotInActivity[$i][2] . " " . $userNotInActivity[$i][3] . "
	";
                                        echo "
";
                                    }

                                    ?>

                              Seleccione taller

                              <select class="form-control" id="workshopsAlumnosRegistrar">
                                  <?php
                                  $workshops = getWorkshops();
                                  $idDefault = $workshops[0][0];
                                  for($i = 0; $i < count($workshops); $i++){
                                      echo "<option id='". $workshops[$i][0] ."' >" . $workshops[$i][1] . "</option>";
                                  }
                                  ?>
                              </select>

Matricula

Nombre

Remover

                                    <?php

                                    $indexUser = getUsersInWorkshop($idDefault);
                                    for($i = 0; $i < count($indexUser); $i++){
                                        echo  "
";
                                        echo "
" . $indexUser[$i][1] . "
	";
                                        echo "
" . $indexUser[$i][2] . " " . $indexUser[$i][3] . "
	";
                                        echo "
<button type='button' data-studentuuid='". $indexUser[$i][0] . "'";
                                        echo "data-workshopuuid='". $idDefault . "'  class='remover-usuario btn btn-danger'>Remover</button>
	";
                                        echo "
";
                                    }

                                    ?>

Agregar

Matricula

Nombre

                                    <?php

                                    $userNotInWorkshops = getUsersNotInWorkshop($idDefault);
                                    for($i = 0; $i < count($userNotInWorkshops); $i++){
                                        echo  "
";
                                        echo "
<button type='button' data-studentuuid='". $userNotInWorkshops[$i][0] . "'";
                                        echo "data-workshopuuid='". $idDefault . "'  class='agregar-usuario btn btn-success'>Agregar</button>
	";
                                        echo "
" . $userNotInWorkshops[$i][1] . "
	";
                                        echo "
" . $userNotInWorkshops[$i][2] . " " . $userNotInWorkshops[$i][3] . "
	";
                                        echo "
";
                                    }

                                    ?>

Eliminar Taller

Nombre Taller

Profesor

                          <?php
                          $workshops = getWorkshops();
                          for($i = 0; $i < count($workshops); $i++){
                              echo "
";
                              echo "
". $workshops[$i][1] . "
	";
                              echo "
". $workshops[$i][2] . "
	";

                              ?>

                                  <form action="workshop.php" >
                                      <input type="hidden" name="id" value="<?php echo $workshops[$i][0];?>" />
                                      <input type="hidden" name="type" value="workshops" />

                                      <button type="submit" class="btn btn-primary btn-info">Ver</button>
                                  </form>

                              <?php

                              echo "
<button type='button'
                            onclick='deleteWorkshop(". $workshops[$i][0] . ")'
                            class='btn btn-danger'>Eliminar</button>
	";
                              echo "
";
                          }
                          ?>

                          <form id="EDIT_MADRE">

 Editar Madre

                                  Usuario
                                  <input id="editMadres" class="form-control"
                                         placeholder="Usuario" style="min-width: 200px;">
                                  <input id="uuid_selected_madr" class="hidden"
                                         placeholder="Matricula" style="min-width: 200px;">

                              <button type="button" class="btn btn-lg btn-primary btn-block" onclick="info_inmodal2()">
                                  Editar
                              </button>

                          </form>

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

Editar Madre

                                  <form id="EDITAR_MADRE_FORM">

 Editar Madre

                                              Matricula
                                              <input type="text" class="form-control" id="matricula_edit2" required autofocus placeholder="######">

                                              Nombre
                                              <input type="name" class="form-control" id="fName1_edit2" required placeholder="Nombre">

                                              Apellido
                                              <input type="name" class="form-control" id="lName1_edit2" required placeholder="Apellido">

                                          <button type="submit" class="btn btn-lg btn-primary btn-block">Editar Madre</button>

                                  </form>

                          <form id="EDIT_USER">

 Editar Alumno

                                  Usuario
                                  <input id="editAlumnos" class="form-control"
                                         placeholder="Usuario" style="min-width: 200px;">
                                  <input id="uuid_selected_alum" class="hidden"
                                         placeholder="Matricula" style="min-width: 200px;">

                              <button type="button" class="btn btn-lg btn-primary btn-block" onclick="info_inmodal()">
                                  Editar
                              </button>

                          </form>

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

Editar Alumno

                                  <form id="EDITAR_ALUMNO_FORM">

 Editar alumno

                                              Matricula
                                              <input type="text" class="form-control" id="matricula_edit" required autofocus placeholder="######">

                                              Nombre
                                              <input type="name" class="form-control" id="fName1_edit" required placeholder="Nombre">

                                              Apellido
                                              <input type="name" class="form-control" id="lName1_edit" required placeholder="Apellido">

                                                  <?php
                                                  $mothers = indexMother();

                                                  echo " Madre";
                                                  echo "<select class=\"form-control\" id=\"madre_edit\">";
                                                  echo "<option data-id='-1'>Default</option>";

                                                  for($i = 0; $i < count($mothers); $i++){
                                                      echo "<option data-id='".$mothers[$i][0]."'>".$mothers[$i][2]." ".$mothers[$i][3]."</option>";
                                                  }

                                                  echo "</select>";

                                                  ?>

                                          <button type="submit" class="btn btn-lg btn-primary btn-block">Editar Alumno</button>

                                  </form>

Eliminar Actividad

Nombre Actividad

Profesor

                          <?php
                          $activity = getActivities();
                          for($i = 0; $i < count($activity); $i++){

                              echo "
";
                              echo "
". $activity[$i][1] . "
	";
                              echo "
". $activity[$i][2] . "
	";

                              ?>

                                  <form action="activity.php" >
                                      <input type="hidden" name="id" value="<?php echo $activity[$i][0];?>" />
                                      <input type="hidden" name="type" value="activity" />

                                      <button type="submit" class="btn btn-primary btn-info">Ver</button>
                                  </form>

                              <?php

                              echo "
<button type='button'
                        onclick='deleteWorkshop(". $activity[$i][0] . ")'
                        class='btn btn-danger'>Eliminar</button>
	";
                              echo "
";

                          }
                          ?>

    <?php include('footer.php'); ?>

<?php }
else {
    header("Location: login.php");
}

?>


text:
package net.oneandone.troilus.api;

import java.io.IOException;

import java.nio.ByteBuffer;

import net.oneandone.troilus.Dao;
import net.oneandone.troilus.DaoImpl;
import net.oneandone.troilus.CassandraDB;
import net.oneandone.troilus.Record;

import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

import com.datastax.driver.core.ConsistencyLevel;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;

public class CollectionsTest {

    private static CassandraDB cassandra;

    @BeforeClass
    public static void beforeClass() throws IOException {
        cassandra = CassandraDB.newInstance();
    }

    @AfterClass
    public static void afterClass() throws IOException {
        cassandra.close();
    }

    @Before
    public void before() throws IOException {
        cassandra.tryExecuteCqlFile(UsersTable.DDL);
    }

    @Test
    public void testSimpleTable() throws Exception {
        Dao usersDao = new DaoImpl(cassandra.getSession(), UsersTable.TABLE)
                                 .withConsistency(ConsistencyLevel.LOCAL_QUORUM);

        String id = "34534535";

        ////////////////
        // inserts
        usersDao.writeWithKey(UsersTable.USER_ID, id)
                .value(UsersTable.IS_CUSTOMER, true)
                .value(UsersTable.PICTURE, ByteBuffer.wrap(new byte[] { 8, 4, 3}))
                .value(UsersTable.ADDRESSES, ImmutableList.of("stuttgart", "baden-baden"))
                .value(UsersTable.PHONE_NUMBERS, ImmutableSet.of("34234243", "9345324"))
                .value(UsersTable.ROLES, ImmutableMap.of("r3", "4455", "r7", "242223"))
                .execute();

        Record record = usersDao.readWithKey(UsersTable.USER_ID, id)
                                .execute()
                                .get();
        Assert.assertEquals(ImmutableList.of("stuttgart", "baden-baden"), record.getList(UsersTable.ADDRESSES, String.class));
        Assert.assertEquals(ImmutableSet.of("34234243", "9345324"), record.getSet(UsersTable.PHONE_NUMBERS, String.class));
        Assert.assertEquals(ImmutableMap.of("r3", "4455", "r7", "242223"), record.getMap(UsersTable.ROLES, String.class, String.class));

        // replace
        usersDao.writeWithKey(UsersTable.USER_ID, id)
                .value(UsersTable.ADDRESSES, ImmutableList.of("london"))
                .value(UsersTable.PHONE_NUMBERS, ImmutableSet.of("12313323"))
                .execute();

        record = usersDao.readWithKey(UsersTable.USER_ID, id)
                         .execute()
                         .get();
        Assert.assertEquals(ImmutableList.of("london"), record.getList(UsersTable.ADDRESSES, String.class));
        Assert.assertEquals(ImmutableSet.of("12313323"), record.getSet(UsersTable.PHONE_NUMBERS, String.class));

        // add entry
        usersDao.writeWithKey(UsersTable.USER_ID, id)
                .appendListValue(UsersTable.ADDRESSES, "paris")
                .addSetValue(UsersTable.PHONE_NUMBERS, "323243")
                .putMapValue(UsersTable.ROLES, "r2", "324325")
                .execute();

        record = usersDao.readWithKey(UsersTable.USER_ID, id)
                         .execute()
                         .get();
        Assert.assertEquals(ImmutableList.of("london", "paris"), record.getList(UsersTable.ADDRESSES, String.class));
        Assert.assertEquals(ImmutableSet.of("12313323", "323243"), record.getSet(UsersTable.PHONE_NUMBERS, String.class));
        Assert.assertEquals(ImmutableMap.of("r2", "324325", "r3", "4455", "r7", "242223"), record.getMap(UsersTable.ROLES, String.class, String.class));

        // add entry
        usersDao.writeWithKey(UsersTable.USER_ID, id)
                .prependListValue(UsersTable.ADDRESSES, "prag")
                .execute();

        record = usersDao.readWithKey(UsersTable.USER_ID, id)
                         .column(UsersTable.ADDRESSES)
                         .column(UsersTable.PHONE_NUMBERS)
                         .execute()
                         .get();
        Assert.assertEquals(ImmutableList.of("prag", "london", "paris"), record.getList(UsersTable.ADDRESSES, String.class));
        Assert.assertEquals(ImmutableSet.of("12313323", "323243"), record.getSet(UsersTable.PHONE_NUMBERS, String.class));

        // remove entry
        usersDao.deleteWithKey(UsersTable.USER_ID, id)
                .removeMapValue(UsersTable.ROLES, "r2")
                .execute();

        record = usersDao.readWithKey(UsersTable.USER_ID, id)
                         .execute()
                         .get();
        Assert.assertEquals(ImmutableMap.of("r3", "4455", "r7", "242223"), record.getMap(UsersTable.ROLES, String.class, String.class));
    }
}


text:
Edit Labels

  <button type="button" class="close pull-right" aria-label="Close" (click)="bsModalRef.hide()">
    ×
  </button>

  <edit-labels [resourceName]="resourceName" [resourceType]="resourceType" [labels]="labels"></edit-labels>

    <button type="button" class="btn btn-default" (click)="bsModalRef.hide()">{{closeBtnName}}</button>
    <input type="submit" class="btn btn-primary" (click)="saveLabels()" ng-disabled="form.$invalid" value="Save"/>


text:
import os

from injector import inject

class PropertiesFile(object):
    """Get the properties file to run on the cluster"""

    @inject(filesystem='filesystem')
    def __init__(self, filesystem):
        """
        Initialize the class
        :param filesystem: Filesystem
        """
        super(PropertiesFile, self).__init__()

        self.__filesystem = filesystem

    def get(self, wf_dir):
        """
        Find all the properties file inside given workflow directory
        :param wf_dir: string
        :return: string
        """
        property_files = self.__filesystem.find_properties_file(wf_dir)

        print 'Properties files found:'
        print '[0] None'
        for index, property_file in enumerate(property_files):
            print '[{index}] {file}'.format(index=(index + 1), file=os.path.basename(property_file))

        file_to_run = int(raw_input('Select which file you would like to run: '))
        if file_to_run > 0:
            return property_files[(file_to_run - 1)]

        return False


text:
'use strict';
let User = require('../../models/user');

let signUp = [
  function (req, res, next) {
    let email = req.body.email;
    let signUpView = req.app.locals.config.views.signUp;

    if (email.length < 6) {
      let alert = 'The email must be at least six characters.';
      res.render(signUpView, { title: 'Sign Up', alert });

    } else if (/^[a-z]([\.\-_]?[a-z0-9])*@[a-z0-9]([a-z0-9-]?[a-z0-9])*\.[a-z]{2,}$/i.test(email)) {
      next();

    } else {
      let alert = 'The email must be a valid email address.';
      res.render(signUpView, { title: 'Sign Up', alert });
    }
  },

  function (req, res, next) {
    let email = req.body.email;
    let password = req.body.password;
    let passwordAgain = req.body.passwordAgain;
    let signUpView = req.app.locals.config.views.signUp;

    User.findOne({ email: email }, (err, user) => {
      if (err) throw err;

      if (user) {
        let alert = 'That user already exists.';
        res.render(signUpView, { title: 'Sign Up', alert });

      } else {
        if (password === passwordAgain) {
          if (password.length >= 6) {
            let user = new User({
              email: email,
              password: password,
            });

            user.save((err) => {
              if (err) throw err;
            });

            let alert = 'Your user has been created.';
            res.render(signUpView, { title: 'Sign Up', alert });

          } else {
            let alert = 'The password must be at least six characters.';
            res.render(signUpView, { title: 'Sign Up', alert });
          }

        } else {
          let alert = 'Passwords do not match.';
          res.render(signUpView, { title: 'Sign Up', alert });
        }
      }
    });
  }
];

module.exports = signUp;