text:
import os
from azure.cli.testsdk import (ScenarioTest, ResourceGroupPreparer, StorageAccountPreparer,
                               JMESPathCheck, NoneCheck, StringCheck, StringContainCheck)
from ..storage_test_util import StorageScenarioMixin

class StorageFileShareScenarios(StorageScenarioMixin, ScenarioTest):
    @ResourceGroupPreparer()
    @StorageAccountPreparer()
    def test_storage_file_copy_scenario(self, resource_group, storage_account):
        account_info = self.get_account_info(resource_group, storage_account)
        s1 = self.create_share(account_info)
        s2 = self.create_share(account_info)
        d1 = 'dir1'
        d2 = 'dir2'

        self.storage_cmd('storage directory create --share-name {} -n {}', account_info, s1, d1)
        self.storage_cmd('storage directory create --share-name {} -n {}', account_info, s2, d2)

        local_file = self.create_temp_file(512, full_random=False)
        src_file = os.path.join(d1, 'source_file.txt')
        dst_file = os.path.join(d2, 'destination_file.txt')

        self.storage_cmd('storage file upload -p "{}" --share-name {} --source "{}"', account_info,
                         src_file, s1, local_file)
        self.storage_cmd('storage file exists -p "{}" -s {}', account_info, src_file, s1) \
            .assert_with_checks(JMESPathCheck('exists', True))

        # test that a file can be successfully copied to root
        src_uri = self.storage_cmd('storage file url -p "{}" -s {}', account_info, src_file,
                                   s1).output
        self.assertTrue(src_uri)

        copy_id = self.storage_cmd('storage file copy start -s {} -p "{}" -u {}',
                                   account_info, s2, dst_file, src_uri) \
            .assert_with_checks(JMESPathCheck('status', 'success')) \
            .get_output_in_json()['id']

        self.storage_cmd('storage file show --share-name {} -p "{}"', account_info, s2, dst_file) \
            .assert_with_checks(JMESPathCheck('name', os.path.basename(dst_file)),
                                JMESPathCheck('properties.copy.id', copy_id),
                                JMESPathCheck('properties.copy.status', 'success'))

        # test that a file can be successfully copied to a directory
        copy_id = \
            self.storage_cmd('storage file copy start -s {} -p "{}" -u {}', account_info, s2,
                             dst_file,
                             src_uri).assert_with_checks(
                JMESPathCheck('status', 'success')).get_output_in_json()['id']

        self.storage_cmd('storage file show -s {} -p "{}"', account_info, s2, dst_file) \
            .assert_with_checks(JMESPathCheck('name', os.path.basename(dst_file)),
                                JMESPathCheck('properties.copy.id', copy_id),
                                JMESPathCheck('properties.copy.status', 'success'))

        # test that a file can be successfully copied by name components
        self.storage_cmd('storage file copy start -s {} -p "{}" --source-share {} --source-path "{}"',
                         account_info, s2, dst_file, s1, src_file) \
            .assert_with_checks(JMESPathCheck('status', 'success'))

    @ResourceGroupPreparer()
    @StorageAccountPreparer()
    def test_storage_file_main_scenario(self, resource_group, storage_account):
        account_info = self.get_account_info(resource_group, storage_account)
        s1 = self.create_share(account_info)
        s2 = self.create_random_name('share', 24)
        self.storage_cmd('storage share create -n {} --metadata foo=bar cat=hat', account_info, s2)
        self.storage_cmd('storage share exists -n {}', account_info, s1) \
            .assert_with_checks(JMESPathCheck('exists', True))
        self.storage_cmd('storage share metadata show --name {}', account_info, s2) \
            .assert_with_checks(JMESPathCheck('cat', 'hat'), JMESPathCheck('foo', 'bar'))

        share_list = self.storage_cmd('storage share list --query "[].name"',
                                      account_info).get_output_in_json()
        self.assertIn(s1, share_list)
        self.assertIn(s2, share_list)

        # verify metadata can be set, queried, and cleared
        self.storage_cmd('storage share metadata update --name {} --metadata a=b c=d', account_info, s1)
        self.storage_cmd('storage share metadata show -n {}', account_info, s1) \
            .assert_with_checks(JMESPathCheck('a', 'b'), JMESPathCheck('c', 'd'))
        self.storage_cmd('storage share metadata update -n {}', account_info, s1)
        self.storage_cmd('storage share metadata show -n {}', account_info, s1) \
            .assert_with_checks(NoneCheck())

        self.storage_cmd('storage share update --name {} --quota 3', account_info, s1)
        self.storage_cmd('storage share show --name {}', account_info, s1) \
            .assert_with_checks(JMESPathCheck('properties.quota', 3))
        self.storage_cmd('storage share url --name {}', account_info, s1) \
            .assert_with_checks(StringContainCheck(s1), StringContainCheck('http'))
        unc = self.storage_cmd('storage share url --name {} --unc', account_info, s1).output
        self.assertTrue('http' not in unc and s1 in unc)

        sas = self.storage_cmd('storage share generate-sas -n {} --permissions r --expiry '
                               '2046-08-23T10:30Z', account_info, s1).output
        self.assertIn('sig=', sas)

        self.validate_file_scenario(account_info, s1)
        self.validate_directory_scenario(account_info, s1)

        self.storage_cmd('storage share delete -n {}', account_info, s1) \
            .assert_with_checks(JMESPathCheck('deleted', True))

    def validate_directory_scenario(self, account_info, share):
        directory = self.create_random_name('dir', 16)
        self.storage_cmd('storage directory create --share-name {} --name {} --fail-on-exist',
                         account_info, share, directory) \
            .assert_with_checks(JMESPathCheck('created', True))
        self.storage_cmd('storage directory list -s {}', account_info, share) \
            .assert_with_checks(JMESPathCheck('length(@)', 1))
        self.storage_cmd('storage directory exists --share-name {} -n {}',
                         account_info, share, directory) \
            .assert_with_checks(JMESPathCheck('exists', True))
        self.storage_cmd('storage directory metadata update -s {} -n {} --metadata a=b c=d',
                         account_info, share, directory)
        self.storage_cmd('storage directory metadata show --share-name {} -n {}',
                         account_info, share, directory) \
            .assert_with_checks(JMESPathCheck('a', 'b'), JMESPathCheck('c', 'd'))
        self.storage_cmd('storage directory show --share-name {} -n {}',
                         account_info, share, directory) \
            .assert_with_checks(JMESPathCheck('metadata', {'a': 'b', 'c': 'd'}),
                                JMESPathCheck('name', directory))
        self.storage_cmd('storage directory metadata update --share-name {} --name {}',
                         account_info, share, directory)
        self.storage_cmd('storage directory metadata show --share-name {} --name {}',
                         account_info, share, directory).assert_with_checks(NoneCheck())

        self.validate_subdir_scenario(account_info, share, directory)

        self.storage_cmd('storage directory delete --share-name {} --name {} --fail-not-exist',
                         account_info, share, directory) \
            .assert_with_checks(JMESPathCheck('deleted', True))
        self.storage_cmd('storage directory exists --share-name {} --name {}',
                         account_info, share, directory) \
            .assert_with_checks(JMESPathCheck('exists', False))

        # verify a directory can be created with metadata and then delete
        directory = self.create_random_name('dir', 16)
        self.storage_cmd('storage directory create --share-name {} --name {} --fail-on-exist '
                         '--metadata foo=bar cat=hat', account_info, share, directory) \
            .assert_with_checks(JMESPathCheck('created', True))
        self.storage_cmd('storage directory metadata show --share-name {} -n {}',
                         account_info, share, directory) \
            .assert_with_checks(JMESPathCheck('cat', 'hat'), JMESPathCheck('foo', 'bar'))
        self.storage_cmd('storage directory delete --share-name {} --name {} --fail-not-exist',
                         account_info, share, directory) \
            .assert_with_checks(JMESPathCheck('deleted', True))

    def validate_file_scenario(self, account_info, share):
        source_file = self.create_temp_file(128, full_random=False)
        dest_file = self.create_temp_file(1)
        filename = "sample_file.bin"

        self.storage_cmd('storage file upload --share-name {} --source "{}" -p {}', account_info,
                         share, source_file, filename)
        self.storage_cmd('storage file exists -s {} -p {}', account_info, share, filename) \
            .assert_with_checks(JMESPathCheck('exists', True))

        if os.path.isfile(dest_file):
            os.remove(dest_file)

        self.storage_cmd('storage file download --share-name {} -p "{}" --dest "{}"', account_info,
                         share, filename, dest_file)

        self.assertTrue(os.path.isfile(dest_file))
        self.assertEqual(os.stat(dest_file).st_size, 128 * 1024)

        self.storage_cmd('storage file download --share-name {} -p "{}" --dest "{}" --start-range 0 --end-range 511', account_info,
                         share, filename, dest_file)

        self.assertTrue(os.path.isfile(dest_file))
        self.assertEqual(os.stat(dest_file).st_size, 512)

        # test resize command
        self.storage_cmd('storage file resize --share-name {} -p "{}" --size 1234', account_info,
                         share, filename)
        self.storage_cmd('storage file show -s {} -p "{}"', account_info, share, filename) \
            .assert_with_checks(JMESPathCheck('properties.contentLength', 1234))

        # test ability to set and reset metadata
        self.storage_cmd('storage file metadata update --share-name {} -p "{}" --metadata a=b c=d',
                         account_info, share, filename)
        self.storage_cmd('storage file metadata show -s {} -p "{}"', account_info, share,
                         filename) \
            .assert_with_checks(JMESPathCheck('a', 'b'), JMESPathCheck('c', 'd'))
        self.storage_cmd('storage file metadata update --share-name {} -p "{}"', account_info,
                         share, filename)
        self.storage_cmd('storage file metadata show -s {} -p "{}"', account_info, share,
                         filename) \
            .assert_with_checks(NoneCheck())

        file_url = 'https://{}.file.core.windows.net/{}/{}'.format(account_info[0], share, filename)
        self.storage_cmd('storage file url -s {} -p "{}"', account_info, share, filename) \
            .assert_with_checks(StringCheck(file_url))

        self.assertIn(filename,
                      self.storage_cmd('storage file list -s {} --query "[].name"',
                                       account_info, share).get_output_in_json())

        from datetime import datetime, timedelta
        expiry = (datetime.utcnow() + timedelta(hours=1)).strftime('%Y-%m-%dT%H:%MZ')
        self.storage_cmd('storage file generate-sas -s {} -p {} --permissions r --expiry {}', account_info, share,
                         filename, expiry).assert_with_checks(StringContainCheck('sig='))

        self.storage_cmd('storage file update -s {} -p {} --content-type "test/type"', account_info,
                         share, filename)
        self.storage_cmd('storage file show -s {} -p {}', account_info, share,
                         filename) \
            .assert_with_checks(JMESPathCheck('properties.contentSettings.contentType',
                                              'test/type'))

        self.storage_cmd('storage file delete --share-name {} -p "{}"',
                         account_info, share, filename)
        self.storage_cmd('storage file exists --share-name {} -p "{}"',
                         account_info, share, filename) \
            .assert_with_checks(JMESPathCheck('exists', False))

    def validate_subdir_scenario(self, account_info, share, directory):
        source_file = self.create_temp_file(64, full_random=False)
        dest_file = self.create_temp_file(1)
        filename = 'testfile.txt'

        self.storage_cmd('storage file upload --share-name {} -p "{}/{}" --source "{}"',
                         account_info, share, directory, filename, source_file)
        self.storage_cmd('storage file exists --share-name {} -p "{}/{}"',
                         account_info, share, directory, filename) \
            .assert_with_checks(JMESPathCheck('exists', True))

        self.storage_cmd('storage file download --share-name {} -p "{}/{}" --dest "{}"',
                         account_info, share, directory, filename, dest_file)

        self.assertTrue(os.path.isfile(dest_file))
        self.assertEqual(os.stat(dest_file).st_size, 64 * 1024)

        self.assertIn(filename, self.storage_cmd('storage file list -s {} -p {} --query "[].name"',
                                                 account_info, share, directory)
                      .get_output_in_json())

        self.storage_cmd('storage share stats --name {}', account_info, share) \
            .assert_with_checks(StringCheck('1'))
        self.storage_cmd('storage file delete --share-name {} -p "{}/{}"',
                         account_info, share, directory, filename)
        self.storage_cmd('storage file exists -s {} -p "{}"', account_info, share, filename) \
            .assert_with_checks(JMESPathCheck('exists', False))


