text:
//
//  MLFile.h
//  MaxLeap
//

#ifdef EXTENSION_IOS
    #import <MaxLeapExt/MLConstants.h>
#else
    #import <MaxLeap/MLConstants.h>
#endif

NS_ASSUME_NONNULL_BEGIN

/*!
 A file of binary data stored on the MaxLeap servers. This can be a image, video, or anything else
 that an application needs to reference in a non-relational way.
 */
@interface MLFile : NSObject <NSSecureCoding>

/** @name Creating a MLFile */

- (instancetype)init NS_UNAVAILABLE;

/*!
 Creates a file with given data. A name will be assigned to it by the server.
 @param data The contents of the new MLFile.
 @result A MLFile.
 */
+ (instancetype)fileWithData:(NSData *)data;

/*!
 Creates a file with given data and name.
 @param name The name of the new MLFile.
 @param data The contents of hte new MLFile.
 @result A MLFile.
 */
+ (instancetype)fileWithName:(nullable NSString *)name data:(NSData *)data;

/*!
 Creates a file with the contents of another file.
 @param name The name of the new MLFile
 @param path The path to the file that will be uploaded to MaxLeap
 */
+ (instancetype)fileWithName:(nullable NSString *)name contentsAtPath:(NSString *)path;

/**
 Create a file with url.

 @param url The url

 @return A MLFile object.
 */
+ (instancetype)fileWithUrl:(NSString *)url;

/*!
 The name of the file.
 */
@property (readonly, copy, nullable) NSString *name;

/*!
 The url of the file.
 */
@property (readonly, copy, nullable) NSString *url;

@property (readonly) long long size;

/*!
 Whether the file has been uploaded for the first time.
 */
@property (readonly) BOOL isDirty;

/*!
 Whether the data is available in memory or needs to be downloaded.
 */
@property (readonly) BOOL isDataAvailable;

#pragma mark -
///--------------------------------------
/// @name Storing Data with MaxLeap
///--------------------------------------

/*!
 Saves the file asynchronously and executes the given block.

 @param block   The block should have the following argument signature: (BOOL succeeded, NSError *error)
 */
- (void)saveInBackgroundWithBlock:(nullable MLBooleanResultBlock)block;

/*!
 Saves the file asynchronously and executes the given resultBlock. Executes the progressBlock periodically with the percent
 progress. progressBlock will get called with 100 before resultBlock is called.

 @param block   The block should have the following argument signature: (BOOL succeeded, NSError *error)
 @param progressBlock The block should have the following argument signature: (int percentDone)
 */
- (void)saveInBackgroundWithBlock:(nullable MLBooleanResultBlock)block progressBlock:(nullable MLProgressBlock)progressBlock;

#pragma mark -
///--------------------------------------
/// @name Getting Data from MaxLeap
///--------------------------------------

/*!
 Synchronously gets the data from cache if available or fetches its contents from the MaxLeap servers. Sets an error if it occurs.

 @param error   Pointer to an NSError that will be set if necessary.
 @result The data of file. Returns nil if there was an error in fetching.
 */
- (nullable NSData *)getData:(NSError  * __nullable * __nullable)error;

/*!
 Asynchronously gets the data from cache if available or fetches its contents
 from the MaxLeap servers. Executes the given block.

 @param block   The block should have the following argument signature: (NSData *result, NSError *error)
 */
- (void)getDataInBackgroundWithBlock:(nullable MLDataResultBlock)block;

/*!
 This method is like getDataInBackgroundWithBlock: but avoids ever holding the
 entire MLFile's contents in memory at once. This can help applications with
 many large MLFiles avoid memory warnings.

 @param block   The block should have the following argument signature: (NSInputStream *result, NSError *error)
 */
- (void)getDataStreamInBackgroundWithBlock:(nullable MLDataStreamResultBlock)block;

/*!
 Asynchronously gets the data from cache if available or fetches its contents
 from the MaxLeap servers. Executes the resultBlock upon
 completion or error. Executes the progressBlock periodically with the percent progress. progressBlock will get called with 100 before resultBlock is called.

 @param resultBlock     The block should have the following argument signature: (NSData *result, NSError *error)
 @param progressBlock   The block should have the following argument signature: (int percentDone)
 */
- (void)getDataInBackgroundWithBlock:(nullable MLDataResultBlock)resultBlock progressBlock:(nullable MLProgressBlock)progressBlock;

/*!
 This method is like getDataInBackgroundWithBlock:progressBlock: but avoids ever
 holding the entire MLFile's contents in memory at once. This can help
 applications with many large MLFiles avoid memory warnings.

 @param resultBlock     The block should have the following argument signature: (NSInputStream *result, NSError *error)
 @param progressBlock   The block should have the following argument signature: (int percentDone)
 */
- (void)getDataStreamInBackgroundWithBlock:(nullable MLDataStreamResultBlock)resultBlock progressBlock:(nullable MLProgressBlock)progressBlock;

#pragma mark -
///--------------------------------------
/// @name Interrupting a Transfer
///--------------------------------------

/*!
 Cancels the current request (whether upload or download of file data).
 */
- (void)cancel;

#pragma mark -
///--------------------------------------
/// @name Other Methods
///--------------------------------------

/*!
 Get file with specified name.

 @param name    The name of a file.
 @param block   The block will execute on main thread.
 */
+ (void)getFileInBackgroundWithName:(NSString *)name block:(nullable MLFileResultBlock)block;

/*!
 Get all files uploaded by current user.

 @param block The callback, will be executed on main thread. The block should have the following argument signature: (NSArray<MLFile *> *files, NSError *error).
 */
+ (void)getAllInBackgroundWithBlock:(nullable MLArrayResultBlock)block;

@end

NS_ASSUME_NONNULL_END


text:
package com.amazonaws.services.mediatailor.model.transform;

import java.util.Map;
import java.util.List;
import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.services.mediatailor.model.*;

import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;

