text:
import os
import sys
import asyncio
import logging
import json
import cmd
import itertools
import functools
# TODO use readline for history ?
#import readline

import websockets
from jsonrpcserver.aio import methods
from jsonrpcserver.response import NotificationResponse
from jsonrpcclient.websockets_client import WebSocketsClient
from jsonrpcclient.exceptions import ReceivedErrorResponse

from aiohttp import web

from pypeman.conf import settings
from pypeman import channels
from pypeman import message
from pypeman import msgstore

logger = logging.getLogger(__name__)

from io import StringIO
import contextlib

@contextlib.contextmanager
def stdoutIO(stdout=None):
    old = sys.stdout
    if stdout is None:
        stdout = StringIO()
    sys.stdout = stdout
    yield stdout
    sys.stdout = old

class RemoteAdminServer():
    """
    Expose json/rpc function to a client by a websocket.
    """

    def __init__(self, loop=None, host='localhost', port='8091', ssl=None, url=None):
        self.host = host
        self.port = port
        self.ssl = ssl
        self.loop = loop or asyncio.get_event_loop()
        self.ctx = {}

    def get_channel(self, name):
        """
        return channel by is name.all
        """
        for chan in channels.all:
            if chan.name == name:
                return chan
        return None

    async def start(self):
        """ Start remote admin server """
        methods.add(self.exec)
        methods.add(self.channels)
        methods.add(self.stop_channel)
        methods.add(self.start_channel)
        methods.add(self.list_msg)
        methods.add(self.replay_msg)
        methods.add(self.push_msg)

        start_server = websockets.serve(
            self.command,
            host=self.host,
            port=self.port,
            ssl=self.ssl,
            loop=self.loop
        )
        await start_server

    async def command(self, websocket, path):
        """
        Generic function to handle a command from client.
        """
        request = await websocket.recv()
        response = await methods.dispatch(request)
        if not response.is_notification:
            await websocket.send(str(response))

    async def exec(self, command):
        """
        Execute a python command on this instance and
        return the stdout result.

        :param command: The python command to execute. Can be multiline.
        :returns: Command stdout result.
        """
        # TODO may cause problem on multi thread access to stdout
        # as we highjack sys.stdout
        with stdoutIO() as out:
            exec(command, globals())

        return out.getvalue()

    async def channels(self):
        """
        Return a list of available channels.
        """
        chans = []
        for chan in channels.all:
            if not chan.parent:
                chan_dict = chan.to_dict()
                chan_dict['subchannels'] = chan.subchannels()

                chans.append(chan_dict)

        return chans

    async def start_channel(self, channel):
        """
        Start the specified channel

        :params channel: The channel name to start.
        """
        chan = self.get_channel(channel)
        await chan.start()
        return {
            'name': chan.name,
            'status': channels.BaseChannel.status_id_to_str(chan.status)
        }

    async def stop_channel(self, channel):
        """
        Stop the specified channel

        :params channel: The channel name to stop.
        """
        chan = self.get_channel(channel)
        await chan.stop()
        return {
            'name': chan.name,
            'status': channels.BaseChannel.status_id_to_str(chan.status)
        }

    async def list_msg(self, channel, start=0, count=10, order_by='timestamp'):
        """
        List first `count` messages from message store of specified channel.

        :params channel: The channel name.
        """
        chan = self.get_channel(channel)

        messages = await chan.message_store.search(start=start, count=count, order_by=order_by)

        for res in messages:
            res['timestamp'] = res['message'].timestamp_str()
            res['message'] = res['message'].to_json()

        return {'messages': messages, 'total': await chan.message_store.total()}

    async def replay_msg(self, channel, msg_ids):
        """
        Replay messages from message store.

        :params channel: The channel name.
        :params msg_ids: The message ids list to replay.
        """
        chan = self.get_channel(channel)
        result = []
        for msg_id in msg_ids:
            try:
                msg_res = await chan.replay(msg_id)
                result.append(msg_res.to_dict())
            except Exception as exc:
                result.append({'error': str(exc)})

        return result

    async def push_msg(self, channel, text):
        """
        Push a message in the channel.

        :params channel: The channel name.
        :params msg_ids: The text added to the payload.
        """
        chan = self.get_channel(channel)
        msg = message.Message(payload=text)
        result = await chan.handle(msg)
        return result.to_dict()

class RemoteAdminClient():
    """
    Remote admin client. To be use by ipython shell or pypeman shell.

    :params url: Pypeman Websocket url.
    """
    def __init__(self, loop=None, url='ws://localhost:8091'):
        self.url = url
        self.loop = loop or asyncio.get_event_loop()

    def init(self):
        pass

    def send_command(self, command, args=None):
        """
        Send a command to remote instance
        """
        if args is None:
            args = []
        return self.loop.run_until_complete(self._send_command(command, args))

    async def _send_command(self, command, args):
        """
        Asynchronous version of command sending
        """
        async with websockets.connect(self.url, loop=self.loop) as ws:
            response = await WebSocketsClient(ws).request(command, *args)
            return response

    def exec(self, command):
        """
        Execute any valid python code on remote instance
        and return stdout result.
        """
        result = self.send_command('exec', [command])
        print(result)
        return

    def channels(self):
        """
        Return a list of available channels on remote instance.
        """
        return self.send_command('channels')

    def start(self, channel):
        """
        Start the specified channel on remote instance.

        :params channel: The channel name.
        """
        return self.send_command('start_channel', [channel])

    def stop(self, channel):
        """
        Stop the specified channel on remote instance.

        :params channel: The channel name.
        """
        return self.send_command('stop_channel', [channel])

    def list_msg(self, channel, start=0, count=10, order_by='timestamp'):
        """
        List first 10 messages on specified channel from remote instance.

        :params channel: The channel name.
        :params start: Start index of listing.
        :params count: Count from index.
        :params order_by: Message order. only 'timestamp' and '-timestamp' handled for now.
        :returns: list of message with status.
        """
        result = self.send_command('list_msg', [channel, start, count, order_by])

        for m in result['messages']:
            m['message'] = message.Message.from_json(m['message'])

        return result

    def replay_msg(self, channel, msg_ids):
        """
        Replay specified message from id list of specified channel on remote instance.

        :params channel: The channel name.
        :params msg_ids: Message id list to replay
        :returns: List of result for each message. Result
            can be {'error': <msg_error>} for one id if error
            occurs.
        """
        request_result = self.send_command('replay_msg', [channel, msg_ids])

        result = []
        for msg in request_result:
            if 'error' not in msg:
                result.append(message.Message.from_dict(msg))
            else:
                result.append(msg)

        return result

    def push_msg(self, channel, text):
        """
        Push a new message from text param to the channel.

        :params channel: The channel name.
        :params text: This text will be the payload of the message.
        """
        msg_dict = self.send_command('push_msg', [channel, text])
        return message.Message.from_dict(msg_dict)