text:
package chunkbuffer

import (
	"errors"
	"github.com/bitantics/chunkbuffer/pile"
	"github.com/bitantics/moreio/meters"
	"github.com/bitantics/moreio/rollingreader"
	"io"
)

var ErrLastChunk = errors.New("last chunk")

// reader end of ChunkBuffer
type reader struct {
	name    string
	pile    pile.Pile
	workers int
	rr      rollingreader.RollingReader
	started bool
}

// newReader creates new reader end of ChunkBuffer
func newReader(name string, pile pile.Pile, workers int) *reader {
	return &reader{
		name:    name,
		pile:    pile,
		workers: workers,
		rr:      *rollingreader.New(),
		started: false,
	}
}

// Read available data from the ChunkBuffer. Block if no data is ready.
func (r *reader) Read(p []byte) (n int, err error) {
	if !r.started {
		r.started = true
		for w := 0; w < r.workers; w += 1 {
			r.startReadingChunk(w)
		}
	}
	if n, err = r.rr.Read(p); err == ErrLastChunk {
		err = io.EOF
		r.rr.Close()
	}
	return
}

// startReadingChunk, but don't wait for any data
func (r *reader) startReadingChunk(n int) {
	ch, err := r.pile.ChunkReader(r.name, n)
	if err != nil {
		r.rr.AddError(err)
		return
	}

	// Wrap chunk in a meter, so we can detect EOF later
	m := meters.NewReadMeter(&readerChunk{ch})
	r.rr.Add(m)

	// If this is not the last chunk, then start downloading the next
	// pending chunk. Last() may block, but this function shouldn't block.
	// So it's in a goroutine.
	go func() {
		<-m.WaitForEOF()
		if !ch.Last() {
			r.startReadingChunk(n + r.workers)
		}
	}()
}

// readerChunk is a wrapper for ChunkReaders. It returns ErrLastChunk
// instead of io.EOF on the last chunk. The error bubbles up through
// the RollingReader, alerting the ChunkBuffer reader it should return
// io.EOF.
type readerChunk struct {
	ch pile.ChunkReader
}

// Read data from the underlying chunk, transforming any io.EOF errors
// to ErrLastChunk if it's the last chunk.
func (rc *readerChunk) Read(p []byte) (n int, err error) {
	n, err = rc.ch.Read(p)
	if err == io.EOF && rc.ch.Last() {
		err = ErrLastChunk
	}
	return
}

redpajama_set_name: RedPajamaGithub


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Sydowia 16: 43 (1963)

#### Original name
Pestalotia poonensis V.G. Rao

### Remarks
null


text:
class ChangeWatchedOnToWatchedIn < ActiveRecord::Migration
  def change
    remove_column :movies, :watched_on
    add_column :movies, :watched_in, :datetime
  end
end


text:
#include <config.h>

#include <stdio.h>
#include <stdlib.h>
#ifdef HAVE_STRING_H
# include <string.h>
#else  /* not HAVE_STRING_H */
# include <strings.h>
#endif /* not HAVE_STRING_H */
#include <ctype.h>
#include <sys/types.h>
#ifdef HAVE_UNISTD_H
# include <unistd.h>
#endif
#ifdef HAVE_PWD_H
# include <pwd.h>
#endif
#include <limits.h>
#ifdef HAVE_UTIME_H
# include <utime.h>
#endif
#ifdef HAVE_SYS_UTIME_H
# include <sys/utime.h>
#endif
#include <errno.h>
#ifdef NeXT
# include <libc.h>		/* for access() */
#endif
#include <assert.h>

#include "wget.h"
#include "utils.h"
#include "fnmatch.h"

#ifndef errno
extern int errno;
#endif

/* Croak the fatal memory error and bail out with non-zero exit
   status.  */
static void
memfatal (const char *s)
{
  /* HACK: expose save_log_p from log.c, so we can turn it off in
     order to prevent saving the log.  Saving the log is dangerous
     because logprintf() and logputs() can call malloc(), so this
     could infloop.  When logging is turned off, infloop can no longer
     happen.  */
  extern int save_log_p;

  save_log_p = 0;
  logprintf (LOG_ALWAYS, _("%s: %s: Not enough memory.\n"), exec_name, s);
  exit (1);
}

/* xmalloc, xrealloc and xstrdup exit the program if there is not
   enough memory.  xstrdup also implements strdup on systems that do
   not have it.  */
void *
xmalloc (size_t size)
{
  void *res;

  res = malloc (size);
  if (!res)
    memfatal ("malloc");
  return res;
}

void *
xrealloc (void *obj, size_t size)
{
  void *res;

  /* Not all Un*xes have the feature of realloc() that calling it with
     a NULL-pointer is the same as malloc(), but it is easy to
     simulate.  */
  if (obj)
    res = realloc (obj, size);
  else
    res = malloc (size);
  if (!res)
    memfatal ("realloc");
  return res;
}

char *
xstrdup (const char *s)
{
#ifndef HAVE_STRDUP
  int l = strlen (s);
  char *s1 = malloc (l + 1);
  if (!s1)
    memfatal ("strdup");
  memcpy (s1, s, l + 1);
  return s1;
#else  /* HAVE_STRDUP */
  char *s1 = strdup (s);
  if (!s1)
    memfatal ("strdup");
  return s1;
#endif /* HAVE_STRDUP */
}

/* Copy the string formed by two pointers (one on the beginning, other
   on the char after the last char) to a new, malloc-ed location.
   0-terminate it.  */
char *
strdupdelim (const char *beg, const char *end)
{
  char *res = (char *)xmalloc (end - beg + 1);
  memcpy (res, beg, end - beg);
  res[end - beg] = '\0';
  return res;
}

/* Parse a string containing comma-separated elements, and return a
   vector of char pointers with the elements.  Spaces following the
   commas are ignored.  */
char **
sepstring (const char *s)
{
  char **res;
  const char *p;
  int i = 0;

  if (!s || !*s)
    return NULL;
  res = NULL;
  p = s;
  while (*s)
    {
      if (*s == ',')
	{
	  res = (char **)xrealloc (res, (i + 2) * sizeof (char *));
	  res[i] = strdupdelim (p, s);
	  res[++i] = NULL;
	  ++s;
	  /* Skip the blanks following the ','.  */
	  while (ISSPACE (*s))
	    ++s;
	  p = s;
	}
      else
	++s;
    }
  res = (char **)xrealloc (res, (i + 2) * sizeof (char *));
  res[i] = strdupdelim (p, s);
  res[i + 1] = NULL;
  return res;
}

/* Return pointer to a static char[] buffer in which zero-terminated
   string-representation of TM (in form hh:mm:ss) is printed.  It is
   shamelessly non-reentrant, but it doesn't matter, really.

   If TM is non-NULL, the time_t of the current time will be stored
   there.  */
char *
time_str (time_t *tm)
{
  static char tms[15];
  struct tm *ptm;
  time_t tim;

  *tms = '\0';
  tim = time (tm);
  if (tim == -1)
    return tms;
  ptm = localtime (&tim);
  sprintf (tms, "%02d:%02d:%02d", ptm->tm_hour, ptm->tm_min, ptm->tm_sec);
  return tms;
}

/* Returns an error message for ERRNUM.  #### This requires more work.
   This function, as well as the whole error system, is very
   ill-conceived.  */
const char *
uerrmsg (uerr_t errnum)
{
  switch (errnum)
    {
    case URLUNKNOWN:
      return _("Unknown/unsupported protocol");
      break;
    case URLBADPORT:
      return _("Invalid port specification");
      break;
    case URLBADHOST:
      return _("Invalid host name");
      break;
    default:
      abort ();
      /* $@#@#$ compiler.  */
      return NULL;
    }
}

/* The Windows versions of the following two functions are defined in
   mswindows.c.  */

/* A cuserid() immitation using getpwuid(), to avoid hassling with
   utmp.  Besides, not all systems have cuesrid().  Under Windows, it
   is defined in mswindows.c.

   If WHERE is non-NULL, the username will be stored there.
   Otherwise, it will be returned as a static buffer (as returned by
   getpwuid()).  In the latter case, the buffer should be copied
   before calling getpwuid() or pwd_cuserid() again.  */
#ifndef WINDOWS
char *
pwd_cuserid (char *where)
{
  struct passwd *pwd;

  if (!(pwd = getpwuid (getuid ())) || !pwd->pw_name)
    return NULL;
  if (where)
    {
      strcpy (where, pwd->pw_name);
      return where;
    }
  else
    return pwd->pw_name;
}

void
fork_to_background (void)
{
#ifndef EMBED
  pid_t pid;
  /* Whether we arrange our own version of opt.lfilename here.  */
  int changedp = 0;

  if (!opt.lfilename)
    {
      opt.lfilename = unique_name (DEFAULT_LOGFILE);
      changedp = 1;
    }
  pid = fork ();
  if (pid < 0)
    {
      /* parent, error */
      perror ("fork");
      exit (1);
    }
  else if (pid != 0)
    {
      /* parent, no error */
      printf (_("Continuing in background.\n"));
      if (changedp)
	printf (_("Output will be written to `%s'.\n"), opt.lfilename);
      exit (0);
    }
  /* child: keep running */
#endif
}
#endif /* not WINDOWS */

/* Canonicalize PATH, and return a new path.  The new path differs from PATH
   in that:
	Multple `/'s are collapsed to a single `/'.
	Leading `./'s and trailing `/.'s are removed.
	Trailing `/'s are removed.
	Non-leading `../'s and trailing `..'s are handled by removing
	portions of the path.

   E.g. "a/b/c/./../d/.." will yield "a/b".  This function originates
   from GNU Bash.

   Changes for Wget:
	Always use '/' as stub_char.
	Don't check for local things using canon_stat.
	Change the original string instead of strdup-ing.
	React correctly when beginning with `./' and `../'.  */
