text:
#include <dfs.h>
#include <dfs_file.h>

/**
 * @addtogroup FileApi
 */

/*@{*/

/**
 * this function will open a file which specified by path with specified flags.
 *
 * @param fd the file descriptor pointer to return the corresponding result.
 * @param path the specified file path.
 * @param flags the flags for open operator.
 *
 * @return 0 on successful, -1 on failed.
 */
int dfs_file_open(struct dfs_fd *fd, const char *path, int flags)
{
    struct dfs_filesystem *fs;
    char *fullpath;
    int result;

    /* parameter check */
    if (fd == RT_NULL)
        return -DFS_STATUS_EINVAL;

    /* make sure we have an absolute path */
    fullpath = dfs_normalize_path(RT_NULL, path);
    if (fullpath == RT_NULL)
    {
        return -1;
    }

    dfs_log(DFS_DEBUG_INFO, ("open file:%s", fullpath));

    /* find filesystem */
    fs = dfs_filesystem_lookup(fullpath);
    if (fs == RT_NULL)
    {
        rt_free(fullpath); /* release path */

        return -DFS_STATUS_ENOENT;
    }

    dfs_log(DFS_DEBUG_INFO, ("open in filesystem:%s", fs->ops->name));
    fd->fs = fs;

    /* initialize the fd item */
    fd->type  = FT_REGULAR;
    fd->flags = flags;
    fd->size  = 0;
    fd->pos   = 0;

    if (!(fs->ops->flags & DFS_FS_FLAG_FULLPATH))
    {
        if (dfs_subdir(fs->path, fullpath) == RT_NULL)
            fd->path = rt_strdup("/");
        else
            fd->path = rt_strdup(dfs_subdir(fs->path, fullpath));
        rt_free(fullpath);
        dfs_log(DFS_DEBUG_INFO, ("Actual file path: %s\n", fd->path));
    }
    else
    {
        fd->path = fullpath;
    }

    /* specific file system open routine */
    if (fs->ops->open == RT_NULL)
    {
        /* clear fd */
        rt_free(fd->path);
        rt_memset(fd, 0, sizeof(*fd));

        return -DFS_STATUS_ENOSYS;
    }

    if ((result = fs->ops->open(fd)) < 0)
    {
        /* clear fd */
        rt_free(fd->path);
        rt_memset(fd, 0, sizeof(*fd));

        dfs_log(DFS_DEBUG_INFO, ("open failed"));

        return result;
    }

    fd->flags |= DFS_F_OPEN;
    if (flags & DFS_O_DIRECTORY)
    {
        fd->type = FT_DIRECTORY;
        fd->flags |= DFS_F_DIRECTORY;
    }

    dfs_log(DFS_DEBUG_INFO, ("open successful"));
    return 0;
}

/**
 * this function will close a file descriptor.
 *
 * @param fd the file descriptor to be closed.
 *
 * @return 0 on successful, -1 on failed.
 */
int dfs_file_close(struct dfs_fd *fd)
{
    int result = 0;

    if (fd != RT_NULL && fd->fs->ops->close != RT_NULL)
        result = fd->fs->ops->close(fd);

    /* close fd error, return */
    if (result < 0)
        return result;

    rt_free(fd->path);
    rt_memset(fd, 0, sizeof(struct dfs_fd));

    return result;
}

/**
 * this function will perform a io control on a file descriptor.
 *
 * @param fd the file descriptor.
 * @param cmd the command to send to file descriptor.
 * @param args the argument to send to file descriptor.
 *
 * @return 0 on successful, -1 on failed.
 */
int dfs_file_ioctl(struct dfs_fd *fd, int cmd, void *args)
{
    struct dfs_filesystem *fs;

    if (fd == RT_NULL || fd->type != FT_REGULAR)
        return -DFS_STATUS_EINVAL;

    fs = fd->fs;
    if (fs->ops->ioctl != RT_NULL)
        return fs->ops->ioctl(fd, cmd, args);

    return -DFS_STATUS_ENOSYS;
}

/**
 * this function will read specified length data from a file descriptor to a
 * buffer.
 *
 * @param fd the file descriptor.
 * @param buf the buffer to save the read data.
 * @param len the length of data buffer to be read.
 *
 * @return the actual read data bytes or 0 on end of file or failed.
 */
int dfs_file_read(struct dfs_fd *fd, void *buf, rt_size_t len)
{
    struct dfs_filesystem *fs;
    int result = 0;

    if (fd == RT_NULL)
        return -DFS_STATUS_EINVAL;

    fs = (struct dfs_filesystem *)fd->fs;
    if (fs->ops->read == RT_NULL)
        return -DFS_STATUS_ENOSYS;

    if ((result = fs->ops->read(fd, buf, len)) < 0)
        fd->flags |= DFS_F_EOF;

    return result;
}

/**
 * this function will fetch directory entries from a directory descriptor.
 *
 * @param fd the directory descriptor.
 * @param dirp the dirent buffer to save result.
 * @param nbytes the available room in the buffer.
 *
 * @return the read dirent, others on failed.
 */
int dfs_file_getdents(struct dfs_fd *fd, struct dirent *dirp, rt_size_t nbytes)
{
    struct dfs_filesystem *fs;

    /* parameter check */
    if (fd == RT_NULL || fd->type != FT_DIRECTORY)
        return -DFS_STATUS_EINVAL;

    fs = (struct dfs_filesystem *)fd->fs;
    if (fs->ops->getdents != RT_NULL)
        return fs->ops->getdents(fd, dirp, nbytes);

    return -DFS_STATUS_ENOSYS;
}

/**
 * this function will unlink (remove) a specified path file from file system.
 *
 * @param path the specified path file to be unlinked.
 *
 * @return 0 on successful, -1 on failed.
 */
int dfs_file_unlink(const char *path)
{
    int result;
    char *fullpath;
    struct dfs_filesystem *fs;

    /* Make sure we have an absolute path */
    fullpath = dfs_normalize_path(RT_NULL, path);
    if (fullpath == RT_NULL)
    {
        return -DFS_STATUS_EINVAL;
    }

    /* get filesystem */
    if ((fs = dfs_filesystem_lookup(fullpath)) == RT_NULL)
    {
        result = -DFS_STATUS_ENOENT;
        goto __exit;
    }

    /* Check whether file is already open */
    if (fd_is_open(fullpath) == 0)
    {
        result = -DFS_STATUS_EBUSY;
        goto __exit;
    }

    if (fs->ops->unlink != RT_NULL)
    {
        if (!(fs->ops->flags & DFS_FS_FLAG_FULLPATH))
        {
            if (dfs_subdir(fs->path, fullpath) == RT_NULL)
                result = fs->ops->unlink(fs, "/");
            else
                result = fs->ops->unlink(fs, dfs_subdir(fs->path, fullpath));
        }
        else
            result = fs->ops->unlink(fs, fullpath);
    }
    else result = -DFS_STATUS_ENOSYS;

__exit:
    rt_free(fullpath);
    return result;
}

/**
 * this function will write some specified length data to file system.
 *
 * @param fd the file descriptor.
 * @param buf the data buffer to be written.
 * @param len the data buffer length
 *
 * @return the actual written data length.
 */
int dfs_file_write(struct dfs_fd *fd, const void *buf, rt_size_t len)
{
    struct dfs_filesystem *fs;

    if (fd == RT_NULL)
        return -DFS_STATUS_EINVAL;

    fs = fd->fs;
    if (fs->ops->write == RT_NULL)
        return -DFS_STATUS_ENOSYS;

    return fs->ops->write(fd, buf, len);
}

/**
 * this function will flush buffer on a file descriptor.
 *
 * @param fd the file descriptor.
 *
 * @return 0 on successful, -1 on failed.
 */
int dfs_file_flush(struct dfs_fd *fd)
{
    struct dfs_filesystem *fs;

    if (fd == RT_NULL)
        return -DFS_STATUS_EINVAL;

    fs = fd->fs;
    if (fs->ops->flush == RT_NULL)
        return -DFS_STATUS_ENOSYS;

    return fs->ops->flush(fd);
}

/**
 * this function will seek the offset for specified file descriptor.
 *
 * @param fd the file descriptor.
 * @param offset the offset to be sought.
 *
 * @return the current position after seek.
 */
int dfs_file_lseek(struct dfs_fd *fd, rt_off_t offset)
{
    int result;
    struct dfs_filesystem *fs = fd->fs;

    if (fd == RT_NULL)
        return -DFS_STATUS_EINVAL;
    if (fs->ops->lseek == RT_NULL)
        return -DFS_STATUS_ENOSYS;

    result = fs->ops->lseek(fd, offset);

    /* update current position */
    if (result >= 0)
        fd->pos = result;

    return result;
}

/**
 * this function will get file information.
 *
 * @param path the file path.
 * @param buf the data buffer to save stat description.
 *
 * @return 0 on successful, -1 on failed.
 */
int dfs_file_stat(const char *path, struct stat *buf)
{
    int result;
    char *fullpath;
    struct dfs_filesystem *fs;

    fullpath = dfs_normalize_path(RT_NULL, path);
    if (fullpath == RT_NULL)
    {
        return -1;
    }

    if ((fs = dfs_filesystem_lookup(fullpath)) == RT_NULL)
    {
        dfs_log(DFS_DEBUG_ERROR,
                ("can't find mounted filesystem on this path:%s", fullpath));
        rt_free(fullpath);

        return -DFS_STATUS_ENOENT;
    }

    if ((fullpath[0] == '/' && fullpath[1] == '\0') ||
        (dfs_subdir(fs->path, fullpath) == RT_NULL))
    {
        /* it's the root directory */
        buf->st_dev   = 0;

        buf->st_mode  = DFS_S_IRUSR | DFS_S_IRGRP | DFS_S_IROTH |
                        DFS_S_IWUSR | DFS_S_IWGRP | DFS_S_IWOTH;
        buf->st_mode |= DFS_S_IFDIR | DFS_S_IXUSR | DFS_S_IXGRP | DFS_S_IXOTH;

        buf->st_size    = 0;
        buf->st_mtime   = 0;
        buf->st_blksize = 512;

        /* release full path */
        rt_free(fullpath);

        return DFS_STATUS_OK;
    }
    else
    {
        if (fs->ops->stat == RT_NULL)
        {
            rt_free(fullpath);
            dfs_log(DFS_DEBUG_ERROR,
                    ("the filesystem didn't implement this function"));

            return -DFS_STATUS_ENOSYS;
        }

        /* get the real file path and get file stat */
        if (fs->ops->flags & DFS_FS_FLAG_FULLPATH)
            result = fs->ops->stat(fs, fullpath, buf);
        else
            result = fs->ops->stat(fs, dfs_subdir(fs->path, fullpath), buf);
    }

    rt_free(fullpath);

    return result;
}

/**
 * this function will rename an old path name to a new path name.
 *
 * @param oldpath the old path name.
 * @param newpath the new path name.
 *
 * @return 0 on successful, -1 on failed.
 */