def _with_current_channel(func):
    """
    Decorator to select channel for command.
    """
    @functools.wraps(func)
    def wrapper(self, *arg, **kwargs):
        if self.current_channel:
            return func(self, self.current_channel, *arg, **kwargs)
        else:
            print("You have to select a channel prior using this command")
            return None

    return wrapper

class PypemanShell(cmd.Cmd):
    intro = 'Welcome to the pypeman shell. Type help or ? to list commands.\n'
    prompt = 'pypeman > '
    use_rawinput = False

    def __init__(self, url):
        super().__init__()
        self.current_channel = None
        self.client = RemoteAdminClient(url=url)
        self.client.init()

    def do_channels(self, arg):
        "List avaible channels"
        result = self.client.channels()
        print("\nChannel list:")
        for idx, channel in enumerate(result):
            print("{idx}) {name} ({status})".format(idx=idx, **channel))

        print("")
        self.current_channel = None
        self.prompt = "pypeman > "

    def do_stop(self, arg):
        "Stop a channel by his name"
        result = self.client.stop_channel(arg)
        print(result)

    def do_start(self, arg):
        "Start a channel by his name"
        result = self.client.start_channel(arg)
        print(result)

    def do_select(self, arg):
        """
        Select a channel by is name.
        Mandatory for channel oriented command
        """
        self.current_channel = arg
        self.prompt = "pypeman(%s) > " % arg

    def get_current_channel(self):
        if self.current_channel:
            return self.current_channel
        else:
            print("You have to select a channel before for this command")
            return None

    @_with_current_channel
    def do_list(self, channel, arg):
        "List messages of selected channel. You can specify start, end and order_by arguments"
        args = arg.split()
        start, end, order_by = 0, 10, '-timestamp'

        if args:
            start = args[0]
        if len(args) > 1:
            start = args[1]
        if len(args) > 2:
            start = args[2]

        result = self.client.list_msg(channel, start, end, order_by)

        if not result['total']:
            print('No message yet.')

        for res in result['messages']:
            print(res['message'].timestamp, res['id'], res['state'])

    @_with_current_channel
    def do_replay(self, channel, arg):
        "Replay a message list by their ids"
        msg_ids = arg.split()
        results = self.client.replay_msg(channel, msg_ids)
        for msg_id, msg in zip(msg_ids, results):
            print("Result message for replaying message %s:" % msg_id)
            if isinstance(msg, message.Message):
                print(msg.to_print())
            else:
                print('Error on msg: %s - %s' % (msg_id, msg['error']))

    @_with_current_channel
    def do_push(self, channel, arg):
        "Inject message with text as payload for selected channel"
        result = self.client.push_msg(channel, arg)
        print("Result message:")
        print(result.to_print())

    def do_exit(self, arg):
        "Exit program"
        sys.exit()