/**
 * CreateLiveSourceRequestMarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class CreateLiveSourceRequestMarshaller {

    private static final MarshallingInfo<List> HTTPPACKAGECONFIGURATIONS_BINDING = MarshallingInfo.builder(MarshallingType.LIST)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("HttpPackageConfigurations").build();
    private static final MarshallingInfo<String> LIVESOURCENAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PATH).marshallLocationName("LiveSourceName").build();
    private static final MarshallingInfo<String> SOURCELOCATIONNAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PATH).marshallLocationName("SourceLocationName").build();
    private static final MarshallingInfo<Map> TAGS_BINDING = MarshallingInfo.builder(MarshallingType.MAP).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("tags").build();

    private static final CreateLiveSourceRequestMarshaller instance = new CreateLiveSourceRequestMarshaller();

    public static CreateLiveSourceRequestMarshaller getInstance() {
        return instance;
    }

    /**
     * Marshall the given parameter object.
     */
    public void marshall(CreateLiveSourceRequest createLiveSourceRequest, ProtocolMarshaller protocolMarshaller) {

        if (createLiveSourceRequest == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(createLiveSourceRequest.getHttpPackageConfigurations(), HTTPPACKAGECONFIGURATIONS_BINDING);
            protocolMarshaller.marshall(createLiveSourceRequest.getLiveSourceName(), LIVESOURCENAME_BINDING);
            protocolMarshaller.marshall(createLiveSourceRequest.getSourceLocationName(), SOURCELOCATIONNAME_BINDING);
            protocolMarshaller.marshall(createLiveSourceRequest.getTags(), TAGS_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

}

redpajama_set_name: RedPajamaGithub


text:
<html>
<body>
                This inspection reports any @GuardedBy annotations (net.jcip.annotations|javax.annotation.concurrent|org.apache.http.annotation) on static fields or methods,
                where the guard is either a non-static field or 'this'. Guarding a static by a non-static may result in
                excessive concurrency, multiple threads may be able to access the guarded field simultaneously, by locking in different object contexts.
</body>
</html>


text:
description: Deploying to Kubernetes on Docker Desktop
keywords: deploy, kubernetes, kubectl, orchestration
title: Deploy on Kubernetes
redirect_from:
- /docker-for-windows/kubernetes/
- /docker-for-mac/kubernetes/
---

Docker Desktop includes a standalone Kubernetes server and client,
as well as Docker CLI integration that runs on your machine.

The Kubernetes server runs locally within your Docker instance, is not configurable, and is a single-node cluster. It runs within a Docker container on your local system, and
is only for local testing.

Enabling Kubernetes allows you to deploy
your workloads in parallel, on Kubernetes, Swarm, and as standalone containers. Enabling or disabling the Kubernetes server does not affect your other
workloads.

## Enable Kubernetes

To enable Kubernetes in Docker Desktop:
1. From the Docker Dashboard, select the **Setting** icon, or **Preferences** icon if you use a macOS.
2. Select **Kubernetes** from the left sidebar.
3. Next to **Enable Kubernetes**, select the checkbox.
4. Select **Apply & Restart** to save the settings and then click **Install** to confirm. This instantiates images required to run the Kubernetes server as containers, and installs the `/usr/local/bin/kubectl` command on your machine.

By default, Kubernetes containers are hidden from commands like `docker ps`, because managing them manually is not supported. Most users do not need this option. To see these internal containers, select **Show system containers (advanced)**.

When Kubernetes is enabled and running, an additional status bar in the Dashboard footer and Docker menu displays.

> Note
>
> Docker Desktop does not upgrade your Kubernetes cluster automatically after a new update. To upgrade your Kubernetes cluster to the latest version, select **Reset Kubernetes Cluster**.

## Use the kubectl command

Kubernetes integration provides the Kubernetes CLI command
at `/usr/local/bin/kubectl` on Mac and at `C:\>Program Files\Docker\Docker\Resources\bin\kubectl.exe` on Windows. This location may not be in your shell's `PATH`
variable, so you may need to type the full path of the command or add it to
the `PATH`.

The kubectl binary is not automatically packaged with Docker Desktop for Linux. To install the kubectl command for Linux, see [Kubernetes documentation](https://kubernetes.io/docs/tasks/tools/install-kubectl-linux/){:target="_blank" rel="noopener" class="_"}. It should be installed at `/usr/local/bin/kubectl`.

If you have already installed `kubectl` and it is
pointing to some other environment, such as `minikube` or a GKE cluster, ensure you change the context so that `kubectl` is pointing to `docker-desktop`:

```console
$ kubectl config get-contexts
$ kubectl config use-context docker-desktop
```

>Note
>
> Run the `kubectl` command in a CMD or PowerShell terminal, otherwise `kubectl config get-contexts` may return an empty result.
>
>If you are using a different terminal and this happens, you can try setting the `kubeconfig` environment variable to the location of the `.kube/config` file.

If you installed `kubectl` using Homebrew, or by some other method, and
experience conflicts, remove `/usr/local/bin/kubectl`.

You can test the command by listing the available nodes:

```console
$ kubectl get nodes

NAME                 STATUS    ROLES     AGE       VERSION
docker-desktop       Ready     master    3h        v1.19.7
```

For more information about `kubectl`, see the
[`kubectl` documentation](https://kubernetes.io/docs/reference/kubectl/overview/){:target="_blank" rel="noopener" class="_"}.

## Disable Kubernetes

To disable Kubernetes in Docker Desktop:
1. From the Docker Dashboard, select the **Setting** icon, or **Preferences** icon if you use a macOS.
2. Select **Kubernetes** from the left sidebar.
3. Next to **Enable Kubernetes**, clear the checkbox
4. Select **Apply & Restart** to save the settings.This stops and removes Kubernetes containers, and also removes the `/usr/local/bin/kubectl` command.


text:
define({
	root: ({
		viewer: {
			common: {
				close: "Close"
			},
			loading: {
				long: "Application is initializing",
				long2: "Thanks for waiting",
				failButton: "Reload the application"
			},
			signin: {
				title: "Authentication is required",
				explainViewer: "Please sign in with an account on %PORTAL_LINK% to access the application.",
				explainBuilder: "Please sign in with an account on %PORTAL_LINK% to configure the application."
			},
			errors: {
				boxTitle: "An error has occurred",
				invalidConfig: "Invalid configuration",
				invalidConfigNoApp: "Web Mapping Application identifier not specified in index.html.",
				invalidConfigNoAppDev: "No Web Mapping Application identifier is specified in URL parameters (?appid=). In development mode, the appid configuration in index.html is ignored.",
				unspecifiedConfigOwner: "Authorized owner hasn't been configured.",
				invalidConfigOwner: "Story owner is not authorized.",
				createMap: "Unable to create map",
				invalidApp: "The %TPL_NAME% does not exist or is inaccessible.",
				appLoadingFail: "Something went wrong, the %TPL_NAME% did not load correctly.",
				notConfiguredDesktop: "The story is not configured yet.",
				notConfiguredMobile: "The %TPL_NAME% builder is not supported at this display size. If possible, resize your browser to access the builder or please build your story on a device with a larger screen.",
				notConfiguredMobile2: "Please rotate your device to landscape orientation to use the %TPL_NAME% builder.",
				notAuthorized: "You are not authorized to access this story",
				notAuthorizedBuilder: "You are not authorized to use %TPL_NAME% builder.",
				noBuilderIE: "The builder is not supported on Internet Explorer before version %VERSION%. %UPGRADE%",
				noViewerIE: "This story is not supported in Internet Explorer before version %VERSION%. %UPGRADE%",
				noViewerIE2: "You are attempting to view this story using an older, unsupported browser. There may be features that do not work or other unexpected issues. We suggest you upgrade to Internet Explorer 11 or use another browser, such as Chrome.",
				noViewerIE3: "In late 2017, this story will no longer load on this browser. At that time, you must use a supported browser to view this story.",
				upgradeBrowser: "Please update your browser.",
				mapLoadingFail: "Something went wrong, the map did not load correctly.",
				signOut: "Sign Out",
				attention: "Attention!",
				noBuilderEdge: "Story Map Shortlists can be viewed in any web browser. However the Story Map Shortlist Builder is not supported on Windows Edge. Please use a different web browser to create or edit a Shortlist.",
				noBuilderAllIE: "Story Map Shortlists can be viewed in any web browser. However the Story Map Shortlist Builder is not supported on Microsoft Edge or Internet Explorer. Please use a different web browser to create or edit a Shortlist."
			},
			headerFromCommon: {
				storymapsText: "A Story Map",
				builderButton: "Edit",
				facebookTooltip: "Share on Facebook",
				twitterTooltip: "Share on Twitter",
				bitlyTooltip: "Get a short link",
				templateTitle: "Set template title",
				templateSubtitle: "Set template subtitle",
				share: "Share"
			},
			shareFromCommon: {
				copy: "Copy",
				copied: "Copied",
				open: "Open",
				embed: "Embed in web page",
				embedExplain: "Use the following HTML code to embed the application in a web page.",
				size: "Size (width/height):",
				autoplayLabel: "Autoplay mode",
				autoplayExplain1: "Autoplay mode will advance through your story at a regular interval. This is ideal on a kiosk or public display monitor, but be aware that in other situations it may make the story harder to read. This feature isn't supported on small displays.",
				autoplayExplain2: "When this mode is active there are controls to play/pause the story and adjust the navigation speed."
			},
			general: {
				noPlaces: "No places are in this area.  Zoom out or click the Home button to see places.",
				start: "Start"
			}
		}
	}),
	"ar": 1,
	"bs": 1,
	"ca": 1,
	"cs": 1,
	"da": 1,
	"de": 1,
	"el": 1,
	"es": 1,
	"et": 1,
	"fi": 1,
	"fr": 1,
	"he": 1,
	"hi": 1,
	"hr": 1,
	"hu": 1,
	"id": 1,
	"it": 1,
	"ja": 1,
	"ko": 1,
	"lt": 1,
	"lv": 1,
	"nl": 1,
	"nb": 1,
	"pl": 1,
	"pt-br": 1,
	"pt-pt": 1,
	"ro": 1,
	"ru": 1,
	"sl": 1,
	"sr": 1,
	"sv": 1,
	"th": 1,
	"tr": 1,
	"vi": 1,
	"zh-cn": 1,
	"zh-hk": 1,
	"zh-tw": 1
});


text:
from __future__ import absolute_import, division, print_function
__metaclass__ = type

ANSIBLE_METADATA = {'metadata_version': '1.1',
                    'status': ['stableinterface'],
                    'supported_by': 'certified'}

DOCUMENTATION = r'''
---
module: bigip_device_group_member
short_description: Manages members in a device group
description:
  - Manages members in a device group. Members in a device group can only
    be added or removed, never updated. This is because the members are
    identified by unique name values and changing that name would invalidate
    the uniqueness.
version_added: 2.5
options:
  name:
    description:
      - Specifies the name of the device that you want to add to the
        device group. Often this will be the hostname of the device.
        This member must be trusted by the device already. Trusting
        can be done with the C(bigip_device_trust) module and the
        C(peer_hostname) option to that module.
    type: str
    required: True
  device_group:
    description:
      - The device group that you want to add the member to.
    type: str
    required: True
  state:
    description:
      - When C(present), ensures that the device group member exists.
      - When C(absent), ensures the device group member is removed.
    type: str
    choices:
      - present
      - absent
    default: present
extends_documentation_fragment: f5
author:
  - Tim Rupp (@caphrim007)
  - Wojciech Wypior (@wojtek0806)
'''

EXAMPLES = r'''
- name: Add the current device to the "device_trust_group" device group
  bigip_device_group_member:
    name: "{{ inventory_hostname }}"
    device_group: device_trust_group
    provider:
      password: secret
      server: lb.mydomain.com
      user: admin
  delegate_to: localhost

- name: Add the hosts in the current scope to "device_trust_group"
  bigip_device_group_member:
    name: "{{ item }}"
    device_group: device_trust_group
    provider:
      password: secret
      server: lb.mydomain.com
      user: admin
  loop: "{{ hostvars.keys() }}"
  run_once: true
  delegate_to: localhost
'''

RETURN = r'''
# only common fields returned
'''

from ansible.module_utils.basic import AnsibleModule

try:
    from library.module_utils.network.f5.bigip import F5RestClient
    from library.module_utils.network.f5.common import F5ModuleError
    from library.module_utils.network.f5.common import AnsibleF5Parameters
    from library.module_utils.network.f5.common import f5_argument_spec
except ImportError:
    from ansible.module_utils.network.f5.bigip import F5RestClient
    from ansible.module_utils.network.f5.common import F5ModuleError
    from ansible.module_utils.network.f5.common import AnsibleF5Parameters
    from ansible.module_utils.network.f5.common import f5_argument_spec

class Parameters(AnsibleF5Parameters):
    api_map = {}

    api_attributes = []

    returnables = []

    updatables = []

class ApiParameters(Parameters):
    pass

class ModuleParameters(Parameters):
    pass

class Changes(Parameters):
    def to_return(self):
        result = {}
        try:
            for returnable in self.returnables:
                change = getattr(self, returnable)
                if isinstance(change, dict):
                    result.update(change)
                else:
                    result[returnable] = change
            result = self._filter_params(result)
        except Exception:
            pass
        return result

class UsableChanges(Changes):
    pass

class ReportableChanges(Changes):
    pass

class Difference(object):
    pass

class ModuleManager(object):
    def __init__(self, *args, **kwargs):
        self.module = kwargs.get('module', None)
        self.client = F5RestClient(**self.module.params)
        self.want = Parameters(params=self.module.params)
        self.have = None
        self.changes = Changes()

    def _set_changed_options(self):
        changed = {}
        for key in Parameters.returnables:
            if getattr(self.want, key) is not None:
                changed[key] = getattr(self.want, key)
        if changed:
            self.changes = Changes(params=changed)

    def _announce_deprecations(self, result):
        warnings = result.pop('__warnings', [])
        for warning in warnings:
            self.module.deprecate(
                msg=warning['msg'],
                version=warning['version']
            )

    def exec_module(self):
        changed = False
        result = dict()
        state = self.want.state

        if state == "present":
            changed = self.present()
        elif state == "absent":
            changed = self.absent()

        reportable = ReportableChanges(params=self.changes.to_return())
        changes = reportable.to_return()
        result.update(**changes)
        result.update(dict(changed=changed))
        self._announce_deprecations(result)
        return result

    def present(self):
        if self.exists():
            return False
        else:
            return self.create()

    def absent(self):
        if self.exists():
            return self.remove()
        return False

    def create(self):
        self._set_changed_options()
        if self.module.check_mode:
            return True
        self.create_on_device()
        return True

    def remove(self):
        if self.module.check_mode:
            return True
        self.remove_from_device()
        if self.exists():
            raise F5ModuleError("Failed to remove the member from the device group.")
        return True

    def exists(self):
        uri = "https://{0}:{1}/mgmt/tm/cm/device-group/{2}/devices/{3}".format(
            self.client.provider['server'],
            self.client.provider['server_port'],
            self.want.device_group,
            self.want.name
        )
        resp = self.client.api.get(uri)
        try:
            response = resp.json()
        except ValueError:
            return False
        if resp.status == 404 or 'code' in response and response['code'] == 404:
            return False
        return True

    def create_on_device(self):
        params = self.changes.api_params()
        params['name'] = self.want.name
        params['partition'] = self.want.partition
        uri = "https://{0}:{1}/mgmt/tm/cm/device-group/{2}/devices/".format(
            self.client.provider['server'],
            self.client.provider['server_port'],
            self.want.device_group
        )
        resp = self.client.api.post(uri, json=params)
        try:
            response = resp.json()
        except ValueError as ex:
            raise F5ModuleError(str(ex))

        if 'code' in response and response['code'] in [400, 403]:
            if 'message' in response:
                raise F5ModuleError(response['message'])
            else:
                raise F5ModuleError(resp.content)

    def remove_from_device(self):
        uri = "https://{0}:{1}/mgmt/tm/cm/device-group/{2}/devices/{3}".format(
            self.client.provider['server'],
            self.client.provider['server_port'],
            self.want.device_group,
            self.want.name
        )
        response = self.client.api.delete(uri)
        if response.status == 200:
            return True
        raise F5ModuleError(response.content)

class ArgumentSpec(object):
    def __init__(self):
        self.supports_check_mode = True
        argument_spec = dict(
            name=dict(required=True),
            device_group=dict(required=True),
            state=dict(
                default='present',
                choices=['absent', 'present']
            ),
        )
        self.argument_spec = {}
        self.argument_spec.update(f5_argument_spec)
        self.argument_spec.update(argument_spec)

def main():
    spec = ArgumentSpec()

    module = AnsibleModule(
        argument_spec=spec.argument_spec,
        supports_check_mode=spec.supports_check_mode
    )

    try:
        mm = ModuleManager(module=module)
        results = mm.exec_module()
        module.exit_json(**results)
    except F5ModuleError as ex:
        module.fail_json(msg=str(ex))

if __name__ == '__main__':
    main()


text:
using System.Net;
using System.Text;
using System.Web.Hosting;
using System.Web.Mvc;
using Frapid.Dashboard.Controllers;
using Frapid.WebsiteBuilder.ViewModels;

namespace Frapid.WebsiteBuilder.Controllers.Backend
{
    public class LayoutController : DashboardController
    {
        [Route("dashboard/website/layouts/master")]
        [Authorize]
        public ActionResult Master()
        {
            var model = this.GetModel(LayoutType.DefaultLayout);
            return this.FrapidView(this.GetRazorView<AreaRegistration>("Layout/Master.cshtml"), model);
        }
        [Route("dashboard/website/layouts/master/home")]
        [Authorize]
        public ActionResult Homepage()
        {
            var model = this.GetModel(LayoutType.HomepageLayout);
            return this.FrapidView(this.GetRazorView<AreaRegistration>("Layout/Homepage.cshtml"), model);
        }

        [Route("dashboard/website/layouts/header")]
        [Authorize]
        public ActionResult Header()
        {
            var model = this.GetModel(LayoutType.Header);
            return this.FrapidView(this.GetRazorView<AreaRegistration>("Layout/Header.cshtml"), model);
        }

        [Route("dashboard/website/layouts/footer")]
        [Authorize]
        public ActionResult Footer()
        {
            var model = this.GetModel(LayoutType.Footer);
            return this.FrapidView(this.GetRazorView<AreaRegistration>("Layout/Footer.cshtml"), model);
        }

        [Route("dashboard/website/layouts/404-not-found-document")]
        [Authorize]
        public ActionResult Http404Document()
        {
            var model = this.GetModel(LayoutType.Http404Document);
            return this.FrapidView(this.GetRazorView<AreaRegistration>("Layout/Http404Document.cshtml"), model);
        }

        [Route("dashboard/website/layouts/save")]
        [HttpPost]
        [Authorize]
        public ActionResult SaveLayoutFile(Layout layout)
        {
            string path = HostingEnvironment.MapPath(Configuration.GetCurrentThemePath());
            var type = (LayoutType)layout.Type;

            switch (type)
            {
                case LayoutType.DefaultLayout:
                    path += "Layout.cshtml";
                    break;
                case LayoutType.HomepageLayout:
                    path += "Layout-Home.cshtml";
                    break;
                case LayoutType.Header:
                    path += "Header.cshtml";
                    break;
                case LayoutType.Footer:
                    path += "Footer.cshtml";
                    break;
                case LayoutType.Http404Document:
                    path += "404.cshtml";
                    break;
            }

            if (path == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.InternalServerError);
            }

            System.IO.File.WriteAllText(path, layout.Contents, Encoding.UTF8);
            return this.Json("OK");
        }

        private Layout GetModel(LayoutType type)
        {
            string directory = HostingEnvironment.MapPath(Configuration.GetCurrentThemePath());
            string path = directory;
            string name = "";

            switch (type)
            {
                case LayoutType.DefaultLayout:
                    name = "Master Layout";
                    path += "Layout.cshtml";
                    break;
                case LayoutType.HomepageLayout:
                    name = "Homepage Layout";
                    path += "Layout-Home.cshtml";
                    break;
                case LayoutType.Header:
                    name = "Header";
                    path += "Header.cshtml";
                    break;
                case LayoutType.Footer:
                    name = "Footer";
                    path += "Footer.cshtml";
                    break;
                case LayoutType.Http404Document:
                    name = "Http 404 Not Found Document";
                    path += "404.cshtml";
                    break;
            }

            if (path == null)
            {
                return new Layout
                {
                    Contents = ""
                };
            }

            string contents = System.IO.File.ReadAllText(path, Encoding.UTF8);

            return new Layout
            {
                Name =  name,
                Type= (int)type,
                Contents = contents
            };
        }
    }
}


text:
class DummyWithDefaultCurrency
  include Mongoid::Document
  include Mongoid::MoneyField

  field :description

  money_field :price, default_currency: 'EUR'
end


text:
const request = require('supertest'),
    app = require('../../../test_util/test_server_app'),
    eventGeneratorConsts =
        require('../../../../../server/db/model/event_generator/event_generator_consts'),
    models = require('../../../../../server/db/model/models'),
    userTestUtil = require('../../../test_util/user_test_util'),
    eventGeneratorTestUtil = require('../../../test_util/event_generator_test_util'),
    apiTestUtil = require('../api_test_util'),
    eventGeneratorRoute = '/api/event_generator/',
    _ = require('lodash');

describe('Event Generator get all event generators for user', function () {
    it('should return all event generators for user', function (done) {
        const agent = request.agent(app),
            expectedEventGenerator = _.extend({}, eventGeneratorTestUtil.testEventGenerators.eg1);
        userTestUtil.loginAsTestUser(userTestUtil.testUsers.u1, agent)
            .then(function (user) {
                expectedEventGenerator._user = user._id;
                agent
                    .get(eventGeneratorRoute)
                    .set('Accept', 'application/json')
                    .expect(200)
                    .expect(function (res) {
                        const eventGenerators = res.body;
                        expect(eventGenerators).toEqual(jasmine.any(Array));
                        eventGeneratorTestUtil.expectEventGenerator(
                            eventGenerators[0],
                            expectedEventGenerator,
                            {
                                isServerResponse: true
                            }
                        );
                    })
                    .end(apiTestUtil.errIfErrElseDone(done));
            })
            .catch(done.fail);
    });

    it('should fail if not logged in', function (done) {
        apiTestUtil.expectFailsIfNotLoggedIn(
            request(app).get(eventGeneratorRoute),
            done
        );
    });
});

describe('Event Generator create new event generator', function () {
    it('should create a event generator for a user', function (done) {
        const agent = request.agent(app),
            expectedEventGenerator = eventGeneratorTestUtil.generateEventGenerator();
        let eventGeneratorId;
        userTestUtil.createAndLoginAsTestUser(agent)
            .then(function (user) {
                expectedEventGenerator._user = user._id;
                agent
                    .post(eventGeneratorRoute)
                    .set('Accept', 'application/json')
                    .send(expectedEventGenerator)
                    .expect(200)
                    .expect(function (res) {
                        const eventGenerator = res.body;
                        eventGeneratorTestUtil.expectEventGenerator(
                            eventGenerator,
                            expectedEventGenerator,
                            {
                                isServerResponse: true
                            }
                        );
                        eventGeneratorId = eventGenerator._id;
                    })
                    .end(function (err) {
                        if(err) {
                            done.fail(err)
                        } else {
                            models.eventGeneratorAPI
                                .findEventGeneratorById(eventGeneratorId)
                                .then(function (eventGenerator) {
                                    expect(eventGenerator).toBeTruthy();
                                    done();
                                })
                                .catch(done.fail)
                        }
                    });
            })
            .catch(done.fail);
    });

    it('should fail if not logged in', function (done) {
        apiTestUtil.expectFailsIfNotLoggedIn(
            request(app).post(eventGeneratorRoute),
            done
        );
    });
});

describe('event generator api update', function () {
    it('should allow a user to update an event generator', function (done) {
        const agent = request.agent(app),
            initialEventGenerator = eventGeneratorTestUtil.generateEventGenerator(),
            targetEventGenerator =
                eventGeneratorTestUtil.generateEventGenerator(eventGeneratorConsts.CAR_OWNER);
        let eventGeneratorId;
        userTestUtil
            .createAndLoginAsTestUser(agent)
            .then(function (user) {
                targetEventGenerator._user = user._id;
                models.eventGeneratorAPI
                    .createEventGenerator(user._id, initialEventGenerator)
                    .then(function (eventGenerator) {
                        agent
                            .put(eventGeneratorRoute + eventGenerator._id)
                            .set('Accept', 'application/json')
                            .send(targetEventGenerator)
                            .expect(200)
                            .expect(function (res) {
                                const returnedEventGenerator = res.body;
                                eventGeneratorTestUtil.expectEventGenerator(
                                    returnedEventGenerator,
                                    targetEventGenerator,
                                    {
                                        isServerResponse: true
                                    }
                                );
                                eventGeneratorId = returnedEventGenerator._id;
                            })
                            .end(function (err) {
                                if(err){
                                    done.fail(err);
                                } else {
                                    models.eventGeneratorAPI
                                        .findEventGeneratorById(eventGeneratorId)
                                        .then(function (eventGenerator) {
                                            eventGeneratorTestUtil.expectEventGenerator(
                                                eventGenerator,
                                                targetEventGenerator
                                            );
                                            done();
                                        })
                                        .catch(done.fail);
                                }
                            });
                    })
                    .catch(done.fail);
            })
            .catch(done.fail);
    });

    it('should fail if not logged in', function (done) {
        eventGeneratorTestUtil.getEventGeneratorsForTestUser(userTestUtil.testUsers.u1)
            .then(function (eventGenerators) {
                // we're using test user u1, who was set up with 1 event generator
                const eventGenerator = eventGenerators[0];
                apiTestUtil.expectFailsIfNotLoggedIn(
                    request(app).put(eventGeneratorRoute + eventGenerator._id.toString()),
                    done
                );
            })
            .catch(done.fail);
    });

     it('should fail if trying to edit someone else\'s', function (done) {
        eventGeneratorTestUtil.getEventGeneratorsForTestUser(userTestUtil.testUsers.u1)
            .then(function (eventGenerators) {
                // we're using test user u1, who was set up with 1 event generator
                const eventGenerator = eventGenerators[0],
                    agent = request.agent(app);
                userTestUtil.createAndLoginAsTestUser(agent)
                    .then(function () {
                        apiTestUtil.expectFailsIfNotOwner(
                            agent.put(eventGeneratorRoute + eventGenerator._id.toString()),
                            done
                        );
                    })
                    .catch(done.fail);

            })
            .catch(done.fail);
    });
});

describe('event generator api delete', function () {
    it('should allow a user to delete an event generator', function (done) {
        const agent = request.agent(app),
            initialEventGenerator = eventGeneratorTestUtil.generateEventGenerator();
        let eventGeneratorId;
        userTestUtil
            .createAndLoginAsTestUser(agent)
            .then(function (user) {
                models.eventGeneratorAPI
                    .createEventGenerator(user._id, initialEventGenerator)
                    .then(function (eventGenerator) {
                        eventGeneratorId = eventGenerator._id;
                        agent
                            .delete(eventGeneratorRoute + eventGeneratorId)
                            .set('Accept', 'application/json')
                            .expect(200)
                            .end(function (err) {
                                if(err){
                                    done.fail(err);
                                } else {
                                    models.eventGeneratorAPI
                                        .findEventGeneratorById(eventGeneratorId)
                                        .then(function (eventGenerator) {
                                            expect(eventGenerator).toBeFalsy();
                                            done();
                                        })
                                        .catch(done.fail);
                                }
                            });
                    })
                    .catch(done.fail);
            })
            .catch(done.fail);
    });

    it('should fail if not logged in', function (done) {
        eventGeneratorTestUtil.getEventGeneratorsForTestUser(userTestUtil.testUsers.u1)
            .then(function (eventGenerators) {
                // we're using test user u1, who was set up with 1 event generator
                const eventGenerator = eventGenerators[0];
                apiTestUtil.expectFailsIfNotLoggedIn(
                    request(app).delete(eventGeneratorRoute + eventGenerator._id.toString()),
                    done
                );
            })
            .catch(done.fail);
    });

     it('should fail if trying to delete someone else\'s', function (done) {
        eventGeneratorTestUtil.getEventGeneratorsForTestUser(userTestUtil.testUsers.u1)
            .then(function (eventGenerators) {
                // we're using test user u1, who was set up with 1 event generator
                const eventGenerator = eventGenerators[0],
                    agent = request.agent(app);
                userTestUtil.createAndLoginAsTestUser(agent)
                    .then(function () {
                        apiTestUtil.expectFailsIfNotOwner(
                            agent.delete(eventGeneratorRoute + eventGenerator._id.toString()),
                            done
                        );
                    })
                    .catch(done.fail);

            })
            .catch(done.fail);
    });
});


text:
require 'spud_core'
require 'paperclip'
require 'tinymce-rails'
module Spud
	module Media
		 class Engine < Rails::Engine
			engine_name :spud_media
			initializer :admin do
				Spud::Core.append_admin_javascripts('spud/admin/media/application')
  			Spud::Core.append_admin_stylesheets('spud/admin/media/application')
				Spud::Core.configure do |config|
				  config.admin_applications += [{:name => "Media",:thumbnail => "spud/admin/media_icon.png",:url => "/spud/admin/media",:order => 3,:retina => true}]
				end
			end
		 end
	end
end


text:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:compat="http://schemas.android.com/apk/res-auto">

    <item
        android:id="@+id/action_profile"
        android:title="@string/action_Profile"
        android:orderInCategory="100"
        compat:showAsAction="never"/>
    <item
        android:id="@+id/action_settings"
        android:title="@string/action_settings"
        android:orderInCategory="100"
        compat:showAsAction="never"/>

    <item
        android:id="@+id/action_about"
        android:title="@string/action_about"
        android:orderInCategory="100"
        compat:showAsAction="never"/>
    <item
        android:id="@+id/action_logout"
        android:title="@string/action_logout"
        android:orderInCategory="100"
        compat:showAsAction="never"/>
    <item
        android:id="@+id/action_search"
        android:orderInCategory="200"
        android:title="@string/action_add"
        android:icon="@mipmap/ic_search_white_24dp"
        compat:showAsAction="ifRoom">
    </item>
    <item
        android:id="@+id/action_add"
        android:orderInCategory="200"
        android:title="@string/action_add"
        android:icon="@mipmap/ic_add_white_24dp"
        compat:showAsAction="ifRoom">
    </item>
</menu>


text:
package net.tokensmith.otter.security.csrf;

import net.tokensmith.otter.security.RandomString;
import net.tokensmith.otter.security.csrf.exception.CsrfException;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Optional;

import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

public class SynchronizerTokenTest {

    @Mock
    private RandomString mockRandomString;
    private SynchronizerToken subject;

    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);
        subject = new SynchronizerToken(mockRandomString);
    }

    @Test
    public void checkTokensShouldBeOk() throws Exception{
        String token = "token";

        HttpSession mockHttpSession = mock(HttpSession.class);
        when(mockHttpSession.getAttribute(SynchronizerToken.CHALLENGE_TOKEN_SESSION_NAME))
                .thenReturn(token);

        HttpServletRequest mockServletRequest = mock(HttpServletRequest.class);
        when(mockServletRequest.getParameter(SynchronizerToken.CHALLENGE_TOKEN_FORM_NAME))
                .thenReturn(token);

        when(mockServletRequest.getMethod()).thenReturn("POST");

        when(mockServletRequest.getSession()).thenReturn(mockHttpSession);

        subject.checkTokens(mockServletRequest);
    }

    @Test(expected = CsrfException.class)
    public void checkTokensShouldThrowCsrfException() throws CsrfException{

        HttpSession mockHttpSession = mock(HttpSession.class);
        when(mockHttpSession.getAttribute(SynchronizerToken.CHALLENGE_TOKEN_SESSION_NAME))
                .thenReturn("token1");

        HttpServletRequest mockServletRequest = mock(HttpServletRequest.class);
        when(mockServletRequest.getParameter(SynchronizerToken.CHALLENGE_TOKEN_FORM_NAME))
                .thenReturn("token2");

        when(mockServletRequest.getMethod()).thenReturn("POST");

        when(mockServletRequest.getSession()).thenReturn(mockHttpSession);

        subject.checkTokens(mockServletRequest);
    }

    @Test
    public void checkTokensShouldInsertTokenToSession() throws CsrfException {
        HttpSession mockHttpSession = mock(HttpSession.class);

        HttpServletRequest mockServletRequest = mock(HttpServletRequest.class);
        when(mockServletRequest.getMethod()).thenReturn("GET");
        when(mockServletRequest.getSession()).thenReturn(mockHttpSession);

        String randomString = "randomString";
        when(mockRandomString.run()).thenReturn(randomString);

        subject.checkTokens(mockServletRequest);

        verify(mockHttpSession, times(1)).setAttribute(SynchronizerToken.CHALLENGE_TOKEN_SESSION_NAME, "cmFuZG9tU3RyaW5n");
    }

    @Test
    public void requestMethodRequiresChallengeTokenWhenPostShouldBeTrue() {
        Boolean actual = subject.requestMethodRequiresChallengeToken("POST");

        assertThat(actual, is(true));
    }

    @Test
    public void requestMethodRequiresChallengeTokenWhenPutShouldBeTrue() {
        Boolean actual = subject.requestMethodRequiresChallengeToken("PUT");

        assertThat(actual, is(true));
    }

    @Test
    public void requestMethodRequiresChallengeTokenWhenDeleteShouldBeTrue() {
        Boolean actual = subject.requestMethodRequiresChallengeToken("DELETE");

        assertThat(actual, is(true));
    }

    @Test
    public void requestMethodRequiresChallengeTokenWhenGetShouldBeFalse() {
        Boolean actual = subject.requestMethodRequiresChallengeToken("GET");

        assertThat(actual, is(false));
    }

    @Test
    public void challengeTokensMatchShouldBeTrue() throws Exception {
        Optional<String> sessionChallengeToken = Optional.of("token");
        Optional<String> formChallengeToken = Optional.of("token");

        Boolean actual = subject.doTokensMatch(sessionChallengeToken, formChallengeToken);
        assertThat(actual, is(true));
    }

    @Test
    public void challengeTokensMatchWhenDifferentShouldBeFalse() throws Exception {
        Optional<String> sessionChallengeToken = Optional.of("token1");
        Optional<String> formChallengeToken = Optional.of("token2");

        Boolean actual = subject.doTokensMatch(sessionChallengeToken, formChallengeToken);
        assertThat(actual, is(false));
    }

    @Test
    public void challengeTokensMatchWhenSessionIsNotPresentShouldBeFalse() throws Exception {
        Optional<String> sessionChallengeToken = Optional.empty();
        Optional<String> formChallengeToken = Optional.of("token");

        Boolean actual = subject.doTokensMatch(sessionChallengeToken, formChallengeToken);
        assertThat(actual, is(false));
    }

    @Test
    public void challengeTokensMatchWhenFormIsNotPresentShouldBeFalse() throws Exception {
        Optional<String> sessionChallengeToken = Optional.of("token");
        Optional<String> formChallengeToken = Optional.empty();

        Boolean actual = subject.doTokensMatch(sessionChallengeToken, formChallengeToken);
        assertThat(actual, is(false));
    }

    @Test
    public void getChallengeTokenFromSessionShouldReturnToken() {

        HttpSession mockHttpSession = mock(HttpSession.class);
        when(mockHttpSession.getAttribute(SynchronizerToken.CHALLENGE_TOKEN_SESSION_NAME))
                .thenReturn("token");

        HttpServletRequest mockServletRequest = mock(HttpServletRequest.class);
        when(mockServletRequest.getSession()).thenReturn(mockHttpSession);

        Optional<String> actual = subject.getChallengeTokenFromSession(mockServletRequest);

        assertThat(actual.isPresent(), is(true));
        assertThat(actual.get(), is("token"));
    }

    @Test
    public void getChallengeTokenFromSessionShouldReturnEmpty() {

        HttpSession mockHttpSession = mock(HttpSession.class);
        when(mockHttpSession.getAttribute(SynchronizerToken.CHALLENGE_TOKEN_SESSION_NAME))
                .thenReturn(null);

        HttpServletRequest mockServletRequest = mock(HttpServletRequest.class);
        when(mockServletRequest.getSession()).thenReturn(mockHttpSession);

        Optional<String> actual = subject.getChallengeTokenFromSession(mockServletRequest);

        assertThat(actual.isPresent(), is(false));
    }

    @Test
    public void insertChallengeTokenIntoSessionShouldInsert() throws Exception{

        String randomString = "randomString";
        String encodedChallengeToken = "cmFuZG9tU3RyaW5n";
        HttpSession mockHttpSession = mock(HttpSession.class);
        HttpServletRequest mockServletRequest = mock(HttpServletRequest.class);
        when(mockServletRequest.getSession()).thenReturn(mockHttpSession);

        when(mockRandomString.run()).thenReturn(randomString);
        subject.insertChallengeTokenIntoSession(mockServletRequest);

        verify(mockHttpSession, times(1)).setAttribute(SynchronizerToken.CHALLENGE_TOKEN_SESSION_NAME, encodedChallengeToken);

    }

    @Test
    public void getChallengeTokenFromFormShouldReturnToken() {
        HttpServletRequest mockServletRequest = mock(HttpServletRequest.class);
        when(mockServletRequest.getParameter(SynchronizerToken.CHALLENGE_TOKEN_FORM_NAME))
                .thenReturn("token");

        Optional<String> actual = subject.getChallengeTokenFromForm(mockServletRequest);
        assertThat(actual.isPresent(), is(true));
        assertThat(actual.get(), is("token"));
    }

    @Test
    public void getChallengeTokenFromFormShouldReturnEmpty() {
        HttpServletRequest mockServletRequest = mock(HttpServletRequest.class);
        when(mockServletRequest.getParameter(SynchronizerToken.CHALLENGE_TOKEN_FORM_NAME))
                .thenReturn(null);

        Optional<String> actual = subject.getChallengeTokenFromForm(mockServletRequest);
        assertThat(actual.isPresent(), is(false));
    }
}


text:
package ca.waterloo.dsg.graphflow.query.operator.resolver;

import ca.waterloo.dsg.graphflow.graph.EdgeStore;
import ca.waterloo.dsg.graphflow.graph.VertexPropertyStore;
import ca.waterloo.dsg.graphflow.query.operator.AbstractOperator;
import ca.waterloo.dsg.graphflow.query.operator.descriptor.EdgeOrVertexPropertyDescriptor;
import ca.waterloo.dsg.graphflow.query.operator.sink.AbstractOutputSink;
import ca.waterloo.dsg.graphflow.query.result.MatchQueryOutput;
import ca.waterloo.dsg.graphflow.query.result.Tuples;
import ca.waterloo.dsg.graphflow.query.result.Tuples.ColumnType;
import ca.waterloo.dsg.graphflow.util.json.JsonKeyConstants;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;

import java.util.ArrayList;
import java.util.List;

/**
 * An operator that takes a list of vertex and edge properties to look up in the
 * {@link VertexPropertyStore} and {@link EdgeStore}. When it is appended {@link MatchQueryOutput}s,
 * it resolves the properties and appends them to the next operator. Other vertices and edges
 * that do not have properties to resolve are also appended to the next operator with only their
 * IDs.
 * Note: For now this operator only appends String outputs to the next operator.
 */
public class PropertyResolver extends PropertyReadingOperator {

    private String[] columnNames;
    private ColumnType[] columnTypes;
    private List<Integer> vertexIndices = new ArrayList<>();
    private List<Integer> edgeIndices = new ArrayList<>();
    private Tuples tuples;

    /**
     * @see PropertyReadingOperator#PropertyReadingOperator(AbstractOperator, List).
     */
    public PropertyResolver(AbstractOutputSink nextOperator, String[] columnNames,
        List<EdgeOrVertexPropertyDescriptor> propertyDescriptors) {
        super(nextOperator, propertyDescriptors);
        this.columnNames = columnNames;
        this.columnTypes = new ColumnType[columnNames.length];
        for (int i = 0; i < propertyDescriptors.size(); i++) {
            EdgeOrVertexPropertyDescriptor descriptor = propertyDescriptors.get(i);
            switch (descriptor.descriptorType) {
                case EDGE_ID:
                    columnTypes[i] = ColumnType.EDGE;
                    edgeIndices.add(descriptor.index);
                    break;
                case VERTEX_ID:
                    columnTypes[i] = ColumnType.VERTEX;
                    vertexIndices.add(descriptor.index);
                    break;
                default:
                    columnTypes[i] = ColumnType.PRIMITIVE_TYPE;
            }
        }
        this.tuples = new Tuples(columnTypes, columnNames);
    }

    @Override
    public void append(MatchQueryOutput matchQueryOutput) {
        Object[] tuple = new Object[propertyDescriptors.size()];
        for (int i = 0; i < propertyDescriptors.size(); i++) {
            tuple[i] = getPropertyOrId(matchQueryOutput, propertyDescriptors.get(i));
        }
        tuples.addTuple(tuple);
        for (int vertexIndex : vertexIndices) {
            int vertexId = matchQueryOutput.vertexIds[vertexIndex];
            if (!tuples.getVertices().containsKey(vertexId)) {
                tuples.getVertices().put(vertexId, SubgraphsResolver.resolveVertex(vertexId));
            }
        }
        for (int edgeIndex : edgeIndices) {
            long edgeId = matchQueryOutput.edgeDescriptors.get(edgeIndex).edgeId;
            if (!tuples.getEdges().containsKey(edgeId)) {
                tuples.getEdges().put(edgeId, SubgraphsResolver.resolveEdge(matchQueryOutput,
                    edgeIndex));
            }
        }
    }

    @Override
    public void notifyDone() {
        ((AbstractOutputSink) nextOperator).append(tuples);
        this.tuples = new Tuples(columnTypes, columnNames);
        this.vertexIndices = new ArrayList<>();
        this.edgeIndices = new ArrayList<>();
        super.notifyDone();
    }

    @Override
    public String getHumanReadableOperator() {
        StringBuilder stringBuilder = new StringBuilder("PropertyResolver:\n");
        appendListAsCommaSeparatedString(stringBuilder, propertyDescriptors,
            "EdgeOrVertexPropertyDescriptors");
        return stringBuilder.toString();
    }

    @Override
    public JsonObject toJson() {
        JsonObject jsonOperator = new JsonObject();

        JsonArray jsonArguments = new JsonArray();
        JsonObject jsonArgument = new JsonObject();
        jsonArgument.addProperty(JsonKeyConstants.NAME.toString(), "Descriptors");
        JsonArray jsonDescriptors = new JsonArray();
        for (EdgeOrVertexPropertyDescriptor descriptor : propertyDescriptors) {
            jsonDescriptors.add(descriptor.toJson());
        }
        jsonArgument.add(JsonKeyConstants.VALUE.toString(), jsonDescriptors);
        jsonArguments.add(jsonArgument);

        jsonOperator.addProperty(JsonKeyConstants.NAME.toString(), "Property Resolver");
        jsonOperator.add(JsonKeyConstants.ARGS.toString(), jsonArguments);
        return jsonOperator;
    }
}


text: PDP-11 Emulator for UNIX v6 in JavaScript.


text: aws iam delete-role --role-name aws-elasticbeanstalk-service-role


text:
<?php

namespace Wpmirror;

/**
 * Class Remote
 * @package Wpmirror
 */
class Remote
{
    /**
     * @var Settings
     */
    private $remoteSettings;

    /**
     * @var int
     */
    private $seed;

    /**
     * @var string
     */
    private $remoteAbsPath;

    /**
     * Remote constructor.
     *
     * @param Settings $remoteSettings
     */
    public function __construct($remoteSettings)
    {
        $this->remoteSettings = $remoteSettings;

        $this->baseUrl = rtrim($this->remoteSettings->url, '/') . '/';
        $this->baseUrl = $this->properUrl($this->baseUrl);

        $this->maxFiles = 100;
        if (isset($remoteSettings->maxFiles)) {
            $this->maxFiles = $remoteSettings->maxFiles;
        }

        $this->initiateRemoteSession();
    }

    /**
     * @return bool|string
     */
    public function remoteScan()
    {
        $url = $this->getUrl('fileindex');
        $strResponse = file_get_contents($url);

        return $strResponse;
    }

    /**
     * Iterates through the $changeSet array and request that the remote server
     * creates and makes available a zip archive with those files.
     *
     * @param array $changeSet
     * @return object
     */
    public function getFiles($changeSet)
    {

        if (count($changeSet) == 0) {
            return json_decode('{"messages":[]}');
        }
        $files = array();
        foreach ($changeSet as $change) {
            $files[] = $change['file'];
            if (count($files) == $this->maxFiles) {
                $this->getFilesSubset($files);
                $files = array();
            }
        }
        if (count($files) > 0) {
            $this->getFilesSubset($files);
        }
    }

    public function cleanUp()
    {
    }

    public function getRemoteAbsPath()
    {
        return $this->remoteAbsPath;
    }

    /**
     *
     */
    public function getDatabase()
    {
        // Get the table index
        $url = $url = $this->getUrl('tableindex');
        $strResponse = file_get_contents($url);
        $arrTables = explode("\n", $strResponse);

        foreach ($arrTables as $table) {
            if (strlen($table) == 0) {
                continue;
            }
            $url = $this->getUrl('packtable');
            $url .= '&table=' . $table;
            $target = tempnam('', 'mirror_');
            file_put_contents($target, fopen($url, 'rb'));

            $this->unpackTableZip($table, $target);
        }
    }

    private function getFilesSubset($files)
    {
        // ask to pack the files

        $url = $this->getUrl('pack');
        $params = array('http' => array(
                'method' => 'POST',
                'header' => 'Content-type: application/json',
                'content' => json_encode($files),
            )
        );
        $ctx = stream_context_create($params);

        // download the zip
        $target = tempnam('', 'mirror_');
        file_put_contents($target, fopen($url, 'rb', false, $ctx));

        // unpack the file
        $this->unpackFilesZip($target);
        unlink($target);

    }

    private function unpackFilesZip($fileName)
    {
        $zip = new \ZipArchive();
        $zip->open($fileName);
        $base = $this->remoteSettings->localpath;
        $baseTrailing = rtrim($base, '/') . '/';
        $localUrl = rtrim($this->remoteSettings->localurl, '/') . '/';
        $localUrl = $this->properUrl($localUrl);

        for ($i = 0; $i<$zip->numFiles; $i++) {
            $file = $zip->getNameIndex($i);
            $success = $zip->extractTo($base, $file);
            if (!$success) {
                //$ret->messages[] = "file $file could not be extracted";
            }

            if ($success) {
                $info = pathinfo($file);
                if (!in_array($info['extension'], array('php', 'json', 'js', 'txt', 'html'))) {
                    continue;
                }
                // check if the file has an internal (hardcoded reference to the
                // remote URL or remote abspath
                $this->searchReplace($base . '/' . $file, $this->remoteAbsPath, $baseTrailing);
                $this->searchReplace($base . '/' . $file, $this->baseUrl, $localUrl);
            }

        }
        $zip->close();
    }

    private function searchReplace($file, $search, $replace)
    {
        file_put_contents($file, str_replace($search, $replace, file_get_contents($file)));
    }

    private function unpackTableZip($table, $fileName)
    {
        $zip = new \ZipArchive();
        $zip->open($fileName);

        $mysqli = new \mysqli(
            $this->remoteSettings->localdbhost,
            $this->remoteSettings->localdbuser,
            $this->remoteSettings->localdbpass,
            $this->remoteSettings->localdbname
        );

        $sql = 'DROP TABLE IF EXISTS ' . $table;
        $mysqli->query($sql);

        $sql = $zip->getFromIndex(0);
        $mysqli->multi_query($sql);
    }

    /**
     * Ensure the URL has a valid protocol
     *
     * @param string $url
     * @return string
     */
    public function properUrl($url)
    {
        if (substr($url, 0, 4) != 'http') {
            $url = 'http://'. $url;
        }

        return $url;
    }

    private function initiateRemoteSession()
    {
        $url = $this->baseUrl . '?wpmirroragent_token=nosession';
        $url .= '&wpmirroragent_action=seed';
        $strResponse = file_get_contents($url);
        $response = json_decode($strResponse);
        if (!$response) {
            // log and exit
        }
        $this->seed = $response->seed;
        $this->remoteAbsPath = $response->abspath;
    }

    private function getUrl($command)
    {
        $url = $this->baseUrl;
        $url .= '?wpmirroragent_token=' . sha1($this->seed . $this->remoteSettings->secret . $command);
        $url .= '&wpmirroragent_action=' . $command;
        return $url;
    }
}


text:
var Mongoose = require('mongoose');

var ProjectSchema = new Mongoose.Schema({
  // fields are defined here
});

exports.Project = Mongoose.model('Project', ProjectSchema);


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>credentials property - Navigator class - polymer_app_layout.behaviors library - Dart API</title>

    <base href="../..">

    <link href='https://fonts.googleapis.com/css?family=Source+Code+Pro|Roboto:500,400italic,300,400' rel='stylesheet' type='text/css'>
    <link rel="stylesheet" href="static-assets/prettify.css">
    <link rel="stylesheet" href="static-assets/css/bootstrap.min.css">
    <link rel="stylesheet" href="static-assets/styles.css">

    <meta name="description" content="API docs for the credentials property from the Navigator class, for the Dart programming language.">
    <link rel="icon" href="static-assets/favicon.png">

            <button id="sidenav-left-toggle" type="button"> </button>

polymer_app_layout_template

polymer_app_layout.behaviors

Navigator

credentials

credentials

polymer_app_layout_template

polymer_app_layout.behaviors

Navigator

credentials

property
 credentials

polymer_app_layout_template

polymer_app_layout.behaviors

Navigator

Properties

appCodeName

appName

appVersion

connection

cookieEnabled

credentials

dartEnabled

doNotTrack

geofencing

geolocation

hardwareConcurrency

language

languages

maxTouchPoints

mimeTypes

onLine

persistentStorage

platform

presentation

product

productSub

push

serviceWorker

storageQuota

temporaryStorage

userAgent

vendor

vendorSub

Methods

getBattery

getGamepads

getStorageUpdates

getUserMedia

isProtocolHandlerRegistered

registerProtocolHandler

sendBeacon

unregisterProtocolHandler

        CredentialsContainer
        credentials

            read-only

Not documented.

                  polymer_app_layout_template 0.1.0 api docs

                •

                •

                  cc license


text:
<?php

if ( ! class_exists( 'TLC_Transient_Update_Server' ) )
	require_once dirname( __FILE__ ) . '/class-tlc-transient-update-server.php';

new TLC_Transient_Update_Server;

if ( ! class_exists( 'TLC_Transient' ) )
	require_once dirname( __FILE__ ) . '/class-tlc-transient.php';

require_once dirname( __FILE__ ) . '/functions.php';

// Example:
/*
function sample_fetch_and_append( $url, $append ) {
	$f  = wp_remote_retrieve_body( wp_remote_get( $url, array( 'timeout' => 30 ) ) );
	$f .= $append;
	return $f;
}

function test_tlc_transient() {
	$t = tlc_transient( 'foo' )
		->expires_in( 30 )
		->background_only()
		->updates_with( 'sample_fetch_and_append', array( 'http://coveredwebservices.com/tools/long-running-request.php', ' appendfooparam ' ) )
		->get();
	var_dump( $t );
	if ( !$t )
		echo "The request is false, because it isn't yet in the cache. It'll be there in about 10 seconds. Keep refreshing!";
}

add_action( 'wp_footer', 'test_tlc_transient' );
*/


text:
package com.yungoushangcheng.yungou.service.impl;

import com.yungoushangcheng.yungou.dao.LotteryDao;
import com.yungoushangcheng.yungou.model.Lottery;
import com.yungoushangcheng.yungou.service.LotteryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * Created by bonismo@hotmail.com
 * 下午11:50 on 16/8/28.
 */
@Service("LotteryService")
@Transactional
@Scope("prototype")
public class LotteryServiceImpl extends BaseServiceImpl<Lottery> implements LotteryService {

    @Autowired
    private LotteryDao lotteryDao;
}


text:
#include "config.h"
#include "ServiceWorkerGlobalScope.h"

#include "bindings/v8/ScriptObject.h"
#include "core/workers/WorkerClients.h"
#include "core/workers/WorkerThreadStartupData.h"
#include "modules/serviceworkers/ServiceWorkerThread.h"
#include "platform/weborigin/KURL.h"
#include "wtf/CurrentTime.h"

namespace WebCore {

PassRefPtr<ServiceWorkerGlobalScope> ServiceWorkerGlobalScope::create(ServiceWorkerThread* thread, PassOwnPtr<WorkerThreadStartupData> startupData)
{
    RefPtr<ServiceWorkerGlobalScope> context = adoptRef(new ServiceWorkerGlobalScope(startupData->m_scriptURL, startupData->m_userAgent, thread, monotonicallyIncreasingTime(), startupData->m_workerClients.release()));

    context->applyContentSecurityPolicyFromString(startupData->m_contentSecurityPolicy, startupData->m_contentSecurityPolicyType);
    return context.release();
}

ServiceWorkerGlobalScope::ServiceWorkerGlobalScope(const KURL& url, const String& userAgent, ServiceWorkerThread* thread, double timeOrigin, PassOwnPtr<WorkerClients> workerClients) :
    WorkerGlobalScope(url, userAgent, thread, timeOrigin, workerClients)
{
    ScriptWrappable::init(this);
}

ServiceWorkerGlobalScope::~ServiceWorkerGlobalScope()
{
}

const AtomicString& ServiceWorkerGlobalScope::interfaceName() const
{
    return EventTargetNames::ServiceWorkerGlobalScope;
}

} // namespace WebCore


text:
#include "useragent_function.h"
#include "mldb/core/mldb_engine.h"
#include "mldb/types/basic_value_descriptions.h"
#include "mldb/types/any_impl.h"

using namespace std;

namespace MLDB {

DEFINE_STRUCTURE_DESCRIPTION(ParseUserAgentFunctionConfig);

ParseUserAgentFunctionConfigDescription::
ParseUserAgentFunctionConfigDescription()
{
    addField("regexFile", &ParseUserAgentFunctionConfig::regexFile,
        "User agent string parser YAML configuration file",
        string("/opt/bin/useragent-regexes.yaml"));
}

DEFINE_STRUCTURE_DESCRIPTION(UserAgentParserArgs);

UserAgentParserArgsDescription::
UserAgentParserArgsDescription()
{
    addField("ua", &UserAgentParserArgs::ua, "User agent string");
}

DEFINE_STRUCTURE_DESCRIPTION(UaDevice);
UaDeviceDescription::UaDeviceDescription()
{
    addField("brand", &UaDevice::brand, "Device brand");
    addField("model", &UaDevice::model, "Device model");
}

DEFINE_STRUCTURE_DESCRIPTION(UaSoftware);
UaSoftwareDescription::UaSoftwareDescription()
{
    addField("family", &UaSoftware::family, "Software family");
    addField("version", &UaSoftware::version, "Software version");
}

DEFINE_STRUCTURE_DESCRIPTION(ParsedUserAgent);
ParsedUserAgentDescription::ParsedUserAgentDescription()
{
    addField("os", &ParsedUserAgent::os, "Operating system");
    addField("browser", &ParsedUserAgent::browser, "Browser");
    addField("device", &ParsedUserAgent::device, "Device");
    addField("isSpider", &ParsedUserAgent::isSpider, "Does this user agent represent a spider");
}

/*****************************************************************************/
/* USER AGENT PARSER FUNCTION                                                */
/*****************************************************************************/

ParseUserAgentFunction::
ParseUserAgentFunction(MldbEngine * owner,
                       PolyConfig config,
                       const std::function<bool (const Json::Value &)> & onProgress)
    : BaseT(owner, config)
{
    functionConfig = config.params.convert<ParseUserAgentFunctionConfig>();

    parser = make_shared<UaParser::UserAgentParser>(functionConfig.regexFile);
}

ParsedUserAgent
ParseUserAgentFunction::
call(UserAgentParserArgs input) const
{
    if(input.ua.empty())
        return ParsedUserAgent();

    auto parsedResults = parser->parse(input.ua.toUtf8String().rawString());

    Date ts = input.ua.getEffectiveTimestamp();

    ParsedUserAgent result;
    result.os.family = ExpressionValue(std::move(Utf8String(parsedResults.os.family)), ts);
    result.os.version = ExpressionValue(std::move(Utf8String(parsedResults.os.toVersionString())), ts);

    result.browser.family = ExpressionValue(std::move(Utf8String(parsedResults.browser.family)), ts);
    result.browser.version = ExpressionValue(std::move(Utf8String(parsedResults.browser.toVersionString())), ts);

    result.device.model = ExpressionValue(std::move(Utf8String(parsedResults.device.model)), ts);
    result.device.brand = ExpressionValue(std::move(Utf8String(parsedResults.device.brand)), ts);

    result.isSpider = ExpressionValue(parsedResults.isSpider(), ts);

    return result;
}

static RegisterFunctionType<ParseUserAgentFunction, ParseUserAgentFunctionConfig>
regParseUserAgentFunction(builtinPackage(),
                          "http.useragent",
                          "Parse user agent strings into their components",
                          "functions/ParseUserAgent.md.html");

} // namespace MLDB


text:
@implementation NIToolbarPhotoViewController

@synthesize toolbarIsTranslucent = _toolbarIsTranslucent;
@synthesize hidesChromeWhenScrolling = _hidesChromeWhenScrolling;
@synthesize chromeCanBeHidden = _chromeCanBeHidden;
@synthesize animateMovingToNextAndPreviousPhotos = _animateMovingToNextAndPreviousPhotos;
@synthesize scrubberIsEnabled = _scrubberIsEnabled;
@synthesize toolbar = _toolbar;
@synthesize photoAlbumView = _photoAlbumView;
@synthesize photoScrubberView = _photoScrubberView;
@synthesize nextButton = _nextButton;
@synthesize previousButton = _previousButton;

///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)shutdown_NIToolbarPhotoViewController {
  _toolbar = nil;
  _photoAlbumView = nil;

  NI_RELEASE_SAFELY(_nextButton);
  NI_RELEASE_SAFELY(_previousButton);

  NI_RELEASE_SAFELY(_photoScrubberView);

  NI_RELEASE_SAFELY(_tapGesture);
}