int dfs_file_rename(const char *oldpath, const char *newpath)
{
    int result;
    struct dfs_filesystem *oldfs, *newfs;
    char *oldfullpath, *newfullpath;

    result = DFS_STATUS_OK;
    newfullpath = RT_NULL;
    oldfullpath = RT_NULL;

    oldfullpath = dfs_normalize_path(RT_NULL, oldpath);
    if (oldfullpath == RT_NULL)
    {
        result = -DFS_STATUS_ENOENT;
        goto __exit;
    }

    newfullpath = dfs_normalize_path(RT_NULL, newpath);
    if (newfullpath == RT_NULL)
    {
        result = -DFS_STATUS_ENOENT;
        goto __exit;
    }

    oldfs = dfs_filesystem_lookup(oldfullpath);
    newfs = dfs_filesystem_lookup(newfullpath);

    if (oldfs == newfs)
    {
        if (oldfs->ops->rename == RT_NULL)
        {
            result = -DFS_STATUS_ENOSYS;
        }
        else
        {
            if (oldfs->ops->flags & DFS_FS_FLAG_FULLPATH)
                result = oldfs->ops->rename(oldfs, oldfullpath, newfullpath);
            else
                /* use sub directory to rename in file system */
                result = oldfs->ops->rename(oldfs,
                                            dfs_subdir(oldfs->path, oldfullpath),
                                            dfs_subdir(newfs->path, newfullpath));
        }
    }
    else
    {
        result = -DFS_STATUS_EXDEV;
    }

__exit:
    rt_free(oldfullpath);
    rt_free(newfullpath);

    /* not at same file system, return EXDEV */
    return result;
}

#ifdef RT_USING_FINSH
#include <finsh.h>

static struct dfs_fd fd;
static struct dirent dirent;
void ls(const char *pathname)
{
    struct stat stat;
    int length;
    char *fullpath, *path;

    fullpath = RT_NULL;
    if (pathname == RT_NULL)
    {
#ifdef DFS_USING_WORKDIR
        /* open current working directory */
        path = rt_strdup(working_directory);
#else
        path = rt_strdup("/");
#endif
        if (path == RT_NULL)
            return ; /* out of memory */
    }
    else
    {
        path = (char *)pathname;
    }

    /* list directory */
    if (dfs_file_open(&fd, path, DFS_O_DIRECTORY) == 0)
    {
        rt_kprintf("Directory %s:\n", path);
        do
        {
            rt_memset(&dirent, 0, sizeof(struct dirent));
            length = dfs_file_getdents(&fd, &dirent, sizeof(struct dirent));
            if (length > 0)
            {
                rt_memset(&stat, 0, sizeof(struct stat));

                /* build full path for each file */
                fullpath = dfs_normalize_path(path, dirent.d_name);
                if (fullpath == RT_NULL)
                    break;

                if (dfs_file_stat(fullpath, &stat) == 0)
                {
                    rt_kprintf("%-20s", dirent.d_name);
                    if ( DFS_S_ISDIR(stat.st_mode))
                    {
                        rt_kprintf("%-25s\n", "<DIR>");
                    }
                    else
                    {
                        rt_kprintf("%-25lu\n", stat.st_size);
                    }
                }
                else
                    rt_kprintf("BAD file: %s\n", dirent.d_name);
                rt_free(fullpath);
            }
        }while(length > 0);

        dfs_file_close(&fd);
    }
    else
    {
        rt_kprintf("No such directory\n");
    }
    if (pathname == RT_NULL)
        rt_free(path);
}
FINSH_FUNCTION_EXPORT(ls, list directory contents)

void rm(const char *filename)
{
    if (dfs_file_unlink(filename) < 0)
    {
        rt_kprintf("Delete %s failed\n", filename);
    }
}
FINSH_FUNCTION_EXPORT(rm, remove files or directories)

void cat(const char* filename)
{
    rt_uint32_t length;
    char buffer[81];

    if (dfs_file_open(&fd, filename, DFS_O_RDONLY) < 0)
    {
        rt_kprintf("Open %s failed\n", filename);

        return;
    }

    do
    {
        rt_memset(buffer, 0, sizeof(buffer));
        length = dfs_file_read(&fd, buffer, sizeof(buffer)-1 );
        if (length > 0)
        {
            rt_kprintf("%s", buffer);
        }
    }while (length > 0);

    dfs_file_close(&fd);
}
FINSH_FUNCTION_EXPORT(cat, print file)

#define BUF_SZ  4096
void copy(const char *src, const char *dst)
{
    struct dfs_fd src_fd;
    rt_uint8_t *block_ptr;
    rt_int32_t read_bytes;

    block_ptr = rt_malloc(BUF_SZ);
    if (block_ptr == RT_NULL)
    {
        rt_kprintf("out of memory\n");

        return;
    }

    if (dfs_file_open(&src_fd, src, DFS_O_RDONLY) < 0)
    {
        rt_free(block_ptr);
        rt_kprintf("Read %s failed\n", src);

        return;
    }
    if (dfs_file_open(&fd, dst, DFS_O_WRONLY | DFS_O_CREAT) < 0)
    {
        rt_free(block_ptr);
        dfs_file_close(&src_fd);

        rt_kprintf("Write %s failed\n", dst);

        return;
    }

    do
    {
        read_bytes = dfs_file_read(&src_fd, block_ptr, BUF_SZ);
        if (read_bytes > 0)
        {
            dfs_file_write(&fd, block_ptr, read_bytes);
        }
    } while (read_bytes > 0);

    dfs_file_close(&src_fd);
    dfs_file_close(&fd);
    rt_free(block_ptr);
}
FINSH_FUNCTION_EXPORT(copy, copy source file to destination file)

#endif
/* @} */


text:
Static Subgraph Optimizations: Usage
====================================================

.. note::
 This is an experimental feature and so the API might change in the future as it is developed.

This feature intends to improve runtime performance by optimizing the execution
of the static subgraphs in a model. When this feature is enabled, the first iteration
runs as normal except that an execution trace is also collected. The
trace is then used to generate optimized code that is will be called instead of the define-by-run
code starting from the second iteration.

.. autosummary::
   :toctree: generated/
   :nosignatures:

   chainer.static_graph

Basic usage
------------

To enable static graph optimizations, it is only necessary to add the
:func:`chainer.static_graph` decorator to a chain's ``__call__()`` method. We will now show how the
Chainer MNIST example can be modified to use this feature. The modified version
with static subgraph optimizations is located at :tree:`examples/static_graph_optimizations/mnist`.

The first step is to import the necessary packages:

.. literalinclude:: ../../../examples/static_graph_optimizations/mnist/train_mnist.py
   :language: python
   :lines: 15-16
   :caption: train_mnist.py

Since the neural network model ``MLP`` corresponds to a static graph, we can annotate it as a static graph by
using the :func:`chainer.static_graph` decorator on the chain's ``__call__()`` method. This lets the framework know that
that the define-by-run code of the chain always creates the same graph (that is, it always performs the same
sequence of computations) each time it is called. We will refer to such a chain as a **static chain** in
the documentation.

.. literalinclude:: ../../../examples/static_graph_optimizations/mnist/train_mnist.py
   :language: python
   :lines: 22-41
   :caption: train_mnist.py

.. note::
   If your model's define-by-run code has any control flow operations that could cause it to potentially call
   different Chainer functions/links each time it is called, then you cannot use this decorator.

.. note::
   There are currently some restrictions on how variables can be passed into a static chain's ``__call__()``
   method. Refer to the documentation of :func:`chainer.static_graph` for details.

Recall that the define-by-run code of a static chain's ``__call__()`` method only actually runs during the
first iteration and is then replaced by optimized static schedule code. The current implementation only
knows how to do this auto-replacement for calls to Chainer functions and links. Any other code that the
user puts in ``__call__()`` (which we refer to as "side-effect code") will only ever get called once
by default, since the define-by-run code is
only executed during the first iteration. In order to make sure such "side effect" code actually gets
called each iteration, we need to put it inside a function or method decorated by :meth:`static_code()`.
We expect there will rarely be a need to use side-effect code but for completeness, an example of
a model that uses it is available in the ``MLPSideEffect`` Chain of the static graph MNIST example.

In this example, we only need to use :func:`chainer.static_graph` on the model chain, since the whole model is static.
However, in more general dynamic models, each of the largest static subgraphs (which should each be
written as a chain) should also use :func:`chainer.static_graph`.

.. note::
   Nested application of :func:`chainer.static_graph` is not allowed. That is, if a :func:`chainer.static_graph`-decorated chain
   calls another chains, only the outermost chain should use the decorator.

Calling a static chain multiple times in the same iteration
----------------------------------------------------------------------------

In a general dynamic graph network, it is not possible
to know in advance how many times a static chain will be called in any particular iteration.
Note that during training, it is necessary to maintain separate internal state (such as intermediate
activations) for each of these calls so that the gradients can be computed in the backward pass.
So, although the layer functions of the static schedule will be identical each time the same
static chain is called, any internal state must be distinct. It is also possible that a static
chain could be called multiple times with inputs of different shapes and/or types during the same iteration.
To avoid confuction, "static schedule" will refer to both the functions and any corresponding internal state
such as activations.

If backpropagation mode is disabled (``chainer.config.enable_backprop`` is ``False``),
it is safe for the implementation to simply compute a
static schedule for the first call and reuse it for subsequent calls, provided that the cached schedule
is compatible with the input shapes/types. However, during training,
it is necessary to maintain distinct internal state for each call in order to compute
the gradients for the backward pass, which prevents us from reusing the same static schedule for each of
the multiple calls of a static chain in an iteration.

The current implementation handles this issues as follows. A cache of static schedules, which is intially
empty, is associated with each static chain. The size of this cache will be equal to the maximum number of
times that the static chain has been called in any previous iteration, and the cache is reset whenever
certain chain configuration flags change, such as training mode and backpropagation model. At the start
of a given iteration, all cached schedules are available for use and the number of available schedules
is decremented each time the static chain is called. If the chain is called when the cache is size zero,
then its define-by-run code will execute to create a new schedule cache.

In order for such an implementation to work, each static chain must be notified when the forward pass
has ended (or when the forward pass is started) so that all cached schedules can be made available for use
again. In the current implementation, this is accomplished by calling the ``backward()`` method on a loss
variable in the model. This is expected to handle the typical use cases. However, in some models it may be necessary to
perform multiple forward passes before calling ``backward()``. In such a case, to signel to a static chain that the
forward pass (and the iteration) has ended, call ``my_chain.schedule_manager.end_forward()``.
The `schedule_manager` attribute of a static chain is an instance of a class called
``StaticScheduleFunction`` that will be available after the chain has been called.

Effects on model debugging
--------------------------

Note that since the code in the static chain's ``__call__()`` only runs during the
first iteration, you will only be able to debug this code as define-by-run during
the first iteration. It is assumed that if the chain is actually is static,
any problems in its define-by-run code should be apparent during the first
iteration and it should not be (as) necessary to debug this code in later iterations.
However, this feature does provide some functionality to help with debugging.
For example, it is possible to obtain and inspect the current static schedules.
It is also possible to directly step through the code of the static schedule if
you wish (by debugging the ``forward()`` method of :class:`~chainer.static_graph.StaticScheduleFunction`
in :mod:`~chainer.static_graph`).

Limitations and future work
---------------------------

- Optimization switches to let the user select the trade-off between runtime performance and memory usage: The current implementation achieves its speedups mainly by reducing the amount of Python code that needs to run, but does not yet implement advanced optimizations for memory usage or runtime performance. Ideally, the user should be able to adjust performance tuning parameters to control the trade-off between memory consumption and runtime performance.

- Incompatibility with GRU and LSTM links: This feature requires that all input variables to a chain need to explicitly appear in the arguments to the chain's ``__call__()`` method. However, the GRU and LSTM links with state maintain variable attributes of the chain for the RNN state variables. Design changes to support such links and/or modifications to these links are being considered. These links may still be used with the current implementation, as long as the corresponding RNN is unrolled inside of a static chain. For an example of this, see the modified ptb example at :tree:`examples/static_graph_optimizations/ptb`

- Memory usage: The current implementation caches all static schedules which can lead to high memory usage in some cases. For example, separate schedules are created when the training mode or mini-batch size changes.

- Advanced graph optimizations: Advanced optimizations such as fusion of operations is not yet implemented.

- Constraints on arguments to a static chain: The current version requires that all input variables used inside ``__call__()`` of a static chain must either appear in the arguments of this method or be defined in the define-by-run code. Furthermore, any variables that appear in the arguments list must appear by themselves or be contained inside a list or tuple. Arbitrary levels of nesting are allowed.