class WebAdmin():
    def __init__(self, loop, host, port, ssl):
        self.host = host
        self.port = port
        self.ssl = ssl
        self.loop = loop

    async def start(self):

        client_dir = os.path.join(os.path.dirname(os.path.join(__file__)), 'client/dist')
        app = web.Application()
        app.router.add_get(
            '/configs.js',
            self.handle_config
        )

        # redirect to index.html
        app.router.add_get('/', self.redirect_to_index)

        app.router.add_static(
            '/',
            path=os.path.join(client_dir),
            name='static'
        )

        await self.loop.create_server(
            protocol_factory=app.make_handler(),
            host=self.host,
            port=self.port,
            ssl=self.ssl
        )

    async def redirect_to_index(self, request):
        """ redirect to index.html"""
        return web.HTTPFound("index.html")

    async def handle_config(self, request):
        conf = settings.REMOTE_ADMIN_WEBSOCKET_CONFIG
        server_url = conf['url'] or "ws{is_secure}://{host}:{port}".format(
            is_secure='s' if conf['ssl'] else '',
            **conf
        )

        conf = {
            'serverConfig': server_url
        }
        # TODO Not really cool but works.
        resp = """window.configs = {};""".format(json.dumps(conf))

        return web.Response(text=resp)


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>com.intel.icecp</groupId>
        <artifactId>icecp</artifactId>
        <version>0.13.0</version>
    </parent>

    <name>icecp-node</name>
    <groupId>com.intel.icecp</groupId>
    <artifactId>icecp-node</artifactId>
    <version>0.13.0</version>
    <packaging>jar</packaging>
    <description>Includes the core API and the reference implementation for an Information-Centric Edge Compute Platform (ICECP) Node</description>

    <properties>
        <!-- overwrite default value inherited from icecp-module-template -->
        <rpm.targetDirectory>/home/icecp/${project.version}-${rpm.release}</rpm.targetDirectory>
    </properties>

    <build>
        <plugins>
            <!-- control logging output during tests -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.18.1</version>
                <configuration>
                    <systemProperties>
                        <property>
                            <name>log4j.configurationFile</name>
                            <value>configuration/log4j2.xml</value>
                        </property>
                        <property>
                            <name>java.util.logging.config.file</name>
                            <value>configuration/logging.properties</value>
                        </property>
                    </systemProperties>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-failsafe-plugin</artifactId>
                <version>2.18.1</version>
                <executions>
                    <execution>
                        <id>runIntegrationTests</id>
                        <phase>integration-test</phase>
                        <goals>
                            <goal>integration-test</goal>
                        </goals>
                    </execution>
                    <execution>
                        <id>verifyIntegrationTests</id>
                        <phase>verify</phase>
                        <goals>
                            <goal>verify</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <systemProperties>
                        <property>
                            <name>log4j.configurationFile</name>
                            <value>configuration/log4j2.xml</value>
                        </property>
                        <property>
                            <name>java.util.logging.config.file</name>
                            <value>configuration/logging.properties</value>
                        </property>
                    </systemProperties>
                </configuration>
            </plugin>
            <!-- set the MainClass property in the JAR manifest -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <version>2.4</version>
                <configuration>
                    <archive>
                        <manifest>
                            <addClasspath>true</addClasspath>
                            <classpathPrefix>.</classpathPrefix>
                            <mainClass>com.intel.icecp.main.MainDaemon</mainClass>
                            <addDefaultImplementationEntries>true</addDefaultImplementationEntries>
                            <addDefaultSpecificationEntries>true</addDefaultSpecificationEntries>
                        </manifest>
                        log4j.configurationFile
                    </archive>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>license-maven-plugin</artifactId>
                <version>1.9</version>
                <executions>
                    <execution>
                        <id>download-licenses</id>
                        <goals>
                            <goal>download-licenses</goal>
                        </goals>
                        <configuration>
                            <licensesOutputDirectory>${project.build.directory}/generated-resources/licenses-icecp-node
                            </licensesOutputDirectory>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

    <dependencies>
        <!-- main dependencies to run -->
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>2.5</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.5</version>
        </dependency>
        <dependency>
            <groupId>com.intel.icecp</groupId>
            <artifactId>icecp-rpc</artifactId>
            <version>[0.2.0, 0.3.0)</version>
        </dependency>
        <dependency>
            <groupId>com.intel.icecp</groupId>
            <artifactId>icecp-core</artifactId>
            <version>0.13.0</version>
        </dependency>
        <dependency>
            <groupId>com.intel.icecp</groupId>
            <artifactId>icecp-mock</artifactId>
            <version>0.13.0</version>
        </dependency>

        <!-- format-specific dependencies; TODO these should be SPI-loaded -->
        <dependency>
            <groupId>com.fasterxml.jackson.dataformat</groupId>
            <artifactId>jackson-dataformat-cbor</artifactId>
            <version>2.6.4</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.6.4</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.module</groupId>
            <artifactId>jackson-module-jsonSchema</artifactId>
            <version>2.6.4</version>
        </dependency>

        <!-- Log4j-core specific dependency -->
        <dependency>
            <groupId>com.fasterxml.jackson.dataformat</groupId>
            <artifactId>jackson-dataformat-xml</artifactId>
            <version>2.7.1</version>
        </dependency>

        <!-- NDN-specific dependencies; TODO these should be SPI-loaded -->
        <dependency>
            <groupId>com.intel.jndn.utils</groupId>
            <artifactId>jndn-utils</artifactId>
            <version>1.1.1</version>
        </dependency>
        <dependency>
            <groupId>com.intel.jndn.management</groupId>
            <artifactId>jndn-management</artifactId>
            <version>1.1.3</version>
        </dependency>

        <!-- test dependencies -->
        <dependency>
            <groupId>com.intel.jndn.mock</groupId>
            <artifactId>jndn-mock</artifactId>
            <version>1.1.0</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.awaitility</groupId>
            <artifactId>awaitility</artifactId>
            <version>2.0.0</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.maven</groupId>
            <artifactId>maven-model</artifactId>
            <version>3.0</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <profiles>
        <!-- Run `mvn package -Pas-application` to build project as a runnable application; look for output in
        'target/appassembler' -->
        <profile>
            <id>as-application</id>
            <build>
                <plugins>
                    <plugin>
                        <groupId>org.codehaus.mojo</groupId>
                        <artifactId>appassembler-maven-plugin</artifactId>
                        <version>1.10</version>
                        <executions>
                            <execution>
                                <id>create-runnable-application</id>
                                <phase>package</phase>
                                <goals>
                                    <goal>assemble</goal>
                                </goals>
                            </execution>
                        </executions>
                        <configuration>
                            <programs>
                                <program>
                                    <mainClass>com.intel.icecp.main.MainDaemon</mainClass>
                                    <id>icecp</id>
                                </program>
                            </programs>
                            <repositoryName>lib</repositoryName>
                            <repositoryLayout>flat</repositoryLayout>
                            <configurationDirectory>configuration</configurationDirectory>
                            <configurationSourceDirectory>configuration</configurationSourceDirectory>
                            <copyConfigurationDirectory>true</copyConfigurationDirectory>
                            <extraJvmArguments>-Ddeap.configuration=@BASEDIR@/configuration
                                -Djava.util.logging.config.file=@BASEDIR@/configuration/logging.properties
                            </extraJvmArguments>
                        </configuration>
                    </plugin>
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-antrun-plugin</artifactId>
                        <version>1.8</version>
                        <executions>
                            <execution>
                                <id>copy-permissions</id>
                                <phase>package</phase>
                                <goals>
                                    <goal>run</goal>
                                </goals>
                            </execution>
                        </executions>
                        <configuration>
                            <target name="copy permissions to appassembly">
                                <copy todir="${project.build.directory}/appassembler/permissions">
                                    <fileset dir="permissions"/>
                                </copy>
                            </target>
                        </configuration>
                    </plugin>
                </plugins>
            </build>
        </profile>

        <!-- Run `mvn package -Pas-rpm` to build project and package it as an RPM; look for output the project directory -->
        <profile>
            <id>as-rpm</id>
            <build>
                <plugins>
                    <plugin>
                        <groupId>org.codehaus.mojo</groupId>
                        <artifactId>appassembler-maven-plugin</artifactId>
                        <version>1.10</version>
                        <executions>
                            <execution>
                                <id>create-runnable-application</id>
                                <phase>package</phase>
                                <goals>
                                    <goal>assemble</goal>
                                </goals>
                            </execution>
                        </executions>
                        <configuration>
                            <programs>
                                <program>
                                    <mainClass>com.intel.icecp.main.MainDaemon</mainClass>
                                    <id>icecp</id>
                                </program>
                            </programs>
                            <repositoryName>lib</repositoryName>
                            <repositoryLayout>flat</repositoryLayout>
                            <configurationDirectory>configuration</configurationDirectory>
                            <configurationSourceDirectory>configuration</configurationSourceDirectory>
                            <copyConfigurationDirectory>true</copyConfigurationDirectory>
                            <extraJvmArguments>-Dicecp.configuration=@BASEDIR@/configuration
                                -Djava.util.logging.config.file=@BASEDIR@/configuration/logging.properties
                            </extraJvmArguments>
                        </configuration>
                    </plugin>
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-antrun-plugin</artifactId>
                        <version>1.8</version>
                        <executions>
                            <execution>
                                <id>copy-permissions</id>
                                <phase>package</phase>
                                <goals>
                                    <goal>run</goal>
                                </goals>
                            </execution>
                        </executions>
                        <configuration>
                            <target name="copy permissions to appassembly">
                                <copy todir="${project.build.directory}/appassembler/permissions">
                                    <fileset dir="permissions"/>
                                </copy>
                            </target>
                        </configuration>
                    </plugin>
                    <plugin>
                        <groupId>org.codehaus.mojo</groupId>
                        <artifactId>exec-maven-plugin</artifactId>
                        <version>1.5.0</version>
                        <executions>
                            <execution>
                                <id>create-rpm</id>
                                <phase>package</phase>
                                <goals>
                                    <goal>exec</goal>
                                </goals>
                            </execution>
                        </executions>
                        <configuration>
                            <!-- see explanations at https://github.com/jordansissel/fpm/wiki#usage -->
                            <executable>fpm</executable>
                            <commandlineArgs>-s dir -t rpm -f
                                --template-scripts
                                --license "Intel Proprietary (see 'licenses' directory for libraries)"
                                --before-install ${project.basedir}/packaging/scripts/before-install.sh
                                --after-install ${project.basedir}/packaging/scripts/after-install.sh
                                --before-remove ${project.basedir}/packaging/scripts/before-remove.sh
                                --after-remove ${project.basedir}/packaging/scripts/after-remove.sh
                                --name ${project.artifactId}
                                --version ${project.version}
                                --iteration ${rpm.release}
                                --architecture all
                                --vendor "${rpm.vendor}"
                                --maintainer "${rpm.maintainer}"
                                --description "${project.description}"
                                --url "${rpm.url}"
                                --rpm-digest "${rpm.digest}"
                                --rpm-auto-add-directories
                                --config-files ${rpm.targetDirectory}/configuration
                                ${project.build.directory}/appassembler/bin=${rpm.targetDirectory}
                                ${project.build.directory}/appassembler/lib=${rpm.targetDirectory}
                                ${project.build.directory}/appassembler/configuration=${rpm.targetDirectory}
                                ${project.build.directory}/appassembler/permissions=${rpm.targetDirectory}
                                ${project.basedir}/packaging/etc=/
                                ${basedir}/target/generated-resources/licenses-icecp-node=${rpm.targetDirectory}/licenses/
                                ${basedir}/target/generated-resources/licenses.xml=${rpm.targetDirectory}/licenses/licenses-icecp-node/licenses.xml
                                ${basedir}/../icecp-mock/target/generated-resources/licenses-icecp-mock=${rpm.targetDirectory}/licenses/
                                ${basedir}/../icecp-mock/target/generated-resources/licenses.xml=${rpm.targetDirectory}/licenses/licenses-icecp-mock/licenses.xml
                                ${basedir}/../icecp-core/target/generated-resources/licenses-icecp-core=${rpm.targetDirectory}/licenses/
                                ${basedir}/../icecp-core/target/generated-resources/licenses.xml=${rpm.targetDirectory}/licenses/licenses-icecp-core/licenses.xml
                            </commandlineArgs>
                        </configuration>
                    </plugin>
                </plugins>
            </build>
        </profile>

        <!-- Run with `mvn package -Pwith-dependencies` to build JAR containing all dependencies; this is deprecated
        and will be removed soon -->
        <profile>
            <id>with-dependencies</id>
            <build>
                <plugins>
                    <!-- build a JAR with dependencies -->
                    <plugin>
                        <artifactId>maven-assembly-plugin</artifactId>
                        <configuration>
                            <descriptorRefs>
                                <descriptorRef>jar-with-dependencies</descriptorRef>
                            </descriptorRefs>
                            <archive>
                                <manifest>
                                    <mainClass>com.intel.icecp.main.MainDaemon</mainClass>
                                    <addDefaultImplementationEntries>true</addDefaultImplementationEntries>
                                    <addDefaultSpecificationEntries>true</addDefaultSpecificationEntries>
                                </manifest>
                            </archive>
                        </configuration>
                        <executions>
                            <execution>
                                <phase>package</phase>
                                <goals>
                                    <goal>single</goal>
                                </goals>
                            </execution>
                        </executions>
                    </plugin>
                </plugins>
            </build>
        </profile>
    </profiles>