void
path_simplify (char *path)
{
  register int i, start, ddot;
  char stub_char;

  if (!*path)
    return;

  /*stub_char = (*path == '/') ? '/' : '.';*/
  stub_char = '/';

  /* Addition: Remove all `./'-s preceding the string.  If `../'-s
     precede, put `/' in front and remove them too.  */
  i = 0;
  ddot = 0;
  while (1)
    {
      if (path[i] == '.' && path[i + 1] == '/')
	i += 2;
      else if (path[i] == '.' && path[i + 1] == '.' && path[i + 2] == '/')
	{
	  i += 3;
	  ddot = 1;
	}
      else
	break;
    }
  if (i)
    strcpy (path, path + i - ddot);

  /* Replace single `.' or `..' with `/'.  */
  if ((path[0] == '.' && path[1] == '\0')
      || (path[0] == '.' && path[1] == '.' && path[2] == '\0'))
    {
      path[0] = stub_char;
      path[1] = '\0';
      return;
    }
  /* Walk along PATH looking for things to compact.  */
  i = 0;
  while (1)
    {
      if (!path[i])
	break;

      while (path[i] && path[i] != '/')
	i++;

      start = i++;

      /* If we didn't find any slashes, then there is nothing left to do.  */
      if (!path[start])
	break;

      /* Handle multiple `/'s in a row.  */
      while (path[i] == '/')
	i++;

      if ((start + 1) != i)
	{
	  strcpy (path + start + 1, path + i);
	  i = start + 1;
	}

      /* Check for trailing `/'.  */
      if (start && !path[i])
	{
	zero_last:
	  path[--i] = '\0';
	  break;
	}

      /* Check for `../', `./' or trailing `.' by itself.  */
      if (path[i] == '.')
	{
	  /* Handle trailing `.' by itself.  */
	  if (!path[i + 1])
	    goto zero_last;

	  /* Handle `./'.  */
	  if (path[i + 1] == '/')
	    {
	      strcpy (path + i, path + i + 1);
	      i = (start < 0) ? 0 : start;
	      continue;
	    }

	  /* Handle `../' or trailing `..' by itself.  */
	  if (path[i + 1] == '.' &&
	      (path[i + 2] == '/' || !path[i + 2]))
	    {
	      while (--start > -1 && path[start] != '/');
	      strcpy (path + start + 1, path + i + 2);
	      i = (start < 0) ? 0 : start;
	      continue;
	    }
	}	/* path == '.' */
    } /* while */

  if (!*path)
    {
      *path = stub_char;
      path[1] = '\0';
    }
}

/* "Touch" FILE, i.e. make its atime and mtime equal to the time
   specified with TM.  */
void
touch (const char *file, time_t tm)
{
#ifdef HAVE_STRUCT_UTIMBUF
  struct utimbuf times;
  times.actime = times.modtime = tm;
#else
  time_t times[2];
  times[0] = times[1] = tm;
#endif

  if (utime (file, &times) == -1)
    logprintf (LOG_NOTQUIET, "utime(%s): %s\n", file, strerror (errno));
}

/* Checks if FILE is a symbolic link, and removes it if it is.  Does
   nothing under MS-Windows.  */
int
remove_link (const char *file)
{
  int err = 0;
  struct stat st;

  if (lstat (file, &st) == 0 && S_ISLNK (st.st_mode))
    {
      DEBUGP (("Unlinking %s (symlink).\n", file));
      err = unlink (file);
      if (err != 0)
	logprintf (LOG_VERBOSE, _("Failed to unlink symlink `%s': %s\n"),
		   file, strerror (errno));
    }
  return err;
}

/* Does FILENAME exist?  This is quite a lousy implementation, since
   it supplies no error codes -- only a yes-or-no answer.  Thus it
   will return that a file does not exist if, e.g., the directory is
   unreadable.  I don't mind it too much currently, though.  The
   proper way should, of course, be to have a third, error state,
   other than true/false, but that would introduce uncalled-for
   additional complexity to the callers.  */
int
file_exists_p (const char *filename)
{
#ifdef HAVE_ACCESS
  return access (filename, F_OK) >= 0;
#else
  struct stat buf;
  return stat (filename, &buf) >= 0;
#endif
}

/* Returns 0 if PATH is a directory, 1 otherwise (any kind of file).
   Returns 0 on error.  */
int
file_non_directory_p (const char *path)
{
  struct stat buf;
  /* Use lstat() rather than stat() so that symbolic links pointing to
     directories can be identified correctly.  */
  if (lstat (path, &buf) != 0)
    return 0;
  return S_ISDIR (buf.st_mode) ? 0 : 1;
}

/* Return a unique filename, given a prefix and count */
static char *
unique_name_1 (const char *fileprefix, int count)
{
  char *filename;

  if (count)
    {
      filename = (char *)xmalloc (strlen (fileprefix) + numdigit (count) + 2);
      sprintf (filename, "%s.%d", fileprefix, count);
    }
  else
    filename = xstrdup (fileprefix);

  if (!file_exists_p (filename))
    return filename;
  else
    {
      free (filename);
      return NULL;
    }
}

/* Return a unique file name, based on PREFIX.  */
char *
unique_name (const char *prefix)
{
  char *file = NULL;
  int count = 0;

  while (!file)
    file = unique_name_1 (prefix, count++);
  return file;
}

/* Create DIRECTORY.  If some of the pathname components of DIRECTORY
   are missing, create them first.  In case any mkdir() call fails,
   return its error status.  Returns 0 on successful completion.

   The behaviour of this function should be identical to the behaviour
   of `mkdir -p' on systems where mkdir supports the `-p' option.  */
int
make_directory (const char *directory)
{
  int quit = 0;
  int i;
  char *dir;

  /* Make a copy of dir, to be able to write to it.  Otherwise, the
     function is unsafe if called with a read-only char *argument.  */
  STRDUP_ALLOCA (dir, directory);

  /* If the first character of dir is '/', skip it (and thus enable
     creation of absolute-pathname directories.  */
  for (i = (*dir == '/'); 1; ++i)
    {
      for (; dir[i] && dir[i] != '/'; i++)
	;
      if (!dir[i])
	quit = 1;
      dir[i] = '\0';
      /* Check whether the directory already exists.  */
      if (!file_exists_p (dir))
	{
	  if (mkdir (dir, 0777) < 0)
	    return -1;
	}
      if (quit)
	break;
      else
	dir[i] = '/';
    }
  return 0;
}

static int in_acclist PARAMS ((const char *const *, const char *, int));

/* Determine whether a file is acceptable to be followed, according to
   lists of patterns to accept/reject.  */
int
acceptable (const char *s)
{
  int l = strlen (s);

  while (l && s[l] != '/')
    --l;
  if (s[l] == '/')
    s += (l + 1);
  if (opt.accepts)
    {
      if (opt.rejects)
	return (in_acclist ((const char *const *)opt.accepts, s, 1)
		&& !in_acclist ((const char *const *)opt.rejects, s, 1));
      else
	return in_acclist ((const char *const *)opt.accepts, s, 1);
    }
  else if (opt.rejects)
    return !in_acclist ((const char *const *)opt.rejects, s, 1);
  return 1;
}

/* Compare S1 and S2 frontally; S2 must begin with S1.  E.g. if S1 is
   `/something', frontcmp() will return 1 only if S2 begins with
   `/something'.  Otherwise, 0 is returned.  */
int
frontcmp (const char *s1, const char *s2)
{
  for (; *s1 && *s2 && (*s1 == *s2); ++s1, ++s2);
  return !*s1;
}

/* Iterate through STRLIST, and return the first element that matches
   S, through wildcards or front comparison (as appropriate).  */
static char *
proclist (char **strlist, const char *s, enum accd flags)
{
  char **x;

  for (x = strlist; *x; x++)
    if (has_wildcards_p (*x))
      {
	if (fnmatch (*x, s, FNM_PATHNAME) == 0)
	  break;
      }
    else
      {
	char *p = *x + ((flags & ALLABS) && (**x == '/')); /* Remove '/' */
	if (frontcmp (p, s))
	  break;
      }
  return *x;
}

/* Returns whether DIRECTORY is acceptable for download, wrt the
   include/exclude lists.

   If FLAGS is ALLABS, the leading `/' is ignored in paths; relative
   and absolute paths may be freely intermixed.  */
int
accdir (const char *directory, enum accd flags)
{
  /* Remove starting '/'.  */
  if (flags & ALLABS && *directory == '/')
    ++directory;
  if (opt.includes)
    {
      if (!proclist (opt.includes, directory, flags))
	return 0;
    }
  if (opt.excludes)
    {
      if (proclist (opt.excludes, directory, flags))
	return 0;
    }
  return 1;
}

/* Match the end of STRING against PATTERN.  For instance:

   match_backwards ("abc", "bc") -> 1
   match_backwards ("abc", "ab") -> 0
   match_backwards ("abc", "abc") -> 1 */
static int
match_backwards (const char *string, const char *pattern)
{
  int i, j;

  for (i = strlen (string), j = strlen (pattern); i >= 0 && j >= 0; i--, j--)
    if (string[i] != pattern[j])
      break;
  /* If the pattern was exhausted, the match was succesful.  */
  if (j == -1)
    return 1;
  else
    return 0;
}

/* Checks whether string S matches each element of ACCEPTS.  A list
   element are matched either with fnmatch() or match_backwards(),
   according to whether the element contains wildcards or not.

   If the BACKWARD is 0, don't do backward comparison -- just compare
   them normally.  */
static int
in_acclist (const char *const *accepts, const char *s, int backward)
{
  for (; *accepts; accepts++)
    {
      if (has_wildcards_p (*accepts))
	{
	  /* fnmatch returns 0 if the pattern *does* match the
	     string.  */
	  if (fnmatch (*accepts, s, 0) == 0)
	    return 1;
	}
      else
	{
	  if (backward)
	    {
	      if (match_backwards (s, *accepts))
		return 1;
	    }
	  else
	    {
	      if (!strcmp (s, *accepts))
		return 1;
	    }
	}
    }
  return 0;
}

/* Return the malloc-ed suffix of STR.  For instance:
   suffix ("foo.bar")       -> "bar"
   suffix ("foo.bar.baz")   -> "baz"
   suffix ("/foo/bar")      -> NULL
   suffix ("/foo.bar/baz")  -> NULL  */
char *
suffix (const char *str)
{
  int i;

  for (i = strlen (str); i && str[i] != '/' && str[i] != '.'; i--);
  if (str[i++] == '.')
    return xstrdup (str + i);
  else
    return NULL;
}

/* Read a line from FP.  The function reallocs the storage as needed
   to accomodate for any length of the line.  Reallocs are done
   storage exponentially, doubling the storage after each overflow to
   minimize the number of calls to realloc() and fgets().  The newline
   character at the end of line is retained.

   After end-of-file is encountered without anything being read, NULL
   is returned.  NULL is also returned on error.  To distinguish
   between these two cases, use the stdio function ferror().  */

char *
read_whole_line (FILE *fp)
{
  int length = 0;
  int bufsize = 81;
  char *line = (char *)xmalloc (bufsize);

  while (fgets (line + length, bufsize - length, fp))
    {
      length += strlen (line + length);
      assert (length > 0);
      if (line[length - 1] == '\n')
	break;
      /* fgets() guarantees to read the whole line, or to use up the
         space we've given it.  We can double the buffer
         unconditionally.  */
      bufsize <<= 1;
      line = xrealloc (line, bufsize);
    }
  if (length == 0 || ferror (fp))
    {
      free (line);
      return NULL;
    }
  if (length + 1 < bufsize)
    /* Relieve the memory from our exponential greediness.  We say
       `length + 1' because the terminating \0 is not included in
       LENGTH.  We don't need to zero-terminate the string ourselves,
       though, because fgets() does that.  */
    line = xrealloc (line, length + 1);
  return line;
}

/* Load file pointed to by FP to memory and return the malloc-ed
   buffer with the contents.  *NREAD will contain the number of read
   bytes.  The file is loaded in chunks, allocated exponentially,
   starting with FILE_BUFFER_SIZE bytes.  */
void
load_file (FILE *fp, char **buf, long *nread)
{
  long bufsize;

  bufsize = 512;
  *nread = 0;
  *buf = NULL;
  while (!feof (fp) && !ferror (fp))
    {
      *buf = (char *)xrealloc (*buf, bufsize + *nread);
      *nread += fread (*buf + *nread, sizeof (char), bufsize, fp);
      bufsize <<= 1;
    }
  /* #### No indication of encountered error??  */
}

/* Free the pointers in a NULL-terminated vector of pointers, then
   free the pointer itself.  */
void
free_vec (char **vec)
{
  if (vec)
    {
      char **p = vec;
      while (*p)
	free (*p++);
      free (vec);
    }
}

/* Append vector V2 to vector V1.  The function frees V2 and
   reallocates V1 (thus you may not use the contents of neither
   pointer after the call).  If V1 is NULL, V2 is returned.  */
