text:
package com.facebook.litho.intellij.services;

import com.facebook.litho.intellij.LithoPluginUtils;
import com.facebook.litho.sections.specmodels.model.GroupSectionSpecModel;
import com.facebook.litho.specmodels.internal.RunMode;
import com.facebook.litho.specmodels.model.LayoutSpecModel;
import com.facebook.litho.specmodels.model.MountSpecModel;
import com.facebook.litho.specmodels.model.SpecModel;
import com.facebook.litho.specmodels.processor.PsiDiffSectionSpecModelFactory;
import com.facebook.litho.specmodels.processor.PsiGroupSectionSpecModelFactory;
import com.facebook.litho.specmodels.processor.PsiLayoutSpecModelFactory;
import com.facebook.litho.specmodels.processor.PsiMountSpecModelFactory;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.PsiClass;
import com.squareup.javapoet.JavaFile;
import com.squareup.javapoet.TypeSpec;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import org.jetbrains.annotations.Nullable;

/**
 * Utility class helping to create {@link SpecModel}s from the given file and update generated
 * Component files with the new model.
 */
public class ComponentGenerateService {
  private static final PsiLayoutSpecModelFactory LAYOUT_SPEC_MODEL_FACTORY =
      new PsiLayoutSpecModelFactory();
  private static final PsiMountSpecModelFactory MOUNT_SPEC_MODEL_FACTORY =
      new PsiMountSpecModelFactory();
  private static final PsiGroupSectionSpecModelFactory GROUP_SECTION_SPEC_MODEL_FACTORY =
      new PsiGroupSectionSpecModelFactory();
  private static final PsiDiffSectionSpecModelFactory DIFF_SECTION_SPEC_MODEL_FACTORY =
      new PsiDiffSectionSpecModelFactory();
  private final Set<SpecUpdateNotifier> listeners = Collections.synchronizedSet(new HashSet<>());
  private final Map<String, SpecModel> specFqnToModelMap =
      Collections.synchronizedMap(createLRUMap(50));

  public interface SpecUpdateNotifier {
    void onSpecModelUpdated(PsiClass specCls);
  }

  public static ComponentGenerateService getInstance() {
    return ServiceManager.getService(ComponentGenerateService.class);
  }

  private ComponentGenerateService() {}

  /** Subscribes listener to Spec model updates. Removes subscription once parent is disposed. */
  public void subscribe(SpecUpdateNotifier listener, Disposable parent) {
    listeners.add(listener);
    Disposer.register(parent, () -> listeners.remove(listener));
  }

  /**
   * Creates new Component file text content.
   *
   * @param specCls corresponding to generated Component.
   * @return a Pair of Component FQN (first) and file text content (second). Null if specCls is not
   *     valid.
   */
  @Nullable
  public Pair<String, String> createLithoFileContent(PsiClass specCls) {
    final String componentQN =
        LithoPluginUtils.getLithoComponentNameFromSpec(specCls.getQualifiedName());
    if (componentQN == null) return null;

    final SpecModel model = getOrCreateSpecModel(specCls);
    if (model == null) return null;

    final String newContent = createFileContentFromModel(componentQN, model);
    return Pair.create(componentQN, newContent);
  }

  @Nullable
  public SpecModel getOrCreateSpecModel(PsiClass specClass) {
    return getOrCreateSpecModel(specClass, true);
  }

  @Nullable
  public SpecModel getOrCreateSpecModel(PsiClass specClass, boolean useCachedValue) {
    final SpecModel model;
    final String specFQN = specClass.getQualifiedName();

    synchronized (specFqnToModelMap) {
      if (useCachedValue && specFqnToModelMap.containsKey(specFQN)) {
        return specFqnToModelMap.get(specFQN);
      }

      model = createModel(specClass);
      if (model == null) return null;

      // New model might be malformed to generate component, but it's accurate to the Spec
      specFqnToModelMap.put(specFQN, model);
    }

    Set<SpecUpdateNotifier> copy;
    synchronized (listeners) {
      copy = new HashSet<>(listeners);
    }
    copy.forEach(listener -> listener.onSpecModelUpdated(specClass));

    return model;
  }

  /**
   * Generates new {@link SpecModel} from the given {@link PsiClass}.
   *
   * @return new {@link SpecModel} or null if provided class is not a {@link
   *     com.facebook.litho.annotations.LayoutSpec} or {@link
   *     com.facebook.litho.annotations.MountSpec} or {@link
   *     com.facebook.litho.sections.annotations.GroupSectionSpec} or {@link
   *     com.facebook.litho.sections.annotations.DiffSectionSpec} class.
   */
  @Nullable
  private static SpecModel createModel(PsiClass specCls) {
    final LayoutSpecModel layoutSpecModel =
        LAYOUT_SPEC_MODEL_FACTORY.createWithPsi(specCls.getProject(), specCls, null);
    if (layoutSpecModel != null) {
      return layoutSpecModel;
    }
    final MountSpecModel mountSpecModel =
        MOUNT_SPEC_MODEL_FACTORY.createWithPsi(specCls.getProject(), specCls, null);
    if (mountSpecModel != null) {
      return mountSpecModel;
    }
    final GroupSectionSpecModel groupSectionSpecModel =
        GROUP_SECTION_SPEC_MODEL_FACTORY.createWithPsi(specCls.getProject(), specCls, null);
    if (groupSectionSpecModel != null) {
      return groupSectionSpecModel;
    }
    return DIFF_SECTION_SPEC_MODEL_FACTORY.createWithPsi(specCls.getProject(), specCls, null);
  }

  private static String createFileContentFromModel(String clsQualifiedName, SpecModel specModel) {
    TypeSpec typeSpec = specModel.generate(RunMode.normal());
    return JavaFile.builder(StringUtil.getPackageName(clsQualifiedName), typeSpec)
        .skipJavaLangImports(true)
        .build()
        .toString();
  }

  private static <K, V> Map<K, V> createLRUMap(final int maxEntries) {
    return new LinkedHashMap<K, V>(maxEntries * 10 / 7, 0.7f, true) {
      @Override
      protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
        return size() > maxEntries;
      }
    };
  }
}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.nemesis.admin;

import com.nemesis.entity.Department;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;

/**
 *
 * @author shareppy
 */
@WebServlet(name = "DepartmentService", urlPatterns = {"/admin/departments", "/admin/departments/create", "/admin/departments/edit/*", "/admin/departments/list", "/admin/departments/delete/*"})
public class DepartmentService extends BaseService<Department> {

    @Override
    protected Class<Department> getEntity() {
        return Department.class;
    }

    @Override
    protected String getEditView(HttpServletRequest rq, boolean isCreate) {
        if (isCreate) {
            setTitle(rq, "Crear un departamento");
            return "../department_edit.jsp";
        }
        rq.setAttribute("_title_", "Editar un departamento");
        return "../../department_edit.jsp";
    }

    @Override
    protected String getSearchView(HttpServletRequest rq) {
        setTitle(rq, "Buscar departamentos");
        return "departments.jsp";
    }

    @Override
    protected String afterSaveUrl() {
        return getServletContext().getContextPath() + "/admin/departments";
    }
}

redpajama_set_name: RedPajamaGithub


text:
from django.shortcuts import get_object_or_404, render
from django.template import RequestContext
from django.http import HttpResponseRedirect, HttpResponse, HttpResponseForbidden, HttpResponseNotAllowed
from django.core.urlresolvers import reverse
from cog.models import *
from django.contrib.auth.decorators import login_required
import re
from django.views.decorators.csrf import csrf_exempt
import json
from django.views.decorators.http import require_GET, require_POST, require_http_methods
from cog.views.views_search import SEARCH_DATA, SEARCH_OUTPUT
from django.core.exceptions import ObjectDoesNotExist
from django_openid_auth.models import UserOpenID
from cog.views.utils import getQueryDict
from cog.site_manager import siteManager

try:
    import esgfpid
except ImportError:
    pass

INVALID_CHARS = "[<>&#%{}\[\]\$]"

# view to display the data cart for a given node, user
@require_GET
@login_required
def datacart_display(request, site_id, user_id):

    # load User object
    user = get_object_or_404(User, pk=user_id)
    # security checl
    if user != request.user:
        return HttpResponseForbidden("Un-authorized attempt to access another user datacart!")
    try:
        datacart = DataCart.objects.get(user=user)
    except DataCart.DoesNotExist:
        datacart = None

    return render(request,
                  'cog/datacart/datacart.html',
                  {'datacart': datacart})

# view to display a user datacart by openid
@require_GET
@login_required
def datacart_byopenid(request):

    if request.method == 'GET':

        openid = request.GET['openid']

        # load User object
        userOpenid = get_object_or_404(UserOpenID, claimed_id=openid)

        # redirect to user profile page on local node
        return HttpResponseRedirect(reverse('datacart_display',
                                    kwargs={'site_id': Site.objects.get_current().id, 'user_id': userOpenid.user.id}))

    else:
        return HttpResponseNotAllowed(['GET'])

# view to add an item to a user data cart
# NOTE: no CSRF token required, but request must be authenticated
@login_required
@require_POST
@csrf_exempt
def datacart_add(request, site_id, user_id):

    # load User object
    user = get_object_or_404(User, pk=user_id)

    # security check
    if not request.user.id != user_id:
        raise Exception("User not authorized to modify datacart")

    datacart = DataCart.objects.get(user=user)

    response_data = {}

    # retrieve data item attributes from request
    identifier = request.POST['id']
    metadata = request.POST['metadata']
    #print 'JSON METADATA=%s' % metadata

    # check item is not in cart already
    items = DataCartItem.objects.filter(cart=datacart, identifier=identifier)
    if len(items.all()) > 0:
        response_data['message'] = 'This item is already in the Data Cart'

    else:
        # add item to the cart
        item = DataCartItem.fromJson(datacart, identifier, metadata)

    # return new number of items in cart
    response_data['datacart_size'] = len(datacart.items.all())
    # return identifier of newly added datcart item
    response_data['item'] = identifier

    return HttpResponse(json.dumps(response_data), content_type='application/json')

# view to add ALL current search results (as displayed in the page) to the user data cart
@login_required
@require_GET
def datacart_add_all(request, site_id, user_id):

    # load User object
    user = get_object_or_404(User, pk=user_id)
    try:
        datacart = DataCart.objects.get(user=user)
    except DataCart.DoesNotExist:
        datacart = None

    # security check
    if not request.user.id != user_id:
        raise Exception("User not authorized to modify datacart")

    # retrieve results from session
    data = request.session.get(SEARCH_DATA, None)
    if data is not None:
        searchOutput = data[SEARCH_OUTPUT]

        # loop over record
        print "Adding %s items" % len(searchOutput.results)
        for record in searchOutput.results:

            # check item is not in cart already
            if DataCartItem.objects.filter(cart=datacart, identifier=record.id).exists():
                print 'Item %s already in Data Cart' % record.id
            else:
                item = DataCartItem.fromRecord(datacart, record)
                print 'Added item: %s' % record.id

    # redirect to search results
    back = request.GET.get('back', '/')
    return HttpResponseRedirect(back)