</project>

redpajama_set_name: RedPajamaGithub


text:
/**
 * Selfbits API V2
 * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
 *
 * OpenAPI spec version: 2.0.0
 *
 *
 * NOTE: This class is auto generated by the swagger code generator program.
 * https://github.com/swagger-api/swagger-codegen.git
 * Do not edit the class manually.
 */
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var NewPushService;
(function (NewPushService) {
    var PushServiceTypeEnum;
    (function (PushServiceTypeEnum) {
        PushServiceTypeEnum[PushServiceTypeEnum["FCM"] = 'FCM'] = "FCM";
        PushServiceTypeEnum[PushServiceTypeEnum["APN"] = 'APN'] = "APN";
    })(PushServiceTypeEnum = NewPushService.PushServiceTypeEnum || (NewPushService.PushServiceTypeEnum = {}));
})(NewPushService = exports.NewPushService || (exports.NewPushService = {}));
//# sourceMappingURL=NewPushService.js.map


text:
/* @flow */
import React, { Component } from 'react';
import {observer} from 'mobx-react';

import CodeMirror from '../CodeMirror';
import InstallInstruction from '../InstallInstruction';

const inputExample = `
/* @flow */
function get (store: Storage, key: string) {
  return store.getItem(key);
}

get(localStorage, 'foo');
`.trim();

const outputExample = `
import t from "flow-runtime";
t.declare(
  t.class(
    "Storage",
    t.object(
      t.property("length", t.number()),
      t.property(
        "getItem",
        t.function(t.param("key", t.string()), t.return(t.nullable(t.string())))
      ),
      t.property(
        "setItem",
        t.function(
          t.param("key", t.string()),
          t.param("data", t.string()),
          t.return(t.void())
        )
      ),
      t.property("clear", t.function(t.return(t.void()))),
      t.property(
        "removeItem",
        t.function(t.param("key", t.string()), t.return(t.void()))
      ),
      t.property(
        "key",
        t.function(
          t.param("index", t.number()),
          t.return(t.nullable(t.string()))
        )
      ),
      t.indexer("name", t.string(), t.nullable(t.string()))
    )
  )
);
`.trim();

@observer
export default class FlowRuntimeCLIPage extends Component {
  render() {
    return (

flow-runtime-cli

                A command line utility for working with flow and flow-runtime.

              {' '}
              flow-runtime-cli on github

What?

Discovers imported and global type dependencies in your source code and produces a single file containing the flow-runtime type definitions for those dependencies.

What?

Let's say you have some code like this:

              <CodeMirror value={inputExample} readOnly />

<samp>Storage</samp> is a global type, built in to Flow, but flow-runtime itself doesn't know anything about it - if you compile this code, flow-runtime will emit a warning about being unable to resolve a type called "Storage".

A possible solution to this would be to include all the type definitions which come with Flow as part of flow-runtime, but this is wasteful - the file would be very large and most definitions would go unused.

To solve this problem, `flow-runtime-cli`:

Crawls your project source code looking for these types.

Discovers the matching type definitions in `flow-typed` or wherever specified by your `.flowconfig` file.

Creates a graph of dependencies and generates the code for only the types you use, this produces a file that looks like this:

              <CodeMirror value={outputExample} readOnly />

You can then import this file once, in your entry point, and flow-runtime will be able to validates values of this type.

Installation

              <InstallInstruction devPackageNames={['flow-runtime-cli']} />

Usage

If your source files are in a folder called <samp>src</samp>, run:

{`flow-runtime generate ./src > ./src/typedefs.js`}

then, in your entry point (e.g. <samp>index.js</samp>) your first import should be:

{`import './typedefs';`}

    );
  }
}


text:
package org.wso2.andes.server.message;