char **
merge_vecs (char **v1, char **v2)
{
  int i, j;

  if (!v1)
    return v2;
  if (!v2)
    return v1;
  if (!*v2)
    {
      /* To avoid j == 0 */
      free (v2);
      return v1;
    }
  /* Count v1.  */
  for (i = 0; v1[i]; i++);
  /* Count v2.  */
  for (j = 0; v2[j]; j++);
  /* Reallocate v1.  */
  v1 = (char **)xrealloc (v1, (i + j + 1) * sizeof (char **));
  memcpy (v1 + i, v2, (j + 1) * sizeof (char *));
  free (v2);
  return v1;
}

/* A set of simple-minded routines to store and search for strings in
   a linked list.  You may add a string to the slist, and peek whether
   it's still in there at any time later.  */

/* Add an element to the list.  If flags is NOSORT, the list will not
   be sorted.  */
slist *
add_slist (slist *l, const char *s, int flags)
{
  slist *t, *old, *beg;
  int cmp;

  if (flags & NOSORT)
    {
      if (!l)
	{
	  t = (slist *)xmalloc (sizeof (slist));
	  t->string = xstrdup (s);
	  t->next = NULL;
	  return t;
	}
      beg = l;
      /* Find the last element.  */
      while (l->next)
	l = l->next;
      t = (slist *)xmalloc (sizeof (slist));
      l->next = t;
      t->string = xstrdup (s);
      t->next = NULL;
      return beg;
    }
  /* Empty list or changing the first element.  */
  if (!l || (cmp = strcmp (l->string, s)) > 0)
    {
      t = (slist *)xmalloc (sizeof (slist));
      t->string = xstrdup (s);
      t->next = l;
      return t;
    }

  beg = l;
  if (cmp == 0)
    return beg;

  /* Second two one-before-the-last element.  */
  while (l->next)
    {
      old = l;
      l = l->next;
      cmp = strcmp (s, l->string);
      if (cmp == 0)             /* no repeating in the list */
	return beg;
      else if (cmp > 0)
	continue;
      /* If the next list element is greater than s, put s between the
	 current and the next list element.  */
      t = (slist *)xmalloc (sizeof (slist));
      old->next = t;
      t->next = l;
      t->string = xstrdup (s);
      return beg;
    }
  t = (slist *)xmalloc (sizeof (slist));
  t->string = xstrdup (s);
  /* Insert the new element after the last element.  */
  l->next = t;
  t->next = NULL;
  return beg;
}

/* Is there a specific entry in the list?  */
int
in_slist (slist *l, const char *s)
{
  int cmp;

  while (l)
    {
      cmp = strcmp (l->string, s);
      if (cmp == 0)
	return 1;
      else if (cmp > 0)         /* the list is ordered!  */
	return 0;
      l = l->next;
    }
  return 0;
}

/* Free the whole slist.  */
void
free_slist (slist *l)
{
  slist *n;

  while (l)
    {
      n = l->next;
      free (l->string);
      free (l);
      l = n;
    }
}

/* Engine for legible and legible_long_long; this function works on
   strings.  */

static char *
legible_1 (const char *repr)
{
  static char outbuf[128];
  int i, i1, mod;
  char *outptr;
  const char *inptr;

  /* Reset the pointers.  */
  outptr = outbuf;
  inptr = repr;
  /* If the number is negative, shift the pointers.  */
  if (*inptr == '-')
    {
      *outptr++ = '-';
      ++inptr;
    }
  /* How many digits before the first separator?  */
  mod = strlen (inptr) % 3;
  /* Insert them.  */
  for (i = 0; i < mod; i++)
    *outptr++ = inptr[i];
  /* Now insert the rest of them, putting separator before every
     third digit.  */
  for (i1 = i, i = 0; inptr[i1]; i++, i1++)
    {
      if (i % 3 == 0 && i1 != 0)
	*outptr++ = ',';
      *outptr++ = inptr[i1];
    }
  /* Zero-terminate the string.  */
  *outptr = '\0';
  return outbuf;
}

/* Legible -- return a static pointer to the legibly printed long.  */
char *
legible (long l)
{
  char inbuf[24];
  /* Print the number into the buffer.  */
  long_to_string (inbuf, l);
  return legible_1 (inbuf);
}

/* The same as legible(), but works on VERY_LONG_TYPE.  See sysdep.h.  */
char *
legible_very_long (VERY_LONG_TYPE l)
{
  char inbuf[128];
  /* Print the number into the buffer.  */
  sprintf (inbuf, VERY_LONG_FORMAT, l);
  return legible_1 (inbuf);
}

/* Count the digits in a (long) integer.  */
int
numdigit (long a)
{
  int res = 1;
  while ((a /= 10) != 0)
    ++res;
  return res;
}

/* Print NUMBER to BUFFER.  This is equivalent to sprintf(buffer,
   "%ld", number), only much faster.

   BUFFER should accept 24 bytes.  This should suffice for the longest
   numbers on 64-bit machines, including the `-' sign and the trailing
   \0.  */
void
long_to_string (char *buffer, long number)
{
#if (SIZEOF_LONG != 4) && (SIZEOF_LONG != 8)
  /* Huh? */
  sprintf (buffer, "%ld", number);
#else /* (SIZEOF_LONG == 4) || (SIZEOF_LONG == 8) */
  char *p = buffer;
  int force = 0;

  if (number < 0)
    {
      *p++ = '-';
      number = -number;
    }

#define FROB(figure) do {						\
    if (force || number >= figure)					\
      *p++ = number / figure + '0', number %= figure, force = 1;	\
    } while (0)
#if SIZEOF_LONG == 8
  FROB (1000000000000000000L);
  FROB (100000000000000000L);
  FROB (10000000000000000L);
  FROB (1000000000000000L);
  FROB (100000000000000L);
  FROB (10000000000000L);
  FROB (1000000000000L);
  FROB (100000000000L);
  FROB (10000000000L);
#endif /* SIZEOF_LONG == 8 */
  FROB (1000000000);
  FROB (100000000);
  FROB (10000000);
  FROB (1000000);
  FROB (100000);
  FROB (10000);
  FROB (1000);
  FROB (100);
  FROB (10);
#undef FROB
  *p++ = number + '0';
  *p = '\0';
#endif /* (SIZEOF_LONG == 4) || (SIZEOF_LONG == 8) */
}


text:
package org.apereo.cas.web.view;

import org.apereo.cas.BaseCasCoreTests;
import org.apereo.cas.CasProtocolConstants;
import org.apereo.cas.CasViewConstants;
import org.apereo.cas.authentication.CoreAuthenticationTestUtils;
import org.apereo.cas.authentication.DefaultAuthenticationAttributeReleasePolicy;
import org.apereo.cas.authentication.DefaultAuthenticationServiceSelectionPlan;
import org.apereo.cas.authentication.DefaultAuthenticationServiceSelectionStrategy;
import org.apereo.cas.authentication.ProtocolAttributeEncoder;
import org.apereo.cas.authentication.support.DefaultCasProtocolAttributeEncoder;
import org.apereo.cas.config.CasThymeleafConfiguration;
import org.apereo.cas.services.ServicesManager;
import org.apereo.cas.services.web.config.CasThemesConfiguration;
import org.apereo.cas.services.web.view.AbstractCasView;
import org.apereo.cas.util.CollectionUtils;
import org.apereo.cas.util.EncodingUtils;
import org.apereo.cas.util.crypto.CipherExecutor;
import org.apereo.cas.util.crypto.PrivateKeyFactoryBean;
import org.apereo.cas.web.AbstractServiceValidateController;
import org.apereo.cas.web.AbstractServiceValidateControllerTests;
import org.apereo.cas.web.ServiceValidateConfigurationContext;
import org.apereo.cas.web.ServiceValidationViewFactory;
import org.apereo.cas.web.config.CasValidationConfiguration;
import org.apereo.cas.web.v2.ServiceValidateController;
import org.apereo.cas.web.view.attributes.DefaultCas30ProtocolAttributesRenderer;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.apache.commons.lang3.tuple.Pair;
import org.apereo.services.persondir.IPersonAttributeDao;
import org.apereo.services.persondir.support.StubPersonAttributeDao;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Lazy;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.mock.web.MockServletContext;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.web.context.support.GenericWebApplicationContext;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.support.RequestContext;

import javax.crypto.Cipher;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Optional;

import static org.junit.jupiter.api.Assertions.*;

/**
 * Unit tests for {@link Cas30ResponseView}.
 *
 * @author Misagh Moayyed
 * @since 4.0.0
 */
@DirtiesContext
@Slf4j
@SpringBootTest(properties = {
    "cas.clearpass.cache-credential=true",
    "cas.clearpass.crypto.enabled=false"
},
    classes = {
        Cas30ResponseViewTests.AttributeRepositoryTestConfiguration.class,
        BaseCasCoreTests.SharedTestConfiguration.class,
        CasThemesConfiguration.class,
        CasThymeleafConfiguration.class,
        CasValidationConfiguration.class
    })
@Tag("CAS")
public class Cas30ResponseViewTests extends AbstractServiceValidateControllerTests {

    @Autowired
    @Qualifier("serviceValidationViewFactory")
    protected ServiceValidationViewFactory serviceValidationViewFactory;

    @Autowired
    @Qualifier("servicesManager")
    protected ServicesManager servicesManager;

    @SneakyThrows
    private static String decryptCredential(final String cred) {
        val factory = new PrivateKeyFactoryBean();
        factory.setAlgorithm("RSA");
        factory.setLocation(new ClassPathResource("keys/RSA4096Private.p8"));
        factory.setSingleton(false);
        val privateKey = factory.getObject();

        LOGGER.debug("Initializing cipher based on [{}]", privateKey.getAlgorithm());
        val cipher = Cipher.getInstance(privateKey.getAlgorithm());

        LOGGER.debug("Decoding value [{}]", cred);
        val cred64 = EncodingUtils.decodeBase64(cred);

        LOGGER.debug("Initializing decrypt-mode via private key [{}]", privateKey.getAlgorithm());
        cipher.init(Cipher.DECRYPT_MODE, privateKey);

        val cipherData = cipher.doFinal(cred64);
        return new String(cipherData, StandardCharsets.UTF_8);
    }

    @Override
    public AbstractServiceValidateController getServiceValidateControllerInstance() {
        val context = ServiceValidateConfigurationContext.builder()
            .validationSpecifications(CollectionUtils.wrapSet(getValidationSpecification()))
            .authenticationSystemSupport(getAuthenticationSystemSupport())
            .servicesManager(getServicesManager())
            .centralAuthenticationService(getCentralAuthenticationService())
            .argumentExtractor(getArgumentExtractor())
            .proxyHandler(getProxyHandler())
            .requestedContextValidator((assertion, request) -> Pair.of(Boolean.TRUE, Optional.empty()))
            .authnContextAttribute("authenticationContext")
            .validationAuthorizers(getServiceValidationAuthorizers())
            .renewEnabled(true)
            .validationViewFactory(serviceValidationViewFactory)
            .build();
        return new ServiceValidateController(context);
    }

    protected Map<?, ?> renderView() throws Exception {
        val modelAndView = this.getModelAndViewUponServiceValidationWithSecurePgtUrl(DEFAULT_SERVICE);
        LOGGER.debug("Retrieved model and view [{}]", modelAndView.getModel());

        val req = new MockHttpServletRequest(new MockServletContext());
        req.setAttribute(RequestContext.WEB_APPLICATION_CONTEXT_ATTRIBUTE, new GenericWebApplicationContext(req.getServletContext()));

        val encoder = new DefaultCasProtocolAttributeEncoder(this.servicesManager, CipherExecutor.noOpOfStringToString());
        val viewDelegated = new View() {
            @Override
            public String getContentType() {
                return MediaType.TEXT_HTML_VALUE;
            }

            @Override
            public void render(final Map<String, ?> map, final HttpServletRequest request, final HttpServletResponse response) {
                LOGGER.warn("Setting attribute [{}]", map.keySet());
                map.forEach(request::setAttribute);
            }
        };

        val view = getCasViewToRender(encoder, viewDelegated);
        val resp = new MockHttpServletResponse();
        view.render(modelAndView.getModel(), req, resp);
        return getRenderedViewModelMap(req);
    }