- Model export: In the case where the complete computation graph for the model is static, it should be possible in principle to export the static schedule in a format that can be run on other platforms and languages. One of the other original motivations for this feature was to support exporting static Chainer models to run on C/C++ and/or optimize the static schedule execution code in Cython/C/C++. However, it seems that ONNX is now fulfilling this purpose and there is a separate ONNX exporter already in development for Chainer. Perhaps these two features can be merged at some point in the future.

- Double-backward support: This feature was designed to support double-backward (gradient of gradient) but it has not been tested.

Examples
--------

For additional examples that use this feature, refer to the examples in :tree:`examples/static_graph_optimizations`.

redpajama_set_name: RedPajamaGithub


text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: google/iam/admin/v1/iam.proto

package com.google.iam.admin.v1;

public interface ServiceAccountKeyOrBuilder
    extends
    // @@protoc_insertion_point(interface_extends:google.iam.admin.v1.ServiceAccountKey)
    com.google.protobuf.MessageOrBuilder {

  /**
   *
   *
   *

   * The resource name of the service account key in the following format
   * `projects/{PROJECT_ID}/serviceAccounts/{ACCOUNT}/keys/{key}`.
   *

   *
   * string name = 1;
   *
   * @return The name.
   */
  java.lang.String getName();
  /**
   *
   *
   *

   * The resource name of the service account key in the following format
   * `projects/{PROJECT_ID}/serviceAccounts/{ACCOUNT}/keys/{key}`.
   *

   *
   * string name = 1;
   *
   * @return The bytes for name.
   */
  com.google.protobuf.ByteString getNameBytes();

  /**
   *
   *
   *

   * The output format for the private key.
   * Only provided in `CreateServiceAccountKey` responses, not
   * in `GetServiceAccountKey` or `ListServiceAccountKey` responses.
   * Google never exposes system-managed private keys, and never retains
   * user-managed private keys.
   *

   *
   * .google.iam.admin.v1.ServiceAccountPrivateKeyType private_key_type = 2;
   *
   * @return The enum numeric value on the wire for privateKeyType.
   */
  int getPrivateKeyTypeValue();
  /**
   *
   *
   *

   * The output format for the private key.
   * Only provided in `CreateServiceAccountKey` responses, not
   * in `GetServiceAccountKey` or `ListServiceAccountKey` responses.
   * Google never exposes system-managed private keys, and never retains
   * user-managed private keys.
   *

   *
   * .google.iam.admin.v1.ServiceAccountPrivateKeyType private_key_type = 2;
   *
   * @return The privateKeyType.
   */
  com.google.iam.admin.v1.ServiceAccountPrivateKeyType getPrivateKeyType();

  /**
   *
   *
   *

   * Specifies the algorithm (and possibly key size) for the key.
   *

   *
   * .google.iam.admin.v1.ServiceAccountKeyAlgorithm key_algorithm = 8;
   *
   * @return The enum numeric value on the wire for keyAlgorithm.
   */
  int getKeyAlgorithmValue();
  /**
   *
   *
   *

   * Specifies the algorithm (and possibly key size) for the key.
   *

   *
   * .google.iam.admin.v1.ServiceAccountKeyAlgorithm key_algorithm = 8;
   *
   * @return The keyAlgorithm.
   */
  com.google.iam.admin.v1.ServiceAccountKeyAlgorithm getKeyAlgorithm();

  /**
   *
   *
   *

   * The private key data. Only provided in `CreateServiceAccountKey`
   * responses. Make sure to keep the private key data secure because it
   * allows for the assertion of the service account identity.
   * When base64 decoded, the private key data can be used to authenticate with
   * Google API client libraries and with
   * <a href="/sdk/gcloud/reference/auth/activate-service-account">gcloud
   * auth activate-service-account</a>.
   *

   *
   * bytes private_key_data = 3;
   *
   * @return The privateKeyData.
   */
  com.google.protobuf.ByteString getPrivateKeyData();

  /**
   *
   *
   *

   * The public key data. Only provided in `GetServiceAccountKey` responses.
   *

   *
   * bytes public_key_data = 7;
   *
   * @return The publicKeyData.
   */
  com.google.protobuf.ByteString getPublicKeyData();

  /**
   *
   *
   *

   * The key can be used after this timestamp.
   *

   *
   * .google.protobuf.Timestamp valid_after_time = 4;
   *
   * @return Whether the validAfterTime field is set.
   */
  boolean hasValidAfterTime();
  /**
   *
   *
   *

   * The key can be used after this timestamp.
   *

   *
   * .google.protobuf.Timestamp valid_after_time = 4;
   *
   * @return The validAfterTime.
   */
  com.google.protobuf.Timestamp getValidAfterTime();
  /**
   *
   *
   *

   * The key can be used after this timestamp.
   *

   *
   * .google.protobuf.Timestamp valid_after_time = 4;
   */
  com.google.protobuf.TimestampOrBuilder getValidAfterTimeOrBuilder();

  /**
   *
   *
   *

   * The key can be used before this timestamp.
   * For system-managed key pairs, this timestamp is the end time for the
   * private key signing operation. The public key could still be used
   * for verification for a few hours after this time.
   *

   *
   * .google.protobuf.Timestamp valid_before_time = 5;
   *
   * @return Whether the validBeforeTime field is set.
   */
  boolean hasValidBeforeTime();
  /**
   *
   *
   *

   * The key can be used before this timestamp.
   * For system-managed key pairs, this timestamp is the end time for the
   * private key signing operation. The public key could still be used
   * for verification for a few hours after this time.
   *

   *
   * .google.protobuf.Timestamp valid_before_time = 5;
   *
   * @return The validBeforeTime.
   */
  com.google.protobuf.Timestamp getValidBeforeTime();
  /**
   *
   *
   *

   * The key can be used before this timestamp.
   * For system-managed key pairs, this timestamp is the end time for the
   * private key signing operation. The public key could still be used
   * for verification for a few hours after this time.
   *

   *
   * .google.protobuf.Timestamp valid_before_time = 5;
   */
  com.google.protobuf.TimestampOrBuilder getValidBeforeTimeOrBuilder();

  /**
   *
   *
   *

   * The key origin.
   *

   *
   * .google.iam.admin.v1.ServiceAccountKeyOrigin key_origin = 9;
   *
   * @return The enum numeric value on the wire for keyOrigin.
   */
  int getKeyOriginValue();
  /**
   *
   *
   *

   * The key origin.
   *

   *
   * .google.iam.admin.v1.ServiceAccountKeyOrigin key_origin = 9;
   *
   * @return The keyOrigin.
   */
  com.google.iam.admin.v1.ServiceAccountKeyOrigin getKeyOrigin();

  /**
   *
   *
   *

   * The key type.
   *

   *
   * .google.iam.admin.v1.ListServiceAccountKeysRequest.KeyType key_type = 10;
   *
   * @return The enum numeric value on the wire for keyType.
   */
  int getKeyTypeValue();
  /**
   *
   *
   *

   * The key type.
   *

   *
   * .google.iam.admin.v1.ListServiceAccountKeysRequest.KeyType key_type = 10;
   *
   * @return The keyType.
   */
  com.google.iam.admin.v1.ListServiceAccountKeysRequest.KeyType getKeyType();

  /**
   *
   *
   *

   * The key status.
   *

   *
   * bool disabled = 11;
   *
   * @return The disabled.
   */
  boolean getDisabled();
}


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

<title>nl.dead_pixel.telebot.api.types.keyboard.helpers Class Hierarchy (telebot 0.3.3 API)</title>
<meta name="date" content="2017-06-08">
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Hierarchy For Package nl.dead_pixel.telebot.api.types.keyboard.helpers

Package Hierarchies:

All Packages

Class Hierarchy

java.lang.Object

nl.dead_pixel.telebot.api.types.keyboard.helpers.CallbackQuery (implements nl.dead_pixel.telebot.interfaces.IUpdate)

nl.dead_pixel.telebot.api.types.keyboard.helpers.ForceReply (implements nl.dead_pixel.telebot.interfaces.IReplyMarkup)

nl.dead_pixel.telebot.api.types.keyboard.helpers.ReplyKeyboardRemove (implements nl.dead_pixel.telebot.interfaces.IReplyMarkup)

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
Error Page!

{{errorMessage}}

You are not authorized to access the page.


text:
<!-- require APlayer -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.css">
<script src="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.js"></script>
<!-- require MetingJS -->
<script src="https://cdn.jsdelivr.net/npm/meting@2/dist/Meting.min.js"></script>

<!-- APlayer 加载参数 -->
<meting-js
	server="{{ page.apserver }}"
	type="{{ page.aptype }}"
	id="{{ page.apsongid }}"
	autoplay="false"
	theme="#CC0000"
	list-max-height="340px"
	preload="none">
</meting-js>


text:
namespace extensions {

AppSyncBundle::AppSyncBundle(ExtensionSyncService* extension_sync_service)
    : extension_sync_service_(extension_sync_service) {}

AppSyncBundle::~AppSyncBundle() {}

void AppSyncBundle::SetupSync(
    syncer::SyncChangeProcessor* sync_change_processor,
    syncer::SyncErrorFactory* sync_error_factory,
    const syncer::SyncDataList& initial_sync_data) {
  sync_processor_.reset(sync_change_processor);
  sync_error_factory_.reset(sync_error_factory);

  for (syncer::SyncDataList::const_iterator i = initial_sync_data.begin();
       i != initial_sync_data.end();
       ++i) {
    AppSyncData app_sync_data(*i);
    AddApp(app_sync_data.id());
    extension_sync_service_->ProcessAppSyncData(app_sync_data);
  }
}

void AppSyncBundle::Reset() {
  sync_processor_.reset();
  sync_error_factory_.reset();
  synced_apps_.clear();
  pending_sync_data_.clear();
}

syncer::SyncChange AppSyncBundle::CreateSyncChangeToDelete(
    const Extension* extension)
    const {
  AppSyncData sync_data = extension_sync_service_->GetAppSyncData(*extension);
  return sync_data.GetSyncChange(syncer::SyncChange::ACTION_DELETE);
}

void AppSyncBundle::ProcessDeletion(std::string extension_id,
                                    const syncer::SyncChange& sync_change) {
  RemoveApp(extension_id);
  sync_processor_->ProcessSyncChanges(FROM_HERE,
                                      syncer::SyncChangeList(1, sync_change));
}

syncer::SyncChange AppSyncBundle::CreateSyncChange(
    const syncer::SyncData& sync_data) {
  if (HasExtensionId(sync_data.GetTag())) {
    return syncer::SyncChange(FROM_HERE,
                              syncer::SyncChange::ACTION_UPDATE,
                              sync_data);
  } else {
    AddApp(sync_data.GetTag());
    return syncer::SyncChange(FROM_HERE,
                              syncer::SyncChange::ACTION_ADD,
                              sync_data);
  }
}

syncer::SyncDataList AppSyncBundle::GetAllSyncData() const {
  std::vector<AppSyncData> app_sync_data =
      extension_sync_service_->GetAppSyncDataList();
  syncer::SyncDataList result(app_sync_data.size());
  for (int i = 0; i < static_cast<int>(app_sync_data.size()); ++i) {
    result[i] = app_sync_data[i].GetSyncData();
  }
  return result;
}

void AppSyncBundle::ProcessSyncChange(AppSyncData app_sync_data) {
  if (app_sync_data.uninstalled())
    RemoveApp(app_sync_data.id());
  else
    AddApp(app_sync_data.id());
  extension_sync_service_->ProcessAppSyncData(app_sync_data);
}

void AppSyncBundle::ProcessSyncChangeList(
    syncer::SyncChangeList sync_change_list) {
  sync_processor_->ProcessSyncChanges(FROM_HERE, sync_change_list);
  extension_sync_service_->extension_prefs().app_sorting()->
      FixNTPOrdinalCollisions();
}

bool AppSyncBundle::HasExtensionId(const std::string& id) const {
  return synced_apps_.find(id) != synced_apps_.end();
}

bool AppSyncBundle::HasPendingExtensionId(const std::string& id) const {
  return pending_sync_data_.find(id) != pending_sync_data_.end();
}

void AppSyncBundle::AddPendingApp(const std::string& id,
                                  const AppSyncData& app_sync_data) {
  pending_sync_data_[id] = app_sync_data;
}

bool AppSyncBundle::IsSyncing() const {
  return sync_processor_ != NULL;
}

void AppSyncBundle::SyncChangeIfNeeded(const Extension& extension) {
  AppSyncData app_sync_data = extension_sync_service_->GetAppSyncData(
      extension);

  syncer::SyncChangeList sync_change_list(1, app_sync_data.GetSyncChange(
      HasExtensionId(extension.id()) ?
      syncer::SyncChange::ACTION_UPDATE : syncer::SyncChange::ACTION_ADD));
  sync_processor_->ProcessSyncChanges(FROM_HERE, sync_change_list);
  MarkPendingAppSynced(extension.id());
}

std::vector<AppSyncData> AppSyncBundle::GetPendingData() const {
  std::vector<AppSyncData> pending_apps;
  for (std::map<std::string, AppSyncData>::const_iterator
           i = pending_sync_data_.begin();
       i != pending_sync_data_.end();
       ++i) {
    pending_apps.push_back(i->second);
  }

  return pending_apps;
}

void AppSyncBundle::GetAppSyncDataListHelper(
    const ExtensionSet* extensions,
    std::vector<AppSyncData>* sync_data_list) const {
  for (ExtensionSet::const_iterator it = extensions->begin();
       it != extensions->end(); ++it) {
    const Extension& extension = *it->get();
    // If we have pending app data for this app, then this
    // version is out of date.  We'll sync back the version we got from
    // sync.
    if (IsSyncing() && sync_helper::IsSyncableApp(&extension) &&
        !HasPendingExtensionId(extension.id())) {
      sync_data_list->push_back(extension_sync_service_->GetAppSyncData(
          extension));
    }
  }
}

void AppSyncBundle::AddApp(const std::string& id) {
  synced_apps_.insert(id);
}

void AppSyncBundle::RemoveApp(const std::string& id) {
  synced_apps_.erase(id);
}

void AppSyncBundle::MarkPendingAppSynced(const std::string& id) {
  pending_sync_data_.erase(id);
  synced_apps_.insert(id);
}

}  // namespace extensions