import org.wso2.andes.framing.ContentHeaderBody;
import org.wso2.andes.framing.BasicContentHeaderProperties;
import org.wso2.andes.framing.EncodingUtils;
import org.wso2.andes.framing.AMQShortString;
import org.wso2.andes.framing.FieldTable;
import org.wso2.andes.framing.abstraction.MessagePublishInfo;
import org.wso2.andes.server.store.StorableMessageMetaData;
import org.wso2.andes.server.store.MessageMetaDataType;
import org.wso2.andes.AMQException;

import java.nio.ByteBuffer;
import java.util.Set;

/**
 * Encapsulates a publish body and a content header. In the context of the message store these are treated as a
 * single unit.
 */
public class MessageMetaData implements StorableMessageMetaData
{
    private MessagePublishInfo _messagePublishInfo;

    private ContentHeaderBody _contentHeaderBody;

    private int _contentChunkCount;

    private String _clientIP = "";

    private long _arrivalTime;

    /**
     * Unique publisher's session id to validate whether subscriber and publisher has the same session
     */
    private long publisherSessionID;
    private static final byte MANDATORY_FLAG = 1;
    private static final byte IMMEDIATE_FLAG = 2;
    public static final MessageMetaDataType.Factory<MessageMetaData> FACTORY = new MetaDataFactory();

    public MessageMetaData(MessagePublishInfo publishBody, ContentHeaderBody contentHeaderBody, int contentChunkCount)
    {
        this(publishBody,contentHeaderBody, contentChunkCount, System.currentTimeMillis());
    }

    public MessageMetaData(MessagePublishInfo publishBody, ContentHeaderBody contentHeaderBody, int contentChunkCount, long arrivalTime)
    {
        _contentHeaderBody = contentHeaderBody;
        _messagePublishInfo = publishBody;
        _contentChunkCount = contentChunkCount;
        _arrivalTime = arrivalTime;
    }

    /**
     * This constructor is used to set session id into message meta data
     *
     * @param publishBody       Message publish information
     * @param contentHeaderBody Message content header body
     * @param sessionID         publisher's SessionId
     * @param contentChunkCount content chunk count
     */
    public MessageMetaData(MessagePublishInfo publishBody, ContentHeaderBody contentHeaderBody, long sessionID,
                           int contentChunkCount) {
        this(publishBody, contentHeaderBody, sessionID, contentChunkCount, System.currentTimeMillis());
    }

    public MessageMetaData(MessagePublishInfo publishBody, ContentHeaderBody contentHeaderBody, long sessionID,
                           int contentChunkCount, long arrivalTime) {
        _contentHeaderBody = contentHeaderBody;
        _messagePublishInfo = publishBody;
        _contentChunkCount = contentChunkCount;
        _arrivalTime = arrivalTime;
        publisherSessionID = sessionID;
    }

    public long getPublisherSessionID() {
        return publisherSessionID;
    }

    public void setPublisherSessionID(long publisherSessionID) {
        this.publisherSessionID = publisherSessionID;
    }

    public int getContentChunkCount()
    {
        return _contentChunkCount;
    }

    public void setContentChunkCount(int contentChunkCount)
    {
        _contentChunkCount = contentChunkCount;
    }

    public ContentHeaderBody getContentHeaderBody()
    {
        return _contentHeaderBody;
    }

    public void setContentHeaderBody(ContentHeaderBody contentHeaderBody)
    {
        _contentHeaderBody = contentHeaderBody;
    }

    public MessagePublishInfo getMessagePublishInfo()
    {
        return _messagePublishInfo;
    }

    public void setMessagePublishInfo(MessagePublishInfo messagePublishInfo)
    {
        _messagePublishInfo = messagePublishInfo;
    }

    public long getArrivalTime()
    {
        return _arrivalTime;
    }

    public void setArrivalTime(long arrivalTime)
    {
        _arrivalTime = arrivalTime;
    }

    public MessageMetaDataType getType()
    {
        return MessageMetaDataType.META_DATA_0_8;
    }

    public int getStorableSize()
    {
        int size = _contentHeaderBody.getSize();
        size += 4;
        size += EncodingUtils.encodedShortStringLength(_messagePublishInfo.getExchange());
        size += EncodingUtils.encodedShortStringLength(_messagePublishInfo.getRoutingKey());
        size += 1; // flags for immediate/mandatory
        size += EncodingUtils.encodedLongLength(); // for sessionID
        size += EncodingUtils.encodedLongLength();

        return size;
    }

    public int writeToBuffer(int offset, ByteBuffer dest)
    {
        ByteBuffer src = ByteBuffer.allocate((int)getStorableSize());

        org.apache.mina.common.ByteBuffer minaSrc = org.apache.mina.common.ByteBuffer.wrap(src);
        EncodingUtils.writeInteger(minaSrc, _contentHeaderBody.getSize());
        _contentHeaderBody.writePayload(minaSrc);
        EncodingUtils.writeShortStringBytes(minaSrc, _messagePublishInfo.getExchange());
        EncodingUtils.writeShortStringBytes(minaSrc, _messagePublishInfo.getRoutingKey());
        byte flags = 0;
        if(_messagePublishInfo.isMandatory())
        {
            flags |= MANDATORY_FLAG;
        }
        if(_messagePublishInfo.isImmediate())
        {
            flags |= IMMEDIATE_FLAG;
        }
        EncodingUtils.writeByte(minaSrc, flags);
        EncodingUtils.writeLong(minaSrc, publisherSessionID);
        EncodingUtils.writeLong(minaSrc, _arrivalTime);
        src.position(minaSrc.position());
        src.flip();
        src.position(offset);
        src = src.slice();
        if(dest.remaining() < src.limit())
        {
            src.limit(dest.remaining());
        }
        dest.put(src);

        return src.limit();
    }

    public int getContentSize()
    {
        return (int) _contentHeaderBody.bodySize;
    }

    public boolean isPersistent()
    {
        BasicContentHeaderProperties properties = (BasicContentHeaderProperties) (_contentHeaderBody.getProperties());
        return properties.getDeliveryMode() ==  BasicContentHeaderProperties.PERSISTENT;
    }

    public String get_clientIP() {
        return _clientIP;
    }

    public void set_clientIP(String _clientIP) {
        this._clientIP = _clientIP;
    }

    private static class MetaDataFactory implements MessageMetaDataType.Factory
    {