    protected Map getRenderedViewModelMap(final MockHttpServletRequest req) {
        return (Map) req.getAttribute(CasProtocolConstants.VALIDATION_CAS_MODEL_ATTRIBUTE_NAME_ATTRIBUTES);
    }

    protected AbstractCasView getCasViewToRender(final ProtocolAttributeEncoder encoder, final View viewDelegated) {
        return new Cas30ResponseView(true, encoder, servicesManager,
            viewDelegated, new DefaultAuthenticationAttributeReleasePolicy("attribute"),
            new DefaultAuthenticationServiceSelectionPlan(new DefaultAuthenticationServiceSelectionStrategy()),
            new DefaultCas30ProtocolAttributesRenderer());
    }

    @Test
    public void verifyViewAuthnAttributes() throws Exception {
        val attributes = renderView();
        assertTrue(attributes.containsKey(CasProtocolConstants.VALIDATION_CAS_MODEL_ATTRIBUTE_NAME_AUTHENTICATION_DATE));
        assertTrue(attributes.containsKey(CasProtocolConstants.VALIDATION_CAS_MODEL_ATTRIBUTE_NAME_FROM_NEW_LOGIN));
        assertTrue(attributes.containsKey(CasProtocolConstants.VALIDATION_REMEMBER_ME_ATTRIBUTE_NAME));
    }

    @Test
    public void verifyPasswordAsAuthenticationAttributeCanDecrypt() throws Exception {
        val attributes = renderView();
        assertTrue(attributes.containsKey(CasViewConstants.MODEL_ATTRIBUTE_NAME_PRINCIPAL_CREDENTIAL));

        val encodedPsw = (String) attributes.get(CasViewConstants.MODEL_ATTRIBUTE_NAME_PRINCIPAL_CREDENTIAL);
        val password = decryptCredential(encodedPsw);
        val creds = CoreAuthenticationTestUtils.getCredentialsWithSameUsernameAndPassword();
        assertEquals(password, creds.getPassword());
    }

    @Test
    public void verifyProxyGrantingTicketAsAuthenticationAttributeCanDecrypt() throws Exception {
        val attributes = renderView();
        LOGGER.trace("Attributes are [{}]", attributes.keySet());
        assertTrue(attributes.containsKey(CasViewConstants.MODEL_ATTRIBUTE_NAME_PROXY_GRANTING_TICKET));

        val encodedPgt = (String) attributes.get(CasViewConstants.MODEL_ATTRIBUTE_NAME_PROXY_GRANTING_TICKET);
        val pgt = decryptCredential(encodedPgt);
        assertNotNull(pgt);
    }

    @Test
    public void verifyViewBinaryAttributes() throws Exception {
        val attributes = renderView();
        assertTrue(attributes.containsKey("binaryAttribute"));
        val binaryAttr = attributes.get("binaryAttribute");
        assertEquals("binaryAttributeValue", EncodingUtils.decodeBase64ToString(binaryAttr.toString()));
    }

    @TestConfiguration("AttributeRepositoryTestConfiguration")
    @Lazy(false)
    public static class AttributeRepositoryTestConfiguration {
        @Bean
        public IPersonAttributeDao attributeRepository() {
            val attrs =
                CollectionUtils.wrap("uid", CollectionUtils.wrap("uid"),
                    "eduPersonAffiliation", CollectionUtils.wrap("developer"),
                    "groupMembership", CollectionUtils.wrap("adopters"),
                    "binaryAttribute", CollectionUtils.wrap("binaryAttributeValue".getBytes(StandardCharsets.UTF_8)));
            return new StubPersonAttributeDao((Map) attrs);
        }
    }
}


text:
#import <XCTest/XCTest.h>
#import "XCTest/XCUIElementTypes.h"

#import "FBIntegrationTestCase.h"
#import "FBTestMacros.h"
#import "FBElement.h"
#import "FBElementUtils.h"
#import "XCUIElement+FBUtilities.h"

@interface XCUIElementHelperIntegrationTests : FBIntegrationTestCase
@end

@implementation XCUIElementHelperIntegrationTests

- (void)setUp
{
  [super setUp];
  [self launchApplication];
  [self goToAlertsPage];
}

- (void)testObstructionByAlert
{
  XCUIElement *showAlertButton = self.testedApplication.buttons[FBShowAlertButtonName];
  XCTAssertTrue(showAlertButton.exists);
  XCTAssertFalse(showAlertButton.fb_isObstructedByAlert);
  [showAlertButton tap];
  FBAssertWaitTillBecomesTrue(self.testedApplication.alerts.count > 0);
  XCTAssertTrue(showAlertButton.fb_isObstructedByAlert);
}

- (void)testElementObstruction
{
  XCUIElement *showAlertButton = self.testedApplication.buttons[FBShowAlertButtonName];
  XCTAssertTrue(showAlertButton.exists);
  [showAlertButton tap];
  FBAssertWaitTillBecomesTrue(self.testedApplication.alerts.count > 0);

  XCUIElement *alert = self.testedApplication.alerts.element;
  XCUIElement *acceptAlertButton = self.testedApplication.buttons[@"Will do"];
  XCTAssertTrue(alert.exists);
  XCTAssertTrue(acceptAlertButton.exists);

  XCTAssertTrue([alert fb_obstructsElement:showAlertButton]);
  XCTAssertFalse([alert fb_obstructsElement:acceptAlertButton]);
}

- (void)testDescendantsFiltering
{
  NSArray<XCUIElement *> *buttons = [self.testedApplication.buttons allElementsBoundByIndex];
  XCTAssertTrue(buttons.count > 0);
  NSArray<XCUIElement *> *windows = [self.testedApplication.windows allElementsBoundByIndex];
  XCTAssertTrue(windows.count > 0);

  NSMutableArray<XCUIElement *> *allElements = [NSMutableArray array];
  [allElements addObjectsFromArray:buttons];
  [allElements addObjectsFromArray:windows];

  NSMutableArray<XCElementSnapshot *> *buttonSnapshots = [NSMutableArray array];
  [buttonSnapshots addObject:[buttons.firstObject fb_lastSnapshot]];

  NSArray<XCUIElement *> *result = [self.testedApplication fb_filterDescendantsWithSnapshots:buttonSnapshots];
  XCTAssertEqual(1, result.count);
  XCTAssertEqual([result.firstObject elementType], XCUIElementTypeButton);
}

@end


text:
"""Internal use: Support for ROS messages, including network serialization routines"""

import types
import time
import struct
import logging
import traceback

import genpy

import rospy.exceptions
import rospy.names

class AnyMsg(genpy.Message):
    """
    Message class to use for subscribing to any topic regardless
    of type. Incoming messages are not deserialized. Instead, the raw
    serialized data can be accssed via the buff property.

    This class is meant to be used by advanced users only.
    """
    _md5sum = rospy.names.TOPIC_ANYTYPE
    _type = rospy.names.TOPIC_ANYTYPE
    _has_header = False
    _full_text = ''
    __slots__ = ['_buff']
    def __init__(self, *args):
        """
        Constructor. Does not accept any arguments.
        """
        if len(args) != 0:
            raise rospy.exceptions.ROSException("AnyMsg does not accept arguments")
        self._buff = None

    def serialize(self, buff):
        """AnyMsg provides an implementation so that a node can forward messages w/o (de)serialization"""
        if self._buff is None:
            raise rospy.exceptions("AnyMsg is not initialized")
        else:
            buff.write(self._buff)

    def deserialize(self, str):
        """Copies raw buffer into self._buff"""
        self._buff = str
        return self

def args_kwds_to_message(data_class, args, kwds):
    """
    Given a data class, take in the args and kwds of a function call and return the appropriate
    data_class instance.

    If kwds are specified, a new data_class instance will be created with keyword-style init.

    If there is only a single arg and it is of the correct type, it
    will be returned. AnyMsg is considered to match all data_class
    types.

    Otherwise, args will be used as args for a new message instance.

    @param data_class: Message class that will be used to instantiate new instances, if necessary.
    @type  data_class: Message class
    @param args: function args
    @type  args: sequence
    @param kwds: function kwds
    @type  kwds: dict
    @raise TypeError: if args and kwds are both specified
    """
    if args and kwds:
        raise TypeError("publish() can be called with arguments or keywords, but not both.")
    elif kwds:
        return data_class(**kwds)
    else:
        if len(args) == 1:
            arg = args[0]
            # #2584: have to compare on md5sum as isinstance check can fail in dyngen case
            if hasattr(arg, '_md5sum') and (arg._md5sum == data_class._md5sum or isinstance(arg, AnyMsg)):
                return arg
            # If the argument is a message, make sure that it matches
            # the type of the first field. This means that the
            # data_class has fields and that the type matches.  This
            # branch isn't necessary but provides more useful
            # information to users
            elif isinstance(arg, genpy.Message):
                if len(data_class._slot_types) == 0:
                    raise TypeError("expected [] but got [%s]"%arg._type)
                elif arg._type != data_class._slot_types[0]:
                    raise TypeError("expected [%s] but got [%s]"%(data_class._slot_types[0], arg._type))
            return data_class(*args)
        else:
            return data_class(*args)

def serialize_message(b, seq, msg):
    """
    Serialize the message to the buffer
    @param b: buffer to write to. WARNING: buffer will be reset after call
    @type  b: StringIO
    @param msg: message to write
    @type  msg: Message
    @param seq: current sequence number (for headers)
    @type  seq: int: current sequence number (for headers)
    @raise ROSSerializationException: if unable to serialize
    message. This is usually due to a type error with one of the
    fields.
    """
    start = b.tell()
    b.seek(start+4) #reserve 4-bytes for length

    #update Header object in top-level message
    if getattr(msg.__class__, "_has_header", False):
        header = msg.header
        header.seq = seq
        # default value for frame_id is '0'
        if header.frame_id is None:
            header.frame_id = "0"

    #serialize the message data
    try:
        msg.serialize(b)
    except struct.error as e:
        raise rospy.exceptions.ROSSerializationException(e)

    #write 4-byte packet length
    # -4 don't include size of length header
    end = b.tell()
    size = end - 4 - start
    b.seek(start)
    b.write(struct.pack('<I', size))
    b.seek(end)