# view to delete ALL current search results (as displayed in the page) from the user data cart
@login_required
@require_GET
def datacart_delete_all(request, site_id, user_id):

    # load User object
    user = get_object_or_404(User, pk=user_id)

    try:
        datacart = DataCart.objects.get(user=user)
    except DataCart.DoesNotExist:
        datacart = None

    # security check
    if not request.user.id != user_id:
        raise Exception("User not authorized to modify datacart")

    # retrieve results from session
    data = request.session.get(SEARCH_DATA, None)
    if data is not None:
        searchOutput = data[SEARCH_OUTPUT]

        # loop over record
        print "Deleting %s items" % len(searchOutput.results)
        for record in searchOutput.results:

            try:
                item = DataCartItem.objects.get(cart=datacart, identifier=record.id)
                print 'Deleting item: %s' % item.id
                item.delete()
            except ObjectDoesNotExist:
                pass

    # redirect to search results
    back = request.GET.get('back', '/')
    return HttpResponseRedirect(back)

# view to generate wget URLS for all selected datacart items
# can be invoked either through GET or POST requests
# NOTE: no CSRF token required, but request must be authenticated
@login_required
@require_http_methods(["GET", "POST"])
#@require_POST
@csrf_exempt
def datacart_wget(request, site_id, user_id):

    # load User object
    user = get_object_or_404(User, pk=user_id)

    # security check
    if not request.user.id != user_id:
        raise Exception("User not authorized to use datacart")

    # retrieve list of selected dataset ids
    queryDict = getQueryDict(request)
    ids = queryDict.getlist('id')

    # map of dataset ids grouped by index node
    response_data = {}

    # loop over datacart items
    try:
        datacart = DataCart.objects.get(user=user)
    except DataCart.DoesNotExist:
        datacart = None

    if datacart:
        for item in datacart.items.all():

            # filter selected datasets only
            if item.identifier in ids:

                # group selected dataset by index_node
                index_node = item.getValue('index_node')
                wget_key = index_node
                shard = item.getValue('shard')
                if shard is not None and len(shard.strip())>0:
                    wget_key += "|" + shard
                if wget_key not in response_data:
                    response_data[wget_key] = []
                response_data[wget_key].append(item.identifier)

    '''
    Example response_data:
    {
        u'esgf-node.jpl.nasa.gov|localhost:8982': [u'CMAC.NASA-GSFC.AIRS.mon.v1|esg-datanode.jpl.nasa.gov'],
        u'esgf-node.jpl.nasa.gov': [u'obs4MIPs.NASA-JPL.QuikSCAT.mon.v1|esgf-node.jpl.nasa.gov'],
        u'pcmdi9.llnl.gov':
            [
              u'cmip5.output1.INM.inmcm4.1pctCO2.day.atmos.day.r1i1p1.v20110323|pcmdi9.llnl.gov',
              u'cmip5.output1.INM.inmcm4.esmHistorical.fx.atmos.fx.r0i0p0.v20110927|pcmdi9.llnl.gov',
              u'cmip5.output1.INM.inmcm4.1pctCO2.day.ocean.day.r1i1p1.v20110323|pcmdi9.llnl.gov'
           ]
    }
    '''
    return HttpResponse(json.dumps(response_data), content_type='application/json')

# view to delete an item to a user data cart
@login_required
@require_POST
@csrf_exempt
def datacart_delete(request, site_id, user_id):

    # check User object
    user = get_object_or_404(User, pk=user_id)

    # security check
    if not request.user.id != user_id:
        raise Exception("User not authorized to modify datacart")

    # TODO:: check node, redirect in case
    identifier = request.POST['item']

    # NOTE: make sure this item belongs to the user's data cart
    (datacart, _) = DataCart.objects.get_or_create(user=user)

    item = DataCartItem.objects.get(identifier=identifier, cart=datacart)
    item.delete()

    # return new number of items in cart
    response_data = {}
    # return id of item just deleted so it can be hidden
    response_data['item'] = identifier
    # return number of remaining items
    response_data['datacart_size'] = len(datacart.items.all())

    return HttpResponse(json.dumps(response_data), content_type='application/json')

# view to completely empty a user data cart
# NOTE: no CSRF token required, but request must be authenticated
@login_required
@require_POST
@csrf_exempt
def datacart_empty(request, site_id, user_id):

    # check User object
    user = get_object_or_404(User, pk=user_id)

    # security check
    if not request.user.id != user_id:
        raise Exception("User not authorized to modify datacart")

    # user data cart
    try:
        datacart = DataCart.objects.get(user=user)
    except DataCart.DoesNotExist:
        datacart = None

    # delete all items associated with user data cart
    DataCartItem.objects.filter(cart=datacart).delete()

    return HttpResponseRedirect(reverse('datacart_display', args=[site_id, user_id]))

# view to generate a collection PID for the selected items in the data cart
@login_required
@require_POST
@csrf_exempt
def datacart_pid(request, site_id, user_id):

    # check User object
    user = get_object_or_404(User, pk=user_id)

    # security check
    if not request.user.id != user_id:
        raise Exception("User not authorized to modify datacart")

    pid_messaging_service_credentials = []
    priority = 1
    for cred in settings.PID_CREDENTIALS:
        parts = cred.split('|')

        if len(parts) == 6:

            ssl_enabled = False
            if parts[5].strip().upper() == 'TRUE':
                ssl_enabled = True

            pid_messaging_service_credentials.append({'url': parts[0].strip(),
                                                      'port': parts[1].strip(),
                                                      'vhost': parts[2].strip(),
                                                      'user': parts[3].strip(),
                                                      'password': parts[4].strip(),
                                                      'ssl_enabled': ssl_enabled,
                                                      'priority': priority})
            priority += 1

    # get list of dataset_pids and dataset_ids
    try:
        datacart = DataCart.objects.get(user=user)
    except DataCart.DoesNotExist:
        datacart = None

    queryDict = getQueryDict(request)
    ids = queryDict.getlist('id')

    dataset_ids = {}
    if datacart:
        for item in datacart.items.all():
            # filter selected datasets only
            if item.identifier in ids:
                dataset_ids[item.identifier.split('|')[0]] = item.getValue('pid')

    # call PID library to generate collection PID
    connector = esgfpid.Connector(handle_prefix=settings.PID_PREFIX,
                                  messaging_service_exchange_name=settings.PID_MESSAGING_SERVICE_EXCHANGE,
                                  messaging_service_credentials=pid_messaging_service_credentials,
                                  )

    connector.start_messaging_thread()
    pid = connector.create_data_cart_pid(dataset_ids)
    connector.finish_messaging_thread()

    print 'Generated data cart PID for %d datasets: %s' % (len(ids), pid)

    return HttpResponse(json.dumps(pid), content_type="application/json")


text:
import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), '../tools'))

from itertools import product

def main(argv):
    with open(argv[0]) as file:
        alpha = file.readline().split()
        n     = int(file.readline().strip())

        print '\n'.join(''.join(p) for p in product(alpha, repeat = n))

if __name__ == "__main__":
    main(sys.argv[1:])


text:
#include <boost/metaparse/v1/string.hpp>

// Include guard is after including v1/string.hpp to make it re-includable
#ifndef BOOST_METAPARSE_STRING_HPP
#define BOOST_METAPARSE_STRING_HPP

#include <boost/metaparse/string_tag.hpp>

#ifdef BOOST_METAPARSE_STRING
#  error BOOST_METAPARSE_STRING already defined
#endif
#define BOOST_METAPARSE_STRING BOOST_METAPARSE_V1_STRING

namespace boost
{
  namespace metaparse
  {
    using v1::string;
  }
}

#endif


text:
<!DOCTYPE html>

<form action="page3-backend.php" method="">

4. Structural Aspects

a. The roof is constructed such that it is not integral within itself (i.e., it does not act as a single unit and breaks open during earthquake shaking) and is not anchored into the walls

    <input type="radio" name="_4a" value='Y'/>Yes
    <input type="radio" name="_4a" value='N'/>No

b. The walls are thick and made in two wythes

    <input type="radio" name="_4b" value='Y'/>Yes
    <input type="radio" name="_4b" value='N'/>No

c. The walls are not integrated into each other at the corners

    <input type="radio" name="_4c" value='Y'/>Yes
    <input type="radio" name="_4c" value='N'/>No

5. Construction Details

a. The walls of the house are made with mud mortar and are exposed to the vagaries of the outside weather (especially rain water beating)

    <input type="radio" name="_5a" value='Y'/>Yes
    <input type="radio" name="_5a" value='N'/>No

    <input type="submit"/>Submit
</form>


text:
'use strict';

// Images

// Required modules
var gulp = require('gulp');

// Task: Compile sass into CSS, compress and auto-inject into browsers
gulp.task('images', function() {
    console.log('images!');
});


text:
package de.haw.se2.person.facade;

import java.time.LocalDate;
import java.util.List;

public interface PersonFactory {
    public Person createPerson(String id, String firstName, String lastName, LocalDate birthday);

    public Person findById(String id);

    public void delete(String id);

    public Person save(Person p);

    public List findAll();
}


text:
/*jshint expr: true*/
"use strict";
var chai = require("chai");
var expect = chai.expect;
chai.config.includeStack = true;
var request = require("supertest");
var alexaAppServer = require("../index");
var fs = require("fs");
var utils = require("../utils");

describe("Alexa App Server with Examples", function() {
  var testServer;
  var sampleLaunchReq, sampleUtterances, sampleSchema;

  before(function() {
    testServer = alexaAppServer.start({
      port: 3000,
      server_root: 'examples'
    });

    sampleLaunchReq = utils.readJsonFile("test/sample-launch-req.json");
    sampleUtterances = utils.readFile("test/sample-utterances.txt");
    sampleSchema = utils.readFile("test/sample-schema.txt");
  });

  after(function() {
    testServer.stop();
  });

  it("starts an express instance", function() {
    return request(testServer.express)
      .get('/')
      .expect(200).then(function(response) {
        expect(response.text).to.contain("alexa-app-server is running");
      });
  });

  describe("GET requests", function() {
    it("mounts hello world app", function() {
      return request(testServer.express)
        .get('/alexa/hello_world')
        .expect(200);
    });

    it("mounts number_guessing_game", function() {
      return request(testServer.express)
        .get('/alexa/number_guessing_game')
        .expect(200);
    });

    it("404s on an invalid app", function() {
      return request(testServer.express)
        .get('/alexa/invalid')
        .expect(404);
    });
  });

  describe("POST requests", function() {
    it("mounts hello world app", function() {
      return request(testServer.express)
        .post('/alexa/hello_world')
        .send(sampleLaunchReq)
        .expect(200);
    });

    it("mounts number_guessing_game", function() {
      return request(testServer.express)
        .post('/alexa/number_guessing_game')
        .send(sampleLaunchReq)
        .expect(200);
    });

    it("404s on an invalid app", function() {
      return request(testServer.express)
        .post('/alexa/invalid')
        .send(sampleLaunchReq)
        .expect(404);
    });
  });

  describe("schema and utterances", function() {
    it("returns the schema of the hello world app", function() {
      return request(testServer.express)
        .get('/alexa/hello_world?schema')
        .expect(200).then(function(res) {
          expect(res.text).to.equal.sampleSchema;
        });
    });

    it("returns the utterances of the hello world app", function() {
      return request(testServer.express)
        .get('/alexa/hello_world?utterances')
        .expect(200).then(function(res) {
          expect(res.text).to.equal.sampleUtterances;
        });
    });
  });
});