        public MessageMetaData createMetaData(ByteBuffer buf)
        {
            try
            {
                org.apache.mina.common.ByteBuffer minaSrc = org.apache.mina.common.ByteBuffer.wrap(buf);
                int size = EncodingUtils.readInteger(minaSrc);
                ContentHeaderBody chb = ContentHeaderBody.createFromBuffer(minaSrc, size);
                final AMQShortString exchange = EncodingUtils.readAMQShortString(minaSrc);
                final AMQShortString routingKey = EncodingUtils.readAMQShortString(minaSrc);

                final byte flags = EncodingUtils.readByte(minaSrc);
                long sessionID = EncodingUtils.readLong(minaSrc);
                long arrivalTime = EncodingUtils.readLong(minaSrc);

                MessagePublishInfo publishBody =
                        new MessagePublishInfo()
                        {

                            public AMQShortString getExchange()
                            {
                                return exchange;
                            }

                            public void setExchange(AMQShortString exchange)
                            {
                            }

                            @Override
                            public void setRoutingKey(AMQShortString routingKey) {

                            }

                            public boolean isImmediate()
                            {
                                return (flags & IMMEDIATE_FLAG) != 0;
                            }

                            public boolean isMandatory()
                            {
                                return (flags & MANDATORY_FLAG) != 0;
                            }

                            public AMQShortString getRoutingKey()
                            {
                                return routingKey;
                            }
                        };
                return new MessageMetaData(publishBody, chb, sessionID, 0, arrivalTime);
            }
            catch (AMQException e)
            {
                throw new RuntimeException(e);
            }

        }
    };

    public AMQMessageHeader getMessageHeader()
    {
        return new MessageHeaderAdapter();
    }

    private final class MessageHeaderAdapter implements AMQMessageHeader
    {
        private BasicContentHeaderProperties getProperties()
        {
            return (BasicContentHeaderProperties) getContentHeaderBody().getProperties();
        }

        public String getCorrelationId()
        {
            return getProperties().getCorrelationIdAsString();
        }

        public long getExpiration()
        {
            return getProperties().getExpiration();
        }

        public String getMessageId()
        {
            return getProperties().getMessageIdAsString();
        }

        public String getMimeType()
        {
            return getProperties().getContentTypeAsString();
        }

        public String getEncoding()
        {
            return getProperties().getEncodingAsString();
        }

        public byte getPriority()
        {
            return getProperties().getPriority();
        }

        public long getTimestamp()
        {
            return getProperties().getTimestamp();
        }

        public String getType()
        {
            return getProperties().getTypeAsString();
        }

        public String getReplyTo()
        {
            return getProperties().getReplyToAsString();
        }

        public String getReplyToExchange()
        {
            // TODO
            return getReplyTo();
        }

        public String getReplyToRoutingKey()
        {
            // TODO
            return getReplyTo();
        }

        public Object getHeader(String name)
        {
            FieldTable ft = getProperties().getHeaders();
            return ft.get(name);
        }

        public boolean containsHeaders(Set<String> names)
        {
            FieldTable ft = getProperties().getHeaders();
            for(String name : names)
            {
                if(!ft.containsKey(name))
                {
                    return false;
                }
            }
            return true;
        }

        public boolean containsHeader(String name)
        {
            FieldTable ft = getProperties().getHeaders();
            return ft.containsKey(name);
        }

    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />

    <title>Test</title>
    <meta name="description" content="" />

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

    <link rel="shortcut icon" href="https://filiplaz.github.io/favicon.ico">

    <link rel="stylesheet" type="text/css" href="//filiplaz.github.io/themes/casper/assets/css/screen.css?v=1468600265307" />
    <link rel="stylesheet" type="text/css" href="//fonts.googleapis.com/css?family=Merriweather:300,700,700italic,300italic|Open+Sans:700,400" />

    <link rel="canonical" href="https://filiplaz.github.io/2015/01/31/Test.html" />
    <meta name="referrer" content="origin" />

    <meta property="og:type" content="website" />
    <meta property="og:title" content="Test" />
    <meta property="og:url" content="https://filiplaz.github.io/2015/01/31/Test.html" />
    <meta name="twitter:card" content="summary" />
    <meta name="twitter:title" content="Test" />
    <meta name="twitter:url" content="https://filiplaz.github.io/2015/01/31/Test.html" />

    <meta name="generator" content="HubPress" />
    <link rel="alternate" type="application/rss+xml" title="" href="https://filiplaz.github.io/rss/" />

Test

                <time class="post-date" datetime="2015-01-31">31 January 2015</time>

                Filip Lazarevic's Picture

Filip Lazarevic

Read more posts by this author.

Share this post

                    Twitter

                    Facebook

                    Google+

 © 2016

Proudly published with HubPress


text:
SPHINXOPTS    =
SPHINXBUILD   = sphinx-build
PAPER         =
BUILDDIR      = build

# Internal variables.
PAPEROPT_a4     = -D latex_paper_size=a4
PAPEROPT_letter = -D latex_paper_size=letter
ALLSPHINXOPTS   = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source

.PHONY: help clean html dirhtml pickle json htmlhelp qthelp latex changes linkcheck doctest

help:
	@echo "Please use \`make <target>' where <target> is one of"
	@echo "  html      to make standalone HTML files"
	@echo "  dirhtml   to make HTML files named index.html in directories"
	@echo "  pickle    to make pickle files"
	@echo "  json      to make JSON files"
	@echo "  htmlhelp  to make HTML files and a HTML help project"
	@echo "  qthelp    to make HTML files and a qthelp project"
	@echo "  latex     to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
	@echo "  changes   to make an overview of all changed/added/deprecated items"
	@echo "  linkcheck to check all external links for integrity"
	@echo "  doctest   to run all doctests embedded in the documentation (if enabled)"

clean:
	-rm -rf $(BUILDDIR)/*

html:
	make -f MakefileMayavi html
	@echo
	make -f MakefileTVTK html
	@echo
	@echo "Build finished. The HTML pages are in $(BUILDDIR)/."

dirhtml:
	make -f MakefileMayavi dirhtml
	@echo
	make -f MakefileTVTK dirhtml
	@echo
	@echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."

pickle:
	make -f MakefileMayavi pickle
	@echo
	make -f MakefileTVTK pickle
	@echo
	@echo "Build finished; now you can process the pickle files."

json:
	make -f MakefileMayavi json
	@echo
	make -f MakefileTVTK json
	@echo
	@echo "Build finished; now you can process the JSON files."

htmlhelp:
	make -f MakefileMayavi htmlhelp
	@echo
	make -f MakefileTVTK htmlhelp
	@echo
	@echo "Build finished; now you can run HTML Help Workshop with the" \
	      ".hhp project file in $(BUILDDIR)/htmlhelp."

qthelp:
	make -f MakefileMayavi qthelp
	@echo
	make -f MakefileTVTK qthelp
	@echo
	@echo "Build finished; now you can run "qcollectiongenerator" with the" \
	      ".qhcp project file in $(BUILDDIR)/qthelp, like this:"
	@echo "# qcollectiongenerator $(BUILDDIR)/mayavi/qthelp/mayavi.qhcp"
	@echo "To view the help file:"
	@echo "# assistant -collectionFile $(BUILDDIR)/mayavi/qthelp/mayavi.qhc"

latex:
	make -f MakefileMayavi latex
	@echo
	make -f MakefileTVTK latex
	@echo
	@echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
	@echo "Run \`make all-pdf' or \`make all-ps' in that directory to" \
	      "run these through (pdf)latex."

changes:
	make -f MakefileMayavi changes
	@echo
	make -f MakefileTVTK changes
	@echo
	@echo "The overview file is in $(BUILDDIR)/changes."

linkcheck:
	make -f MakefileMayavi linkcheck
	@echo
	make -f MakefileTVTK linkcheck
	@echo
	@echo "Link check complete; look for any errors in the above output " \
	      "or in $(BUILDDIR)/linkcheck/output.txt."

doctest:
	make -f MakefileMayavi doctest
	@echo
	make -f MakefileTVTK doctest
	@echo
	@echo "Testing of doctests in the sources finished, look at the " \
	      "results in $(BUILDDIR)/doctest/output.txt."


text:
package il.co.All4Students.homemovies.util.imageWeb;

import static il.co.All4Students.homemovies.app.AppConstants.LOG_TAG_ImageLoader;
import il.co.All4Students.homemovies.R;
import il.co.All4Students.homemovies.util.log.util.AppLog;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Collections;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.ImageView;

/**
 *
 * @author Arkadi Yoskovitz
 * @date 2013-02-08
 */
public class ImageLoader {