def deserialize_messages(b, msg_queue, data_class, queue_size=None, max_msgs=None, start=0):
    """
    Read all messages off the buffer

    @param b: buffer to read data from
    @type  b: StringIO
    @param msg_queue: queue to append deserialized data to
    @type  msg_queue: list
    @param data_class: message deserialization class
    @type  data_class: Message class
    @param queue_size: message queue size. all but the last
    queue_size messages are discarded if this parameter is specified.
    @type  queue_size: int
    @param start: starting position to read in b
    @type  start: int
    @param max_msgs int: maximum number of messages to deserialize or None
    @type  max_msgs: int
    @raise genpy.DeserializationError: if an error/exception occurs during deserialization
    """
    try:
        pos = start
        btell = b.tell()
        left = btell - pos

        # check to see if we even have a message
        if left < 4:
            return

        # read in each message from the buffer as a string. each
        # message is preceded by a 4-byte integer length. the
        # serialized messages are appended to buff.
        b.seek(pos)
        buffs = []
        # size of message
        size = -1
        while (size < 0 and left >= 4) or (size > -1 and left >= size):
            # - read in the packet length
            #   NOTE: size is not inclusive of itself.
            if size < 0 and left >= 4:
                (size,) = struct.unpack('<I', b.read(4))
                left -= 4
            # - deserialize the complete buffer
            if size > -1 and left >= size:
                buffs.append(b.read(size))
                pos += size + 4
                left = btell - pos
                size = -1
                if max_msgs and len(buffs) >= max_msgs:
                    break

        #Before we deserialize, prune our buffers baed on the
        #queue_size rules.
        if queue_size is not None:
            buffs = buffs[-queue_size:]

        # Deserialize the messages into msg_queue, then trim the
        # msg_queue as specified.
        for q in buffs:
            data = data_class()
            msg_queue.append(data.deserialize(q))
        if queue_size is not None:
            del msg_queue[:-queue_size]

        #update buffer b to its correct write position.
        if btell == pos:
            #common case: no leftover data, reset the buffer
            b.seek(start)
            b.truncate(start)
        else:
            if pos != start:
                #next packet is stuck in our buffer, copy it to the
                #beginning of our buffer to keep things simple
                b.seek(pos)
                leftovers = b.read(btell-pos)
                b.truncate(start + len(leftovers))
                b.seek(start)
                b.write(leftovers)
            else:
                b.seek(btell)
    except Exception as e:
        logging.getLogger('rospy.msg').error("cannot deserialize message: EXCEPTION %s", traceback.format_exc())
        raise genpy.DeserializationError("cannot deserialize: %s"%str(e))


text:
package com.amazonaws.services.codedeploy.model;

import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;

/**
 *

 * A configuration that shifts traffic from one version of a Lambda function to another in equal increments, with an
 * equal number of minutes between each increment. The original and target Lambda function versions are specified in the
 * deployment's AppSpec file.
 *

 *
 * @see AWS API
 *      Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class TimeBasedLinear implements Serializable, Cloneable, StructuredPojo {

    /**
     *

     * The percentage of traffic that is shifted at the start of each increment of a TimeBasedLinear
     * deployment.
     *

     */
    private Integer linearPercentage;
    /**
     *

     * The number of minutes between each incremental traffic shift of a TimeBasedLinear deployment.
     *

     */
    private Integer linearInterval;

    /**
     *

     * The percentage of traffic that is shifted at the start of each increment of a TimeBasedLinear
     * deployment.
     *

     *
     * @param linearPercentage
     *        The percentage of traffic that is shifted at the start of each increment of a TimeBasedLinear
     *        deployment.
     */

    public void setLinearPercentage(Integer linearPercentage) {
        this.linearPercentage = linearPercentage;
    }

    /**
     *

     * The percentage of traffic that is shifted at the start of each increment of a TimeBasedLinear
     * deployment.
     *

     *
     * @return The percentage of traffic that is shifted at the start of each increment of a
     *         TimeBasedLinear deployment.
     */

    public Integer getLinearPercentage() {
        return this.linearPercentage;
    }

    /**
     *

     * The percentage of traffic that is shifted at the start of each increment of a TimeBasedLinear
     * deployment.
     *

     *
     * @param linearPercentage
     *        The percentage of traffic that is shifted at the start of each increment of a TimeBasedLinear
     *        deployment.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public TimeBasedLinear withLinearPercentage(Integer linearPercentage) {
        setLinearPercentage(linearPercentage);
        return this;
    }

    /**
     *

     * The number of minutes between each incremental traffic shift of a TimeBasedLinear deployment.
     *

     *
     * @param linearInterval
     *        The number of minutes between each incremental traffic shift of a TimeBasedLinear deployment.
     */

    public void setLinearInterval(Integer linearInterval) {
        this.linearInterval = linearInterval;
    }

    /**
     *

     * The number of minutes between each incremental traffic shift of a TimeBasedLinear deployment.
     *

     *
     * @return The number of minutes between each incremental traffic shift of a TimeBasedLinear
     *         deployment.
     */

    public Integer getLinearInterval() {
        return this.linearInterval;
    }

    /**
     *

     * The number of minutes between each incremental traffic shift of a TimeBasedLinear deployment.
     *

     *
     * @param linearInterval
     *        The number of minutes between each incremental traffic shift of a TimeBasedLinear deployment.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public TimeBasedLinear withLinearInterval(Integer linearInterval) {
        setLinearInterval(linearInterval);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getLinearPercentage() != null)
            sb.append("LinearPercentage: ").append(getLinearPercentage()).append(",");
        if (getLinearInterval() != null)
            sb.append("LinearInterval: ").append(getLinearInterval());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof TimeBasedLinear == false)
            return false;
        TimeBasedLinear other = (TimeBasedLinear) obj;
        if (other.getLinearPercentage() == null ^ this.getLinearPercentage() == null)
            return false;
        if (other.getLinearPercentage() != null && other.getLinearPercentage().equals(this.getLinearPercentage()) == false)
            return false;
        if (other.getLinearInterval() == null ^ this.getLinearInterval() == null)
            return false;
        if (other.getLinearInterval() != null && other.getLinearInterval().equals(this.getLinearInterval()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getLinearPercentage() == null) ? 0 : getLinearPercentage().hashCode());
        hashCode = prime * hashCode + ((getLinearInterval() == null) ? 0 : getLinearInterval().hashCode());
        return hashCode;
    }

    @Override
    public TimeBasedLinear clone() {
        try {
            return (TimeBasedLinear) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
        }
    }

    @com.amazonaws.annotation.SdkInternalApi
    @Override
    public void marshall(ProtocolMarshaller protocolMarshaller) {
        com.amazonaws.services.codedeploy.model.transform.TimeBasedLinearMarshaller.getInstance().marshall(this, protocolMarshaller);
    }
}


text:
$(document).ready(function() {

    /// (C) Ken Fyrstenberg Nilsen, Abdias Software, CC3.0-attribute.
    var ctx = canvas.getContext('2d');
    var img = new Image();
    var play = false;

    /// turn off image smoothing - this will give the pixelated effect
    ctx.mozImageSmoothingEnabled = false;
    ctx.imageSmoothingEnabled = false;

    var zoomFactor = 50;
    console.log(zoomFactor);

    /// wait until image is actually available
    img.onload = pixelate;

    /// some image, we are not struck with CORS restrictions as we
    /// do not use pixel buffer to pixelate, so any image will do
    img.src = 'img/butterflies.jpg';

    /// MAIN function
    function pixelate(v) {
        /// if in play mode use that value, else use slider value
        //var size = (play ? v : blocks.value) * 0.01,
        var size = zoomFactor * 0.01,

        /// cache scaled width and height
        w = canvas.width * size ,
        h = canvas.height * size;

        /// draw original image to the scaled size
        ctx.drawImage(img, 0, 0, w, h);

        /// then draw that scaled image thumb back to fill canvas
        /// As smoothing is off the result will be pixelated
        ctx.drawImage(canvas, 0, 0, w, h, 0, 0, canvas.width, canvas.height);
    }

    window.requestAnimationFrame = (function () {
        return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || function (callback) {
            window.setTimeout(callback, 1000 / 60);
        };
    })();

    // using the event helper
    var popupyet = false;
    $('#canvas').mousewheel(function(event) {
        //
        // pseudocode for auto-scroll:
        // 1. check which way mouse is scrolling (positive or negative)
        // 2. auto-zoom (animate?) --> http://jsfiddle.net/AbdiasSoftware/QznT7/
        //
        //

        event.preventDefault(); // Stop window scroll when mouse is inside canvas

        if(zoomFactor == 40 && popupyet== false){
            //pop up that says to click on pixels
            $('#popup').css({
                display: "block",
            });
            $('.alert').css({
                display: "block",
            });
            $('.alert-warning').css({
                display: "block",
            });
            $('.alert-dismissible').css({
                display: "block",
            });

            popupyet=true;
        }
        if(event.deltaY > 0 && zoomFactor<50){
            zoomFactor++;
            deltaY=0;
            console.log(zoomFactor);
            pixelate();
        }
        if(event.deltaY < 0 && zoomFactor > 1){
            zoomFactor--;
            deltaY=0;
            console.log(zoomFactor);
            pixelate();
        }
        if (zoomFactor <=0){
            zoomFactor=0;
        }
        if (zoomFactor >=50){
            zoomFactor=50;
        }
        // pixelate();
    });

    function findPos(obj) {
        var curleft = 0, curtop = 0;
        if (obj.offsetParent) {
            do {
                curleft += obj.offsetLeft;
                curtop += obj.offsetTop;
            } while (obj = obj.offsetParent);
            return { x: curleft, y: curtop };
        }
    }

    function rgbToHex(r, g, b) {
        if (r > 255 || g > 255 || b > 255)
            throw "Invalid color component";
        return ((r << 16) | (g << 8) | b).toString(16);
    }

    $('#canvas').mousemove(function(e) {
        var pos = findPos(this);
        var x = e.pageX - pos.x;
        var y = e.pageY - pos.y;
        var coord = "x=" + x + ", y=" + y;
        var c = this.getContext('2d');
        var p = c.getImageData(x, y, 1, 1).data;
        var hex = "#" + ("000000" + rgbToHex(p[0], p[1], p[2])).slice(-6);
        var r = p[0];
        var g = p[1];
        var b = p[2];
        var bright = parseInt((r+g+b)/3);
        var brightPercent = parseInt((bright/255)*100);

        $('#status').html("" + r + " "+"  - "+ ""+ g + " - " + ""+ b +"");
        document.getElementById("color-box").style.backgroundColor = hex;
        $('.computed#r').html(r);
        $('.computed#g').html(g);
        $('.computed#b').html(b);
        $('.computed#x').html(x);
        $('.computed#y').html(y);
        $('.computed#bright').html(bright + ' / ' + brightPercent + '%');
    });

    var showColorBox = false;

    $('#canvas').click(function(){
        var yOffset = -10;
        var xOffset = 10;
        showColorBox = !showColorBox;

        $(document).on('mousemove', function(e){
            if($('#canvas').is(':hover') && showColorBox){
                $('#color-box-wrapper').show();
                $('#color-box-background').show();
                $('#color-box-wrapper').css("top", (e.pageY - yOffset) + "px").css("left", (e.pageX + xOffset) + "px");
                $('#color-box-background').css("top", (e.pageY - yOffset) + "px").css("left", (e.pageX + xOffset) + "px");
            }
            else{
                $('#color-box-wrapper').hide();
                $('#color-box-background').hide();
            }
        });
        $('#color-box-wrapper').toggle();
        $('#color-box-background').toggle();
        $('#computed').toggle();
    });

    $('#color-box-wrapper').hide();
    $('#color-box-background').hide();
    $('#computed').hide();

    // Closes the sidebar menu
    $("#menu-close").click(function(e) {
        e.preventDefault();
        $("#sidebar-wrapper").toggleClass("active");
    });

    // Opens the sidebar menu
    $("#menu-toggle").click(function(e) {
        e.preventDefault();
        $("#sidebar-wrapper").toggleClass("active");
    });

    // Scrolls to the selected menu item on the page
    $(function() {
        $('a[href*=#]:not([href=#])').click(function() {
            if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') || location.hostname == this.hostname) {

                var target = $(this.hash);
                target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
                if (target.length) {
                    $('html,body').animate({
                        scrollTop: target.offset().top
                    }, 1000);
                    return false;
                }
            }
        });
    });

});


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

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>DataMapper (JUnitParams 1.0.3-SNAPSHOT API)</title>
<meta name="date" content="2014-07-28">
<link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

junitparams.mappers

Interface DataMapper

All Known Implementing Classes:

CsvWithHeaderMapper, IdentityMapper

public interface DataMapper

Interface to be used by FileParameters'ized test methods. If you want to read
 your own format of data from file, implement the map method appropriately.
 For CSV files, just skip it.

Author:

Pawel Lipinski

Method Summary

All Methods Instance Methods Abstract Methods

Modifier and Type
Method and Description

Object[]
map(Reader reader)

Maps file contents to parameters.

Method Detail

map

Object[] map(Reader reader)

Maps file contents to parameters. In your implementation read the data
 from the reader. The reader is closed in the framework, so just read it
 :)

 While reading transform the data into Object[][], where external
 dimension are different parameter sets, and internal dimension is the set
 of params per single test call

 You can optionally return Object[] with Strings inside, but each String
 must be a string in the same format as what you would normally pass to
 @Parameters({})

Parameters:

reader -

Returns:

an array with all parameter sets

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Copyright © 2014 Pragmatists. All rights reserved.


text:
package com.gemstone.gemfire.internal.cache.extension.mock;

import com.gemstone.gemfire.cache.Cache;
import com.gemstone.gemfire.cache.CacheFactory;
import com.gemstone.gemfire.cache.Region;
import com.gemstone.gemfire.cache.execute.Function;
import com.gemstone.gemfire.cache.execute.FunctionAdapter;
import com.gemstone.gemfire.cache.execute.FunctionContext;
import com.gemstone.gemfire.cache.execute.FunctionException;
import com.gemstone.gemfire.cache.execute.ResultSender;
import com.gemstone.gemfire.internal.cache.extension.Extensible;
import com.gemstone.gemfire.internal.cache.extension.Extension;
import com.gemstone.gemfire.internal.cache.xmlcache.CacheXml;
import com.gemstone.gemfire.management.internal.cli.CliUtil;
import com.gemstone.gemfire.management.internal.cli.functions.CliFunctionResult;
import com.gemstone.gemfire.management.internal.cli.i18n.CliStrings;
import com.gemstone.gemfire.management.internal.configuration.domain.XmlEntity;

/**
 * Function to alter {@link MockRegionExtension} on a {@link Region}.
 *
 *

 *
Arguments:

 *

 *

 *
{@link String} regionName

 *
Name of region on which to create {@link MockCacheExtension}.

 *
{@link String} value

 *
Value to set. See {@link MockCacheExtension#setValue()}.

 *

 *

 *

 *
 * @author jbarrett@pivotal.io
 *
 * @since 8.1
 */