///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)dealloc {
  [self shutdown_NIToolbarPhotoViewController];

  [super dealloc];
}

///////////////////////////////////////////////////////////////////////////////////////////////////
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
  if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
    // Default Configuration Settings
    self.toolbarIsTranslucent = YES;
    self.hidesChromeWhenScrolling = YES;
    self.chromeCanBeHidden = YES;
    self.animateMovingToNextAndPreviousPhotos = NO;

    // The scrubber is better use of the extra real estate on the iPad.
    // If you ask me, though, the scrubber works pretty well on the iPhone too. It's up
    // to you if you want to use it in your own implementations.
    self.scrubberIsEnabled = NIIsPad();

    // Allow the photos to display beneath the status bar.
    self.wantsFullScreenLayout = YES;
  }
  return self;
}

///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)addTapGestureToView {
  if ([self isViewLoaded]
      && nil != NIUITapGestureRecognizerClass()
      && [self.photoAlbumView respondsToSelector:@selector(addGestureRecognizer:)]) {
    if (nil == _tapGesture) {
      _tapGesture =
      [[NIUITapGestureRecognizerClass() alloc] initWithTarget: self
                                                       action: @selector(didTap)];

      [self.photoAlbumView addGestureRecognizer:_tapGesture];
    }
  }

  [_tapGesture setEnabled:YES];
}