	// Attributes
	MemoryCache memoryCache = new MemoryCache();
	FileCache fileCache;
	private Map<ImageView, String> imageViews = Collections
			.synchronizedMap(new WeakHashMap<ImageView, String>());
	final int stub_id = R.drawable.ic_list_placeholder;
	ExecutorService executorService;
	private Context mContext;

	// Constractors
	public ImageLoader(Context context) {
		fileCache = new FileCache(context);
		this.mContext = context;
		executorService = Executors.newFixedThreadPool(5);
	}

	// Inner Classes
	private class PhotoToLoad {
		public String url;
		public ImageView imageView;

		public PhotoToLoad(String u, ImageView i) {
			url = u;
			imageView = i;
		}
	}

	class PhotosLoader implements Runnable {
		PhotoToLoad photoToLoad;

		PhotosLoader(PhotoToLoad photoToLoad) {
			this.photoToLoad = photoToLoad;
		}

		@Override
		public void run() {
			if (imageViewReused(photoToLoad)) {
				return;
			}
			Bitmap bmp = getBitmap(photoToLoad.url);
			memoryCache.put(photoToLoad.url, bmp);
			if (imageViewReused(photoToLoad)) {
				return;
			}
			BitmapDisplayer bd = new BitmapDisplayer(bmp, photoToLoad);
			Activity activity = (Activity) photoToLoad.imageView.getContext();
			activity.runOnUiThread(bd);
		}
	}

	class BitmapDisplayer implements Runnable {
		Bitmap bitmap;
		PhotoToLoad photoToLoad;

		public BitmapDisplayer(Bitmap b, PhotoToLoad p) {
			bitmap = b;
			photoToLoad = p;
		}

		public void run() {
			if (imageViewReused(photoToLoad)) {
				return;
			}
			if (bitmap != null) {
				photoToLoad.imageView.setImageBitmap(bitmap);
			} else {
				photoToLoad.imageView.setImageResource(stub_id);
			}
		}
	}

	// Additional Methods

	public void DisplayImage(String url, ImageView imageView) {
		imageViews.put(imageView, url);
		Bitmap bitmap = memoryCache.get(url);
		if (bitmap != null) {
			imageView.setImageBitmap(bitmap);
		} else {
			queuePhoto(url, imageView);
			imageView.setImageResource(stub_id);
		}
	}

	private void queuePhoto(String url, ImageView imageView) {
		PhotoToLoad p = new PhotoToLoad(url, imageView);
		executorService.submit(new PhotosLoader(p));
	}

	private Bitmap getBitmap(String url) {
		File f = fileCache.getFile(url);

		// from SD cache
		Bitmap b = decodeFile(f);
		if (b != null) {
			return b;
		}

		// from web
		try {
			Bitmap bitmap = null;
			URL imageUrl = new URL(url);
			HttpURLConnection conn = (HttpURLConnection) imageUrl
					.openConnection();
			conn.setConnectTimeout(30000);
			conn.setReadTimeout(30000);
			conn.setInstanceFollowRedirects(true);
			InputStream is = conn.getInputStream();
			OutputStream os = new FileOutputStream(f);

			final int buffer_size = 1024;
			try {
				byte[] bytes = new byte[buffer_size];
				for (;;) {
					int count = is.read(bytes, 0, buffer_size);
					if (count == -1)
						break;
					os.write(bytes, 0, count);
				}
			} catch (Exception ex) {
				ex.printStackTrace();
			} finally {
				os.close();
				bitmap = decodeFile(f);
			}
			return bitmap;
		} catch (Throwable ex) {
			ex.printStackTrace();
			if (ex instanceof OutOfMemoryError) {
				memoryCache.clear();
			}
			return null;
		}
	}

	private Bitmap decodeFile(File f) {
		try {
			// decode image size
			BitmapFactory.Options options = new BitmapFactory.Options();
			options.inJustDecodeBounds = true;
			BitmapFactory.decodeStream(new FileInputStream(f), null, options);

			// Find the correct scale value. It should be the power of 2.
			final int REQUIRED_SIZE = 70;
			int width_tmp = options.outWidth, height_tmp = options.outHeight;
			int scale = 1;
			while (true) {
				if (width_tmp / 2 < REQUIRED_SIZE
						|| height_tmp / 2 < REQUIRED_SIZE) {
					break;
				}
				width_tmp /= 2;
				height_tmp /= 2;
				scale *= 2;
			}

			// decode with inSampleSize
			BitmapFactory.Options o2 = new BitmapFactory.Options();
			o2.inSampleSize = scale;
			return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
		} catch (FileNotFoundException e) {
			AppLog.log(mContext, LOG_TAG_ImageLoader, e.getMessage());
		}
		return null;
	}

	boolean imageViewReused(PhotoToLoad photoToLoad) {
		String tag = imageViews.get(photoToLoad.imageView);
		if (tag == null || !tag.equals(photoToLoad.url)) {
			return true;
		}
		return false;
	}

	public void clearCache() {
		memoryCache.clear();
		fileCache.clear();
	}
}


text:
package org.topcat.store.utils;

import java.util.Locale;

import org.springframework.web.servlet.View;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.view.json.MappingJacksonJsonView;

/**
 * View resolver for returning JSON in a view-based system. Always returns a
 * {@link MappingJacksonJsonView}.
 */
public class JsonViewResolver implements ViewResolver {