public class AlterMockRegionExtensionFunction extends FunctionAdapter {

  private static final long serialVersionUID = 1L;

  public static final Function INSTANCE = new AlterMockRegionExtensionFunction();

  @Override
  public void execute(FunctionContext context) {
    final Cache cache = CacheFactory.getAnyInstance();

    final Region<?, ?> region = cache.getRegion((String) ((Object[]) context.getArguments())[0]);
    if (!(region instanceof Extensible)) {
      throw new FunctionException("Not extensible region.");
    }

    final String value = (String) ((Object[]) context.getArguments())[1];

    @SuppressWarnings("unchecked")
    final Extensible<Region<?, ?>> extensible = (Extensible<Region<?, ?>>) region;
    for (Extension<Region<?, ?>> extension : extensible.getExtensionPoint().getExtensions()) {
      if (extension instanceof MockRegionExtension) {
        ((MockRegionExtension) extension).setValue(value);
      }
    }

    XmlEntity xmlEntity = new XmlEntity(CacheXml.REGION, "name", region.getName());

    final ResultSender<Object> resultSender = context.getResultSender();
    final String memberNameOrId = CliUtil.getMemberNameOrId(cache.getDistributedSystem().getDistributedMember());

    resultSender.lastResult(new CliFunctionResult(memberNameOrId, xmlEntity, CliStrings.format("Mock region extension \"{0}\" altered on \"{1}\"",
        new Object[] { region.getFullPath(), memberNameOrId })));

  }

  @Override
  public String getId() {
    return AlterMockRegionExtensionFunction.class.getName();
  }

  /**
   * @param regionName
   * @param value
   * @return
   * @since 8.1
   */
  public static Object[] toArgs(final String regionName, final String value) {
    return new Object[] { regionName, value };
  }
}


text:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

    <TextView android:text="begin" android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/begin"/>
    <TextView android:text="stop" android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="clip_vertical"
        android:id="@+id/stop"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="clean"
        android:id="@+id/clean"/>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="upload"
        android:id="@+id/upload"/>
    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/img"/>
</LinearLayout>


text:
namespace XPNet
{
    // The automatic DataRef generation creates a companion to this partial class where you can access the
    // generated DataRefs.  If you don't run that generation, this class provides a stub that allows the
    // rest of the project to still compile.
    public partial class SimDataRefs
    {
        private readonly XPlaneData m_data;

        internal SimDataRefs(XPlaneData data)
        {
            m_data = data;

            Init();
        }

        partial void Init();
    }
}


text:
<?php declare(strict_types = 1);

namespace SlevomatCodingStandard\Sniffs\Commenting;

use SlevomatCodingStandard\Sniffs\TestCase;

class DisallowOneLinePropertyDocCommentSniffTest extends TestCase
{

	public function testNoErrors(): void
	{
		$report = self::checkFile(__DIR__ . '/data/multiLinePropertyDocCommentNoErrors.php');
		self::assertNoSniffErrorInFile($report);
	}

	public function testErrors(): void
	{
		$report = self::checkFile(__DIR__ . '/data/multiLinePropertyDocCommentErrors.php');

		self::assertSame(12, $report->getErrorCount());

		self::assertSniffError($report, 6, DisallowOneLinePropertyDocCommentSniff::CODE_ONE_LINE_PROPERTY_COMMENT);
		self::assertSniffError($report, 9, DisallowOneLinePropertyDocCommentSniff::CODE_ONE_LINE_PROPERTY_COMMENT);
		self::assertSniffError($report, 12, DisallowOneLinePropertyDocCommentSniff::CODE_ONE_LINE_PROPERTY_COMMENT);
		self::assertSniffError($report, 15, DisallowOneLinePropertyDocCommentSniff::CODE_ONE_LINE_PROPERTY_COMMENT);
		self::assertSniffError($report, 18, DisallowOneLinePropertyDocCommentSniff::CODE_ONE_LINE_PROPERTY_COMMENT);
		self::assertSniffError($report, 21, DisallowOneLinePropertyDocCommentSniff::CODE_ONE_LINE_PROPERTY_COMMENT);
		self::assertSniffError($report, 24, DisallowOneLinePropertyDocCommentSniff::CODE_ONE_LINE_PROPERTY_COMMENT);
		self::assertSniffError($report, 27, DisallowOneLinePropertyDocCommentSniff::CODE_ONE_LINE_PROPERTY_COMMENT);
		self::assertSniffError($report, 30, DisallowOneLinePropertyDocCommentSniff::CODE_ONE_LINE_PROPERTY_COMMENT);
		self::assertSniffError($report, 33, DisallowOneLinePropertyDocCommentSniff::CODE_ONE_LINE_PROPERTY_COMMENT);
		self::assertSniffError($report, 36, DisallowOneLinePropertyDocCommentSniff::CODE_ONE_LINE_PROPERTY_COMMENT);
		self::assertSniffError($report, 39, DisallowOneLinePropertyDocCommentSniff::CODE_ONE_LINE_PROPERTY_COMMENT);

		self::assertAllFixedInFile($report);
	}

}


text:
using System.Reflection;

[assembly: AssemblyTitle("Leak.Memory")]
[assembly: AssemblyProduct("Leak.Memory")]
[assembly: AssemblyCopyright("Copyright © Adrian Macal 2016")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]


text:
var sandbox = require('nodeunit').utils.sandbox;
var path = require('path');
var context = {
	process: Object.create(process),
	module: {
		exports: {}
	},
	require: require,
	console: console,
	__dirname: path.resolve(path.join(__dirname,'..','libs'))
};
context.global = context;

context.process.stdout = Object.create(process.stdout);
context.process.stdout.getWindowSize = function(){
	return [80,60];
}

module.exports = sandbox(__dirname+'/../libs/commandio.js', context);


text:
package com.bookstore.controller.order;

import com.bookstore.bean.Order;
import com.bookstore.dao.OrderDAO;
import com.bookstore.util.DbUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * Class IndexController
 */
@WebServlet("/orders")
public class IndexController extends BaseOrderController {
    @Override
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        int page = 1;
        int perPage = 10;
        if (request.getParameter("page") != null) {
            page = Integer.parseInt(request.getParameter("page"));
        }

        OrderDAO orderDAO = DbUtil.getDAO(OrderDAO.class);

        List<Order> orderList = orderDAO.findAll((page - 1) * perPage, perPage);
        int orderCount = orderDAO.count();
        setOrderDetail(orderList);

        request.setAttribute("orderList", orderList);
        request.setAttribute("orderPage", page);
        request.setAttribute("orderPageCount", (int)Math.ceil((double)orderCount / perPage));

        forward(request, response, "/orders/index.jsp");
    }
}


text:
<?php

namespace Extranet\DiversBundle\Entity;

use Doctrine\ORM\EntityRepository;