///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)updateToolbarItems {
  UIBarItem* flexibleSpace =
  [[[UIBarButtonItem alloc] initWithBarButtonSystemItem: UIBarButtonSystemItemFlexibleSpace
                                                 target: nil
                                                 action: nil] autorelease];

  if ([self isScrubberEnabled]) {
    NI_RELEASE_SAFELY(_nextButton);
    NI_RELEASE_SAFELY(_previousButton);

    if (nil == _photoScrubberView) {
      CGRect scrubberFrame = CGRectMake(0, 0,
                                        self.toolbar.bounds.size.width,
                                        self.toolbar.bounds.size.height);
      _photoScrubberView = [[NIPhotoScrubberView alloc] initWithFrame:scrubberFrame];
      _photoScrubberView.autoresizingMask = (UIViewAutoresizingFlexibleWidth
                                             | UIViewAutoresizingFlexibleHeight);
      _photoScrubberView.delegate = self;
    }

    UIBarButtonItem* scrubberItem =
    [[[UIBarButtonItem alloc] initWithCustomView:self.photoScrubberView] autorelease];
    self.toolbar.items = [NSArray arrayWithObjects:
                          flexibleSpace, scrubberItem, flexibleSpace,
                          nil];

    [_photoScrubberView setSelectedPhotoIndex:self.photoAlbumView.centerPageIndex];

  } else {
    NI_RELEASE_SAFELY(_photoScrubberView);

    if (nil == _nextButton) {
      UIImage* nextIcon = [UIImage imageWithContentsOfFile:
                           NIPathForBundleResource(nil, @"NimbusPhotos.bundle/gfx/next.png")];

      // We weren't able to find the next or previous icons in your application's resources.
      // Ensure that you've dragged the NimbusPhotos.bundle from src/photos/resources into your
      // application with the "Create Folder References" option selected. You can verify that
      // you've done this correctly by expanding the NimbusPhotos.bundle file in your project
      // and verifying that the 'gfx' directory is blue. Also verify that the bundle is being
      // copied in the Copy Bundle Resources phase.
      NIDASSERT(nil != nextIcon);

      _nextButton = [[UIBarButtonItem alloc] initWithImage: nextIcon
                                                     style: UIBarButtonItemStylePlain
                                                    target: self
                                                    action: @selector(didTapNextButton)];

    }

    if (nil == _previousButton) {
      UIImage* previousIcon = [UIImage imageWithContentsOfFile:
                               NIPathForBundleResource(nil, @"NimbusPhotos.bundle/gfx/previous.png")];

      // We weren't able to find the next or previous icons in your application's resources.
      // Ensure that you've dragged the NimbusPhotos.bundle from src/photos/resources into your
      // application with the "Create Folder References" option selected. You can verify that
      // you've done this correctly by expanding the NimbusPhotos.bundle file in your project
      // and verifying that the 'gfx' directory is blue. Also verify that the bundle is being
      // copied in the Copy Bundle Resources phase.
      NIDASSERT(nil != previousIcon);

      _previousButton = [[UIBarButtonItem alloc] initWithImage: previousIcon
                                                         style: UIBarButtonItemStylePlain
                                                        target: self
                                                        action: @selector(didTapPreviousButton)];
    }

    self.toolbar.items = [NSArray arrayWithObjects:
                          flexibleSpace, self.previousButton,
                          flexibleSpace, self.nextButton,
                          flexibleSpace,
                          nil];
  }

}