	/**
	 * Get the view to use.
	 *
	 * @return Always returns an instance of {@link MappingJacksonJsonView}.
	 */
	@Override
	public View resolveViewName(String viewName, Locale locale)
			throws Exception {
		MappingJacksonJsonView view = new MappingJacksonJsonView();
		view.setPrettyPrint(true);
		return view;
	}

}


text:
package flickr.demo.qvdev.com.flickrdemo.detail;

import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.drawee.view.SimpleDraweeView;

import flickr.demo.qvdev.com.flickrdemo.R;
import flickr.demo.qvdev.com.flickrdemo.model.PhotoDetail;
import flickr.demo.qvdev.com.flickrdemo.network.FlickrApiAdapter;
import flickr.demo.qvdev.com.flickrdemo.search.FlickrItemListActivity;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * A fragment representing a single FlickrItem detail screen.
 * This fragment is either contained in a {@link FlickrItemListActivity}
 * in two-pane mode (on tablets) or a {@link FlickrItemDetailActivity}
 * on handsets.
 */
public class FlickrItemDetailFragment extends Fragment {

    public static final String ARG_ITEM_ID = "item_id";
    public static final String ARG_ITEM_MEDIUM_URL = "item_medium_url";
    private static final String PHOTO_DETAILS = "photo_details";
    private static final String PHOTO_TITLE = "photo_title";

    private SimpleDraweeView mImageView;
    private TextView mPhotoDetails;
    private String mMediumUrl;
    private String mTitle;

    /**
     * Mandatory empty constructor for the fragment manager to instantiate the
     * fragment (e.g. upon screen orientation changes).
     */
    public FlickrItemDetailFragment() {
        // ;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (getArguments().containsKey(ARG_ITEM_ID) && getArguments().containsKey(ARG_ITEM_MEDIUM_URL)) {
            String itemId = getArguments().getString(ARG_ITEM_ID);
            mMediumUrl = getArguments().getString(ARG_ITEM_MEDIUM_URL);
            if (savedInstanceState == null) {
                loadPhotoDetails(itemId);
            }
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        outState.putString(PHOTO_DETAILS, mPhotoDetails.getText().toString());
        outState.putString(PHOTO_TITLE, mTitle);
        super.onSaveInstanceState(outState);
    }

    @Override
    public void onViewStateRestored(@Nullable Bundle savedInstanceState) {
        super.onViewStateRestored(savedInstanceState);
        if (savedInstanceState != null) {
            mPhotoDetails.setText(savedInstanceState.getString(PHOTO_DETAILS));
            itemDetailsLoaded(savedInstanceState.getString(PHOTO_TITLE));
        }
    }

    private void loadImageUrl() {
        Uri uri = Uri.parse(mMediumUrl);
        mImageView.setImageURI(uri);
    }

    private void loadPhotoDetails(String photoId) {
        final FlickrApiAdapter flickrApiAdapter = new FlickrApiAdapter();
        final Observable<PhotoDetail> photo = flickrApiAdapter.getPhotoDetails(photoId);

        photo.subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .unsafeSubscribe(new Subscriber<PhotoDetail>() {
                    @Override
                    public void onCompleted() {
                        // ;
                    }

                    @Override
                    public void onError(Throwable e) {
                        if (isVisible()) {
                            Toast.makeText(getContext(), R.string.error_message, Toast.LENGTH_LONG).show();
                        }
                    }

                    @Override
                    public void onNext(PhotoDetail photoDetail) {
                        if (isVisible()) {
                            itemDetailsLoaded(photoDetail.getPhoto().getTitle().get_content());
                            loadPhotoDetails(photoDetail);
                        }
                    }
                });
    }

    private void loadPhotoDetails(PhotoDetail photo) {
        String date = photo.getPhoto().getDateuploaded();
        String description = photo.getPhoto().getDescription().get_content();

        mPhotoDetails.setText(getString(R.string.photo_views, date, description));
    }

    private void itemDetailsLoaded(final String title) {
        Activity activity = this.getActivity();
        if (activity != null) {
            CollapsingToolbarLayout appBarLayout = (CollapsingToolbarLayout) activity.findViewById(R.id.toolbar_layout);
            if (appBarLayout != null) {
                mTitle = title;
                appBarLayout.setTitle(title);
            }
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.flickritem_detail, container, false);

        mImageView = (SimpleDraweeView) rootView.findViewById(R.id.medium_image);
        loadImageUrl();
        mPhotoDetails = (TextView) rootView.findViewById(R.id.photo_details);

        return rootView;
    }
}


text:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const sequences = {};
const DEFAULTS = {
    timestamp: () => () => Date.now(),
    datetime: () => () => new Date().toISOString(),
    date: () => () => new Date().toISOString().slice(0, 10),
    time: () => () => new Date().toISOString().slice(11),
    random: () => () => Math.random(),
    randomint: (args) => {
        var _a;
        const max = (_a = args === null || args === void 0 ? void 0 : args.max) !== null && _a !== void 0 ? _a : 2;
        return () => Math.floor(Math.random() * max);
    },
    seq: (args) => {
        var _a;
        const name = (_a = args === null || args === void 0 ? void 0 : args.name) !== null && _a !== void 0 ? _a : "";
        sequences[name] || (sequences[name] = 0);
        return () => sequences[name]++;
    },
};
const getDef = Object.assign(_getDef, { DEFAULTS });
function _getDef() {
    return {
        keyword: "dynamicDefaults",
        type: "object",
        schemaType: ["string", "object"],
        modifying: true,
        valid: true,
        compile(schema, _parentSchema, it) {
            if (!it.opts.useDefaults || it.compositeRule)
                return () => true;
            const fs = {};
            for (const key in schema)
                fs[key] = getDefault(schema[key]);
            const empty = it.opts.useDefaults === "empty";
            return (data) => {
                for (const prop in schema) {
                    if (data[prop] === undefined || (empty && (data[prop] === null || data[prop] === ""))) {
                        data[prop] = fs[prop]();
                    }
                }
                return true;
            };
        },
        metaSchema: {
            type: "object",
            additionalProperties: {
                anyOf: [
                    { type: "string" },
                    {
                        type: "object",
                        additionalProperties: false,
                        required: ["func", "args"],
                        properties: {
                            func: { type: "string" },
                            args: { type: "object" },
                        },
                    },
                ],
            },
        },
    };
}
function getDefault(d) {
    return typeof d == "object" ? getObjDefault(d) : getStrDefault(d);
}
function getObjDefault({ func, args }) {
    const def = DEFAULTS[func];
    assertDefined(func, def);
    return def(args);
}
function getStrDefault(d = "") {
    const def = DEFAULTS[d];
    assertDefined(d, def);
    return def();
}
function assertDefined(name, def) {
    if (!def)
        throw new Error(`invalid "dynamicDefaults" keyword property value: ${name}`);
}
exports.default = getDef;
module.exports = getDef;
//# sourceMappingURL=dynamicDefaults.js.map