/**
 * TauxRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class TauxRepository extends EntityRepository
{
}


text:
``flask.ext.admin.form.fields``
===============================

.. automodule:: flask.ext.admin.form.fields

	.. autoclass:: TimeField
		:members:

	.. autoclass:: Select2Field
		:members:

	.. autoclass:: Select2TagsField
		:members:


text:
Julia HDF5 Guide
================

Overview
--------

[HDF5][HDF5] stands for Hierarchical Data Format v5 and is closely modeled on file systems. In HDF5, a "group" is analogous to a directory, a "dataset" is like a file. HDF5 also uses "attributes" to associate metadata with a particular group or dataset. HDF5 uses ASCII names for these different objects, and objects can be accessed by UNIX-like pathnames, e.g., "/sample1/tempsensor/firsttrial" for a top-level group "sample1", a subgroup "tempsensor", and a dataset "firsttrial".

For simple types (scalars, strings, and arrays), HDF5 provides sufficient metadata to know how each item is to be interpreted. For example, HDF5 encodes that a given block of bytes is to be interpreted as an array of `Int64`, and represents them in a way that is compatible across different computing architectures.

However, to preserve Julia objects, one generally needs additional type information to be supplied, which is easy to provide using attributes. This is handled for you automatically in the JLD and MatIO modules for \*.jld and \*.mat files. These specific formats (conventions) provide "extra" functionality, but they are still both regular HDF5 files and are therefore compatible with any HDF5 reader or writer.

Language wrappers for HDF5 are often described as either "low level" or "high level." This package contains both flavors: at the low level, it directly wraps HDF5's functions, thus copying their API and making them available from within Julia. At the high level, it provides a set of functions built on the low-level wrap which may make the usage of this library more convenient.

Opening and closing files
-------------------------

"Plain" (i.e., with no extra formatting conventions) HDF5 files are created and/or opened with the `h5open` command:

```julia
fid = h5open(filename, mode)
```

The mode can be any one of the following:

    mode	 Meaning

    "r"	 read-only

    "r+"	 read-write, preserving any existing contents

    "w"	 read-write, destroying any existing contents (if any)

This produces an object of type `PlainHDF5File`, a subtype of the abstract type `HDF5File`. The subtypes of `HDF5File` are used in method dispatch to enforce any file-type-specific formatting. "Plain" files have no elements (groups, datasets, or attributes) that are not explicitly created by the user.

When you're finished with a file, you should close it:

```julia
close(fid)
```

Closing a file also closes any other open objects (e.g., datasets, groups) in that file. In general, you need to close an HDF5 file to "release" it for use by other applications.

Opening and closing objects
---------------------------

If you have a file object `fid`, and this has a group or dataset called `"myobject"` at the top level of a file, you can open it in the following way:

```julia
obj = fid["myobject"]
```

This does not read any data or attributes associated with the object, it's simply a handle for further manipulations. For example:

```julia
g = fid["mygroup"]
dset = g["mydataset"]
```

or simply

```julia
dset = fid["mygroup/mydataset"]
```

When you're done with an object, you can close it using `close(obj)`. If you forget to do this, it will be closed for you anyway when the file is closed, or if `obj` goes out of scope and gets garbage collected.

Reading and writing data
------------------------

Suppose you have a group `g` which contains a dataset with path `"mydataset"`, and that you've also opened this dataset as `dset = g["mydataset"]`.
You can read information in this dataset in any of the following ways:

```julia
A = read(dset)
A = read(g, "mydataset")
Asub = dset[2:3, 1:3]
```

The last syntax reads just a subset of the data array (assuming that `dset` is an array of sufficient size).
libhdf5 has internal mechanisms for slicing arrays, and consequently if you need only a small piece of a large array, it can be faster to read just what you need rather than reading the entire array and discarding most of it.

Datasets can be created with either

```julia
g["mydataset"] = rand(3,5)
write(g, "mydataset", rand(3,5))
```

You can also optionally "chunk" and compress your data. For example,

```julia
A = rand(100,100)
g["A", "chunk", (5,5), "compress", 3] = A
```

stores the matrix `A` in 5-by-5 chunks and uses a compression level
`3`. Instead of `"compress"`, you can use `"deflate"` to specify
[deflate/zlib](http://en.wikipedia.org/wiki/DEFLATE) compression, or
`"blosc"` to specify [Blosc](http://www.blosc.org/) compress (which is
generally much faster than deflate); currently, `"compress"`
corresponds to `"blosc"`. Chunking can be useful if you will typically
extract small segments of an array.  A heuristic chunking is
automatically used if you specify compression but don't specify
chunking.

It is also possible to write to subsets of an on-disk HDF5 dataset. This is
useful to incrementally save to very large datasets you don't want to keep in
memory. For example,

```julia
dset = d_create(g, "B", datatype(Float64), dataspace(1000,100,10), "chunk", (100,100,1))
dset[:,1,1] = rand(1000)
```

creates a Float64 dataset in the file or group `g`, with dimensions 1000x100x10, and then
writes to just the first 1000 element slice.
If you know the typical size of subset reasons you'll be reading/writing, it can be beneficial to set the chunk dimensions appropriately.

More [fine-grained control](#mid-level-routines) is also available.

Memory mapping
--------------

If you will frequently be accessing individual elements or small regions of array datasets, it can be substantially more efficient to bypass HDF5 routines and use direct [memory mapping](https://en.wikipedia.org/wiki/Memory-mapped_file).
This is possible only under particular conditions: when the dataset is an array of standard "bits" types (e.g., `Float64` or `Int32`) and no chunking/compression is being used.
You can use the `ismmappable` function to test whether this is possible; for example,

```julia
dset = g["x"]
if ismmappable(dset)
    dset = readmmap(dset)
end
val = dset[15]
```

Note that `readmmap` returns an `Array` rather than an HDF5 object.

**Note**: if you use `readmmap` on a dataset and subsequently close the file, the array data are still available---and file continues to be in use---until all of the arrays are garbage-collected.
This is in contrast to standard HDF5 datasets, where closing the file prevents further access to any of the datasets, but the file is also detached and can safely be rewritten immediately.

Supported data types
--------------------

PlainHDF5File knows how to store values of the following types: signed and unsigned integers of 8, 16, 32, and 64 bits, `Float32` and `Float64`; `Array`s of these numeric types; `ASCIIString` and `UTF8String`; and `Array`s of these two string types. `Array`s of strings are supported using HDF5's variable-length-strings facility.

This module also supports HDF5's VLEN, OPAQUE, and REFERENCE types, which can be used to encode more complex types. In general, you need to specify how you want to combine these more advanced facilities to represent more complex data types. For many of the data types in Julia, the JLD module implements support. You can likewise define your own file format if, for example, you need to interact with some external program that has explicit formatting requirements.

Creating groups and attributes
------------------------------

Create a new group in the following way:

```julia
g = g_create(parent, name)
```

The named group will be created as a child of the parent.

Attributes can be created using

```julia
attrs(parent)[name] = value
```

where `attrs` simply indicates that the object referenced by `name` (a string) is an attribute, not another group or dataset. (Datasets cannot have child datasets, but groups can have either.) `value` must be a simple type: `BitsKind`s, strings, and arrays of either of these. The HDF5 standard recommends against storing large objects as attributes.

Getting information
-------------------

```julia
name(obj)
```

will return the full HDF5 pathname of object `obj`.

```julia
names(g)
```

returns a string array containing all objects inside group `g`. These relative pathnames, not absolute pathnames.

You can iterate over the objects in a group, i.e.,
```julia
for obj in g
  data = read(obj)
  println(data)
end
```
This gives you a straightforward way of recursively exploring an entire HDF5 file. A convenient way of examining the structure of an HDF5 file is the `dump` function, e.g.,
```julia
dump(fid)
```

If you need to know whether group `g` has a dataset named `mydata`, you can test that with
```julia
if exists(g, "mydata")
   ...
end
tf = has(g, "mydata")  # synonym for "exists"
```
If instead you want to know whether `g` has an attribute named `myattribute`, do it this way:
```julia
tf = exists(attrs(g), "myattribute")
```

If you have an HDF5 object, and you want to know where it fits in the hierarchy of the file, the following can be useful:
```julia
p = parent(obj)     # p is the parent object (usually a group)
fn = filename(obj)  # fn is a string
g = root(obj)       # g is the group "/"
```

For array objects (datasets and attributes) the following methods work:
```
dims = size(dset)
nd = ndims(dset)
len = length(dset)
```

Objects can be created with properties, and you can query those
properties in the following way:
```
p = get_create_properties(dset)
chunksz = get_chunk(p)
```
The simpler syntax `chunksz = get_chunk(dset)` is also available.

Finally, sometimes you need to be able to conveniently test whether a file is an HDF5 file:
```julia
tf = ishdf5(filename)
```

Mid-level routines
------------------

Sometimes you might want more fine-grained control, which can be achieved using a different set of routines. For example,
```julia
g = g_open(parent, name)
dset = d_open(parent, name[, apl])
attr = a_open(parent, name)
t = t_open(parent, name)
```

These open the named group, dataset, attribute, and committed datatype, respectively. For datasets, `apl` stands for "access parameter list" and provides opportunities for more sophisticated control (see the [HDF5][HDF5] documentation).

New objects can be created in the following ways:
```julia
g = g_create(parent, name[, lcpl, dcpl])
dset = d_create(parent, name, data[, lcpl, dcpl, dapl])
attr = a_create(parent, name, data)
```
creates groups, datasets, and attributes without writing any data to them. You can then use `write(obj, data)` to store the data. The optional property lists allow even more fine-grained control. This syntax uses `data` to infer the object's "datatype" and "dataspace"; for the most explicit control, `data` can be replaced with `dtype, dspace`, where `dtype` is an `HDF5Datatype` and `dspace` is an `HDF5Dataspace`.

Analogously, to create committed data types, use
```julia
t = t_commit(parent, name, dtype[, lcpl, tcpl, tapl])
```

You can create and write data in one step,
```julia
d_write(parent, name, data[, lcpl, dcpl, dapl])
a_write(parent, name, data)
```

You can use extendible dimensions,
```julia
d = d_create(parent, name, dtype, (dims, max_dims), "chunk", (chunk_dims), [lcpl, dcpl, dapl])
set_dims!(d, new_dims)
```
where dims is a tuple of integers.  For example
```julia
b = d_create(fid, "b", Int, ((1000,),(-1,)), "chunk", (100,)) #-1 is equivalent to typemax(Hsize)
set_dims!(b, (10000,))
b[1:10000] = [1:10000]
```
when dimensions are reduced, the truncated data is lost.  A maximum dimension of -1 is often referred to as unlimited dimensions, though it is limited by the maximum size of an unsigned integer.

Finally, it's possible to delete objects:
```julia
o_delete(parent, name)   # for groups, datasets, and datatypes
a_delete(parent, name)   # for attributes
```

Low-level routines
------------------

Many of the most commonly-used libhdf5 functions have been wrapped. These are not exported, so you need to preface them with `HDF5.function` to use them. The library follows a consistent convention: for example, libhdf5's `H5Adelete` is wrapped with a Julia function called `h5a_delete`. The arguments are exactly as specified in the [HDF5][HDF5] reference manual.

HDF5 is a large library, and the low-level wrap is not complete. However, many of the most-commonly used functions are wrapped, and in general wrapping a new function takes only a single line of code. Users who need additional functionality are encourage to contribute it.

Note that Julia's HDF5 directly uses the "2" interfaces, e.g., `H5Dcreate2`, so you need to have version 1.8 of the HDF5 library or later.

Details
-------

Julia, like Fortran and Matlab, stores arrays in column-major order.
HDF5 uses C's row-major order, and consequently every array's
dimensions are inverted compared to what you see with tools like
h5dump. This is the same convention as for the Fortran and Matlab HDF5
interfaces. The advantage is that no data rearrangement takes place,
neither when reading nor when writing.

[HDF5]: http://www.hdfgroup.org/HDF5/ "HDF5"


text:
#ifndef EXECUTIONRESULTBUILDER_H
#define EXECUTIONRESULTBUILDER_H

#include <QObject>
#include <QSharedPointer>
#include <QWebElement>
#include <QPair>
#include <QList>
#include <QString>

#include "runtime/browser/executionresult.h"
#include "runtime/browser/artemiswebpage.h"

namespace artemis
{

/**
 * @brief The ExecutionResultBuilder class
 *
 * The ExecutionResultBuilder is tasked with constructing a ExecutionResult object
 * based on a concrete execution of a configuration.
 *
 * Notice, that this class has access to execution time information (the web page
 * and the DOM model) that the ExecutionResult object can't contain - since it is
 * retained long after the web page have been deallocated.
 *
 * Notice, that signals will be sent from the webpage after getResult and before
 * reset is called! E.g. if a webpage is deallocated then we will receive "event
 * handler removed" events.
 */
class ExecutionResultBuilder : public QObject
{
    Q_OBJECT

public:
    explicit ExecutionResultBuilder(ArtemisWebPagePtr page);

    void reset();
    void notifyPageLoaded();
    void notifyStartingEvent();
    void notifyStartingLoad();
    QSharedPointer<ExecutionResult> getResult();

private:
    void registerFromFieldsIntoResult();
    void registerEventHandlersIntoResult();

    QSet<QString> getSelectOptions(const QWebElement&);
    QSet<QWebFrame*> getAllFrames();

    QSharedPointer<ExecutionResult> mResult;
    ArtemisWebPagePtr mPage;
    QString mPageStateAfterLoad;

    QList<QPair<QWebElement*, QString> > mElementPointers;

public slots:
    void slScriptCrashed(QString cause, intptr_t sourceID, int lineNumber);
    void slStringEvaled(const QString);

    void slTimerAdded(int timerId, int timeout, bool singleShot);
    void slTimerRemoved(int timerId);

    void slEventListenerAdded(QWebElement* elem, QString name);
    void slEventListenerRemoved(QWebElement* elem, QString name);

    void slAjaxCallbackHandlerAdded(int callbackId);
    void slAjaxRequestInitiated(QUrl, QString postData);

    void slJavascriptConstantEncountered(QString constant);

};

typedef QSharedPointer<ExecutionResultBuilder> ExecutionResultBuilderPtr;
typedef QSharedPointer<const ExecutionResultBuilder> ExecutionResultBuilderConstPtr;

}

#endif // EXECUTIONRESULTBUILDER_H


text:
<!doctype html>

  <meta charset="utf-8">
  <title>Extinction</title>
  <meta name="description" content="The Extinction Guild">
  <meta name="author" content="Kris Williams">