///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)loadView {
  [super loadView];

  CGRect bounds = self.view.bounds;

  // Toolbar Setup

  CGFloat toolbarHeight = NIToolbarHeightForOrientation(NIInterfaceOrientation());
  CGRect toolbarFrame = CGRectMake(0, bounds.size.height - toolbarHeight,
                                   bounds.size.width, toolbarHeight);

  _toolbar = [[[UIToolbar alloc] initWithFrame:toolbarFrame] autorelease];
  _toolbar.barStyle = UIBarStyleBlack;
  _toolbar.translucent = self.toolbarIsTranslucent;
  _toolbar.autoresizingMask = (UIViewAutoresizingFlexibleWidth
                               | UIViewAutoresizingFlexibleTopMargin);

  [self updateToolbarItems];

  // Photo Album View Setup

  CGRect photoAlbumFrame = bounds;
  if (!self.toolbarIsTranslucent) {
    photoAlbumFrame = NIRectContract(bounds, 0, toolbarHeight);
  }
  _photoAlbumView = [[[NIPhotoAlbumScrollView alloc] initWithFrame:photoAlbumFrame] autorelease];
  _photoAlbumView.autoresizingMask = (UIViewAutoresizingFlexibleWidth
                                      | UIViewAutoresizingFlexibleHeight);
  _photoAlbumView.delegate = self;

  [self.view addSubview:_photoAlbumView];
  [self.view addSubview:_toolbar];

  if (self.hidesChromeWhenScrolling) {
    [self addTapGestureToView];
  }
}