text:
module Compote

  class CLI < Thor

    COMPOSE_COMMANDS = %w()

    COMPOTE_COMMANDS = %w( env help version )

    compose_help = `docker-compose --help`

    compose_help = compose_help.split "\n"

    compose_help = compose_help.slice ( compose_help.index( "Commands:" ) + 1 )..-1

    compose_help.each do | command_info |

      command, description = command_info.strip.split( /\s+/, 2 )

      next if COMPOTE_COMMANDS.include? command

      COMPOSE_COMMANDS.push command

      desc command, description

      define_method "compose_#{ command }" do | *arguments |

        next exec 'docker-compose', command, *arguments if %w(-h --help).include? arguments[ 0 ]

        run_compose command, *arguments

      end

      map command => "compose_#{ command }"

    end

  end

end


text:
@interface ARDynamicScreenDimensions ()
@property (nonatomic, strong, readwrite) NSDictionary *currentDimensions;
@property (nonatomic, assign, readwrite) BOOL isBeingObserved;
@end

static NSDictionary *
getSafeAreaInsets()
{
  if (@available(iOS 11.0, *)) {
    return @{
             @"top": @(UIApplication.sharedApplication.keyWindow.safeAreaInsets.top),
             @"bottom": @(UIApplication.sharedApplication.keyWindow.safeAreaInsets.bottom),
             @"left": @(UIApplication.sharedApplication.keyWindow.safeAreaInsets.left),
             @"right": @(UIApplication.sharedApplication.keyWindow.safeAreaInsets.right)
             };
  } else {
    return @{
             @"top": @(20),
             @"bottom": @(0),
             @"left": @(0),
             @"right": @(0),
             };
  }
}

static NSDictionary *
getScreenDimensions()
{
  CGSize size = UIApplication.sharedApplication.keyWindow.bounds.size;
  return @{
           @"width": @(size.width),
           @"height": @(size.height),
           @"orientation": size.width > size.height ? @"landscape" : @"portrait",
           @"safeAreaInsets": getSafeAreaInsets()
           };
}

@implementation ARDynamicScreenDimensions

@synthesize isBeingObserved;
@synthesize currentDimensions;

RCT_EXPORT_MODULE()

- (NSArray<NSString *> *)supportedEvents
{
  return @[@"change"];
}

- (dispatch_queue_t)methodQueue
{
  return dispatch_get_main_queue();
}

+ (BOOL)requiresMainQueueSetup
{
  return YES;
}

- (void)orientationChanged:(NSNotification *)note
{
  __weak ARDynamicScreenDimensions *wself = self;

  dispatch_async(dispatch_get_main_queue(), ^{
    __strong ARDynamicScreenDimensions *sself = wself;
    if (!sself) {
      return;
    }
    sself.currentDimensions = getScreenDimensions();
    if (sself.isBeingObserved) {
      [sself sendEventWithName:@"change" body:sself.currentDimensions];
    }
  });
}

- (void)startObserving
{
  self.isBeingObserved = true;
}

-(void)stopObserving
{
  self.isBeingObserved = false;
}

- (NSDictionary *)constantsToExport
{
  return self.currentDimensions;
}