text:
import React, {FC} from 'react';

export interface Props {
	/**
	 * Number of newlines to insert.
	 *
	 * @default 1
	 */
	readonly count?: number;
}

/**
 * Adds one or more newline (\n) characters. Must be used within <Text> components.
 */
const Newline: FC<Props> = ({count = 1}) => (
	<ink-text>{'\n'.repeat(count)}</ink-text>
);

Newline.displayName = 'Newline';

export default Newline;


text:
This is a git repository for my personal dot files.

This repo is heavily influenced by [Ben Orenstein's dot files](https://github.com/r00k/dotfiles).

### Preferences

I'm a big fan of Ruby, ZSH, tmux, Git and VIM so a lot of configurations are related to this ecosystem. I use both Mac and Linux and therefore no preferences will be taken there.

### Installation

 - `git clone git://github.com/cadizjavier/dotfiles ~/.dotfiles`
 - `cd ~/.dotfiles`
 - `rake install`

Vim plugins are managed through vundle. You'll need to install vundle to get them.

- `git clone https://github.com/gmarik/Vundle.vim.git ~/.vim/bundle/Vundle.vim`
- `vim +PluginInstall +qall`

Zsh plugins are managed through antibody. You'll need to install antibody to get them.

- `curl -s https://raw.githubusercontent.com/getantibody/installer/master/install | bash -s`
- `antibody bundle`


text:
using DemoCRUD.Models;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
using System.Linq;
using System.Web;

namespace DemoCRUD.AcessoDados
{
    public class LivrosContexto :
    {
        public DbSet<Genero> Generos { get; set; }
        public DbSet<Livro> Livros { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();

            modelBuilder.Properties<String>().Configure(c => c.HasMaxLength(100));

            modelBuilder.Entity<Genero>().Property(g => g.Nome).HasMaxLength(30);
        }
    }
}


text:
Create a namespace with the specified name.

### Synopsis

Create a namespace with the specified name.

```
kubectl create namespace NAME [--dry-run]
```

### Examples

```
  # Create a new namespace named my-namespace
  kubectl create namespace my-namespace
```

### Options

```
      --dry-run[=false]: If true, only print the object that would be sent, without sending it.
      --generator="namespace/v1": The name of the API generator to use.
      --no-headers[=false]: When using the default output, don't print headers.
  -o, --output="": Output format. One of: json|yaml|wide|name|go-template=...|go-template-file=...|jsonpath=...|jsonpath-file=... See golang template [http://golang.org/pkg/text/template/#pkg-overview] and jsonpath template [http://releases.k8s.io/release-1.2/docs/user-guide/jsonpath.md].
      --output-version="": Output the formatted object with the given group version (for ex: 'extensions/v1beta1').
      --save-config[=false]: If true, the configuration of current object will be saved in its annotation. This is useful when you want to perform kubectl apply on this object in the future.
      --schema-cache-dir="~/.kube/schema": If non-empty, load/store cached API schemas in this directory, default is '$HOME/.kube/schema'
  -a, --show-all[=false]: When printing, show all resources (default hide terminated pods.)
      --show-labels[=false]: When printing, show all labels as the last column (default hide labels column)
      --sort-by="": If non-empty, sort list types using this field specification.  The field specification is expressed as a JSONPath expression (e.g. '{.metadata.name}'). The field in the API resource specified by this JSONPath expression must be an integer or a string.
      --template="": Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [http://golang.org/pkg/text/template/#pkg-overview].
      --validate[=true]: If true, use a schema to validate the input before sending it
```

### Options inherited from parent commands

```
      --alsologtostderr[=false]: log to standard error as well as files
      --certificate-authority="": Path to a cert. file for the certificate authority.
      --client-certificate="": Path to a client certificate file for TLS.
      --client-key="": Path to a client key file for TLS.
      --cluster="": The name of the kubeconfig cluster to use
      --context="": The name of the kubeconfig context to use
      --insecure-skip-tls-verify[=false]: If true, the server's certificate will not be checked for validity. This will make your HTTPS connections insecure.
      --kubeconfig="": Path to the kubeconfig file to use for CLI requests.
      --log-backtrace-at=:0: when logging hits line file:N, emit a stack trace
      --log-dir="": If non-empty, write log files in this directory
      --log-flush-frequency=5s: Maximum number of seconds between log flushes
      --logtostderr[=true]: log to standard error instead of files
      --match-server-version[=false]: Require server version to match client version
      --namespace="": If present, the namespace scope for this CLI request.
      --password="": Password for basic authentication to the API server.
  -s, --server="": The address and port of the Kubernetes API server
      --stderrthreshold=2: logs at or above this threshold go to stderr
      --token="": Bearer token for authentication to the API server.
      --user="": The name of the kubeconfig user to use
      --username="": Username for basic authentication to the API server.
      --v=0: log level for V logs
      --vmodule=: comma-separated list of pattern=N settings for file-filtered logging
```

### SEE ALSO

* [kubectl create](kubectl_create/)	 - Create a resource by filename or stdin

###### Auto generated by spf13/cobra on 11-Mar-2016


text:
package com.taocoder.ourea.core.consumer;

import com.google.common.base.Joiner;
import com.taocoder.ourea.core.config.ThriftClientConfig;
import com.taocoder.ourea.core.config.ZkConfig;
import com.taocoder.ourea.core.model.ServiceInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Proxy;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author tao.ke Date: 16/4/27 Time: 上午11:41
 */
public class ConsumerProxyFactory {

    private static final Logger LOGGER = LoggerFactory.getLogger(ConsumerProxyFactory.class);

    /**
     * 正常的业务需求,是保证全局的thrift client 单例的,因为构造client成本是很重的. 这里的,key为class_group_version
     */
    private static final ConcurrentHashMap<String, Object> SERVICE_CLIENT_CONCURRENT_HASH_MAP = new ConcurrentHashMap<String, Object>();

    private static final Joiner CLIENT_KEY_JOINER = Joiner.on("_");

    private static final Object SERVICE_CLIENT_LOCK = new Object();

    public <T> T getProxyClient(Class<T> clientClazz, ZkConfig zkConfig) {
        return getProxyClient(clientClazz, new ThriftClientConfig(), zkConfig);
    }

    @SuppressWarnings("unchecked")
    public <T> T getProxyClient(Class<T> clientClazz, ThriftClientConfig config, ZkConfig zkConfig) {

        String clientKey = CLIENT_KEY_JOINER.join(clientClazz.getCanonicalName(), config.getGroup(),
                config.getVersion());
        T client = (T) SERVICE_CLIENT_CONCURRENT_HASH_MAP.get(clientKey);

        if (client == null) {
            synchronized (SERVICE_CLIENT_LOCK) {
                client = (T) SERVICE_CLIENT_CONCURRENT_HASH_MAP.get(clientKey);
                if (client == null) {

                    long start = System.currentTimeMillis();
                    final ServiceInfo serviceInfo = new ServiceInfo(clientClazz, config.getVersion(),
                            config.getGroup());

                    client = (T) Proxy.newProxyInstance(ConsumerProxyFactory.class.getClassLoader(),
                            new Class[] { clientClazz }, new ConsumerProxy(serviceInfo, zkConfig, config));
                    SERVICE_CLIENT_CONCURRENT_HASH_MAP.putIfAbsent(clientKey, client);
                    LOGGER.info("build thrift client succ.cost:{},clientConfig:{},zkConfig:{}",
                            System.currentTimeMillis() - start, config, zkConfig);
                }
            }
        }
        return client;
    }

}


text:
def stock_picker(stocks)
	#1) Find Pairs
	pairs = stocks.combination(2).to_a

	#2) Iterate pairs and find pair with largest difference
	bestPair = [0,0]
	pairs.each{|pair|
		if (pair[1] - pair[0]) > (bestPair[1] - bestPair[0])
			bestPair.replace(pair)
		end}

	#3) Check if a pair was found
	if bestPair[0] == 0 and bestPair[1] == 0
		puts "No profit margin found in given range."
	else
		#4) Find the indexes, Low always appears first.
		lowIndex = stocks.index(bestPair[0])
		highIndex = Array.new()
		loop do
			highIndex = stocks.index(bestPair[1])
			break if highIndex > lowIndex
		end

		#5) Return the good day pair
		return [lowIndex, highIndex]
	end
end

puts stock_picker([17,3,6,9,15,8,6,1,10]).inspect #expect [1,4]
puts stock_picker([17,16,15,14,13,12,11,10,9]).inspect


text:
<?php

declare(strict_types=1);

namespace Contentful\Tests\Management\Unit;

use Contentful\Management\ApiConfiguration;
use Contentful\Management\Resource\Asset;
use Contentful\Management\Resource\Entry;
use Contentful\Management\Resource\Upload;
use Contentful\Tests\Management\BaseTestCase;

class ApiConfigurationTest extends BaseTestCase
{
    public function testGetFromString()
    {
        $config = (new ApiConfiguration())
            ->getConfigFor(Upload::class)
        ;

        $this->assertSame([
            'class' => Upload::class,
            'uri' => '/spaces/{space}/uploads/{upload}',
            'host' => 'https://upload.contentful.com',
            'parameters' => ['space'],
            'id' => 'upload',
        ], $config);
    }

    public function testGetFromStringWithoutInitialBackslash()
    {
        $config = (new ApiConfiguration())
            ->getConfigFor('\\Contentful\\Management\\Resource\\PersonalAccessToken')
        ;

        $this->assertSame([
            'class' => 'Contentful\\Management\\Resource\\PersonalAccessToken',
            'uri' => 'users/me/access_tokens/{personalAccessToken}',
            'parameters' => [],
            'id' => 'personalAccessToken',
        ], $config);
    }

    public function testGetFromBaseObject()
    {
        $config = (new ApiConfiguration())
            ->getConfigFor(new Asset())
        ;

        $this->assertSame([
            'class' => Asset::class,
            'uri' => '/spaces/{space}/environments/{environment}/assets/{asset}',
            'parameters' => ['space', 'environment'],
            'id' => 'asset',
        ], $config);
    }

    public function testGetFromExtendedObject()
    {
        $config = (new ApiConfiguration())
            ->getConfigFor(new ExtendedResource('contentType'))
        ;

        $this->assertSame([
            'class' => ExtendedResource::class,
            'uri' => '/spaces/{space}/environments/{environment}/entries/{entry}',
            'parameters' => ['space', 'environment'],
            'id' => 'entry',
        ], $config);
    }

    public function testThrowOnInvalidResourceObject()
    {
        $this->expectException(\InvalidArgumentException::class);
        $this->expectExceptionMessage('Trying to access invalid configuration for class "stdClass".');

        (new ApiConfiguration())
            ->getConfigFor(\stdClass::class)
        ;
    }

    public function testGetLinkConfiguration()
    {
        $config = (new ApiConfiguration())
            ->getLinkConfigFor('WebhookDefinition')
        ;

        $this->assertSame([
            'class' => 'Contentful\\Management\\Resource\\Webhook',
            'uri' => '/spaces/{space}/webhook_definitions/{webhook}',
            'parameters' => ['space'],
            'id' => 'webhook',
            'class' => 'Contentful\Management\\Resource\\Webhook',
        ], $config);
    }

    public function testGetConfigForInvalidLinkType()
    {
        $this->expectException(\InvalidArgumentException::class);
        $this->expectExceptionMessage('Trying to get link configuration for an invalid link type "Invalid".');

        (new ApiConfiguration())
            ->getLinkConfigFor('Invalid')
        ;
    }
}

class ExtendedResource extends Entry
{
}


text:
<component name="ProjectDictionaryState">
  <dictionary name="Metarin" />
</component>


text:
import { ArmSiteDescriptor } from 'app/shared/resourceDescriptors';
import { FunctionAppService } from 'app/shared/services/function-app.service';
import { FunctionAppContextComponent } from 'app/shared/components/function-app-context-component';
import { LogCategories } from './../shared/models/constants';
import { LogService } from './../shared/services/log.service';
import { ArmService } from 'app/shared/services/arm.service';
import { BusyStateScopeManager } from './../busy-state/busy-state-scope-manager';
import { BroadcastService } from './../shared/services/broadcast.service';
import { DropDownElement } from './../shared/models/drop-down-element';
import { PortalResources } from './../shared/models/portal-resources';
import { TableItem, TblComponent } from './../controls/tbl/tbl.component';
import { ViewChild } from '@angular/core';
import { Subscription as RxSubscription } from 'rxjs/Subscription';
import { TranslateService } from '@ngx-translate/core';
import { CacheService } from './../shared/services/cache.service';
import { PortalService } from './../shared/services/portal.service';
import { Component } from '@angular/core';
import { Observable } from 'rxjs/Observable';

interface LogicAppInfo {
    name: string;
    id: string;
    resourceGroup: string;
    location: string;
}

export interface LogicAppTableItem extends TableItem {
    title: string;
    id: string;
    resourceGroup: string;
    location: string;
}

@Component({
    selector: 'app-logic-apps',
    templateUrl: './logic-apps.component.html',
    styleUrls: ['./logic-apps.component.scss']
})

export class LogicAppsComponent extends FunctionAppContextComponent {
    private _resourceId: string;

    public logicApps: LogicAppInfo[] = [];
    public tableItems: TableItem[] = [];
    public subId: string;
    public logicAppsIcon = 'image/logicapp.svg';
    public initialized = false;

    public allLocations = this._translateService.instant(PortalResources.allLocations);
    public numberLocations = this._translateService.instant(PortalResources.locationCount);
    public locationOptions: DropDownElement<string>[] = [];
    public locationsDisplayText = this.allLocations;
    public selectedLocations: string[] = [];

    public allResourceGroups = this._translateService.instant(PortalResources.allResourceGroups);
    public numberResourceGroups = this._translateService.instant(PortalResources.resourceGroupCount);
    public resourceGroupOptions: DropDownElement<string>[] = [];
    public resourceGroupsDisplayText = this.allResourceGroups;
    public selectedResourceGroups: string[] = [];

    private _busyManager: BusyStateScopeManager;

    @ViewChild('table') logicAppTable: TblComponent;

    public groupOptions: DropDownElement<string>[] = [
        { displayLabel: this._translateService.instant(PortalResources.grouping_none), value: 'none' },
        { displayLabel: this._translateService.instant(PortalResources.grouping_resourceGroup), value: 'resourceGroup' },
        { displayLabel: this._translateService.instant(PortalResources.grouping_location), value: 'location' }];
    public groupDisplayText = '';
    public currGroup = 'none';

    constructor(
        private _armService: ArmService,
        private _portalService: PortalService,
        private _cacheService: CacheService,
        private _translateService: TranslateService,
        private _logService: LogService,
        _functionAppService: FunctionAppService,
        broadcastService: BroadcastService) {
        super('logic-apps', _functionAppService, broadcastService);

        this._busyManager = new BusyStateScopeManager(broadcastService, 'site-tabs');
    }

    setup(): RxSubscription {
        return this.viewInfoEvents
            .switchMap(viewInfo => {
                this._busyManager.setBusy();
                this.initialized = false;

                this._resourceId = viewInfo.resourceId;
                this.subId = new ArmSiteDescriptor(this._resourceId).getWebsiteId().SubscriptionId;
                // Have to remove leading '/' for filter to function and ending '/' for unique function apps
                const logicAppResId = this._resourceId.substr(1) + '/';

                return Observable.zip(
                    this._cacheService.getArm(
                        `/subscriptions/${this.subId}/providers/Microsoft.Logic/workflows?api-version=2017-07-01&$filter=contains(referencedResourceId, '${logicAppResId}')`,
                        true,
                        this._armService.logicAppsApiVersion,
                        true
                    ),
                    this._cacheService.getArm(
                        `/subscriptions/${this.subId}/providers/Microsoft.Logic/workflows`,
                        true,
                        this._armService.logicAppsApiVersion,
                        true
                    ),
                    (a, s) => ({ app: a.json(), sub: s.json() })
                );
            })
            .do(null, e => {
                this._logService.error(LogCategories.generalSettings, '/logic-apps', e);
            })
            .retry()
            .subscribe(r => {
                const selectedJson = r.app.value.length > 0 ? r.app : r.sub;
                this.logicApps = selectedJson.value
                    .map(app => (<LogicAppInfo>{
                        name: app.name,
                        id: app.id,
                        resourceGroup: app.id.split('/')[4],
                        location: this._translateService.instant(app.location),
                        type: 'row'
                    }))
                    .sort((a: LogicAppInfo, b: LogicAppInfo) => {
                        return a.name.localeCompare(b.name);
                    });

                this.tableItems = this.logicApps
                    .map(app => (<LogicAppTableItem>{
                        title: app.name,
                        id: app.id,
                        resourceGroup: app.resourceGroup,
                        location: app.location,
                        type: 'row'
                    }));

                this.locationOptions = this.uniqueTypes(this.logicApps, 'location')
                    .map(location => ({
                        displayLabel: location,
                        value: location
                    }));

                this.resourceGroupOptions = this.uniqueTypes(this.logicApps, 'resourceGroup')
                    .map(resourceGroup => ({
                        displayLabel: resourceGroup,
                        value: resourceGroup
                    }));

                this._busyManager.clearBusy();
                this.initialized = true;
            });
    }

    clickRow(item: LogicAppTableItem) {
        this._portalService.openBlade(
            {
                detailBlade: 'LogicAppsDesignerBlade',
                detailBladeInputs: {
                    id: item.id
                },
                extension: 'Microsoft_Azure_EMA'
            },
            'LogicAppsComponent'
        );
    }

    uniqueTypes(apps: LogicAppInfo[], type: string) {
        const typeDict = {};
        apps.forEach(app => typeDict[app[type]] = app[type]);

        const typeArray = [];
        for (const typeItem in typeDict) {
            if (typeDict.hasOwnProperty(typeItem)) {
                typeArray.push(typeItem);
            }
        }

        return typeArray.sort();
    }

    // Todo: [agruning] Encapsulate locations/resources drop-down logic - https://github.com/Azure/azure-functions-ux/issues/1897
    onLocationsSelect(locations: string[]) {
        this.selectedLocations = locations;
        const newItems = this.tableItems.filter(item => item.type === 'group');
        const filteredItems = this.logicApps.filter(app => this.selectedLocations.find(l => l === app.location))
            .filter(app => this.selectedResourceGroups.find(r => r === app.resourceGroup))
            .map(app => (<LogicAppTableItem>{
                title: app.name,
                id: app.id,
                type: 'row',
                resourceGroup: app.resourceGroup,
                location: app.location,
            }));
        this.tableItems = newItems.concat(filteredItems);

        // timeout is needed to re-render to page for the grouping update with new locations
        setTimeout(() => {
            this.logicAppTable.groupItems(this.currGroup);
        }, 0);

        if (this.selectedLocations.length === this.locationOptions.length) {
            this._updateLocDisplayText(this.allLocations);
        } else if (this.selectedLocations.length > 1) {
            this._updateLocDisplayText(this.numberLocations.format(locations.length));
        } else {
            this._updateLocDisplayText(`${this.selectedLocations[0]}`);
        }
    }

    private _updateLocDisplayText(displayText: string) {
        // timeout is needed to re-render the page for display update
        setTimeout(() => {
            this.locationsDisplayText = displayText;
        }, 0);
    }

    onResourceGroupsSelect(resourceGroups: string[]) {
        this.selectedResourceGroups = resourceGroups;
        const newItems = this.tableItems.filter(item => item.type === 'group');
        const filteredItems = this.logicApps.filter(app => this.selectedResourceGroups.find(r => r === app.resourceGroup))
            .filter(app => this.selectedLocations.find(l => l === app.location))
            .map(app => (<LogicAppTableItem>{
                title: app.name,
                id: app.id,
                type: 'row',
                resourceGroup: app.resourceGroup,
                location: app.location
            }));
        this.tableItems = newItems.concat(filteredItems);

        // timeout is needed to re-render to page for the grouping update with new resourceGroups
        setTimeout(() => {
            this.logicAppTable.groupItems(this.currGroup);
        }, 0);

        if (this.selectedResourceGroups.length === this.resourceGroupOptions.length) {
            this._updateResGroupDisplayText(this.allResourceGroups);
        } else if (this.selectedResourceGroups.length > 1) {
            this._updateResGroupDisplayText(this.numberResourceGroups.format(resourceGroups.length));
        } else {
            this._updateResGroupDisplayText(`${this.selectedResourceGroups[0]}`);
        }
    }

    private _updateResGroupDisplayText(displayText: string) {
        // timeout is needed to re-render the page for display update
        setTimeout(() => {
            this.resourceGroupsDisplayText = displayText;
        }, 0);
    }

    onGroupSelect(group: string) {
        this.currGroup = group;

        // timeout is needed to re-render the page for grouping update
        setTimeout(() => {
            this.logicAppTable.groupItems(group);
        }, 0);
    }

}


text:
module DataAggregation::Accumulator
  module Controls
    module PositionStore
      class Example
        include DataAggregation::Accumulator::PositionStore

        category :some_accumulator
      end
    end
  end
end


text:
/*
 */
package eu.uqasar.auth.strategies.metadata;

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

import eu.uqasar.model.role.Role;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;
import org.apache.wicket.authorization.Action;
import org.apache.wicket.util.io.IClusterable;

/**
 *
 *
 */
class ActionPermissions implements IClusterable {

	/**
	 * Map from an action to a set of roles
	 */
	private final Map<Action, EnumSet<Role>> authorizedRolesForAction = new HashMap<>();

	/**
	 * Gives permission for the given roles to perform the given action
	 *
	 * @param action The action
	 * @param rolesToAuthorize The roles that will be authorized to perform the
	 * action
	 */
	public final void authorize(final Action action, Role... rolesToAuthorize) {
		if (action == null) {
			throw new IllegalArgumentException("Argument action cannot be null");
		}

		if (rolesToAuthorize == null) {
			throw new IllegalArgumentException("Argument rolesToAuthorize cannot be null");
		}

		EnumSet<Role> roleslevels = authorizedRolesForAction.get(action);
		if (roleslevels == null) {
			roleslevels = EnumSet.noneOf(Role.class);
		}
		roleslevels.addAll(Arrays.asList(rolesToAuthorize));
		authorizedRolesForAction.put(action, roleslevels);
	}

	/**
	 * Gives permission for the given roles to perform the given action
	 *
	 * @param action The action
	 * @param rolesToAuthorize The roles that will be authorized to perform the
	 * action
	 */
	public final void authorize(final Action action, EnumSet<Role> rolesToAuthorize) {
		this.authorize(action, rolesToAuthorize.toArray(new Role[rolesToAuthorize.size()]));
	}

	/**
	 * Remove all authorization roles for the given action.
	 *
	 * @param action The action to clear
	 */
	public final void authorizeAll(final Action action) {
		if (action == null) {
			throw new IllegalArgumentException("Argument action cannot be null");
		}

		authorizedRolesForAction.remove(action);
	}

	/**
	 * Gets the roles that have a binding for the given action.
	 *
	 * @param action The action
	 * @return The roles authorized for the given action
	 */
	public final EnumSet<Role> rolesFor(final Action action) {
		if (action == null) {
			throw new IllegalArgumentException("Argument action cannot be null");
		}

		return authorizedRolesForAction.get(action);
	}

	/**
	 * Remove the given authorized roles from an action. Note that this is only
	 * relevant if a role was previously authorized for that action. If no roles
	 * where previously authorized the effect of the unauthorize call is that no
	 * roles at all will be authorized for that action.
	 *
	 * @param action The action
	 * @param rolesToUnauthorize The list of roles that will no longer be
	 * authorized to perform the action
	 */
	public final void unauthorize(final Action action, final Role... rolesToUnauthorize) {
		if (action == null) {
			throw new IllegalArgumentException("Argument action cannot be null");
		}

		if (rolesToUnauthorize == null) {
			throw new IllegalArgumentException("Argument rolesToUnauthorize cannot be null");
		}

		EnumSet<Role> roleslevels = authorizedRolesForAction.get(action);
		if (roleslevels != null) {
			roleslevels.removeAll(Arrays.asList(rolesToUnauthorize));
		} else {
			roleslevels = EnumSet.noneOf(Role.class);
		}

		// If we removed the last authorized role, we authorize the empty role
		// so that removing authorization can't suddenly open something up to
		// everyone.
		if (roleslevels.size() == 0) {
			roleslevels.add(Role.NoRole);
		}
		authorizedRolesForAction.put(action, roleslevels);
	}

	/**
	 * Remove the given authorized roles from an action. Note that this is only
	 * relevant if a role was previously authorized for that action. If no roles
	 * where previously authorized the effect of the unauthorize call is that no
	 * roles at all will be authorized for that action.
	 *
	 * @param action The action
	 * @param rolesToUnauthorize The list of roles that will no longer be
	 * authorized to perform the action
	 */
	public final void unauthorize(final Action action, final EnumSet<Role> rolesToUnauthorize) {
		this.unauthorize(action, rolesToUnauthorize.toArray(new Role[rolesToUnauthorize.size()]));
	}
}


text:
import jQuery from 'jquery-ts'

export function getJQueryById(id: string): jQuery.IInstance | null {
	var result = document.getElementById(id + '')
	if (result) return jQuery(result)
	else return null
}


text:
package android.database.sqlite;

import android.database.Cursor;
import android.os.CancellationSignal;

public class SQLiteQueryBuilder {

    public Cursor query(SQLiteDatabase db, String[] projectionIn,
                        String selection, String[] selectionArgs, String groupBy,
                        String having, String sortOrder) {
        return query(db, projectionIn, selection, selectionArgs, groupBy, having, sortOrder,
                null /* limit */, null /* cancellationSignal */);
    }

    public Cursor query(SQLiteDatabase db, String[] projectionIn,
                        String selection, String[] selectionArgs, String groupBy,
                        String having, String sortOrder, String limit) {
        return query(db, projectionIn, selection, selectionArgs,
                groupBy, having, sortOrder, limit, null);
    }

    public Cursor query(SQLiteDatabase db, String[] projectionIn,
                        String selection, String[] selectionArgs, String groupBy,
                        String having, String sortOrder, String limit,
                        CancellationSignal cancellationSignal) {
        return new SQLiteCursor(null, null, null);
    }

}


text:
<!doctype html>

		<meta charset="utf-8">

		<title>Creative Code: Final Project Overview</title>

		<meta name="description" content="A framework for easily creating beautiful presentations using HTML">
		<meta name="author" content="Hakim El Hattab">

		<meta name="apple-mobile-web-app-capable" content="yes" />
		<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />

		<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, minimal-ui">

		<link rel="stylesheet" href="css/reveal.css">
		<link rel="stylesheet" href="css/theme/moon.css" id="theme">

		<link rel="stylesheet" href="lib/css/zenburn.css">

Creative Code Immersive

 Final Project Overview

						by Andrew V.

PROJECT OVERVIEW: Objective

The goal is to enable people to enjoy music with others around them.

It does so by aggregating everyones' playlist in the same physical space and playing back songs that the majority would enjoy.

PROJECT OVERVIEW: Physical Description

Web Application built with Spotify Web API

Users (on Spotify) would access the Web App and authorize the app to pull his/her playlist from Spotify

The Web App would aggregate all playlists in the area and create a Group playlist based on shared attributes

Visualization

Informational graphics of the current track and playlist visualized with Processing

THANK YOU


text:
import os
import re
from datetime import timedelta, datetime
from typing import List, Any, Optional

from cryptography import x509
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import ec, rsa
from cryptography.hazmat.primitives.asymmetric.ec import EllipticCurvePrivateKey
from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateKey
from cryptography.hazmat.primitives.serialization import Encoding, PrivateFormat, NoEncryption, load_pem_private_key
from cryptography.x509 import ExtendedKeyUsageOID, NameOID

EC_SUPPORTED = {}
EC_SUPPORTED.update([(curve.name.upper(), curve) for curve in [
    ec.SECP192R1,
    ec.SECP224R1,
    ec.SECP256R1,
    ec.SECP384R1,
]])

def _private_key(key_type):
    if isinstance(key_type, str):
        key_type = key_type.upper()
        m = re.match(r'^(RSA)?(\d+)$', key_type)
        if m:
            key_type = int(m.group(2))

    if isinstance(key_type, int):
        return rsa.generate_private_key(
            public_exponent=65537,
            key_size=key_type,
            backend=default_backend()
        )
    if not isinstance(key_type, ec.EllipticCurve) and key_type in EC_SUPPORTED:
        key_type = EC_SUPPORTED[key_type]
    return ec.generate_private_key(
        curve=key_type,
        backend=default_backend()
    )

class CertificateSpec:

    def __init__(self, name: str = None, domains: List[str] = None,
                 email: str = None,
                 key_type: str = None, single_file: bool = False,
                 valid_from: timedelta = timedelta(days=-1),
                 valid_to: timedelta = timedelta(days=89),
                 client: bool = False,
                 sub_specs: List['CertificateSpec'] = None):
        self._name = name
        self.domains = domains
        self.client = client
        self.email = email
        self.key_type = key_type
        self.single_file = single_file
        self.valid_from = valid_from
        self.valid_to = valid_to
        self.sub_specs = sub_specs

    @property
    def name(self) -> Optional[str]:
        if self._name:
            return self._name
        elif self.domains:
            return self.domains[0]
        return None

class Credentials:

    def __init__(self, name: str, cert: Any, pkey: Any):
        self._name = name
        self._cert = cert
        self._pkey = pkey
        self._cert_file = None
        self._pkey_file = None
        self._store = None

    @property
    def name(self) -> str:
        return self._name

    @property
    def subject(self) -> x509.Name:
        return self._cert.subject

    @property
    def key_type(self):
        if isinstance(self._pkey, RSAPrivateKey):
            return f"rsa{self._pkey.key_size}"
        elif isinstance(self._pkey, EllipticCurvePrivateKey):
            return f"{self._pkey.curve.name}"
        else:
            raise Exception(f"unknown key type: {self._pkey}")

    @property
    def private_key(self) -> Any:
        return self._pkey

    @property
    def certificate(self) -> Any:
        return self._cert

    @property
    def cert_pem(self) -> bytes:
        return self._cert.public_bytes(Encoding.PEM)

    @property
    def pkey_pem(self) -> bytes:
        return self._pkey.private_bytes(
            Encoding.PEM,
            PrivateFormat.TraditionalOpenSSL if self.key_type.startswith('rsa') else PrivateFormat.PKCS8,
            NoEncryption())

    def set_store(self, store: 'CertStore'):
        self._store = store

    def set_files(self, cert_file: str, pkey_file: str = None):
        self._cert_file = cert_file
        self._pkey_file = pkey_file

    @property
    def cert_file(self) -> str:
        return self._cert_file

    @property
    def pkey_file(self) -> Optional[str]:
        return self._pkey_file

    def get_first(self, name) -> Optional['Credentials']:
        creds = self._store.get_credentials_for_name(name) if self._store else []
        return creds[0] if len(creds) else None

    def get_credentials_for_name(self, name) -> List['Credentials']:
        return self._store.get_credentials_for_name(name) if self._store else []

    def issue_certs(self, specs: List[CertificateSpec],
                    chain: List['Credentials'] = None) -> List['Credentials']:
        return [self.issue_cert(spec=spec, chain=chain) for spec in specs]

    def issue_cert(self, spec: CertificateSpec, chain: List['Credentials'] = None) -> 'Credentials':
        key_type = spec.key_type if spec.key_type else self.key_type
        creds = self._store.load_credentials(name=spec.name, key_type=key_type, single_file=spec.single_file) \
            if self._store else None
        if creds is None:
            creds = MDTestCA.create_credentials(spec=spec, issuer=self, key_type=key_type,
                                                valid_from=spec.valid_from, valid_to=spec.valid_to)
            if self._store:
                self._store.save(creds, single_file=spec.single_file)

        if spec.sub_specs:
            if self._store:
                sub_store = CertStore(fpath=os.path.join(self._store.path, creds.name))
                creds.set_store(sub_store)
            subchain = chain.copy() if chain else []
            subchain.append(self)
            creds.issue_certs(spec.sub_specs, chain=subchain)
        return creds

class CertStore:

    def __init__(self, fpath: str):
        self._store_dir = fpath
        if not os.path.exists(self._store_dir):
            os.makedirs(self._store_dir)
        self._creds_by_name = {}

    @property
    def path(self) -> str:
        return self._store_dir

    def save(self, creds: Credentials, name: str = None,
             chain: List[Credentials] = None,
             single_file: bool = False) -> None:
        name = name if name is not None else creds.name
        cert_file = self.get_cert_file(name=name, key_type=creds.key_type)
        pkey_file = self.get_pkey_file(name=name, key_type=creds.key_type)
        if single_file:
            pkey_file = None
        with open(cert_file, "wb") as fd:
            fd.write(creds.cert_pem)
            if chain:
                for c in chain:
                    fd.write(c.cert_pem)
            if pkey_file is None:
                fd.write(creds.pkey_pem)
        if pkey_file is not None:
            with open(pkey_file, "wb") as fd:
                fd.write(creds.pkey_pem)
        creds.set_files(cert_file, pkey_file)
        self._add_credentials(name, creds)

    def _add_credentials(self, name: str, creds: Credentials):
        if name not in self._creds_by_name:
            self._creds_by_name[name] = []
        self._creds_by_name[name].append(creds)

    def get_credentials_for_name(self, name) -> List[Credentials]:
        return self._creds_by_name[name] if name in self._creds_by_name else []

    def get_cert_file(self, name: str, key_type=None) -> str:
        key_infix = ".{0}".format(key_type) if key_type is not None else ""
        return os.path.join(self._store_dir, f'{name}{key_infix}.cert.pem')

    def get_pkey_file(self, name: str, key_type=None) -> str:
        key_infix = ".{0}".format(key_type) if key_type is not None else ""
        return os.path.join(self._store_dir, f'{name}{key_infix}.pkey.pem')

    def load_pem_cert(self, fpath: str) -> x509.Certificate:
        with open(fpath) as fd:
            return x509.load_pem_x509_certificate("".join(fd.readlines()).encode())

    def load_pem_pkey(self, fpath: str):
        with open(fpath) as fd:
            return load_pem_private_key("".join(fd.readlines()).encode(), password=None)

    def load_credentials(self, name: str, key_type=None, single_file: bool = False):
        cert_file = self.get_cert_file(name=name, key_type=key_type)
        pkey_file = cert_file if single_file else self.get_pkey_file(name=name, key_type=key_type)
        if os.path.isfile(cert_file) and os.path.isfile(pkey_file):
            cert = self.load_pem_cert(cert_file)
            pkey = self.load_pem_pkey(pkey_file)
            creds = Credentials(name=name, cert=cert, pkey=pkey)
            creds.set_store(self)
            creds.set_files(cert_file, pkey_file)
            self._add_credentials(name, creds)
            return creds
        return None

class MDTestCA:

    @classmethod
    def create_root(cls, name: str, store_dir: str, key_type: str = "rsa2048") -> Credentials:
        store = CertStore(fpath=store_dir)
        creds = store.load_credentials(name="ca", key_type=key_type)
        if creds is None:
            creds = MDTestCA._make_ca_credentials(name=name, key_type=key_type)
            store.save(creds, name="ca")
            creds.set_store(store)
        return creds

    @staticmethod
    def create_credentials(spec: CertificateSpec, issuer: Credentials, key_type: Any,
                           valid_from: timedelta = timedelta(days=-1),
                           valid_to: timedelta = timedelta(days=89),
                           ) -> Credentials:
        """Create a certificate signed by this CA for the given domains.
        :returns: the certificate and private key PEM file paths
        """
        if spec.domains and len(spec.domains):
            creds = MDTestCA._make_server_credentials(name=spec.name, domains=spec.domains,
                                                      issuer=issuer, valid_from=valid_from,
                                                      valid_to=valid_to, key_type=key_type)
        elif spec.client:
            creds = MDTestCA._make_client_credentials(name=spec.name, issuer=issuer,
                                                      email=spec.email, valid_from=valid_from,
                                                      valid_to=valid_to, key_type=key_type)
        elif spec.name:
            creds = MDTestCA._make_ca_credentials(name=spec.name, issuer=issuer,
                                                  valid_from=valid_from, valid_to=valid_to,
                                                  key_type=key_type)
        else:
            raise Exception(f"unrecognized certificate specification: {spec}")
        return creds

    @staticmethod
    def _make_x509_name(org_name: str = None, common_name: str = None, parent: x509.Name = None) -> x509.Name:
        name_pieces = []
        if org_name:
            oid = NameOID.ORGANIZATIONAL_UNIT_NAME if parent else NameOID.ORGANIZATION_NAME
            name_pieces.append(x509.NameAttribute(oid, org_name))
        elif common_name:
            name_pieces.append(x509.NameAttribute(NameOID.COMMON_NAME, common_name))
        if parent:
            name_pieces.extend([rdn for rdn in parent])
        return x509.Name(name_pieces)

    @staticmethod
    def _make_csr(
            subject: x509.Name,
            pkey: Any,
            issuer_subject: Optional[Credentials],
            valid_from_delta: timedelta = None,
            valid_until_delta: timedelta = None
    ):
        pubkey = pkey.public_key()
        issuer_subject = issuer_subject if issuer_subject is not None else subject

        valid_from = datetime.now()
        if valid_until_delta is not None:
            valid_from += valid_from_delta
        valid_until = datetime.now()
        if valid_until_delta is not None:
            valid_until += valid_until_delta

        return (
            x509.CertificateBuilder()
            .subject_name(subject)
            .issuer_name(issuer_subject)
            .public_key(pubkey)
            .not_valid_before(valid_from)
            .not_valid_after(valid_until)
            .serial_number(x509.random_serial_number())
            .add_extension(
                x509.SubjectKeyIdentifier.from_public_key(pubkey),
                critical=False,
            )
        )

    @staticmethod
    def _add_ca_usages(csr: Any) -> Any:
        return csr.add_extension(
            x509.BasicConstraints(ca=True, path_length=9),
            critical=True,
        ).add_extension(
            x509.KeyUsage(
                digital_signature=True,
                content_commitment=False,
                key_encipherment=False,
                data_encipherment=False,
                key_agreement=False,
                key_cert_sign=True,
                crl_sign=True,
                encipher_only=False,
                decipher_only=False),
            critical=True
        ).add_extension(
            x509.ExtendedKeyUsage([
                ExtendedKeyUsageOID.CLIENT_AUTH,
                ExtendedKeyUsageOID.SERVER_AUTH,
                ExtendedKeyUsageOID.CODE_SIGNING,
            ]),
            critical=True
        )

    @staticmethod
    def _add_leaf_usages(csr: Any, domains: List[str], issuer: Credentials) -> Any:
        return csr.add_extension(
            x509.BasicConstraints(ca=False, path_length=None),
            critical=True,
        ).add_extension(
            x509.AuthorityKeyIdentifier.from_issuer_subject_key_identifier(
                issuer.certificate.extensions.get_extension_for_class(
                    x509.SubjectKeyIdentifier).value),
            critical=False
        ).add_extension(
            x509.SubjectAlternativeName([x509.DNSName(domain) for domain in domains]),
            critical=True,
        ).add_extension(
            x509.ExtendedKeyUsage([
                ExtendedKeyUsageOID.SERVER_AUTH,
            ]),
            critical=True
        )

    @staticmethod
    def _add_client_usages(csr: Any, issuer: Credentials, rfc82name: str = None) -> Any:
        cert = csr.add_extension(
            x509.BasicConstraints(ca=False, path_length=None),
            critical=True,
        ).add_extension(
            x509.AuthorityKeyIdentifier.from_issuer_subject_key_identifier(
                issuer.certificate.extensions.get_extension_for_class(
                    x509.SubjectKeyIdentifier).value),
            critical=False
        )
        if rfc82name:
            cert.add_extension(
                x509.SubjectAlternativeName([x509.RFC822Name(rfc82name)]),
                critical=True,
            )
        cert.add_extension(
            x509.ExtendedKeyUsage([
                ExtendedKeyUsageOID.CLIENT_AUTH,
            ]),
            critical=True
        )
        return cert

    @staticmethod
    def _make_ca_credentials(name, key_type: Any,
                             issuer: Credentials = None,
                             valid_from: timedelta = timedelta(days=-1),
                             valid_to: timedelta = timedelta(days=89),
                             ) -> Credentials:
        pkey = _private_key(key_type=key_type)
        if issuer is not None:
            issuer_subject = issuer.certificate.subject
            issuer_key = issuer.private_key
        else:
            issuer_subject = None
            issuer_key = pkey
        subject = MDTestCA._make_x509_name(org_name=name, parent=issuer.subject if issuer else None)
        csr = MDTestCA._make_csr(subject=subject,
                                 issuer_subject=issuer_subject, pkey=pkey,
                                 valid_from_delta=valid_from, valid_until_delta=valid_to)
        csr = MDTestCA._add_ca_usages(csr)
        cert = csr.sign(private_key=issuer_key,
                        algorithm=hashes.SHA256(),
                        backend=default_backend())
        return Credentials(name=name, cert=cert, pkey=pkey)

    @staticmethod
    def _make_server_credentials(name: str, domains: List[str], issuer: Credentials,
                                 key_type: Any,
                                 valid_from: timedelta = timedelta(days=-1),
                                 valid_to: timedelta = timedelta(days=89),
                                 ) -> Credentials:
        name = name
        pkey = _private_key(key_type=key_type)
        subject = MDTestCA._make_x509_name(common_name=name, parent=issuer.subject)
        csr = MDTestCA._make_csr(subject=subject,
                                 issuer_subject=issuer.certificate.subject, pkey=pkey,
                                 valid_from_delta=valid_from, valid_until_delta=valid_to)
        csr = MDTestCA._add_leaf_usages(csr, domains=domains, issuer=issuer)
        cert = csr.sign(private_key=issuer.private_key,
                        algorithm=hashes.SHA256(),
                        backend=default_backend())
        return Credentials(name=name, cert=cert, pkey=pkey)

    @staticmethod
    def _make_client_credentials(name: str,
                                 issuer: Credentials, email: Optional[str],
                                 key_type: Any,
                                 valid_from: timedelta = timedelta(days=-1),
                                 valid_to: timedelta = timedelta(days=89),
                                 ) -> Credentials:
        pkey = _private_key(key_type=key_type)
        subject = MDTestCA._make_x509_name(common_name=name, parent=issuer.subject)
        csr = MDTestCA._make_csr(subject=subject,
                                 issuer_subject=issuer.certificate.subject, pkey=pkey,
                                 valid_from_delta=valid_from, valid_until_delta=valid_to)
        csr = MDTestCA._add_client_usages(csr, issuer=issuer, rfc82name=email)
        cert = csr.sign(private_key=issuer.private_key,
                        algorithm=hashes.SHA256(),
                        backend=default_backend())
        return Credentials(name=name, cert=cert, pkey=pkey)


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

<wicket:extend>

<form style="padding-top:5px;" wicket:id="editForm">

<wicket:message key="gb.general"></wicket:message>

<wicket:message key="gb.attributes"></wicket:message>

<wicket:message key="gb.accessPermissions"></wicket:message>

<wicket:message key="gb.username"></wicket:message>	<input type="text" wicket:id="username" id="username" size="30" tabindex="1" />

<wicket:message key="gb.password"></wicket:message>	<input type="password" wicket:id="password" size="30" tabindex="2" />

<wicket:message key="gb.confirmPassword"></wicket:message>	<input type="password" wicket:id="confirmPassword" size="30" tabindex="3" />

<wicket:message key="gb.displayName"></wicket:message>	<input type="text" wicket:id="displayName" size="30" tabindex="4" />

<wicket:message key="gb.emailAddress"></wicket:message>	<input type="text" wicket:id="emailAddress" size="30" tabindex="5" />

<wicket:message key="gb.canAdmin"></wicket:message>	<input type="checkbox" wicket:id="canAdmin" tabindex="6" />  <wicket:message key="gb.canAdminDescription"></wicket:message>

<wicket:message key="gb.canCreate"></wicket:message>	<input type="checkbox" wicket:id="canCreate" tabindex="7" />  <wicket:message key="gb.canCreateDescription"></wicket:message>

<wicket:message key="gb.canFork"></wicket:message>	<input type="checkbox" wicket:id="canFork" tabindex="8" />  <wicket:message key="gb.canForkDescription"></wicket:message>

<wicket:message key="gb.excludeFromFederation"></wicket:message>	<input type="checkbox" wicket:id="excludeFromFederation" tabindex="9" />  <wicket:message key="gb.excludeFromFederationDescription"></wicket:message>

<wicket:message key="gb.organizationalUnit"></wicket:message> (OU)	<input type="text" wicket:id="organizationalUnit" size="30" tabindex="1" />

<wicket:message key="gb.organization"></wicket:message> (O)	<input type="text" wicket:id="organization" size="30" tabindex="2" />

<wicket:message key="gb.locality"></wicket:message> (L)	<input type="text" wicket:id="locality" size="30" tabindex="3" />

<wicket:message key="gb.stateProvince"></wicket:message> (ST)	<input type="text" wicket:id="stateProvince" size="30" tabindex="4" />

<wicket:message key="gb.countryCode"></wicket:message> (C)	<input type="text" wicket:id="countryCode" size="15	" tabindex="5" />

<wicket:message key="gb.teamMemberships"></wicket:message>

<wicket:message key="gb.repositoryPermissions"></wicket:message>

<input class="btn btn-primary" type="submit" value="Save" wicket:message="value:gb.save" wicket:id="save" tabindex="9" />   <input class="btn" type="submit" value="Cancel" wicket:message="value:gb.cancel" wicket:id="cancel" tabindex="10" />

</form>

</wicket:extend>


text:
<?php

/** @file
* @brief
* @since version 0.85
*/

include ('../inc/includes.php');

$dropdown = new ProjectState();
include (GLPI_ROOT . "/front/dropdown.common.form.php");
?>


text:
<?php

namespace PostmanGeneratorBundle\Normalizer;

use Doctrine\Common\Inflector\Inflector;
use PostmanGeneratorBundle\Model\Request;
use PostmanGeneratorBundle\Model\Test;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;

class RequestNormalizer implements NormalizerInterface
{
    /**
     * {@inheritdoc}
     *
     * @param Request $object
     */
    public function normalize($object, $format = null, array $context = [])
    {
        $data = [];
        $reflectionClass = new \ReflectionClass($object);
        /** @var \ReflectionProperty[] $properties */
        $properties = array_filter($reflectionClass->getProperties(), function (\ReflectionProperty $property) {
            return 'resource' !== $property->getName();
        });

        foreach ($properties as $property) {
            if ('fromCollection' !== $property->getName()) {
                $method = $reflectionClass->getMethod('get'.Inflector::classify($property->getName()));
            } else {
                $method = $reflectionClass->getMethod('is'.Inflector::classify($property->getName()));
            }
            if ('folder' === $property->getName()) {
                $data[$property->getName()] = $method->invoke($object)->getId();
            } elseif ('collection' === $property->getName()) {
                $data[$property->getName().'Id'] = $method->invoke($object)->getId();
            } elseif ('headers' === $property->getName()) {
                $data[$property->getName()] = '';
                foreach ($method->invoke($object) as $key => $value) {
                    $data[$property->getName()] .= "$key: $value\n";
                }
            } elseif ('rawModeData' === $property->getName()) {
                $rawModeData = json_encode((object)$method->invoke($object));
                if ('{}' !== $rawModeData) {
                    $rawModeData = preg_replace('/([{,])/', "\$1\n    ", $rawModeData);
                    $rawModeData = preg_replace('/([}])/', "\n}", $rawModeData);
                }
                $data[$property->getName()] = $rawModeData;
            } elseif ('tests' === $property->getName()) {
                $tests = implode("\n\n", array_map(function (Test $test) {
                    return sprintf('tests["%s"] = %s;', $test->getMessage(), $test->getExecutor());
                }, $object->getTests()));
                $data[$property->getName()] = $tests;
            } else {
                $data[$property->getName()] = $method->invoke($object);
            }
        }

        return $data;
    }

    /**
     * {@inheritdoc}
     */
    public function supportsNormalization($data, $format = null)
    {
        return 'json' === $format && is_object($data) && $data instanceof Request;
    }
}


text:
from django.urls import reverse

from fiscal.forms import MembershipTaskForm
from fiscal.models import MembershipPersonRole, MembershipTask
from workshops.models import Membership
from workshops.tests.base import TestBase

class TestMembershipTaskFormLayout(TestBase):
    def test_main_helper_layout(self):
        form = MembershipTaskForm()

        self.assertEqual(
            list(form.helper.layout),
            ["membership", "person", "role", "EDITABLE", "id", "DELETE"],
        )

    def test_empty_helper_layout(self):
        form = MembershipTaskForm()

        self.assertEqual(len(form.helper_empty_form.layout), 5)
        self.assertEqual(
            list(form.helper_empty_form.layout)[:-1],
            ["membership", "person", "role", "id"],
        )
        self.assertEqual(form.helper_empty_form.layout[-1].fields, ["DELETE"])

class TestMembershipTasks(TestBase):
    def setUp(self):
        super().setUp()
        self._setUpUsersAndLogin()

        self.membership = Membership.objects.create(
            public_status="public",
            variant="partner",
            agreement_start="2021-02-14",
            agreement_end="2022-02-14",
            contribution_type="financial",
            public_instructor_training_seats=0,
            additional_public_instructor_training_seats=0,
        )
        self.membership_person_role = MembershipPersonRole.objects.first()

    def test_adding_new_tasks(self):
        self.assertEqual(self.membership.membershiptask_set.count(), 0)
        data = {
            "form-TOTAL_FORMS": 2,
            "form-INITIAL_FORMS": 0,
            "form-MIN_NUM_FORMS": 0,
            "form-MAX_NUM_FORMS": 1000,
            "form-0-membership": self.membership.pk,
            "form-0-person": self.hermione.pk,
            "form-0-role": self.membership_person_role.pk,
            "form-0-id": "",
            "form-0-EDITABLE": True,
            "form-1-membership": self.membership.pk,
            "form-1-person": self.harry.pk,
            "form-1-role": self.membership_person_role.pk,
            "form-1-id": "",
            "form-1-EDITABLE": True,
        }
        response = self.client.post(
            reverse("membership_tasks", args=[self.membership.pk]),
            data=data,
            follow=True,
        )

        self.assertRedirects(
            response, reverse("membership_details", args=[self.membership.pk])
        )
        self.assertEqual(self.membership.membershiptask_set.count(), 2)
        self.assertEqual(
            list(self.membership.persons.all()), [self.hermione, self.harry]
        )

    def test_removing_tasks(self):
        mt1 = MembershipTask.objects.create(
            person=self.hermione,
            membership=self.membership,
            role=self.membership_person_role,
        )
        mt2 = MembershipTask.objects.create(
            person=self.harry,
            membership=self.membership,
            role=self.membership_person_role,
        )

        data = {
            "form-TOTAL_FORMS": 2,
            "form-INITIAL_FORMS": 2,
            "form-MIN_NUM_FORMS": 0,
            "form-MAX_NUM_FORMS": 1000,
            "form-0-membership": self.membership.pk,
            "form-0-person": mt1.person.pk,
            "form-0-role": mt1.role.pk,
            "form-0-id": mt1.pk,
            "form-0-EDITABLE": True,
            "form-0-DELETE": "on",
            "form-1-membership": self.membership.pk,
            "form-1-person": mt2.person.pk,
            "form-1-role": mt2.role.pk,
            "form-1-id": mt2.pk,
            "form-1-EDITABLE": True,
            "form-1-DELETE": "on",
        }
        response = self.client.post(
            reverse("membership_tasks", args=[self.membership.pk]),
            data=data,
            follow=True,
        )

        self.assertRedirects(
            response, reverse("membership_details", args=[self.membership.pk])
        )

        self.assertEqual(list(self.membership.persons.all()), [])

    def test_mix_adding_removing_tasks(self):
        mt1 = MembershipTask.objects.create(
            person=self.hermione,
            membership=self.membership,
            role=self.membership_person_role,
        )
        mt2 = MembershipTask.objects.create(
            person=self.harry,
            membership=self.membership,
            role=self.membership_person_role,
        )

        data = {
            "form-TOTAL_FORMS": 3,
            "form-INITIAL_FORMS": 2,
            "form-MIN_NUM_FORMS": 0,
            "form-MAX_NUM_FORMS": 1000,
            "form-0-membership": self.membership.pk,
            "form-0-person": mt1.person.pk,
            "form-0-role": mt1.role.pk,
            "form-0-id": mt1.pk,
            "form-0-EDITABLE": True,
            "form-0-DELETE": "on",
            "form-1-membership": self.membership.pk,
            "form-1-person": mt2.person.pk,
            "form-1-role": mt2.role.pk,
            "form-1-id": mt2.pk,
            "form-1-EDITABLE": True,
            "form-1-DELETE": "on",
            "form-2-membership": self.membership.pk,
            "form-2-person": self.ron.pk,
            "form-2-role": self.membership_person_role.pk,
            "form-2-id": "",
            "form-2-EDITABLE": True,
        }
        response = self.client.post(
            reverse("membership_tasks", args=[self.membership.pk]),
            data=data,
            follow=True,
        )

        self.assertRedirects(
            response, reverse("membership_details", args=[self.membership.pk])
        )

        self.assertEqual(list(self.membership.persons.all()), [self.ron])


text:
@interface XNFPSLabel : UILabel

@end


text:
/**
 * Integration of examples with strata-report.
 */
package com.opengamma.strata.examples.report;


text:
@interface NSString (Addition)

+ (BOOL)IsNilOrEmpty:(NSString *)str;

- (BOOL)isNilOrEmpty;

///
/// 判断是否是电话格式
///
- (BOOL) isValidPhone;

- (CGFloat)heightForWidth:(CGFloat)width
                     font:(UIFont *)font;

//用作只有一行文字的实际宽度
- (CGFloat)realWidthForWidth:(CGFloat)width
                        font:(UIFont *)font;

@property (nonatomic, readonly) NSString* md5Hash;

- (NSComparisonResult)versionStringCompare:(NSString *)other;

- (BOOL)isWhitespaceAndNewlines;

- (BOOL)isEmptyOrWhitespace;

- (BOOL)isEmail;

- (BOOL)isLegalPrice;

- (BOOL)isNumber;

- (BOOL) isHttpUrl;

-(BOOL)isLegalName;

- (BOOL)isOnlyContainNumberOrLatter;

-(unichar) intToHex:(int)n;

-(BOOL) isCharSafe:(unichar)ch;

-(BOOL)containString:(NSString *)string;

-(NSString *)removeSpace;

-(NSString *)replaceSpaceWithUnderline;

- (NSString *)replaceDotWithUnderline;

- (NSString *)encodeString;

-(NSString *)trimmedWhitespaceString;

-(NSString *)trimmedWhitespaceAndNewlineString;

// date
+(NSDate *)dateFromString:(NSString *)string;

- (NSDictionary *)parseURLParams;

- (NSString *)getValueStringFromUrlForParam:(NSString *)param;

- (NSDate *)date;

//formart
+ (id)stringWithActivityMessageType:(NSInteger)typeIndex ZPKID:(NSString*) pkid;

+(NSString * ) stringLocationbyint:(double) value;
@end