///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)viewDidUnload {
  [self shutdown_NIToolbarPhotoViewController];

  [super viewDidUnload];
}

///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)viewWillAppear:(BOOL)animated {
  [super viewWillAppear:animated];

  [NINavigationAppearance pushAppearanceForNavigationController:self.navigationController];

  [[UIApplication sharedApplication] setStatusBarStyle: (NIIsPad()
                                                         ? UIStatusBarStyleBlackOpaque
                                                         : UIStatusBarStyleBlackTranslucent)
                                              animated: animated];

  UINavigationBar* navBar = self.navigationController.navigationBar;
  navBar.barStyle = UIBarStyleBlack;
  navBar.translucent = YES;

  _previousButton.enabled = [self.photoAlbumView hasPrevious];
  _nextButton.enabled = [self.photoAlbumView hasNext];
}

///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)viewWillDisappear:(BOOL)animated {
  [super viewWillDisappear:animated];

  [NINavigationAppearance popAppearanceForNavigationController:self.navigationController animated:YES];
}

///////////////////////////////////////////////////////////////////////////////////////////////////
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation {
  return NIIsSupportedOrientation(toInterfaceOrientation);
}

///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)willRotateToInterfaceOrientation: (UIInterfaceOrientation)toInterfaceOrientation
                                duration: (NSTimeInterval)duration {
  [super willRotateToInterfaceOrientation:toInterfaceOrientation duration:duration];

  [self.photoAlbumView willRotateToInterfaceOrientation:toInterfaceOrientation duration:duration];
}