-(instancetype)init
{
  self = [super init];
  if (self) {
    self.currentDimensions = getScreenDimensions();
    [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
    [[NSNotificationCenter defaultCenter]
     addObserver:self selector:@selector(orientationChanged:)
     name:UIDeviceOrientationDidChangeNotification
     object:[UIDevice currentDevice]];
  }
  return self;
}

-(void)dealloc
{
  [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end


text:
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**links** | [**PipelineBranchesitempullRequestlinks**](PipelineBranchesitempullRequestlinks.md) |  |  [optional]
**author** | **kotlin.String** |  |  [optional]
**id** | **kotlin.String** |  |  [optional]
**title** | **kotlin.String** |  |  [optional]
**url** | **kotlin.String** |  |  [optional]
**propertyClass** | **kotlin.String** |  |  [optional]


text:
class ConfiguracionesFisiatriaController < ApplicationController
  before_filter :require_login
  before_filter :is_admin_or_fisiatra_fisiatria

  def index
  	@tratamiento = Tratamiento.new
  	@tratamiento.item_tratamientos.build
  	@tratamientos = Tratamiento.all
    @item = ItemTratamiento.new

  end

  def horarios
  	@horario = Horario.new
  	@horarios = Horario.all
    @config = FisiatriaConfiguracion.last
  end

  def certificados
    @config = FisiatriaConfiguracion.last
  end

  def tratamientos
  	index
  end
end


text:
<?php

namespace App\Domain\Contracts;

/**
 * Interface ContactInterface
 * @package App\Domain\Contracts
 */
interface TeachersInterface {

    /**
     * @param int $limit
     * @param int $page
     * @param array $column
     * @param $field
     * @param string $search
     * @return mixed
     */
    public function paginate($limit = 10, $page = 1, array $column, $field, $search = '');

}


text:
import os

import click

from ..core import Core
from ..programmers import JLink, STLink

# DEVICE ID register valueto name mapping
DEVICEID_CHIPNAME_LOOKUP = {
    0x411: 'STM32F2xx'
}

# DEVICE ID register value to Segger '-device' name mapping
# Segger ID List: https://www.segger.com/jlink_supported_devices.html
DEVICEID_SEGGER_LOOKUP = {
    0x411: 'STM32F205RG'
}

# REV_D name mapping
# See Section 32.6.1 of the STM32F205 Reference Manual (DBGMDU_IDCODE)
DEVICEID_CHIPREV_LOOKUP = {
    0x1000: 'A (0x1000)',
    0x1001: 'Z (0x1001)',
    0x2000: 'B (0x2000)',
    0x2001: 'Y (0x2001)',
    0x2003: 'X (0x2003)',
    0x2007: '1 (0x2007)',
    0x200F: 'V (0x200F)',
    0x201F: '2 (0x201F)'
}

class STLink_STM32F2(STLink):
    # STM32F2-specific STLink-based programmer.  Required to add custom mass
    # erase command logic to wiping.

    def __init__(self):
        # Call base STLink initializer and set it up to program the STM32F2.
        super(STLink_STM32F2, self).__init__(params='-f interface/stlink-v2.cfg -f target/stm32f2x.cfg')

    def wipe(self):
        # Run OpenOCD commands to wipe STM32F2 memory.
        commands = [
            'init',
            'reset init',
            'halt',
            'stm32f2x mass_erase 0',
            'exit'
        ]
        self.run_commands(commands)

class STM32F2(Core):
    """STMicro STM32F2 CPU."""
    # Note that the docstring will be used as the short help description.

    def __init__(self):
        # Call base class constructor.
        super(STM32F2, self).__init__()

    def list_programmers(self):
        """Return a list of the programmer names supported by this CPU."""
        return ['jlink','stlink']

    def create_programmer(self, programmer):
        """Create and return a programmer instance that will be used to program
        the core.  Must be implemented by subclasses!
        """
        if programmer == 'jlink':
            return JLink('Cortex-M3 r2p0, Little endian',
                         params='-device STM32F205RG -if swd -speed 2000')
        elif programmer == 'stlink':
            return STLink_STM32F2()

    def info(self, programmer):
        """Display info about the device."""
        # [0xE0042000] = CHIP_REVISION[31:16] + RESERVED[15:12] + DEVICE_ID[11:0]
        deviceid = programmer.readmem32(0xE0042000) & 0xFFF
        chiprev  = (programmer.readmem32(0xE0042000) & 0xFFFF0000) >> 16
        click.echo('Device ID : {0}'.format(DEVICEID_CHIPNAME_LOOKUP.get(deviceid,
                                                   '0x{0:03X}'.format(deviceid))))
        click.echo('Chip Rev  : {0}'.format(DEVICEID_CHIPREV_LOOKUP.get(chiprev,
                                                   '0x{0:04X}'.format(chiprev))))
        # Try to detect the Segger Device ID string and print it if using JLink
        if isinstance(programmer, JLink):
            hwid = programmer.readmem32(0xE0042000) & 0xFFF
            hwstring = DEVICEID_SEGGER_LOOKUP.get(hwid, '0x{0:03X}'.format(hwid))
            if '0x' not in hwstring:
                click.echo('Segger ID : {0}'.format(hwstring))


text:
'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
    Schema = mongoose.Schema;
/**
 * Progress Schema
 */
var ProgressSchema = new Schema({
  created: {
    type: Date,
    default: Date.now
  },
  note: {
    type: String,
    required: false,
    trim: true
  },
  goalTotal: {
    type: Number,
    required: false
  }
});
/**
 * Statics
 */
ProgressSchema.statics.load = function(id, cb) {
  this.findOne({
    _id: id
  }).exec(cb);
};
mongoose.model('Progress', ProgressSchema);


text:
package attr;

import java.io.*;
//import checkers.inference.ownership.quals.*;
import util.*;
import jconst.*;

/**

   This object represents the Java class file inner class
   information.

   Inner classes were added to Java 1.1 and are described by
   Sun's Inner Class Specification, 2/10/97.

   An inner class is a class that is nested inside another class.  The
   inner class exists in the local scope of its enclosing class.  So
   an inner class may access any class variables or member functions
   of the parent class.  It may also reference any visible methods
   from the parent classes super class.

   Although the inner class shares scoping with its parent class, it
   is compiled into a separate class file.  This class has a name that
   is created from the inner class and its parent class.  To quote the
   Inner class specification (Class Name Transformations):

     Names of nested classes are transformed as necessary by the
     compiler to avoid conflicts with identical names in other
     scopes.  Names are encoded to the virtual machine by taking their
     source form, qualified with dots, and changing each dot after a
     class name into a dollar sign.

   The JVM has no special support for inner classes.  They are
   supported in the compiler by allowing inner class methods to
   reference class variables and methods that might not normally be in
   scope for an external class.  To quote Sun's inner class
   specification "This complicates the compiler's job."

   The format for the inner classes attribute is:

     innerClasses_attribute {
       u2 attribute_name_index;
       u4 attribute_name_length;
       u2 number_of_classes
       innerClassInfo classes[ number_of_classes];
     }

   The attribute_name_index and attribute length are read by the
   attrFactory.allocAttr method.  These values are passed into the class
   constructor.

   Here innerClassInfo is

   innerClassInfo {
     u2 inner_class_info_index;
     u2 outer_class_info_index;
     u2 inner_name_index;
     u2 inner_class_access_flags;
   }

   Sun's JVM Specification and inner class specification is difficult
   to understand when it comes to inner classes.

   The inner_class_info_index is either zero or an index into the
   constant table for a constClass_or_String representing the
   inner class.

   The outer_class_info_index is zero if the inner_class is not a
   member.  Otherwise the value of outer_class_info_index is an index
   into the constant table for a constClass_or_String representing the
   class or interface of which the inner_class is a member.

   If the inner_class is anonymous, the inner_name_index will be
   zero.  Otherwise this is an index into the constant table for
   a constUtf8 object which contains the class name.

   The inner_class_access_flags are the access mask for the inner
   class or interface.

 */
public class innerClassAttr extends attrInfo {

  class innerClassInfo {
    constClass_or_String innerClass = null;
    constClass_or_String outerClass = null;
    constUtf8 className = null;
    int accessFlags;

    innerClassInfo( DataInputStream dStream, constPool constPoolSec ) {

      int inner_class_info_index = readU2( dStream );
      int outer_class_info_index = readU2( dStream );
      int inner_name_index = readU2( dStream );
      accessFlags = readU2( dStream );
      constBase obj;

      if (inner_class_info_index > 0) {
	obj = constPoolSec.constPoolElem( inner_class_info_index );
	if (obj != null && obj instanceof constClass_or_String) {
	  innerClass = (constClass_or_String)obj;
	}
      }

      if (outer_class_info_index > 0) {
	obj = constPoolSec.constPoolElem( outer_class_info_index );
	if (obj != null && obj instanceof constClass_or_String) {
	  outerClass = (constClass_or_String)obj;
	}
      }

      if (inner_name_index > 0) {
	obj = constPoolSec.constPoolElem( inner_name_index );
	if (obj != null && obj instanceof constUtf8) {
	  className = (constUtf8)obj;
	}
      }

    } // innerClassInfo constructor

    void pr() {
      System.out.print("innerClass: ");
      innerClass.pr();
      System.out.print("outerClass: ");
      outerClass.pr();
    } // pr

  } // class innderClassInfo

  innerClassInfo classInfoTab[] = null;

  public innerClassAttr( String name, int length,
		   DataInputStream dStream,    constPool constPoolSec ) {

    int numInnerClasses = readU2( dStream );
    if (numInnerClasses > 0) {

	classInfoTab = new   innerClassInfo  /*@RepPar*/  [ numInnerClasses ]; //ANA: Analysis correctly figures this class is dead code.

      for (int i = 0; i < numInnerClasses; i++) {
	  classInfoTab[i] = new  /*@RepPar*/  innerClassInfo( dStream, constPoolSec );
      }
    }
  } // innerClassAttr constructor

} // innerClassAttr


text:
class User < ActiveRecord::Base
  include ActiveModel::ForbiddenAttributesProtection
  validates_presence_of :name, :gender, :mile_time, :longest_distance, :goal_type
  has_many :workouts, :dependent => :destroy
  has_many :workout_exercises, :through => :workouts
  has_one :event

  after_save :recluster

  def has_event?
    event.present?
  end

  def save_mile_time_with_minutes_and_seconds minutes, seconds
    milliseconds = (minutes.to_i * 60 + seconds.to_i) * 1000
    self.mile_time = milliseconds
  end

  def mile_time_minutes
    (mile_time.to_i/1000) / 60
  end

  def mile_time_seconds
    (mile_time.to_i/1000) % 60
  end

  def gender_num
    if gender == "male"
      1
    else
      0
    end
  end

  def recluster
    UserClusterGenerator.perform_async gender_num, mile_time, longest_distance rescue nil
  end

  def goal_score
    if goal_type == "both"
      "general"
    elsif goal_type == "faster"
      "speed"
    else
      "distance"
    end
  end

  def search_goal
    if self.longest_distance < 3.1 or ( self.longest_distance > 3.1 and self.longest_distance < 6.2 and self.goal_type == "faster" )
      "5k"
    elsif self.longest_distance > 3.1 and self.longest_distance < 6.2 or ( self.longest_distance > 6.2 and self.longest_distance < 13.1 and self.goal_type == "faster" )
      "10k"
    elsif self.longest_distance > 6.2 and self.longest_distance < 13.1 or ( self.longest_distance > 13.1 and self.longest_distance < 26.2 and self.goal_type == "faster" )
      "half marathon"
    elsif self.longest_distance > 13.1 and self.longest_distance < 26.2 or ( self.longest_distance > 26.2 and self.longest_distance < 50 and self.goal_type == "faster" )
      "marathon"
    else
      "ultra marathon"
    end
  end

  def exercise_history exercise
    hsh = {}
    workout_exercises.where(:exercise_id => exercise.id).load.each do |workout_exercise|
      JSON.parse(workout_exercise.exercise.units).each do |unit|
        hsh.merge_or_add unit => [workout_exercise.measurements.where(:unit => unit).first.value]
      end
      hsh.merge_or_add "timestamps" => [workout_exercise.workout.day.to_i]
    end

    hsh
  end
end


text:
package org.fcrepo.http.api;

import static com.google.common.base.Predicates.containsPattern;
import static com.google.common.collect.Lists.newArrayList;
import static com.google.common.collect.Lists.transform;

import static com.hp.hpl.jena.graph.NodeFactory.createURI;
import static javax.ws.rs.core.MediaType.APPLICATION_OCTET_STREAM;
import static javax.ws.rs.core.MediaType.APPLICATION_OCTET_STREAM_TYPE;
import static javax.ws.rs.core.MediaType.TEXT_PLAIN_TYPE;
import static javax.ws.rs.core.Response.Status.CREATED;
import static javax.ws.rs.core.Response.Status.NO_CONTENT;
import static javax.ws.rs.core.Response.Status.OK;
import static javax.ws.rs.core.Response.Status.TEMPORARY_REDIRECT;
import static org.apache.commons.io.IOUtils.toInputStream;
import static org.apache.jena.riot.WebContent.contentTypeSPARQLUpdate;
import static org.fcrepo.http.api.ContentExposingResource.getSimpleContentType;
import static org.fcrepo.http.commons.domain.RDFMediaType.NTRIPLES_TYPE;
import static org.fcrepo.http.commons.test.util.TestHelpers.getUriInfoImpl;
import static org.fcrepo.http.commons.test.util.TestHelpers.mockSession;
import static org.fcrepo.kernel.api.FedoraTypes.LDP_BASIC_CONTAINER;
import static org.fcrepo.kernel.api.FedoraTypes.LDP_DIRECT_CONTAINER;
import static org.fcrepo.kernel.api.FedoraTypes.LDP_INDIRECT_CONTAINER;
import static org.fcrepo.kernel.api.RdfLexicon.BASIC_CONTAINER;
import static org.fcrepo.kernel.api.RdfLexicon.DIRECT_CONTAINER;
import static org.fcrepo.kernel.api.RdfLexicon.INBOUND_REFERENCES;
import static org.fcrepo.kernel.api.RdfLexicon.INDIRECT_CONTAINER;
import static org.fcrepo.kernel.api.RdfLexicon.LDP_NAMESPACE;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.mockito.MockitoAnnotations.initMocks;
import static org.slf4j.LoggerFactory.getLogger;
import static org.springframework.test.util.ReflectionTestUtils.setField;

import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.text.ParseException;
import java.util.List;

import javax.jcr.AccessDeniedException;
import javax.jcr.Node;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.Workspace;
import javax.jcr.observation.ObservationManager;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.BadRequestException;
import javax.ws.rs.ClientErrorException;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.ServerErrorException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;

import org.apache.commons.io.IOUtils;
import org.fcrepo.http.commons.api.rdf.HttpResourceConverter;
import org.fcrepo.http.commons.domain.MultiPrefer;
import org.fcrepo.kernel.api.exception.InvalidChecksumException;
import org.fcrepo.kernel.api.exception.MalformedRdfException;
import org.fcrepo.kernel.api.identifiers.IdentifierConverter;
import org.fcrepo.kernel.api.models.Container;
import org.fcrepo.kernel.api.models.FedoraBinary;
import org.fcrepo.kernel.api.models.FedoraResource;
import org.fcrepo.kernel.api.models.NonRdfSourceDescription;
import org.fcrepo.kernel.api.services.BinaryService;
import org.fcrepo.kernel.api.services.ContainerService;
import org.fcrepo.kernel.api.services.NodeService;
import org.fcrepo.kernel.api.utils.iterators.RdfStream;
import org.fcrepo.kernel.modeshape.rdf.impl.ReferencesRdfContext;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.slf4j.Logger;
import org.springframework.mock.web.MockHttpServletResponse;

import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.hp.hpl.jena.graph.Triple;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.RDFNode;
import com.hp.hpl.jena.rdf.model.Resource;

/**
 * @author cabeer
 * @author ajs6f
 */
public class FedoraLdpTest {

    private final String path = "/some/path";
    private final String binaryPath = "/some/binary/path";
    private final String binaryDescriptionPath = "/some/other/path";
    private FedoraLdp testObj;

    private static final String BASEURL_PROP = "fcrepo.jms.baseUrl";

    @Mock
    private Request mockRequest;

    private HttpServletResponse mockResponse;

    private Session mockSession;

    @Mock
    private Node mockNode;

    @Mock
    private Container mockContainer;

    @Mock
    private NonRdfSourceDescription mockNonRdfSourceDescription;

    @Mock
    private FedoraBinary mockBinary;

    private IdentifierConverter<Resource, FedoraResource> idTranslator;

    @Mock
    private NodeService mockNodeService;

    @Mock
    private ContainerService mockContainerService;

    @Mock
    private BinaryService mockBinaryService;

    @Mock
    private FedoraHttpConfiguration mockHttpConfiguration;

    @Mock
    private HttpHeaders mockHeaders;

    private static final Logger log = getLogger(FedoraLdpTest.class);

    @Before
    public void setUp() {
        initMocks(this);
        testObj = spy(new FedoraLdp(path));

        mockResponse = new MockHttpServletResponse();

        mockSession = mockSession(testObj);
        setField(testObj, "session", mockSession);

        idTranslator = new HttpResourceConverter(mockSession,
                UriBuilder.fromUri("http://localhost/fcrepo/{path: .*}"));

        setField(testObj, "request", mockRequest);
        setField(testObj, "servletResponse", mockResponse);
        setField(testObj, "uriInfo", getUriInfoImpl());
        setField(testObj, "headers", mockHeaders);
        setField(testObj, "idTranslator", idTranslator);
        setField(testObj, "nodeService", mockNodeService);
        setField(testObj, "containerService", mockContainerService);
        setField(testObj, "binaryService", mockBinaryService);
        setField(testObj, "httpConfiguration", mockHttpConfiguration);

        when(mockHttpConfiguration.putRequiresIfMatch()).thenReturn(false);

        when(mockContainer.getEtagValue()).thenReturn("");
        when(mockContainer.getPath()).thenReturn(path);

        when(mockNonRdfSourceDescription.getEtagValue()).thenReturn("");
        when(mockNonRdfSourceDescription.getPath()).thenReturn(binaryDescriptionPath);
        when(mockNonRdfSourceDescription.getDescribedResource()).thenReturn(mockBinary);

        when(mockBinary.getEtagValue()).thenReturn("");
        when(mockBinary.getPath()).thenReturn(binaryPath);
        when(mockBinary.getDescription()).thenReturn(mockNonRdfSourceDescription);

        when(mockHeaders.getHeaderString("user-agent")).thenReturn("Test UserAgent");
    }

    @SuppressWarnings("unchecked")
    private FedoraResource setResource(final Class<? extends FedoraResource> klass) throws RepositoryException {
        final FedoraResource mockResource = mock(klass);

        doReturn(mockResource).when(testObj).resource();
        when(mockResource.getNode()).thenReturn(mockNode);
        when(mockResource.getPath()).thenReturn(path);
        when(mockNode.getPath()).thenReturn(path);
        when(mockResource.getEtagValue()).thenReturn("");
        when(mockResource.getTriples(eq(idTranslator), any(Class.class))).thenAnswer(new Answer<RdfStream>() {
            @Override
            public RdfStream answer(final InvocationOnMock invocationOnMock) {
                return new RdfStream(Triple.create(createURI(invocationOnMock.getMock().toString()),
                                                   createURI("called"),
                                                   createURI(invocationOnMock.getArguments()[1].toString())
                        ));
            }
        });

        return mockResource;
    }

    @Test
    public void testHead() throws Exception {
        setResource(FedoraResource.class);
        final Response actual = testObj.head();
        assertEquals(OK.getStatusCode(), actual.getStatus());
        assertTrue("Should have a Link header", mockResponse.containsHeader("Link"));
        assertTrue("Should have an Allow header", mockResponse.containsHeader("Allow"));
        assertTrue("Should be an LDP Resource",
                mockResponse.getHeaders("Link").contains("<" + LDP_NAMESPACE + "Resource>;rel=\"type\""));
    }

    @Test
    public void testHeadWithObject() throws Exception {
        setResource(Container.class);
        final Response actual = testObj.head();
        assertEquals(OK.getStatusCode(), actual.getStatus());
        assertTrue("Should advertise Accept-Post flavors", mockResponse.containsHeader("Accept-Post"));
        assertTrue("Should advertise Accept-Patch flavors", mockResponse.containsHeader("Accept-Patch"));
    }

    @Test
    public void testHeadWithDefaultContainer() throws Exception {
        setResource(Container.class);
        final Response actual = testObj.head();
        assertEquals(OK.getStatusCode(), actual.getStatus());
        assertTrue("Should be an LDP BasicContainer",
                mockResponse.getHeaders("Link").contains("<" + BASIC_CONTAINER.getURI() + ">;rel=\"type\""));
    }

    @Test
    public void testHeadWithBasicContainer() throws Exception {
        final FedoraResource resource = setResource(Container.class);
        when(resource.hasType(LDP_BASIC_CONTAINER)).thenReturn(true);
        final Response actual = testObj.head();
        assertEquals(OK.getStatusCode(), actual.getStatus());
        assertTrue("Should be an LDP BasicContainer",
                mockResponse.getHeaders("Link").contains("<" + BASIC_CONTAINER.getURI() + ">;rel=\"type\""));
    }

    @Test
    public void testHeadWithDirectContainer() throws Exception {
        final FedoraResource resource = setResource(Container.class);
        when(resource.hasType(LDP_DIRECT_CONTAINER)).thenReturn(true);
        final Response actual = testObj.head();
        assertEquals(OK.getStatusCode(), actual.getStatus());
        assertTrue("Should be an LDP DirectContainer",
                mockResponse.getHeaders("Link").contains("<" + DIRECT_CONTAINER.getURI() + ">;rel=\"type\""));
    }

    @Test
    public void testHeadWithIndirectContainer() throws Exception {
        final FedoraResource resource = setResource(Container.class);
        when(resource.hasType(LDP_INDIRECT_CONTAINER)).thenReturn(true);
        final Response actual = testObj.head();
        assertEquals(OK.getStatusCode(), actual.getStatus());
        assertTrue("Should be an LDP IndirectContainer",
                mockResponse.getHeaders("Link").contains("<" + INDIRECT_CONTAINER.getURI() + ">;rel=\"type\""));
    }

    @Test
    public void testHeadWithBinary() throws Exception {
        final FedoraBinary mockResource = (FedoraBinary)setResource(FedoraBinary.class);
        when(mockResource.getDescription()).thenReturn(mockNonRdfSourceDescription);
        final Response actual = testObj.head();
        assertEquals(OK.getStatusCode(), actual.getStatus());
        assertTrue("Should be an LDP NonRDFSource", mockResponse.getHeaders("Link").contains("<" + LDP_NAMESPACE +
                "NonRDFSource>;rel=\"type\""));
        assertFalse("Should not advertise Accept-Post flavors", mockResponse.containsHeader("Accept-Post"));
        assertFalse("Should not advertise Accept-Patch flavors", mockResponse.containsHeader("Accept-Patch"));
        assertTrue("Should contain a link to the binary description",
                mockResponse.getHeaders("Link")
                        .contains("<" + idTranslator.toDomain(binaryDescriptionPath + "/fcr:metadata")
                                + ">; rel=\"describedby\""));
    }

    @Test
    public void testHeadWithBinaryDescription() throws Exception {
        final NonRdfSourceDescription mockResource
                = (NonRdfSourceDescription)setResource(NonRdfSourceDescription.class);
        when(mockResource.getDescribedResource()).thenReturn(mockBinary);
        final Response actual = testObj.head();
        assertEquals(OK.getStatusCode(), actual.getStatus());
        assertTrue("Should be an LDP RDFSource", mockResponse.getHeaders("Link").contains("<" + LDP_NAMESPACE +
                "RDFSource>;rel=\"type\""));
        assertFalse("Should not advertise Accept-Post flavors", mockResponse.containsHeader("Accept-Post"));
        assertTrue("Should advertise Accept-Patch flavors", mockResponse.containsHeader("Accept-Patch"));
        assertTrue("Should contain a link to the binary",
                mockResponse.getHeaders("Link")
                        .contains("<" + idTranslator.toDomain(binaryPath) + ">; rel=\"describes\""));
    }

    @Test
    public void testOption() throws Exception {
        setResource(FedoraResource.class);
        final Response actual = testObj.options();
        assertEquals(OK.getStatusCode(), actual.getStatus());
        assertTrue("Should have an Allow header", mockResponse.containsHeader("Allow"));
    }

    @Test
    public void testOptionWithObject() throws Exception {
        setResource(Container.class);
        final Response actual = testObj.options();
        assertEquals(OK.getStatusCode(), actual.getStatus());
        assertTrue("Should advertise Accept-Post flavors", mockResponse.containsHeader("Accept-Post"));
        assertTrue("Should advertise Accept-Patch flavors", mockResponse.containsHeader("Accept-Patch"));
    }

    @Test
    public void testOptionWithBinary() throws Exception {
        final FedoraBinary mockResource = (FedoraBinary)setResource(FedoraBinary.class);
        when(mockResource.getDescription()).thenReturn(mockNonRdfSourceDescription);
        final Response actual = testObj.options();
        assertEquals(OK.getStatusCode(), actual.getStatus());
        assertFalse("Should not advertise Accept-Post flavors", mockResponse.containsHeader("Accept-Post"));
        assertFalse("Should not advertise Accept-Patch flavors", mockResponse.containsHeader("Accept-Patch"));
        assertTrue("Should contain a link to the binary description",
                mockResponse.getHeaders("Link")
                        .contains("<" + idTranslator.toDomain(binaryDescriptionPath + "/fcr:metadata")
                                + ">; rel=\"describedby\""));
    }

    @Test
    public void testOptionWithBinaryDescription() throws Exception {
        final NonRdfSourceDescription mockResource
                = (NonRdfSourceDescription)setResource(NonRdfSourceDescription.class);
        when(mockResource.getDescribedResource()).thenReturn(mockBinary);
        final Response actual = testObj.options();
        assertEquals(OK.getStatusCode(), actual.getStatus());
        assertFalse("Should not advertise Accept-Post flavors", mockResponse.containsHeader("Accept-Post"));
        assertTrue("Should advertise Accept-Patch flavors", mockResponse.containsHeader("Accept-Patch"));
        assertTrue("Should contain a link to the binary",
                mockResponse.getHeaders("Link")
                        .contains("<" + idTranslator.toDomain(binaryPath) + ">; rel=\"describes\""));
    }

    @Test
    public void testGet() throws Exception {
        setResource(FedoraResource.class);
        final Response actual = testObj.describe(null);
        assertEquals(OK.getStatusCode(), actual.getStatus());
        assertTrue("Should have a Link header", mockResponse.containsHeader("Link"));
        assertTrue("Should have an Allow header", mockResponse.containsHeader("Allow"));
        assertTrue("Should be an LDP Resource",
                mockResponse.getHeaders("Link").contains("<" + LDP_NAMESPACE + "Resource>;rel=\"type\""));

        final RdfStream entity = (RdfStream) actual.getEntity();
        final Model model = entity.asModel();
        final List<String> rdfNodes = transform(newArrayList(model.listObjects()), RDFNode::toString);

        assertTrue("Expected RDF contexts missing", rdfNodes.containsAll(ImmutableSet.of(
                "class org.fcrepo.kernel.modeshape.rdf.impl.LdpContainerRdfContext",
                "class org.fcrepo.kernel.modeshape.rdf.impl.LdpIsMemberOfRdfContext",
                "class org.fcrepo.kernel.modeshape.rdf.impl.TypeRdfContext",
                "class org.fcrepo.kernel.modeshape.rdf.impl.LdpRdfContext",
                "class org.fcrepo.kernel.modeshape.rdf.impl.PropertiesRdfContext",
                "class org.fcrepo.kernel.modeshape.rdf.impl.ChildrenRdfContext",
                "class org.fcrepo.kernel.modeshape.rdf.impl.AclRdfContext",
                "class org.fcrepo.kernel.modeshape.rdf.impl.ParentRdfContext"
        )));

    }

    @Test
    public void testGetWithObject() throws Exception {
        setResource(Container.class);
        final Response actual = testObj.describe(null);
        assertEquals(OK.getStatusCode(), actual.getStatus());
        assertTrue("Should advertise Accept-Post flavors", mockResponse.containsHeader("Accept-Post"));
        assertTrue("Should advertise Accept-Patch flavors", mockResponse.containsHeader("Accept-Patch"));

        final RdfStream entity = (RdfStream) actual.getEntity();
        final Model model = entity.asModel();

        final List<String> rdfNodes = transform(newArrayList(model.listObjects()), RDFNode::toString);
        assertTrue("Expected RDF contexts missing", rdfNodes.containsAll(ImmutableSet.of(
                "class org.fcrepo.kernel.modeshape.rdf.impl.LdpContainerRdfContext",
                "class org.fcrepo.kernel.modeshape.rdf.impl.LdpIsMemberOfRdfContext",
                "class org.fcrepo.kernel.modeshape.rdf.impl.TypeRdfContext",
                "class org.fcrepo.kernel.modeshape.rdf.impl.LdpRdfContext",
                "class org.fcrepo.kernel.modeshape.rdf.impl.PropertiesRdfContext",
                "class org.fcrepo.kernel.modeshape.rdf.impl.ChildrenRdfContext",
                "class org.fcrepo.kernel.modeshape.rdf.impl.AclRdfContext",
                "class org.fcrepo.kernel.modeshape.rdf.impl.ParentRdfContext"
        )));

    }

    @Test
    public void testGetWithBasicContainer() throws Exception {
        final FedoraResource resource = setResource(Container.class);
        when(resource.hasType(LDP_BASIC_CONTAINER)).thenReturn(true);
        final Response actual = testObj.describe(null);
        assertEquals(OK.getStatusCode(), actual.getStatus());
        assertTrue("Should be an LDP BasicContainer",
                mockResponse.getHeaders("Link").contains("<" + BASIC_CONTAINER.getURI() + ">;rel=\"type\""));
    }

    @Test
    public void testGetWithDirectContainer() throws Exception {
        final FedoraResource resource = setResource(Container.class);
        when(resource.hasType(LDP_DIRECT_CONTAINER)).thenReturn(true);
        final Response actual = testObj.describe(null);
        assertEquals(OK.getStatusCode(), actual.getStatus());
        assertTrue("Should be an LDP DirectContainer",
                mockResponse.getHeaders("Link").contains("<" + DIRECT_CONTAINER.getURI() + ">;rel=\"type\""));
    }

    @Test
    public void testGetWithIndirectContainer() throws Exception {
        final FedoraResource resource = setResource(Container.class);
        when(resource.hasType(LDP_INDIRECT_CONTAINER)).thenReturn(true);
        final Response actual = testObj.describe(null);
        assertEquals(OK.getStatusCode(), actual.getStatus());
        assertTrue("Should be an LDP IndirectContainer",
                mockResponse.getHeaders("Link").contains("<" + INDIRECT_CONTAINER.getURI() + ">;rel=\"type\""));
    }

    @Test
    public void testGetWithObjectPreferMinimal() throws Exception {

        setResource(Container.class);
        setField(testObj, "prefer", new MultiPrefer("return=minimal"));
        final Response actual = testObj.describe(null);
        assertEquals(OK.getStatusCode(), actual.getStatus());

        final RdfStream entity = (RdfStream) actual.getEntity();
        final Model model = entity.asModel();
        final List<String> rdfNodes = transform(newArrayList(model.listObjects()), RDFNode::toString);

        assertTrue("Expected RDF contexts missing", rdfNodes.containsAll(ImmutableSet.of(
                "class org.fcrepo.kernel.modeshape.rdf.impl.TypeRdfContext",
                "class org.fcrepo.kernel.modeshape.rdf.impl.PropertiesRdfContext"
        )));

        assertFalse("Included non-minimal contexts",
                rdfNodes.contains("class org.fcrepo.kernel.modeshape.rdf.impl.LdpContainerRdfContext"));

        assertFalse("Included non-minimal contexts",
                rdfNodes.contains("class org.fcrepo.kernel.modeshape.rdf.impl.ChildrenRdfContext"));

    }

    @Test
    public void testGetWithObjectOmitContainment() throws Exception {
        setResource(Container.class);
        setField(testObj, "prefer",
                new MultiPrefer("return=representation; omit=\"" + LDP_NAMESPACE + "PreferContainment\""));
        final Response actual = testObj.describe(
                null);
        assertEquals(OK.getStatusCode(), actual.getStatus());

        final RdfStream entity = (RdfStream) actual.getEntity();
        final Model model = entity.asModel();
        final List<String> rdfNodes = transform(newArrayList(model.listObjects()), RDFNode::toString);
        assertTrue("Should include membership contexts",
                rdfNodes.contains("class org.fcrepo.kernel.modeshape.rdf.impl.LdpContainerRdfContext"));

        assertFalse("Should not include containment contexts",
                rdfNodes.contains("class org.fcrepo.kernel.modeshape.rdf.impl.ChildrenRdfContext"));

    }

    @Test
    public void testGetWithObjectOmitMembership() throws Exception {
        setResource(Container.class);
        setField(testObj, "prefer",
                new MultiPrefer("return=representation; omit=\"" + LDP_NAMESPACE + "PreferMembership\""));
        final Response actual = testObj.describe(null);
        assertEquals(OK.getStatusCode(), actual.getStatus());

        final RdfStream entity = (RdfStream) actual.getEntity();
        final Model model = entity.asModel();
        final List<String> rdfNodes = transform(newArrayList(model.listObjects()), RDFNode::toString);

        assertFalse("Should not include membership contexts",
                rdfNodes.contains("class org.fcrepo.kernel.modeshape.rdf.impl.LdpContainerRdfContext"));
        assertFalse("Should not include membership contexts",
                rdfNodes.contains("class org.fcrepo.kernel.modeshape.rdf.impl.LdpIsMemberOfRdfContext"));

        assertTrue("Should include containment contexts",
                rdfNodes.contains("class org.fcrepo.kernel.modeshape.rdf.impl.ChildrenRdfContext"));

    }

    @Test
    public void testGetWithObjectIncludeReferences() throws ParseException, IOException, RepositoryException {
        setResource(Container.class);
        setField(testObj, "prefer", new MultiPrefer("return=representation; include=\"" + INBOUND_REFERENCES + "\""));
        final Response actual = testObj.describe(null);
        assertEquals(OK.getStatusCode(), actual.getStatus());

        final RdfStream entity = (RdfStream) actual.getEntity();
        final Model model = entity.asModel();

        final List<String> rdfNodes = transform(newArrayList(model.listObjects()), RDFNode::toString);
        log.debug("Received RDF nodes: {}", rdfNodes);
        final String referencesContextClassName = ReferencesRdfContext.class.getName();
        assertTrue("Should include references contexts",
                rdfNodes.stream().anyMatch(containsPattern(referencesContextClassName)::apply));
    }

    @Test
    public void testGetWithBinary() throws Exception {
        final FedoraBinary mockResource = (FedoraBinary)setResource(FedoraBinary.class);
        when(mockResource.getDescription()).thenReturn(mockNonRdfSourceDescription);
        when(mockResource.getMimeType()).thenReturn("text/plain");
        when(mockResource.getContent()).thenReturn(toInputStream("xyz"));
        final Response actual = testObj.describe(null);
        assertEquals(OK.getStatusCode(), actual.getStatus());
        assertTrue("Should be an LDP NonRDFSource",
                mockResponse.getHeaders("Link").contains("<" + LDP_NAMESPACE + "NonRDFSource>;rel=\"type\""));
        assertFalse("Should not advertise Accept-Post flavors", mockResponse.containsHeader("Accept-Post"));
        assertFalse("Should not advertise Accept-Patch flavors", mockResponse.containsHeader("Accept-Patch"));
        assertTrue("Should contain a link to the binary description",
                mockResponse.getHeaders("Link")
                        .contains("<" + idTranslator.toDomain(binaryDescriptionPath + "/fcr:metadata")
                                + ">; rel=\"describedby\""));
        assertTrue(IOUtils.toString((InputStream)actual.getEntity()).equals("xyz"));
    }

    @Test
    public void testGetWithExternalMessageBinary() throws Exception {
        final FedoraBinary mockResource = (FedoraBinary)setResource(FedoraBinary.class);
        when(mockResource.getDescription()).thenReturn(mockNonRdfSourceDescription);
        when(mockResource.getMimeType()).thenReturn("message/external-body; access-type=URL; URL=\"some:uri\"");
        when(mockResource.getContent()).thenReturn(toInputStream("xyz"));
        final Response actual = testObj.describe(null);
        assertEquals(TEMPORARY_REDIRECT.getStatusCode(), actual.getStatus());
        assertTrue("Should be an LDP NonRDFSource", mockResponse.getHeaders("Link").contains("<" + LDP_NAMESPACE +
                "NonRDFSource>;rel=\"type\""));
        assertTrue("Should contain a link to the binary description", mockResponse.getHeaders("Link").contains("<" +
                idTranslator.toDomain(binaryDescriptionPath + "/fcr:metadata") + ">; rel=\"describedby\""));
        assertEquals(new URI("some:uri"), actual.getLocation());
    }

    @Test
    @SuppressWarnings("unchecked")
    public void testGetWithBinaryDescription() throws RepositoryException, IOException {

        final NonRdfSourceDescription mockResource
                = (NonRdfSourceDescription)setResource(NonRdfSourceDescription.class);
        when(mockResource.getDescribedResource()).thenReturn(mockBinary);
        when(mockBinary.getTriples(eq(idTranslator), any(Class.class))).thenReturn(new RdfStream());
        when(mockBinary.getTriples(eq(idTranslator), any(List.class))).thenReturn(new RdfStream(new Triple
                (createURI("mockBinary"), createURI("called"), createURI("child:properties"))));
        final Response actual = testObj.describe(null);
        assertEquals(OK.getStatusCode(), actual.getStatus());
        assertTrue("Should be an LDP RDFSource",
                mockResponse.getHeaders("Link").contains("<" + LDP_NAMESPACE + "RDFSource>;rel=\"type\""));
        assertFalse("Should not advertise Accept-Post flavors", mockResponse.containsHeader("Accept-Post"));
        assertTrue("Should advertise Accept-Patch flavors", mockResponse.containsHeader("Accept-Patch"));
        assertTrue("Should contain a link to the binary",
                mockResponse.getHeaders("Link")
                        .contains("<" + idTranslator.toDomain(binaryPath) + ">; rel=\"describes\""));

        final Model model = ((RdfStream) actual.getEntity()).asModel();
        final List<String> rdfNodes = transform(newArrayList(model.listObjects()), RDFNode::toString);
        log.info("Found RDF objects\n{}", rdfNodes);
        assertTrue("Expected RDF contexts missing", rdfNodes.containsAll(ImmutableSet.of(
                "class org.fcrepo.kernel.modeshape.rdf.impl.LdpContainerRdfContext",
                "class org.fcrepo.kernel.modeshape.rdf.impl.LdpIsMemberOfRdfContext",
                "class org.fcrepo.kernel.modeshape.rdf.impl.TypeRdfContext",
                "class org.fcrepo.kernel.modeshape.rdf.impl.LdpRdfContext",
                "class org.fcrepo.kernel.modeshape.rdf.impl.PropertiesRdfContext",
                "class org.fcrepo.kernel.modeshape.rdf.impl.ChildrenRdfContext",
                "class org.fcrepo.kernel.modeshape.rdf.impl.AclRdfContext",
                "class org.fcrepo.kernel.modeshape.rdf.impl.ParentRdfContext"
        )));

    }

    @Test
    public void testDelete() throws Exception {
        final FedoraResource fedoraResource = setResource(FedoraResource.class);
        final Response actual = testObj.deleteObject();
        assertEquals(NO_CONTENT.getStatusCode(), actual.getStatus());
        verify(fedoraResource).delete();
    }

    @Test
    public void testPutNewObject() throws Exception {
        setField(testObj, "externalPath", "some/path");
        when(mockContainer.isNew()).thenReturn(true);

        when(mockNodeService.exists(mockSession, "/some/path")).thenReturn(false);
        when(mockContainerService.findOrCreate(mockSession, "/some/path")).thenReturn(mockContainer);

        final Response actual = testObj.createOrReplaceObjectRdf(null, null, null, null, null, null);

        assertEquals(CREATED.getStatusCode(), actual.getStatus());
    }

    @Test(expected = ServerErrorException.class)
    public void testPutNewObjectLdpr() throws Exception {
        testObj.createOrReplaceObjectRdf(null, null, null, null, null,
                "<http://www.w3.org/ns/ldp#Resource>; rel=\"type\"");
    }

    @Test
    public void testPutNewObjectWithRdf() throws Exception {

        setField(testObj, "externalPath", "some/path");
        when(mockContainer.isNew()).thenReturn(true);

        when(mockNodeService.exists(mockSession, "/some/path")).thenReturn(false);
        when(mockContainerService.findOrCreate(mockSession, "/some/path")).thenReturn(mockContainer);

        final Response actual = testObj.createOrReplaceObjectRdf(NTRIPLES_TYPE,
                toInputStream("_:a <info:x> _:c ."), null, null, null, null);

        assertEquals(CREATED.getStatusCode(), actual.getStatus());
        verify(mockContainer).replaceProperties(eq(idTranslator), any(Model.class), any(RdfStream.class));
    }

    @Test
    public void testPutNewBinary() throws Exception {
        setField(testObj, "externalPath", "some/path");
        when(mockBinary.isNew()).thenReturn(true);

        when(mockNodeService.exists(mockSession, "/some/path")).thenReturn(false);
        when(mockBinaryService.findOrCreate(mockSession, "/some/path")).thenReturn(mockBinary);

        final Response actual = testObj.createOrReplaceObjectRdf(TEXT_PLAIN_TYPE,
                toInputStream("xyz"), null, null, null, null);

        assertEquals(CREATED.getStatusCode(), actual.getStatus());
    }

    @Test
    public void testPutReplaceRdfObject() throws Exception {

        setField(testObj, "externalPath", "some/path");
        final Container mockObject = (Container)setResource(Container.class);
        doReturn(mockObject).when(testObj).resource();
        when(mockObject.isNew()).thenReturn(false);

        when(mockNodeService.exists(mockSession, "/some/path")).thenReturn(true);
        when(mockContainerService.findOrCreate(mockSession, "/some/path")).thenReturn(mockObject);

        final Response actual = testObj.createOrReplaceObjectRdf(NTRIPLES_TYPE,
                toInputStream("_:a <info:x> _:c ."), null, null, null, null);

        assertEquals(NO_CONTENT.getStatusCode(), actual.getStatus());
        verify(mockObject).replaceProperties(eq(idTranslator), any(Model.class), any(RdfStream.class));
    }

    @Test(expected = ClientErrorException.class)
    public void testPutWithStrictIfMatchHandling() throws Exception {

        when(mockHttpConfiguration.putRequiresIfMatch()).thenReturn(true);
        final Container mockObject = (Container)setResource(Container.class);
        doReturn(mockObject).when(testObj).resource();
        when(mockObject.isNew()).thenReturn(false);

        when(mockNodeService.exists(mockSession, "/some/path")).thenReturn(true);
        when(mockContainerService.findOrCreate(mockSession, "/some/path")).thenReturn(mockObject);

        testObj.createOrReplaceObjectRdf(NTRIPLES_TYPE,
                toInputStream("_:a <info:x> _:c ."), null, null, null, null);

    }

    @Test
    public void testPatchObject() throws Exception {

        setResource(Container.class);

        testObj.updateSparql(toInputStream("xyz"));
    }

    @Test
    @SuppressWarnings("unchecked")
    public void testPatchBinaryDescription() throws RepositoryException, MalformedRdfException, IOException {

        final NonRdfSourceDescription mockObject = (NonRdfSourceDescription)setResource(NonRdfSourceDescription.class);
        when(mockObject.getDescribedResource()).thenReturn(mockBinary);

        when(mockBinary.getTriples(eq(idTranslator), any(Class.class))).thenReturn(new RdfStream());
        when(mockBinary.getTriples(eq(idTranslator), any(List.class))).thenReturn(
                new RdfStream(new Triple(createURI("mockBinary"), createURI("called"), createURI("child:properties"))));

        doReturn(mockObject).when(testObj).resource();

        testObj.updateSparql(toInputStream("xyz"));
    }

    @Test(expected = BadRequestException.class)
    public void testPatchWithoutContent() throws MalformedRdfException, AccessDeniedException, IOException {
        testObj.updateSparql(null);
    }

    @Test(expected = BadRequestException.class)
    public void testPatchWithMissingContent() throws RepositoryException, MalformedRdfException, IOException {
        setResource(Container.class);
        testObj.updateSparql(toInputStream(""));
    }

    @Test(expected = BadRequestException.class)
    public void testPatchBinary() throws RepositoryException, MalformedRdfException, IOException {
        setResource(FedoraBinary.class);
        testObj.updateSparql(toInputStream(""));
    }

    @Test
    public void testCreateNewObject() throws RepositoryException, MalformedRdfException, InvalidChecksumException,
            IOException {
        setResource(Container.class);
        when(mockContainerService.findOrCreate(mockSession, "/b")).thenReturn(mockContainer);
        final Response actual = testObj.createObject(null, null, null, "b", null, null);
        assertEquals(CREATED.getStatusCode(), actual.getStatus());
    }

    @Test
    public void testCreateNewObjectWithSparql() throws RepositoryException, MalformedRdfException,
            InvalidChecksumException, IOException {

        setResource(Container.class);
        when(mockContainerService.findOrCreate(mockSession, "/b")).thenReturn(mockContainer);
        final Response actual = testObj.createObject(null, null,
                MediaType.valueOf(contentTypeSPARQLUpdate), "b", toInputStream("x"), null);
        assertEquals(CREATED.getStatusCode(), actual.getStatus());
        verify(mockContainer).updateProperties(eq(idTranslator), eq("x"), any(RdfStream.class));
    }

    @Test
    public void testCreateNewObjectWithRdf() throws RepositoryException, MalformedRdfException,
            InvalidChecksumException, IOException {
        setResource(Container.class);
        when(mockContainerService.findOrCreate(mockSession, "/b")).thenReturn(mockContainer);
        final Response actual = testObj.createObject(null, null, NTRIPLES_TYPE, "b",
                toInputStream("_:a <info:b> _:c ."), null);
        assertEquals(CREATED.getStatusCode(), actual.getStatus());
        verify(mockContainer).replaceProperties(eq(idTranslator), any(Model.class), any(RdfStream.class));
    }

    @Test
    public void testCreateNewBinary() throws RepositoryException, MalformedRdfException, InvalidChecksumException,
            IOException {
        setResource(Container.class);
        when(mockBinaryService.findOrCreate(mockSession, "/b")).thenReturn(mockBinary);
        try (final InputStream content = toInputStream("x")) {
            final Response actual = testObj.createObject(null, null, APPLICATION_OCTET_STREAM_TYPE, "b",
                    content, null);
            assertEquals(CREATED.getStatusCode(), actual.getStatus());
            verify(mockBinary).setContent(content, APPLICATION_OCTET_STREAM, null, "", null);
        }
    }

    @Test
    public void testCreateNewBinaryWithContentTypeWithParams() throws RepositoryException, MalformedRdfException,
            InvalidChecksumException, IOException {

        setResource(Container.class);
        when(mockBinaryService.findOrCreate(mockSession, "/b")).thenReturn(mockBinary);
        try (final InputStream content = toInputStream("x")) {
            final MediaType requestContentType = MediaType.valueOf("some/mime-type; with=some; param=s");
            final Response actual = testObj.createObject(null, null, requestContentType, "b",
                    content, null);
            assertEquals(CREATED.getStatusCode(), actual.getStatus());
            verify(mockBinary).setContent(content, requestContentType.toString(), null, "", null);
        }
    }

    @Test(expected = ClientErrorException.class)
    public void testPostToBinary() throws MalformedRdfException, InvalidChecksumException,
            IOException, RepositoryException {
        final FedoraBinary mockObject = (FedoraBinary)setResource(FedoraBinary.class);
        doReturn(mockObject).when(testObj).resource();
        testObj.createObject(null, null, null, null, null, null);
    }

    @Test(expected = ServerErrorException.class)
    public void testLDPRNotImplemented() throws MalformedRdfException, AccessDeniedException,
            InvalidChecksumException, IOException {
        testObj.createObject(null, null, null, null, null, "<http://www.w3.org/ns/ldp#Resource>; rel=\"type\"");
    }

    @Test(expected = ClientErrorException.class)
    public void testLDPRNotImplementedInvalidLink() throws MalformedRdfException, AccessDeniedException,
            InvalidChecksumException, IOException {
        testObj.createObject(null, null, null, null, null, "Link: <http://www.w3.org/ns/ldp#Resource;rel=type");
    }

    @Test
    public void testGetSimpleContentType() {
        final MediaType mediaType = new MediaType("text", "plain", ImmutableMap.of("charset", "UTF-8"));
        final MediaType sanitizedMediaType = getSimpleContentType(mediaType);
        assertEquals("text/plain", sanitizedMediaType.toString());
    }

    @Test
    public void testSetUpJMSBaseURIs() throws RepositoryException {
        final ObservationManager mockManager = mock(ObservationManager.class);
        final Workspace mockWorkspace = mock(Workspace.class);
        doReturn(mockWorkspace).when(mockSession).getWorkspace();
        doReturn(mockManager).when(mockWorkspace).getObservationManager();
        final String json = "{\"baseURL\":\"http://localhost/fcrepo\",\"userAgent\":\"Test UserAgent\"}";
        testObj.setUpJMSInfo(getUriInfoImpl(), mockHeaders);
        verify(mockManager).setUserData(eq(json));
    }

    @Test
    public void testSetUpJMSBaseURIsWithSystemProperty() throws RepositoryException {
        System.setProperty(BASEURL_PROP, "https://localhome:8443");

        final ObservationManager mockManager = mock(ObservationManager.class);
        final Workspace mockWorkspace = mock(Workspace.class);
        doReturn(mockWorkspace).when(mockSession).getWorkspace();
        doReturn(mockManager).when(mockWorkspace).getObservationManager();
        final String json = "{\"baseURL\":\"https://localhome:8443/fcrepo\",\"userAgent\":\"Test UserAgent\"}";

        testObj.setUpJMSInfo(getUriInfoImpl(), mockHeaders);
        verify(mockManager).setUserData(eq(json));
    }
}


text:
from flask import Flask
from flask import send_file
from flask import g, request
import seaborn as sns
import pandas as pd
import subprocess
import boto3
import psycopg2
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import linear_kernel
from nltk.stem import SnowballStemmer
from nltk import word_tokenize
import json
import uuid

# Flask app should start in global layout
app = Flask(__name__)

with open('config.json') as config_file:
    login = json.load(config_file)

    database = login["database"]
    user = login["user"]
    password = login["password"]
    host = login["host"]
    port = login["port"]
    aws_access_key_id = login['aws_access_key_id']
    aws_secret_access_key = login['aws_secret_access_key']

def turn_list_to_str(input):
    if str(type(input)) == "<class 'list'>":
        return " ".join(input)
    else:
        return input

class StemTokenizer(object):
    def __init__(self):
        self.snbl = SnowballStemmer('english')

    def __call__(self, doc):
        return [self.snbl.stem(t) for t in word_tokenize(doc)]

stemmer = SnowballStemmer('english')
def stem_sentence(sentence):
    stemmed = []
    for word in word_tokenize(sentence):
        stemmed.append(stemmer.stem(word))
    return " ".join(stemmed)

def create_table_name(id):
    return 'table_' + id.replace('-', '_')

def get_conn():
    return psycopg2.connect(database=database, user=user, password=password,
        host=host, port=port)

def get_db():
    """Opens a new database connection if there is none yet for the
    current application context.
    """
    if not hasattr(g, 'pg_conn'):
        g.pg_conn = get_conn()
    return g.pg_conn

s3Prefix = 'https://s3.amazonaws.com/codex-images/'

conn = get_conn()

data = pd.read_sql(sql="""
        select * from
        (
        select
            metadata->>'title' as package_title,
            metadata->'description' as package_description,
            metadata->'keywords' as keywords,
            jsonb_array_elements(metadata->'resources')->'description' as resource_description,
            jsonb_array_elements(metadata->'resources')->>'identifier' as identifier,
            jsonb_array_elements(metadata->'resources')->>'format' as resource_format
        from package
        ) t where t.resource_format = 'CSV'
    """, con=conn)

print('connected!')

data['info'] = data.apply(
    lambda row: row.package_title + " "
                + turn_list_to_str(row.package_description) + " "
                + turn_list_to_str(row.keywords), axis=1)
vectorizer = TfidfVectorizer(tokenizer=StemTokenizer()).fit(data['info'])
tf_idf_matrix = vectorizer.transform(data['info'])
conn.close()

print('ready!')

@app.teardown_appcontext
def close_db(error):
    """Closes the database again at the end of the request."""
    if hasattr(g, 'pg_conn'):
        g.pg_conn.close()

def query(query_str):
    query = [stem_sentence(query_str)]
    query_vector = vectorizer.transform(query)
    cosine_similarities = linear_kernel(query_vector, tf_idf_matrix).flatten()
    related_docs_indices = cosine_similarities.argsort()[:-6:-1]
    result = data['identifier'][related_docs_indices]
    sql_str = "select * from " + create_table_name(result.values.tolist()[0])
    print(sql_str)
    selected_result = pd.read_sql(sql=sql_str, con=get_db())
    return selected_result

@app.route("/search")
def search():
    # to test, use:
    # /search?query=3G%20Public%20Cellular%20Mobile%20Telephone%20Services%20-%20Average%20Success%20Rate%20Across%20All%20Cells
    print('Search called')
    running_number = str(uuid.uuid4())
    query_str = request.args.get('query')
    query(query_str).head().to_html('table.html')

    # saving image
    image_name = 'table' + str(running_number) + '.png'
    subprocess.call('/usr/bin/wkhtmltoimage -f png --width 0 table.html ' + image_name, shell=True)
    client = boto3.client('s3',
                          aws_access_key_id=aws_access_key_id,
                          aws_secret_access_key=aws_secret_access_key)

    client.upload_file(image_name, 'codex-images', image_name, ExtraArgs={'ACL': 'public-read'})
    return s3Prefix + image_name

@app.route("/visualize")
def visualize():
    print('Visualize called')
    running_number = str(uuid.uuid4())
    query_str = request.args.get('query')

    # assume columns to be space separated column list
    columns = request.args.get('columns').split()
    print(columns)
    query_result = query(query_str)
    sns_plot = sns.countplot(data=query_result, x='telco')
    fig = sns_plot.get_figure()
    image_name = 'viz' + str(running_number) + '.png'
    fig.savefig(image_name)
    client = boto3.client('s3',
                          aws_access_key_id=aws_access_key_id,
                          aws_secret_access_key=aws_secret_access_key)

    client.upload_file(image_name, 'codex-images', image_name, ExtraArgs={'ACL': 'public-read'})
    return s3Prefix + image_name

if __name__ == '__main__':
    app.run(debug=False, port=80, host='0.0.0.0')


text:
package bs.util.tool.commongui.utils;

import java.util.Map;
import java.util.regex.Pattern;

import bs.util.tool.commongui.GuiUtils;

public class SearchFileNameParams {

	public String fileNameCsText;
	public String fileNameNCsText;
	public boolean fileNameSRegex;

	public Pattern fileNameCsPattern;
	public Pattern fileNameNCsPattern;

	public SearchFileNameParams(Map<String, Object> paramsMap) {
		fileNameCsText = GuiUtils.toString(paramsMap.get("fileNameContainsText"));
		fileNameNCsText = GuiUtils.toString(paramsMap.get("fileNameNotContainsText"));
		fileNameSRegex = Boolean.parseBoolean(GuiUtils.toString(paramsMap.get("fileNameSupportRegex")));
		if (fileNameSRegex) {
			fileNameCsPattern = Pattern.compile(fileNameCsText, Pattern.CASE_INSENSITIVE);
			fileNameNCsPattern = Pattern.compile(fileNameNCsText, Pattern.CASE_INSENSITIVE);
		}
	}

}


text:
/**
 * Before running this C++ code example, set up your development environment, including your credentials.
 *
 * For more information, see the following documentation topic:
 * https://docs.aws.amazon.com/sdk-for-cpp/v1/developer-guide/getting-started.html.
 *
 * For information on the structure of the code examples and how to build and run the examples, see
 * https://docs.aws.amazon.com/sdk-for-cpp/v1/developer-guide/getting-started-code-examples.html.
 *
 * Purpose
 *
 * Demonstrates detaching a policy from a role.
 *
 */

//snippet-start:[iam.cpp.detach_role_policy.inc]
#include <aws/core/Aws.h>
#include <aws/iam/IAMClient.h>
#include <aws/iam/model/DetachRolePolicyRequest.h>
#include <aws/iam/model/ListAttachedRolePoliciesRequest.h>
#include <aws/iam/model/ListAttachedRolePoliciesResult.h>
#include <iostream>
#include "iam_samples.h"
//snippet-end:[iam.cpp.detach_role_policy.inc]

//! Detaches a policy from a role.
/*!
  \sa detachRolePolicy()
  \param roleName: The user name.
  \param policyArn: The policy Amazon Resource Name (ARN).
  \param clientConfig: Aws client configuration.
  \return bool: Successful completion.
*/

bool AwsDoc::IAM::detachRolePolicy(const Aws::String &roleName,
                                   const Aws::String &policyArn,
                                   const Aws::Client::ClientConfiguration &clientConfig) {
    // snippet-start:[iam.cpp.detach_role_policy01.code]
    Aws::IAM::IAMClient iam(clientConfig);
    // snippet-end:[iam.cpp.detach_role_policy01.code]

    Aws::IAM::Model::ListAttachedRolePoliciesRequest list_request;
    list_request.SetRoleName(roleName);

    bool done = false;
    bool attached = false;
    while (!done) {
        auto listOutcome = iam.ListAttachedRolePolicies(list_request);
        if (!listOutcome.IsSuccess()) {
            std::cerr << "Failed to list attached policies of role " <<
                      roleName << ": " << listOutcome.GetError().GetMessage() <<
                      std::endl;
            return false;
        }

        const auto &policies = listOutcome.GetResult().GetAttachedPolicies();
        attached = std::any_of(
                policies.cbegin(), policies.cend(),
                [=](const Aws::IAM::Model::AttachedPolicy &policy) {
                        return policy.GetPolicyArn() == policyArn;
                });
        if (attached) {
            break;
        }

        done = !listOutcome.GetResult().GetIsTruncated();
        list_request.SetMarker(listOutcome.GetResult().GetMarker());
    }

    if (!attached) {
        std::cerr << "Policy " << policyArn << " is not attached to role " <<
                  roleName << std::endl;
        return false;
    }

    // snippet-start:[iam.cpp.detach_role_policy02.code]
    Aws::IAM::Model::DetachRolePolicyRequest detachRequest;
    detachRequest.SetRoleName(roleName);
    detachRequest.SetPolicyArn(policyArn);

    auto detachOutcome = iam.DetachRolePolicy(detachRequest);
    if (!detachOutcome.IsSuccess()) {
        std::cerr << "Failed to detach policy " << policyArn << " from role "
                  << roleName << ": " << detachOutcome.GetError().GetMessage() <<
                  std::endl;
    }
    else {
        std::cout << "Successfully detached policy " << policyArn << " from role "
                  << roleName << std::endl;
    }

    return detachOutcome.IsSuccess();
    // snippet-end:[iam.cpp.detach_role_policy02.code]
}
/*
 *
 *  main function
 *
 * Prerequisites: An existing IAM role with an attached policy.
 *
 * Usage: 'run_detach_role_policy <role_name> <policy_arn>'
 *
 */

#ifndef TESTING_BUILD

int main(int argc, char **argv) {
    if (argc != 3) {
        std::cout << "Usage: run_detach_role_policy <role_name> <policy_arn>" <<
                  std::endl;
        return 1;
    }

    Aws::SDKOptions options;
    Aws::InitAPI(options);
    {
        Aws::String roleName(argv[1]);
        Aws::String policyArn = argv[2];

        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region in which the bucket was created (overrides config file).
        // clientConfig.region = "us-east-1";
        AwsDoc::IAM::detachRolePolicy(roleName, policyArn, clientConfig);
    }
    Aws::ShutdownAPI(options);
    return 0;
}

#endif  // TESTING_BUILD


text:
<?php

namespace ITDoors\PayMasterBundle\Entity;

use Doctrine\ORM\EntityRepository;

/**
 * PayMasterStatusRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class PayMasterStatusRepository extends EntityRepository
{
    /**
     * Searches status by $q
     *
     * @param string  $q
     *
     * @return mixed[]
     */
    public function getSearchQuery($q)
    {
        $sql = $this->createQueryBuilder('s');
        $sql->where($sql->expr()->like('lower(s.name)', ':q'))
            ->setParameter(':q', '%' . mb_strtolower($q, 'UTF-8') . '%');

        return $sql->getQuery()->getResult();
    }
}


text:
<?php

declare(strict_types=1);

namespace Fresh\TimestampableEntityBundle\EventListener;

use Doctrine\ORM\Event\LifecycleEventArgs;
use Doctrine\ORM\Events;
use Fresh\TimestampableEntityBundle\Model\TimestampableInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * DoctrineEventSubscriber.
 *
 * @author Artem Henvald <genvaldartem@gmail.com>
 */
class DoctrineEventSubscriber implements EventSubscriberInterface
{
    /**
     * {@inheritdoc}
     */
    public static function getSubscribedEvents(): array
    {
        return [
            Events::prePersist => 'prePersist',
            Events::preUpdate => 'preUpdate',
        ];
    }

    /**
     * @param LifecycleEventArgs $args
     */
    public function prePersist(LifecycleEventArgs $args): void
    {
        if ($args->getEntity() instanceof TimestampableInterface) {
            $args->getEntity()->setCreatedAt(new \DateTimeImmutable('now'))
                              ->setUpdatedAt(new \DateTime('now'));
        }
    }

    /**
     * @param LifecycleEventArgs $args
     */
    public function preUpdate(LifecycleEventArgs $args): void
    {
        if ($args->getEntity() instanceof TimestampableInterface) {
            $args->getEntity()->setUpdatedAt(new \DateTime('now'));
        }
    }
}