///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)willAnimateRotationToInterfaceOrientation: (UIInterfaceOrientation)toInterfaceOrientation
                                         duration: (NSTimeInterval)duration {
  [self.photoAlbumView willAnimateRotationToInterfaceOrientation: toInterfaceOrientation
                                                        duration: duration];

  [super willAnimateRotationToInterfaceOrientation:toInterfaceOrientation
                                          duration:duration];

  CGRect toolbarFrame = self.toolbar.frame;
  toolbarFrame.size.height = NIToolbarHeightForOrientation(toInterfaceOrientation);
  toolbarFrame.origin.y = self.view.bounds.size.height - toolbarFrame.size.height;
  self.toolbar.frame = toolbarFrame;

  if (!self.toolbarIsTranslucent) {
    CGRect photoAlbumFrame = self.photoAlbumView.frame;
    photoAlbumFrame.size.height = self.view.bounds.size.height - toolbarFrame.size.height;
    self.photoAlbumView.frame = photoAlbumFrame;
  }
}

///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)didHideChrome {
  _isAnimatingChrome = NO;
  if (self.toolbarIsTranslucent) {
    self.toolbar.hidden = YES;
  }

  _isChromeHidden = YES;
}

///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)didShowChrome {
  _isAnimatingChrome = NO;

  _isChromeHidden = NO;
}

///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)setChromeVisibility:(BOOL)isVisible animated:(BOOL)animated {
  if (_isAnimatingChrome
      || (!isVisible && _isChromeHidden)
      || (isVisible && !_isChromeHidden)
      || !self.chromeCanBeHidden) {
    // Nothing to do here.
    return;
  }

  CGRect toolbarFrame = self.toolbar.frame;
  CGRect bounds = self.view.bounds;

  if (self.toolbarIsTranslucent) {
    // Reset the toolbar's initial position.
    if (!isVisible) {
      toolbarFrame.origin.y = bounds.size.height - toolbarFrame.size.height;

    } else {
      // Ensure that the toolbar is visible through the animation.
      self.toolbar.hidden = NO;

      toolbarFrame.origin.y = bounds.size.height;
    }
    self.toolbar.frame = toolbarFrame;
  }

  // Show/hide the system chrome.
  if ([[UIApplication sharedApplication] respondsToSelector:
       @selector(setStatusBarHidden:withAnimation:)]) {
    // On 3.2 and higher we can slide the status bar out.
    [[UIApplication sharedApplication] setStatusBarHidden: !isVisible
                                            withAnimation: (animated
                                                            ? UIStatusBarAnimationSlide
                                                            : UIStatusBarAnimationNone)];

  } else {
#if __IPHONE_OS_VERSION_MIN_REQUIRED < NIIOS_3_2
    // On 3.0 devices we use the boring fade animation.
    [[UIApplication sharedApplication] setStatusBarHidden: !isVisible
                                                 animated: animated];
#endif
  }

  if (self.toolbarIsTranslucent) {
    // Place the toolbar at its final location.
    if (isVisible) {
      // Slide up.
      toolbarFrame.origin.y = bounds.size.height - toolbarFrame.size.height;

    } else {
      // Slide down.
      toolbarFrame.origin.y = bounds.size.height;
    }
  }

  // If there is a navigation bar, place it at its final location.
  CGRect navigationBarFrame = CGRectZero;
  if (nil != self.navigationController.navigationBar) {
    navigationBarFrame = self.navigationController.navigationBar.frame;
    CGRect statusBarFrame = [[UIApplication sharedApplication] statusBarFrame];
    CGFloat statusBarHeight = MIN(statusBarFrame.size.width, statusBarFrame.size.height);

    if (isVisible) {
      navigationBarFrame.origin.y = statusBarHeight;

    } else {
      navigationBarFrame.origin.y = 0;
    }
  }

  if (animated) {
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDidStopSelector:(isVisible
                                         ? @selector(didShowChrome)
                                         : @selector(didHideChrome))];

    // Ensure that the animation matches the status bar's.
    [UIView setAnimationDuration:NIStatusBarAnimationDuration()];
    [UIView setAnimationCurve:NIStatusBarAnimationCurve()];
  }

  if (self.toolbarIsTranslucent) {
    self.toolbar.frame = toolbarFrame;
  }
  if (nil != self.navigationController.navigationBar) {
    self.navigationController.navigationBar.frame = navigationBarFrame;
    self.navigationController.navigationBar.alpha = (isVisible ? 1 : 0);
  }

  if (animated) {
    _isAnimatingChrome = YES;
    [UIView commitAnimations];

  } else if (!isVisible) {
    [self didHideChrome];

  } else if (isVisible) {
    [self didShowChrome];
  }
}

///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)toggleChromeVisibility {
  [self setChromeVisibility:(_isChromeHidden || _isAnimatingChrome) animated:YES];
}

///////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark -
#pragma mark UIGestureRecognizer

///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)didTap {
  SEL selector = @selector(toggleChromeVisibility);
  if (self.photoAlbumView.zoomingIsEnabled) {
    // Cancel any previous delayed performs so that we don't stack them.
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:selector object:nil];

    // We need to delay taking action on the first tap in case a second tap comes in, causing
    // a double-tap gesture to be recognized and the photo to be zoomed.
    [self performSelector: selector
               withObject: nil
               afterDelay: 0.3];

  } else {
    // When zooming is disabled, double-tap-to-zoom is also disabled so we don't have to
    // be as careful; just toggle the chrome immediately.
    [self toggleChromeVisibility];
  }
}

///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)refreshChromeState {
  self.previousButton.enabled = [self.photoAlbumView hasPrevious];
  self.nextButton.enabled = [self.photoAlbumView hasNext];

  self.title = [NSString stringWithFormat:@"%d of %d",
                (self.photoAlbumView.centerPageIndex + 1),
                self.photoAlbumView.numberOfPages];
}

///////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark -
#pragma mark NIPhotoAlbumScrollViewDelegate

///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)pagingScrollViewDidScroll:(NIPagingScrollView *)pagingScrollView {
  if (self.hidesChromeWhenScrolling) {
    [self setChromeVisibility:NO animated:YES];
  }
}

///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)photoAlbumScrollView: (NIPhotoAlbumScrollView *)photoAlbumScrollView
                   didZoomIn: (BOOL)didZoomIn {
  // This delegate method is called after a double-tap gesture, so cancel any pending
  // single-tap gestures.
  [NSObject cancelPreviousPerformRequestsWithTarget: self
                                           selector: @selector(toggleChromeVisibility)
                                             object: nil];
}

///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)pagingScrollViewDidChangePages:(NIPagingScrollView *)pagingScrollView {
  // We animate the scrubber when the chrome won't disappear as a nice touch.
  // We don't bother animating if the chrome disappears when scrolling because the user
  // will barely see the animation happen.
  [self.photoScrubberView setSelectedPhotoIndex: [pagingScrollView centerPageIndex]
                                       animated: !self.hidesChromeWhenScrolling];

  [self refreshChromeState];
}

///////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark -
#pragma mark NIPhotoScrubberViewDelegate

///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)photoScrubberViewDidChangeSelection:(NIPhotoScrubberView *)photoScrubberView {
  [self.photoAlbumView moveToPageAtIndex:photoScrubberView.selectedPhotoIndex animated:NO];

  [self refreshChromeState];
}

///////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark -
#pragma mark Actions

///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)didTapNextButton {
  [self.photoAlbumView moveToNextAnimated:self.animateMovingToNextAndPreviousPhotos];
}

///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)didTapPreviousButton {
  [self.photoAlbumView moveToPreviousAnimated:self.animateMovingToNextAndPreviousPhotos];
}

///////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark -
#pragma mark Public Methods

///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)settoolbarIsTranslucent:(BOOL)enabled {
  _toolbarIsTranslucent = enabled;

  self.toolbar.translucent = enabled;
}

///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)setHidesChromeWhenScrolling:(BOOL)hidesToolbar {
  _hidesChromeWhenScrolling = hidesToolbar;

  if (hidesToolbar) {
    [self addTapGestureToView];

  } else {
    [_tapGesture setEnabled:NO];
  }
}

///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)setChromeCanBeHidden:(BOOL)canBeHidden {
  if (nil == NIUITapGestureRecognizerClass()) {
    // Don't allow the chrome to be hidden if we can't tap to make it visible again.
    canBeHidden = NO;
  }

  _chromeCanBeHidden = canBeHidden;

  if (!canBeHidden) {
    self.hidesChromeWhenScrolling = NO;

    if ([self isViewLoaded]) {
      // Ensure that the toolbar is visible.
      self.toolbar.hidden = NO;

      CGRect toolbarFrame = self.toolbar.frame;
      CGRect bounds = self.view.bounds;
      toolbarFrame.origin.y = bounds.size.height - toolbarFrame.size.height;
      self.toolbar.frame = toolbarFrame;
    }
  }
}

///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)setScrubberIsEnabled:(BOOL)enabled {
  if (_scrubberIsEnabled != enabled) {
    _scrubberIsEnabled = enabled;

    if ([self isViewLoaded]) {
      [self updateToolbarItems];
    }
  }
}

@end


text:
#include <stdbool.h>

#ifdef __cplusplus
extern "C" {
#endif

	typedef struct ArrayList {
		const int capacity;
		void** const pBuf;
		size_t index;
		struct ArrayList* (*const add)(struct ArryaList* pThis, void* pData);
		void* (*const remove)(struct ArrayList* pThis, void* pData);
		void* (*const get)(struct ArrayList* pThis, int index);
		size_t (*const size)(struct ArrayList* pThis);
	} ArrayList;

	ArrayList* add_to_array_list(ArrayList* pThis, void* pData);
	void* remove_from_array_list(ArrayList* pThis, void* pData);
	void* get_from_array_list(ArrayList* pThis, int index);
	size_t array_list_size(ArrayList* pThis);

#define new_array_list(array) {sizeof(array)/sizeof(void*), array, 0, add_to_array_list, remove_from_array_list, get_from_array_list, array_list_size}

#ifdef __cplusplus
}
#endif

#endif


text:
/*jslint node: true*/

"use strict";

var url = require("url"),
    lodash = require("lodash"),
    q = require("q"),
    site = require("../scraper").site;

module.exports = function archiver(spec) {
    var isRunning,

        getDb = function getDb() {
            return spec.db;
        },

        getRecipeIds = function getRecipeIds() {
            return q(getDb().
                allDocs().
                then(function (result) {
                    return result.
                        rows.
                        map(function (row) {
                            return row.id;
                        });
                }));
        },

        putRecipe = function putRecipe(id, recipe, image) {
            var db = getDb();
            return q(db.
                put(lodash.merge({type: "recipe", retrieved: new Date()}, recipe), id).
                then(function (result) {
                    db.putAttachment(
                        result.id,
                        "image",
                        result.rev,
                        image.buffer,
                        image.contentType
                    );
                }));
        },

        idify = function idify(recipeUrl) {
            var path = url.
                parse(recipeUrl).
                pathname.
                replace(/\/$/, "");
            if (path.length === 0) {
                return undefined;
            }
            return path.substr(path.lastIndexOf("/") + 1);
        },

        createTask = function createTask(recipesPage, recipeUrl) {
            return function () {
                return recipesPage.
                    createRecipePage(recipeUrl).
                    then(function (recipePage) {
                        return recipePage.
                            createRecipeImage().
                            then(function (recipeImage) {
                                return [recipePage.getRecipe(), recipeImage.toBuffer()];
                            });
                    }).
                    spread(function (recipe, image) {
                        putRecipe(idify(recipeUrl), recipe, image);
                    });
            };
        },

        createQueue = function createQueue() {
            var recipesPage = site.createRecipesPage();
            return q.
                all([recipesPage.getRecipeUrls(), getRecipeIds()]).
                spread(function (recipeUrls, recipeIds) {
                    return recipeUrls.
                        filter(function (recipeUrl) {
                            return !lodash.contains(recipeIds, idify(recipeUrl));
                        }).
                        map(function (recipeUrl) {
                            return createTask(recipesPage, recipeUrl);
                        });
                });
        },

        processQueue = function processQueue(queue) {
            if (queue.length === 0) {
                return;
            }
            var func = queue.shift();
            return func().then(function () {
                return processQueue(queue);
            });
        },

        archiveRecipes = function archiveRecipes() {
            if (isRunning) {
                return q.fcall(function () {
                    throw {name: "still running", message: "archive recipes is still running"};
                });
            }
            isRunning = true;
            return createQueue().
                then(processQueue).
                then(function () {
                    isRunning = false;
                });
        },

        initialise = function initialise() {
            isRunning = false;
            return {archiveRecipes: archiveRecipes};
        };

    return initialise();
};