text:
package net.firejack.platform.service.directory.broker.directory;

import net.firejack.platform.api.directory.domain.Directory;
import net.firejack.platform.core.broker.ServiceBroker;
import net.firejack.platform.core.domain.NamedValues;
import net.firejack.platform.core.request.ServiceRequest;
import net.firejack.platform.core.response.ServiceResponse;
import net.firejack.platform.core.utils.Tuple;
import net.firejack.platform.web.security.directory.DirectoryServiceRepository;
import net.firejack.platform.web.statistics.annotation.TrackDetails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

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

@TrackDetails
@Component("readDirectoryServiceListBroker")
public class ReadDirectoryServiceListBroker extends ServiceBroker<ServiceRequest<NamedValues>, ServiceResponse<Directory>> {

	@Autowired
	private DirectoryServiceRepository directoryServiceRepository;

	@Override
	protected ServiceResponse<Directory> perform(ServiceRequest<NamedValues> request) throws Exception {
		List<Tuple<String, String>> directoryServiceLabels = directoryServiceRepository.getDirectoryServiceLabels();
		List<Directory> voList = new ArrayList<Directory>();
		for (Tuple<String, String> serviceLabel : directoryServiceLabels) {
			voList.add(new Directory(serviceLabel.getKey(), serviceLabel.getValue()));
		}

		return new ServiceResponse<Directory>(voList,"Read Directory Service successfully.", true);
	}
}


text:
get '/gadgets' do
  @gadgets = Gadget.all
  erb :'gadgets/index'
end

post '/gadgets' do
  gadget = Gadget.new(name: params[:name], body: params[:body])

  if gadget.save
    redirect to('/gadgets')
  else
    status 422
  end

end

redpajama_set_name: RedPajamaGithub


text:
export const DISPATCHER_IPC_KEY = 'ipc-dispatcher';

export const dispatcherChannels = {
  BROADCAST: 'broadcast',
  MESSAGE: 'send',
  REQUEST: 'request',
};

export const ipcChannels = {
  TEST_BROADCAST_MSG: 'test:broadcast-msg',
  TEST_SEND_REQUEST: 'test:send-request',
};

export interface ITestPayload {
  title: string;
}


text:
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)
require 'htmon/icinga'


text:
> This library is no longer maintained. I recommend using [dflydev/doctrine-orm-service-provider](https://github.com/dflydev/dflydev-doctrine-orm-service-provider) instead.

[![Build Status](https://secure.travis-ci.org/kherge/Entities.png?branch=master)](http://travis-ci.org/kherge/Entities)

Entities is a Silex service provider for Doctrine ORM.

## Installing

To install Entities, you must add it to the list of dependencies in your [`composer.json`][Composer] file.

    $ php composer.phar require kherge/entities

If you are not using Composer to manage your dependencies, you may use any [PSR-0][PSR-0] class loader to load Entities.

## Usage

Please see [the wiki][Wiki] for usage information.

[Composer]: http://getcomposer.org/
[PSR-0]: https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md
[Wiki]: https://github.com/kherge/Entities/wiki/Configure


text:
user-storage-jpa: User Storage Provider with EJB and JPA
========================================================

Level: Beginner
Technologies: JavaEE, EJB, JPA
Summary: User Storage Provider with EJB and JPA
Target Product: Keycloak
Source: <https://github.com/keycloak/keycloak-quickstarts>

What is it?
-----------

This is an example of the User Storage SPI implemented using EJB and JPA.  It shows you how you might use these components
to integrate Keycloak with an existing external custom user database.  The example integrates with a simple relational
database schema that has one user table that stores a username, email, phone number, and password for one particular user.
Using the User Storage SPI this table is mapped to the Keycloak user metamodel so that it can be consumed by the Keycloak
runtime. Before using this example, you should probably read the User Storage SPI chapter of our server developer guide.

System Requirements
-------------------

You need to have Keycloak running.

All you need to build this project is Java 8.0 (Java SDK 1.8) or later and Maven 3.3.3 or later.

Build and Deploy the Quickstart
-------------------------------

You must first deploy the datasource it uses.
Start up the Keycloak server.  Then in the directory of this example type the following maven command:

   ````
   mvn -Padd-datasource install
   ````

**Note**: If the server runs on different port than `10090`, you have to specify it by setting a
maven property `keycloak.management.port`.

   ````
   mvn -Padd-datasource install -Dkeycloak.management.port=9990
   ````

You only need to execute this maven command once.  If you execute this again, then you will get an error message that the datasource
already exists.

If you open the pom.xml file you'll see that the add-datasource profile creates an XA datasource using the built
in H2 database that comes with the server.  An XA datasource is required because you cannot use two non-xa datasources
in the same transaction.  The Keycloak database is non-xa.

Another thing to note is that the xa-datasource created is in-memory only.  If you reboot the server, any users you've
added or changes you've made to users loaded by this provider will be wiped clean.

To deploy the provider, run the following maven command:

   ````
   mvn clean install wildfly:deploy
   ````

If you want to play with and modify the example, simply rerun the maven deploy command above and the new version will be hot deployed.

Enable the Provider for a Realm
-------------------------------
Login to the Keycloak Admin Console and got to the User Federation tab.   You should now see your deployed provider in the add-provider list box.
Add the provider, save it.  This will now enable the provider for the 'master' realm.  Because this provider implements the UserRegistrationProvider interface, any new user you create in the
admin console or on the registration pages of Keycloak, will be created in the custom store used by the provider.  If you go
to the Users tab in the Admin Console and create a new user, you'll be able to see the provider in action.

Integration test of the Quickstart
----------------------------------

1. Make sure you have an Keycloak server running with an admin user in the `master` realm or use the provided docker image.
2. You need to have Chrome browser installed and updated to the latest version.
3. Run `mvn test -Pkeycloak-remote`. (The datasource will be deployed automatically.)

More Information
----------------
The User Storage SPI and how you can use Java EE to implement it is covered in detail in our server developer guide.


text:
@interface WDRequestMaker : NSObject

//custom more
+ (NSString *)defaultURL:(NSString *)component;
+ (NSString *)defaultURLImage:(NSString *)component;
//info = @{@"files":@{key:path},@"params":@{key:value}}
+ (NSURLRequest *)uploadDataRequest:(NSString *)urlString method:(NSString *)method info:(NSDictionary *)info;

+ (NSURLRequest *)makeRequest:(NSString *)url method:(NSString *)method info:(NSDictionary *)info;
+ (NSURLRequest *)makePostRequest:(NSString *)url info:(NSDictionary *)info;
+ (NSURLRequest *)makeGetRequest:(NSString *)url info:(NSDictionary *)info;

+ (NSURLRequest *)makeDownloadHeaderRequest:(NSString *)url;
+ (NSURLRequest *)makeDownloadRequest:(NSString *)url;//if first eTag = nil bytes = 0
+ (NSURLRequest *)makeDownloadRequest:(NSString *)url eTag:(NSString *)_eTag size:(long long)_bytes;//if first time eTag = nil

//please set these thing when call make request
//recommend call in Appdelegate first
//except Current Request Subject  that change everytime up to name of request
+ (void)setCurrentRequestSubject:(NSString *)subject;
+ (void)setAuthenKeyCallBack:(NSString *(^)(NSString *subject))handler;
+ (void)setMainURL:(NSString *)mainURL;
+ (void)setMainURLImage:(NSString *)mainURLImage;

@end


text:
module Numeric.Decidable.Zero
  ( DecidableZero(..)
  ) where

import Numeric.Algebra.Class
import Data.Int
import Data.Word
import Numeric.Natural

class Monoidal r => DecidableZero r where
  isZero :: r -> Bool

instance DecidableZero Bool where isZero = not
instance DecidableZero Integer where isZero = (0==)
instance DecidableZero Int where isZero = (0==)
instance DecidableZero Int8 where isZero = (0==)
instance DecidableZero Int16 where isZero = (0==)
instance DecidableZero Int32 where isZero = (0==)
instance DecidableZero Int64 where isZero = (0==)

instance DecidableZero Natural where isZero = (0==)
instance DecidableZero Word where isZero = (0==)
instance DecidableZero Word8 where isZero = (0==)
instance DecidableZero Word16 where isZero = (0==)
instance DecidableZero Word32 where isZero = (0==)
instance DecidableZero Word64 where isZero = (0==)

instance DecidableZero () where isZero _ = True

instance (DecidableZero a, DecidableZero b) => DecidableZero (a, b) where
  isZero (a,b) = isZero a && isZero b

instance (DecidableZero a, DecidableZero b, DecidableZero c) => DecidableZero (a, b, c) where
  isZero (a,b,c) = isZero a && isZero b && isZero c

instance (DecidableZero a, DecidableZero b, DecidableZero c, DecidableZero d) => DecidableZero (a, b, c, d) where
  isZero (a,b,c,d) = isZero a && isZero b && isZero c && isZero d

instance (DecidableZero a, DecidableZero b, DecidableZero c, DecidableZero d, DecidableZero e) => DecidableZero (a, b, c, d, e) where
  isZero (a,b,c,d,e) = isZero a && isZero b && isZero c && isZero d && isZero e


text:
from flask_login import current_user
from flask import has_request_context, request, abort
from notifications_python_client.base import BaseAPIClient
from notifications_python_client import __version__

def _attach_current_user(data):
    return dict(
        created_by=current_user.id,
        **data
    )

class NotifyAdminAPIClient(BaseAPIClient):
    def generate_headers(self, api_token):
        headers = {
            "Content-type": "application/json",
            "Authorization": "Bearer {}".format(api_token),
            "User-agent": "NOTIFY-API-PYTHON-CLIENT/{}".format(__version__)
        }
        return self._add_request_id_header(headers)

    @staticmethod
    def _add_request_id_header(headers):
        if not has_request_context():
            return headers
        headers['NotifyRequestID'] = request.request_id
        return headers

    def check_inactive_service(self):
        # this file is imported in app/__init__.py before current_service is initialised, so need to import later
        # to prevent cyclical imports
        from app import current_service

        # if the current service is inactive and the user isn't a platform admin, we should block them from making any
        # stateful modifications to that service
        if current_service and not current_service['active'] and not current_user.platform_admin:
            abort(403)

    def post(self, *args, **kwargs):
        self.check_inactive_service()
        return super().post(*args, **kwargs)

    def put(self, *args, **kwargs):
        self.check_inactive_service()
        return super().put(*args, **kwargs)

    def delete(self, *args, **kwargs):
        self.check_inactive_service()
        return super().delete(*args, **kwargs)


text:
<link href="css/style.css?token=dsfgsdfgsdg" rel="stylesheet">
<link href="css/style1.css" rel="stylesheet">


text:
exports.run = function(testRun, valueOf) {
	valueOf(testRun, require('./a/b/c/d').foo()).shouldBe(1);

	return testRun;
}


text:
package ocp._00_utils;

public interface Creator {
	public Example create(Chapter chapter);
}


text:
using UnityEngine;
using System.Collections;

public class GLOBAL : MonoBehaviour {

	private  int glasses = 0;
	public  int getNumberOfGlasses() {
		return glasses;
	}

	public int Hipped(int hits) {
		if (glasses >= 1) {
			glasses--;
		}
		return glasses;
	}
	public  void PlusOne() {
		glasses++;
	}
}


text:
package controller;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.namespace.QName;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.ws.Service;

import org.xml.sax.SAXException;

import soap.JaxboxServiceInterface;
import bean.Album;

/**
 * Servlet implementation class SearchServlet
 */
@WebServlet("/SearchServlet")
public class SearchServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public SearchServlet() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("search albums--->");
		String requestTerms = request.getParameter("q");

		// SENDING REQUEST
		// ---------------
		URL url = new URL("http://localhost:9999/ws/jaxbox?wsdl");
		QName qname = new QName("http://soap/", "JaxboxServiceService");

		Service service = Service.create(url, qname);
		JaxboxServiceInterface jaxbox = service.getPort(JaxboxServiceInterface.class);

		Album[] albums;

		try {
			System.out.println("in the try------------");
			albums = jaxbox.searchAlbumArtist(requestTerms);

			System.out.println("[client] size: " + albums.length);
//			for (Album album : albums) {
//				System.out.println(album);
//			}

			HttpSession session = request.getSession(true);
			session.setAttribute("mediaType", "albums");
			session.setAttribute("list", albums);

			getServletContext().getRequestDispatcher("/index.jsp").forward(request, response);

		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		}

	}

}


text:
package ru.vyukov.prometheus.starter;

import static org.junit.Assert.assertEquals;

import org.junit.Test;

public class DefaultPrometeusMetricNameConverterTest {

	@Test
	public void testConvertName() throws Exception {
		DefaultPrometeusMetricNameConverter converter = new DefaultPrometeusMetricNameConverter();
		String result = converter.convertName("mem");
		assertEquals("mem_bytes", result);
	}

}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
in Guzmán, Bononi & Grandi, Mycotaxon 19: 347 (1984)

#### Original name
Psilocybe banderillensis var. paulensis Guzmán & Bononi

### Remarks
null


text:
// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// MediaGalleriesPrivate eject API browser tests.

#include "base/files/file_path.h"
#include "base/stringprintf.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/extensions/extension_process_manager.h"
#include "chrome/browser/extensions/extension_system.h"
#include "chrome/browser/extensions/extension_test_message_listener.h"
#include "chrome/browser/media_galleries/media_galleries_test_util.h"
#include "chrome/browser/storage_monitor/media_storage_util.h"
#include "chrome/browser/storage_monitor/storage_monitor.h"
#include "chrome/browser/storage_monitor/test_storage_monitor.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/extensions/extension.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/test/test_utils.h"

namespace {

// Id of test extension from
// chrome/test/data/extensions/api_test/|kTestExtensionPath|
const char kTestExtensionId[] = "omeaapacpflbppbhigoacmagclbjhhmo";
const char kTestExtensionPath[] = "media_galleries_private/eject";

// JS commands.
const char kAddAttachListenerCmd[] = "addAttachListener()";
const char kRemoveAttachListenerCmd[] = "removeAttachListener()";
const char kEjectTestCmd[] = "ejectTest()";
const char kEjectFailTestCmd[] = "ejectFailTest()";

// And JS reply messages.
const char kAddAttachListenerOk[] = "add_attach_ok";
const char kAttachTestOk[] = "attach_test_ok";
const char kRemoveAttachListenerOk[] = "remove_attach_ok";
const char kEjectListenerOk[] = "eject_ok";
const char kEjectFailListenerOk[] = "eject_no_such_device";

const char kDeviceId[] = "testDeviceId";
const char kDeviceName[] = "foobar";
base::FilePath::CharType kDevicePath[] = FILE_PATH_LITERAL("/qux");

}  // namespace

///////////////////////////////////////////////////////////////////////////////
//                 MediaGalleriesPrivateEjectApiTest                         //
///////////////////////////////////////////////////////////////////////////////

class MediaGalleriesPrivateEjectApiTest : public ExtensionApiTest {
 public:
  MediaGalleriesPrivateEjectApiTest() : device_id_(GetDeviceId()) {}
  virtual ~MediaGalleriesPrivateEjectApiTest() {}

 protected:
  // ExtensionApiTest overrides.
  virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
    ExtensionApiTest::SetUpCommandLine(command_line);
    command_line->AppendSwitchASCII(switches::kWhitelistedExtensionID,
                                    kTestExtensionId);
  }

  content::RenderViewHost* GetHost() {
    const extensions::Extension* extension =
        LoadExtension(test_data_dir_.AppendASCII(kTestExtensionPath));
    return extensions::ExtensionSystem::Get(browser()->profile())->
        process_manager()->GetBackgroundHostForExtension(extension->id())->
            render_view_host();
  }

  void ExecuteCmdAndCheckReply(content::RenderViewHost* host,
                               const std::string& js_command,
                               const std::string& ok_message) {
    ExtensionTestMessageListener listener(ok_message, false);
    host->ExecuteJavascriptInWebFrame(string16(), ASCIIToUTF16(js_command));
    EXPECT_TRUE(listener.WaitUntilSatisfied());
  }

  void Attach() {
    chrome::StorageInfo info(device_id_, ASCIIToUTF16(kDeviceName), kDevicePath,
                             string16(), string16(), string16(), 0);
    chrome::StorageMonitor::GetInstance()->receiver()->ProcessAttach(info);
    content::RunAllPendingInMessageLoop();
  }

  void Detach() {
    chrome::StorageMonitor::GetInstance()->receiver()->ProcessDetach(
        device_id_);
    content::RunAllPendingInMessageLoop();
  }

  static std::string GetDeviceId() {
    return chrome::MediaStorageUtil::MakeDeviceId(
        chrome::MediaStorageUtil::REMOVABLE_MASS_STORAGE_WITH_DCIM, kDeviceId);
  }

 protected:
  const std::string device_id_;

 private:
  DISALLOW_COPY_AND_ASSIGN(MediaGalleriesPrivateEjectApiTest);
};

///////////////////////////////////////////////////////////////////////////////
//                               TESTS                                       //
///////////////////////////////////////////////////////////////////////////////

IN_PROC_BROWSER_TEST_F(MediaGalleriesPrivateEjectApiTest, EjectTest) {
  scoped_ptr<chrome::test::TestStorageMonitor> monitor(
      chrome::test::TestStorageMonitor::CreateForBrowserTests());

  content::RenderViewHost* host = GetHost();
  ExecuteCmdAndCheckReply(host, kAddAttachListenerCmd, kAddAttachListenerOk);

  // Attach / detach
  const std::string expect_attach_msg =
      base::StringPrintf("%s,%s", kAttachTestOk, kDeviceName);
  ExtensionTestMessageListener attach_finished_listener(expect_attach_msg,
                                                        false  /* no reply */);
  Attach();
  EXPECT_TRUE(attach_finished_listener.WaitUntilSatisfied());

  ExecuteCmdAndCheckReply(host, kEjectTestCmd, kEjectListenerOk);
  EXPECT_EQ(device_id_, monitor->ejected_device());

  Detach();
}

IN_PROC_BROWSER_TEST_F(MediaGalleriesPrivateEjectApiTest, EjectBadDeviceTest) {
  scoped_ptr<chrome::test::TestStorageMonitor> monitor(
      chrome::test::TestStorageMonitor::CreateForBrowserTests());

  ExecuteCmdAndCheckReply(GetHost(), kEjectFailTestCmd, kEjectFailListenerOk);

  EXPECT_EQ("", monitor->ejected_device());
}


text:
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)
require 'ruboty'
require 'ruboty/can_i_borrow'


text:
The Mathmos is an entry point for searching annotations and text images. These are indexed into elasticsearch using separate indexes and mappings. For annotations we will have indexed any annotation that is uploaded into the Elucidate server. For text, we will have indexed any text that has been fed to us by Starsky. Text searching requires further lookups from a coordinate service; given a text phrase and its position in an indexed text item, give us the xywh coordinates for that phrase in the corresponding image, possibly scaled with width and height input parameters). These are then made into annotations on the fly when searched, and in addition to resources, also yield hits.

## Entry points:
There are a number of entry points into the Mathmos. These are for search and autocomplete, both for text and annotations alone and for both together, and for **w3c** and **oa**.

These are:

###  Search

#### Annotations only:

    /search/oa/search
    /search/w3c/search

#### Text only:

    /search/oa/text/search
    /search/w3c/text/search

#### Both text and annotations:

    /search/search/oa
    /search/search/w3c

###  Autocomplete

#### Annotations only:

```
/search/oa/autocomplete
/search/w3c/autocomplete
```

#### Text only:

```
/search/oa/text/autocomplete
/search/w3c/text/autocomplete
```

#### Both text and annotations:

```
/search/autocomplete/oa
/search/autocomplete/w3c
```

## Search Request:

### Parameters:

The following parameters (inline with http://iiif.io/api/search/1.0/#query-parameters) are allowed in a mathmos search:

#### keywords

`/search/oa/search?q=bacon`

This is a phrase based search on the body, target, bodyURI and targetURI fields of indexed annotation items. The text field of text image items are also searchable here.

`/search/oa/search?q=bacon sandwich`

This will search for the phrase 'bacon sandwich' as written, and will not pull back items with just bacon or sandwich or 'sandwich bacon'.

#### motivation

Singular or multiple (space separated) motivations can be queried, and we can also search for a non-motivation. If searching for a non-motivation, only one is allowed.

`/search/oa/search?motivation=painting`

`/search/oa/search?motivation=painting tagging`

`/search/oa/search?motivation=non-painting`

When we indexed annotations for motivation we pulled data from any top level **motivation** or resource **purpose** fields. We index the w3c form of an annotation, and this may have motivations that are oa specific. These are usually prefixed by  oa:. We remove this when we index an item so e.g. oa:painting, which has no w3c equivalent is indexed with painting.

#### user

 singular or multiple (space separated) users can be queried

`/search/oa/search?user=sarah`

`/search/oa/search?user=sarah dave`

When we indexed users we pulled data from any top level **creator** field.

#### date

 Singular or multiple (space separated) dates can be queried

`/search/oa/search?date=1985-05-01T00:00:00+00:00/1986-05-01T00:00:00+00:00`

`/search/oa/search?date=1985-05-01T00:00:00+00:00/1986-05-01T00:00:00+00:00 1995-05-01T00:00:00+00:00/1996-05-01T00:00:00+00:00`

When we indexed dates we pulled data from any top level **created** field. Dates must be in the  ISO8601 format
YYYY-MM-DDThh:mm:ssZ/YYYY-MM-DDThh:mm:ssZ.

We can search on just keywords, just motivation, just user or just date, or a combination of any.  e.g.

`search/oa/search?q=bacon&motivation=painting&user=sarah&date=date=1985-05-01T00:00:00+00:00/1986-05-01T00:00:00+00:00`

Annotations can have motivation, user, date, but Text images by definition are only motivation=painting.

#### page

When we get a response for a search, we may have hundreds or thousands of annotations listed in the response, these are paged when the number of annotations in our list reaches > 100. Results with <= 100
show as non-paged annotation lists. Worth noting that paging will only handle 10,000 items, so if we have 13,678 items returned in our search results, we will only be able to go to page 99. This setting can be altering in the elasticsearch.yml by upping the index.max_result_window from 10000.

#### width/height

For text searches, we may need to scale our results. We can pass the width and height parameters to the coordinate service so that the resulting coordinates are scaled. Should no width/height parameters be passed then the coordinate service should deal with scaling.

When searching annotations and text together, a motivation of non-painting will limit the results to annotations only. Search parameters for text don't have motivation, user or date. Text only requests will only have query, page, width and height parameters. **All query strings must be URL encoded**.

## Search Response:

Regardless of what search is implemented, we return an [annotation list](http://iiif.io/api/presentation/2.1/#annotation-list)  response. Where the number of results are > 100, we allow the user to [page results](http://iiif.io/api/search/1.0/#paging-results).  When searching text we cannot know the exact number of results that will be obtained for each page, as they may be multiple hits for a word/phrase on one text item. In this instance we may not keep each page to 100 items, but allow >100 items per page, the startIndex and total will change to reflect this.

### Annotation-only Search Request:

`http://localhost:8080/search/oa/search/?q=84.jpg&page=1`

### Annotation-only Search Response:

    {
      "@context": "http://iiif.io/api/presentation/2/context.json",
      "@id": "http://localhost:8080/search/oa/search/?q=84.jpg&page=1",
      "@type": "sc:AnnotationList",
      "within": {
        "@type": "sc:Layer",
        "total": "2738",
        "first": "http://localhost:8080/search/oa/search/?q=84.jpg&page=1",
        "last": "http://localhost:8080/search/oa/search/?q=84.jpg&page=28"
      },
      "next": "http://localhost:8080/search/oa/search/?q=84.jpg&page=2",
      "startIndex": "0",
      "resources": [
        {
          "@context": "https://raw.githubusercontent.com/dlcs/elucidate-server/master/elucidate-server/src/main/resources/contexts/oa.jsonld",
          "@id": "http://annotation-local.digtest.co.uk/annotation/oa/156dd8e1-bec5-404d-8a32-e7668d3b750d/989a2cad-bedc-441c-b2c3-98aa638025f8",
          "@type": "oa:Annotation",
          "hasBody": "https://randomuser.me/api/portraits/women/74.jpg",
          "hasTarget": "https://randomuser.me/api/portraits/men/84.jpg"
        },
        {
          "@context": "https://raw.githubusercontent.com/dlcs/elucidate-server/master/elucidate-server/src/main/resources/contexts/oa.jsonld",
          "@id": "http://annotation-local.digtest.co.uk/annotation/oa/156dd8e1-bec5-404d-8a32-e7668d3b750d/dbf34d3a-9fc9-48a0-becb-8eb7af86c76a",
          "@type": "oa:Annotation",
          "hasBody": "https://randomuser.me/api/portraits/men/13.jpg",
          "hasTarget": "https://randomuser.me/api/portraits/women/84.jpg"
        },.....

### Text-only Search Request:

Text search results create annotations on the fly. We have previously indexed text items, which are basically a canvas URI, an image URI and the text itself.  These are fed by a Starsky service. When we search for a phrase in elasticsearch, we find hits, and then pass the offset positions of the hits in the text to a coordinate service.

```
{
  "@context": [
    "http://iiif.io/api/presentation/2/context.json",
    "http://iiif.io/api/search/1/context.json"
  ],
  "@id": "http://localhost:8080/search/search/oa?q=fifty",
  "@type": "sc:AnnotationList",
  "resources": [
    {
      "@id": "http://localhost:8080/search/search/oa/searchResultVIAHTTuH654,278,48,9",
      "@type": "oa:Annotation",
      "motivation": "sc:painting",
      "resource": {
        "@type": "cnt:ContentAsText",
        "chars": "fifty"
      },
      "on": "https://presley.dlcs-ida.org/iiif/idatest01/_roll_M-1011_145_cvs-31-33/canvas/c31#xywh=654,278,48,9"
    }
  ],
  "hits": [
    {
      "@type": "search:Hit",
      "annotations": [
        "http://localhost:8080/search/search/oa/searchResultVIAHTTuH654,278,48,9"
      ],
      "match": "fifty",
      "before": "enrolled during the last year the agency consists of about ",
      "after": " frame and concrete buildings this agenoy and school is"
    }
  ]
}
```

This search result illustrates what happens when we have 2 annotations for one search hit. This means that  we have gone over a line in our text document. The '**concrete**' is at the end of a line, and '**buildings**' at the start of another.

    {
      "@context": [
        "http://iiif.io/api/presentation/2/context.json",
        "http://iiif.io/api/search/1/context.json"
      ],
      "@id": "http://localhost:8080/search/search/oa?q=concrete%20buildings",
      "@type": "sc:AnnotationList",
      "resources": [
        {
          "@id": "http://localhost:8080/search/search/oa/searchResultDNWkMOSI821,278,75,9",
          "@type": "oa:Annotation",
          "motivation": "sc:painting",
          "resource": {
            "@type": "cnt:ContentAsText",
            "chars": "concrete"
          },
          "on": "https://presley.dlcs-ida.org/iiif/idatest01/_roll_M-1011_145_cvs-31-33/canvas/c31#xywh=821,278,75,9"
        },
        {
          "@id": "http://localhost:8080/search/search/oa/searchResultskyCDKmn122,290,88,9",
          "@type": "oa:Annotation",
          "motivation": "sc:painting",
          "resource": {
            "@type": "cnt:ContentAsText",
            "chars": "buildings"
          },
          "on": "https://presley.dlcs-ida.org/iiif/idatest01/_roll_M-1011_145_cvs-31-33/canvas/c31#xywh=122,290,88,9"
        }
      ],
      "hits": [
        {
          "@type": "search:Hit",
          "annotations": [
            "http://localhost:8080/search/search/oa/searchResultDNWkMOSI821,278,75,9",
            "http://localhost:8080/search/search/oa/searchResultskyCDKmn122,290,88,9"
          ],
          "match": "concrete buildings",
          "before": "last year the agency consists of about fifty frame and ",
          "after": " this agenoy and school is situated upon the western"
        }
      ]
    }

At present we do not allow searching that spans image boundaries, as we do not index images with this in mind. In our hit we show 10 words **before** and the 10 words **after** the **match**. We also only show lowercase words for the hit.

### Text-only Search Request:

`http://localhost:8080/search/oa/text/search?q=fifty%20frame`

### Text-only Search Response:

    {
      "@context": [
        "http://iiif.io/api/presentation/2/context.json",
        "http://iiif.io/api/search/1/context.json"
      ],
      "@id": "http://localhost:8080/search/search/oa?q=fifty%20frame",
      "@type": "sc:AnnotationList",
      "resources": [
        {
          "@id": "http://localhost:8080/search/search/oa/searchResulthNbQmoDS654,278,109,10",
          "@type": "oa:Annotation",
          "motivation": "sc:painting",
          "resource": {
            "@type": "cnt:ContentAsText",
            "chars": "fifty frame"
          },
          "on": "https://presley.dlcs-ida.org/iiif/idatest01/_roll_M-1011_145_cvs-31-33/canvas/c31#xywh=654,278,109,10"
        }
      ],
      "hits": [
        {
          "@type": "search:Hit",
          "annotations": [
            "http://localhost:8080/search/search/oa/searchResulthNbQmoDS654,278,109,10"
          ],
          "match": "fifty frame",
          "before": "enrolled during the last year the agency consists of about ",
          "after": " and concrete buildings this agenoy and school is situated"
        }
      ]
    }

## Autocomplete Request:

### Intro:

Autocomplete makes use of Elasticsearch [Completion](https://www.elastic.co/guide/en/elasticsearch/reference/5.4/search-suggesters-completion.html) and [Context](https://www.elastic.co/guide/en/elasticsearch/reference/5.4/suggester-context.html) Suggesters.  These are implemented when indexing. We take all the values (parsed by spaces) of the data in an annotation an add this to the documents suggest input field as lowercase String array. For plaintext we add the space separated terms in the plaintext field as input. We use the [Context](https://www.elastic.co/guide/en/elasticsearch/reference/5.4/suggester-context.html) Suggester to hold information on the manifest(s).

### Parameters:

The following query parameters inline with the http://iiif.io/api/search/1.0/#query-parameters-1 have been implemented:

#### keywords

`/search/oa/autocomplete?q=bacon`

The keyword parameter is mandatory for an autocomplete, but motivation, user and date in addition to min have not been implemented.

##Autocomplete Response:

The responses are in line with http://iiif.io/api/search/1.0/#response, however we have omitted the count property. We have not implemented any labels for autocomplete. We limit the number of results returned to 1000.  The only difference between an oa and w3c response is the terms url will have the path for an oa search or a w3c search. We always URL encode the terms:url field.

### Autocomplete request:

`http://localhost:8080/search/w3c/text/autocomplete?q=therapeuti`

### Autocomplete response:

    {
      "@context": "http://iiif.io/api/search/1/context.json",
      "@id": "http://localhost:8080/search/w3c/text/autocomplete?q=therapeuti",
      "@type": "search:TermList",
      "terms": [
          {
            "match": "therapeutics",
            "url": "http://localhost:8080/search/w3c/text/search?q=therapeutics"
          },
          {
            "match": "therapeutics,",
            "url": "http://localhost:8080/search/w3c/text/search?q=therapeutics%2C"
          },
          {
            "match": "therapeutics:",
            "url": "http://localhost:8080/search/w3c/text/search?q=therapeutics%3A"
          },
          {
            "match": "therapeutique,",
            "url": "http://localhost:8080/search/w3c/text/search?q=therapeutique%2C"
          },
          {
            "match": "therapeutische",
            "url": "http://localhost:8080/search/w3c/text/search?q=therapeutische"
          },
          {
            "match": "therapeutische,",
            "url": "http://localhost:8080/search/w3c/text/search?q=therapeutische%2C"
          },
          {
            "match": "therapeutischen",
            "url": "http://localhost:8080/search/w3c/text/search?q=therapeutischen"
          }
        ]
      }
    }

### Topic Autocomplete Requests:

If we were doing the autocomplete for e.g. a specific topic then we would do something like:

Place is an umbrella term for GPE (Geo Political Entity), LOC (Location), FAC (Facilities) etc. Topics can be real or virtual so we need to query for six uri's:

```
https://omeka.dlcsida.org/s/ida/page/topics/virtual:gpe/sa

https://omeka.dlcsida.org/s/ida/page/topics/gpe/sa

https://omeka.dlcsida.org/s/ida/page/topics/virtual:loc/sa

https://omeka.dlcsida.org/s/ida/page/topics/loc/sa

https://omeka.dlcsida.org/s/ida/page/topics/virtual:fac/sa

https://omeka.dlcsida.org/s/ida/page/topics/fac/sa

```

We need to URL- encode each uri to autocomplete on e.g.

```
http://mathmos.dlcs-ida.org/search/oa/autocomplete?q=https%3A%2F%2Fomeka.dlcsida.org%2Fs%2Fida%2Fpage%2Ftopics%2Fvirtual%3Agpe%2Fsa
```

and so on for each topic uri..

This will pull back six sets of results, some of which may be empty if say there are no https://omeka.dlcsida.org/s/ida/page/topics/gpe/sa topics.  These will be of the form:

### Topic Autocomplete Responses:

```
{
    "@context": "http://iiif.io/api/search/1/context.json",
    "@id": "http://mathmos.dlcs-ida.org/search/oa/autocomplete?q=https%3A%2F%2Fomeka.dlcsida.org%2Fs%2Fida%2Fpage%2Ftopics%2Fvirtual%3Agpe%2Fsa",
    "@type": "search:TermList",
    "terms": [
        {
            "match": "https://omeka.dlcsida.org/s/ida/page/topics/virtual:gpe/samir",
            "url": "http://mathmos.dlcs-ida.org/search/oa/search?q=https%3A%2F%2Fomeka.dlcsida.org%2Fs%2Fida%2Fpage%2Ftopics%2Fvirtual%3Agpe%2Fsamir"
        },
        {
            "match": "https://omeka.dlcsida.org/s/ida/page/topics/virtual:gpe/santafe",
            "url": "http://mathmos.dlcs-ida.org/search/oa/search?q=https%3A%2F%2Fomeka.dlcsida.org%2Fs%2Fida%2Fpage%2Ftopics%2Fvirtual%3Agpe%2Fsantafe"
        },
        {
            "match": "https://omeka.dlcsida.org/s/ida/page/topics/virtual:gpe/saslar",
            "url": "http://mathmos.dlcs-ida.org/search/oa/search?q=https%3A%2F%2Fomeka.dlcsida.org%2Fs%2Fida%2Fpage%2Ftopics%2Fvirtual%3Agpe%2Fsaslar"
        },
        .....
```

or for an empty response:

```
{
    "@context": "http://iiif.io/api/search/1/context.json",
    "@id": "http://mathmos.dlcs-ida.org/search/oa/autocomplete?q=https://BAD",
    "@type": "search:TermList",
    "terms": []
}
```

Iteration through each response and merging results of the match field minus the autocomplete strings e.g.

```
https://omeka.dlcsida.org/s/ida/page/topics/virtual:gpe/samir
```

minus

```
https://omeka.dlcsida.org/s/ida/page/topics/virtual:gpe
```

will give you the terms you are looking for e.g.

```
samir
```

We could narrow down the number of requests we need to make by doing an autocomplete as we drilldown to searching for a place topic, as we will know if there is any data for e.g.

```
https://omeka.dlcsida.org/s/ida/page/topics/virtual:gpe

https://omeka.dlcsida.org/s/ida/page/topics/gpe

https://omeka.dlcsida.org/s/ida/page/topics/virtual:loc

https://omeka.dlcsida.org/s/ida/page/topics/loc

https://omeka.dlcsida.org/s/ida/page/topics/virtual:fac

https://omeka.dlcsida.org/s/ida/page/topics/fac

```

And if we only get  a response with data for e.g.

```
https://omeka.dlcsida.org/s/ida/page/topics/virtual:gpe
```

Then only make requests for this data. Potential to cache this higher level topic information so that you can periodically query for update how many actual queries you need to make for a place.

# Caching

We have used ehcache to cache the search results from mathmos. This is done on the queryString in annotation only searches. Caching of text and mixed searches is done slightly differently, as we have a potential shift in the total number of results as we page through.

# Within (coming soon)

Within is where we want to limit the results returned to a particular collection. We will Base64 encode the within collection url and use this to call another service that allows us to filter our set of results to a subset only concerned with that collection.

The entry points for within will be:

### Search

#### Annotations only:

`/search/{withinId}/oa/search`

`/search/{withinId}/w3c/search`

#### Text only:

`/search/{withinId}/oa/text/search`

`/search/{withinId}/w3c/text/search`

#### Annotations and text:

`/search/{withinId}/search/oa`

`/search/{withinId}/search/w3c`

### Autocomplete

#### Annotations only:

`/search/{withinId}/oa/autocomplete`

`/search/{withinId}/w3c/autocomplete`

#### Text only:

`/search/{withinId}/oa/text/autocomplete`

`/search/{withinId}/w3c/text/autocomplete`

#### Annotations and text:

`/search/{withinId}/autocomplete/oa`

`/search/{withinId}/autocomplete/w3c`


text:
const fs = require('fs-extra')
const path = require('path')
const spinner = require('../../scripts/commons/spinner')

/** @type {Boolean} 标记流程是否已运行 */
let complete = false

const webappBefore = async (data = {}) => {
    let { dist } = data
    if (!dist) {
        dist = (() => {
            const { dist } = require('../../../koot.config')

            if (path.isAbsolute(dist))
                return dist

            return path.resolve(__dirname, '../../../', dist)
        })()
    }

    if (complete) return
    if (process.env.WEBPACK_BUILD_ENV !== 'prod') {
        complete = true
        return
    }

    const channel = require('../../channel')
    const repoPath = (() => {
        if (channel === 'yuubari')
            return 'git@github.com:TeamFleet/yuubari-server.git'
        return ''
    })()
    const isDistRepo = fs.existsSync(dist) && fs.existsSync(path.resolve(dist, '.git'))
    const step = '准备打包结果目录'
    const waiting = spinner(step + '...')

    // 如果目标路径存在但不是 git 项目,删除,git clone
    if (!isDistRepo) {
        await fs.remove(dist)
        await fs.ensureDir(dist)
        const git = require('simple-git/promise')(dist)
        await git.clone(repoPath, dist)
            .catch(err => {
                waiting.fail(err)
            })
    }

    const git = require('simple-git/promise')(dist)

    /** @type {Boolean} 是否有 git repo 操作权限 */
    const hasGitAccess = await (async () => {
        let err

        git.silent(true)

        await git.push('origin', 'master')
            .catch(e => {
                err = e
            })

        git.silent(false)

        if (err instanceof Error) err = err.message
        if (typeof err === 'string')
            return !/permission.+denied/i.test(err)

        return true
    })()

    if (hasGitAccess) {
        // 如果有操作权限,git pull
        await git.reset('hard')
        await git.clean('f')
        await git.pull()
    }

    waiting.stop()
    // spinner(step).succeed()
    complete = true
}

if (!module || !module.parent)
    webappBefore({ dist: path.resolve(__dirname, '../../../', 'dist-webapp') })
else
    module.exports = webappBefore


text: a public repo of some arduino stuff I use in my classes


text:
/*! Select2 4.0.0 | https://github.com/select2/select2/blob/master/LICENSE.md */

(function () {
    if (jQuery && jQuery.fn && jQuery.fn.select2 && jQuery.fn.select2.amd)
        var e = jQuery.fn.select2.amd;
    return e.define("es", [], function () {
        return {
            errorLoading: function () { return "La carga falló" },
            inputTooLong: function (e) { var t = e.input.length - e.maximum, n = "Por favor, elimine " + t + " car"; return t == 1?n += "ácter":n += "acteres", n },
            inputTooShort: function (e) { var t = e.minimum - e.input.length, n = "Por favor, introduzca " + t + " car"; return t == 1?n += "ácter":n += "acteres", n },
            loadingMore: function () { return "Cargando más resultados…" },
            maximumSelected: function (e) { var t = "Sólo puede seleccionar " + e.maximum + " elemento"; return e.maximum != 1 && (t += "s"), t },
            noResults: function () { return "No se encontraron resultados" },
            searching: function () { return "Buscando…" }
        }
    }), { define: e.define, require: e.require }
})();


text:
package com.facebook.buck.apple;

import com.facebook.buck.model.BuildTargets;
import com.facebook.buck.rules.AddToRuleKey;
import com.facebook.buck.rules.BuildContext;
import com.facebook.buck.rules.BuildRule;
import com.facebook.buck.rules.BuildRuleParams;
import com.facebook.buck.rules.HasRuntimeDeps;
import com.facebook.buck.rules.Label;
import com.facebook.buck.rules.NoopBuildRule;
import com.facebook.buck.rules.SourcePathResolver;
import com.facebook.buck.rules.TestRule;
import com.facebook.buck.rules.Tool;
import com.facebook.buck.step.ExecutionContext;
import com.facebook.buck.step.Step;
import com.facebook.buck.step.fs.MakeCleanDirectoryStep;
import com.facebook.buck.test.TestCaseSummary;
import com.facebook.buck.test.TestResults;
import com.facebook.buck.test.TestRunningOptions;
import com.facebook.buck.util.BuckConstant;
import com.facebook.buck.util.HumanReadableException;
import com.facebook.buck.zip.UnzipStep;
import com.google.common.base.Function;
import com.google.common.base.Functions;
import com.google.common.base.Joiner;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.collect.Iterables;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;

@SuppressWarnings("PMD.TestClassWithoutTestCases")
public class AppleTest extends NoopBuildRule implements TestRule, HasRuntimeDeps {

  @AddToRuleKey
  private final Optional<Path> xctoolPath;

  @AddToRuleKey
  private final Optional<BuildRule> xctoolZipRule;

  @AddToRuleKey
  private final Tool xctest;

  @AddToRuleKey
  private final Optional<Tool> otest;

  @AddToRuleKey
  private final boolean useXctest;

  @AddToRuleKey
  private final String platformName;

  private final Optional<String> defaultDestinationSpecifier;
  private final Optional<ImmutableMap<String, String>> destinationSpecifier;

  @AddToRuleKey
  private final BuildRule testBundle;

  @AddToRuleKey
  private final Optional<AppleBundle> testHostApp;

  private final ImmutableSet<String> contacts;
  private final ImmutableSet<Label> labels;

  @AddToRuleKey
  private final boolean runTestSeparately;

  private final Path xctoolUnzipDirectory;
  private final Path testOutputPath;

  private final String testBundleExtension;

  private Optional<AppleTestXctoolStdoutReader> xctoolStdoutReader;

  private static class AppleTestXctoolStdoutReader
    implements XctoolRunTestsStep.StdoutReadingCallback {

    private final TestCaseSummariesBuildingXctoolEventHandler xctoolEventHandler;

    public AppleTestXctoolStdoutReader(TestRule.TestReportingCallback testReportingCallback) {
      this.xctoolEventHandler = new TestCaseSummariesBuildingXctoolEventHandler(
          testReportingCallback);
    }

    @Override
    public void readStdout(InputStream stdout) throws IOException {
      try (InputStreamReader stdoutReader =
               new InputStreamReader(stdout, StandardCharsets.UTF_8);
           BufferedReader bufferedReader = new BufferedReader(stdoutReader)) {
        XctoolOutputParsing.streamOutputFromReader(bufferedReader, xctoolEventHandler);
      }
    }

    public ImmutableList<TestCaseSummary> getTestCaseSummaries() {
      return xctoolEventHandler.getTestCaseSummaries();
    }
  }

  AppleTest(
      Optional<Path> xctoolPath,
      Optional<BuildRule> xctoolZipRule,
      Tool xctest,
      Optional<Tool> otest,
      Boolean useXctest,
      String platformName,
      Optional<String> defaultDestinationSpecifier,
      Optional<ImmutableMap<String, String>> destinationSpecifier,
      BuildRuleParams params,
      SourcePathResolver resolver,
      BuildRule testBundle,
      Optional<AppleBundle> testHostApp,
      String testBundleExtension,
      ImmutableSet<String> contacts,
      ImmutableSet<Label> labels,
      boolean runTestSeparately) {
    super(params, resolver);
    this.xctoolPath = xctoolPath;
    this.xctoolZipRule = xctoolZipRule;
    this.useXctest = useXctest;
    this.xctest = xctest;
    this.otest = otest;
    this.platformName = platformName;
    this.defaultDestinationSpecifier = defaultDestinationSpecifier;
    this.destinationSpecifier = destinationSpecifier;
    this.testBundle = testBundle;
    this.testHostApp = testHostApp;
    this.contacts = contacts;
    this.labels = labels;
    this.runTestSeparately = runTestSeparately;
    this.testBundleExtension = testBundleExtension;
    this.xctoolUnzipDirectory = BuildTargets.getScratchPath(
        params.getBuildTarget(),
        "__xctool_%s__");
    this.testOutputPath = getPathToTestOutputDirectory().resolve("test-output.json");
    this.xctoolStdoutReader = Optional.absent();
  }

  @Override
  public ImmutableSet<Label> getLabels() {
    return labels;
  }

  @Override
  public ImmutableSet<String> getContacts() {
    return contacts;
  }

  @Override
  public ImmutableSet<BuildRule> getSourceUnderTest() {
    // Apple tests always express a rule -> test dependency, not the other way
    // around.
    return ImmutableSet.of();
  }

  @Override
  public boolean hasTestResultFiles(ExecutionContext executionContext) {
    return getProjectFilesystem().exists(testOutputPath);
  }

  @Override
  public ImmutableList<Step> runTests(
      BuildContext buildContext,
      ExecutionContext executionContext,
      TestRunningOptions options,
      TestRule.TestReportingCallback testReportingCallback) {
    ImmutableList.Builder<Step> steps = ImmutableList.builder();
    Path resolvedTestBundleDirectory = getProjectFilesystem().resolve(
        Preconditions.checkNotNull(testBundle.getPathToOutput()));

    Path pathToTestOutput = getProjectFilesystem().resolve(
        getPathToTestOutputDirectory());
    steps.add(new MakeCleanDirectoryStep(getProjectFilesystem(), pathToTestOutput));

    Path resolvedTestOutputPath = getProjectFilesystem().resolve(
        testOutputPath);

    Optional<Path> testHostAppPath = Optional.absent();
    if (testHostApp.isPresent()) {
      Path resolvedTestHostAppDirectory = getProjectFilesystem().resolve(
          Preconditions.checkNotNull(testHostApp.get().getPathToOutput()));
      testHostAppPath = Optional.of(
          resolvedTestHostAppDirectory.resolve(
              testHostApp.get().getUnzippedOutputFilePathToBinary()));
    }

    if (!useXctest) {
      if (!xctoolPath.isPresent() && !xctoolZipRule.isPresent()) {
        throw new HumanReadableException(
            "Set xctool_path = /path/to/xctool or xctool_zip_target = //path/to:xctool-zip " +
            "in the [apple] section of .buckconfig to run this test");
      }

      ImmutableSet.Builder<Path> logicTestPathsBuilder = ImmutableSet.builder();
      ImmutableMap.Builder<Path, Path> appTestPathsToHostAppsBuilder = ImmutableMap.builder();

      if (testHostAppPath.isPresent()) {
        appTestPathsToHostAppsBuilder.put(
            resolvedTestBundleDirectory,
            testHostAppPath.get());
      } else {
        logicTestPathsBuilder.add(resolvedTestBundleDirectory);
      }

      Path xctoolBinaryPath;

      if (xctoolZipRule.isPresent()) {
        Path resolvedXctoolUnzipDirectory = getProjectFilesystem().resolve(
            xctoolUnzipDirectory);
        steps.add(new MakeCleanDirectoryStep(getProjectFilesystem(), resolvedXctoolUnzipDirectory));
        steps.add(
            new UnzipStep(
                getProjectFilesystem(),
                // This is added as a runtime dependency via getRuntimeDeps() earlier.
                Preconditions.checkNotNull(xctoolZipRule.get().getPathToOutput()),
                resolvedXctoolUnzipDirectory));
        xctoolBinaryPath = resolvedXctoolUnzipDirectory.resolve("bin/xctool");
      } else {
        xctoolBinaryPath = xctoolPath.get();
      }

      xctoolStdoutReader = Optional.of(new AppleTestXctoolStdoutReader(testReportingCallback));
      Optional<String> destinationSpecifierArg;
      if (!destinationSpecifier.get().isEmpty()) {
        destinationSpecifierArg = Optional.of(
            Joiner.on(',').join(
                Iterables.transform(
                    destinationSpecifier.get().entrySet(),
                    new Function<Map.Entry<String, String>, String>() {
                      @Override
                      public String apply(Map.Entry<String, String> input) {
                        return input.getKey() + "=" + input.getValue();
                      }
                    })));
      } else {
        destinationSpecifierArg = defaultDestinationSpecifier;
      }
      steps.add(
          new XctoolRunTestsStep(
              getProjectFilesystem(),
              xctoolBinaryPath,
              platformName,
              destinationSpecifierArg,
              logicTestPathsBuilder.build(),
              appTestPathsToHostAppsBuilder.build(),
              resolvedTestOutputPath,
              xctoolStdoutReader));
    } else {
      Tool testRunningTool;
      if (testBundleExtension.equals("xctest")) {
        testRunningTool = xctest;
      } else if (otest.isPresent()) {
        testRunningTool = otest.get();
      } else {
        throw new HumanReadableException(
            "Cannot run non-xctest bundle type %s (otest not present)",
            testBundleExtension);
      }
      steps.add(
          new XctestRunTestsStep(
              getProjectFilesystem(),
              testRunningTool.getCommandPrefix(getResolver()),
              (testBundleExtension.equals("xctest") ? "-XCTest" : "-SenTest"),
              resolvedTestBundleDirectory,
              resolvedTestOutputPath));
    }

    return steps.build();
  }

  @Override
  public Callable<TestResults> interpretTestResults(
      final ExecutionContext executionContext,
      boolean isUsingTestSelectors,
      boolean isDryRun) {
    return new Callable<TestResults>() {
      @Override
      public TestResults call() throws Exception {
        List<TestCaseSummary> testCaseSummaries;
        if (xctoolStdoutReader.isPresent()) {
          // We've already run the tests with 'xctool' and parsed
          // their output; no need to parse the same output again.
          testCaseSummaries = xctoolStdoutReader.get().getTestCaseSummaries();
        } else {
          Path resolvedOutputPath = getProjectFilesystem().resolve(testOutputPath);
          try (BufferedReader reader =
              Files.newBufferedReader(resolvedOutputPath, StandardCharsets.UTF_8)) {
            if (useXctest) {
              testCaseSummaries = XctestOutputParsing.parseOutputFromReader(reader);
            } else {
              TestCaseSummariesBuildingXctoolEventHandler xctoolEventHandler =
                  new TestCaseSummariesBuildingXctoolEventHandler(NOOP_REPORTING_CALLBACK);
              XctoolOutputParsing.streamOutputFromReader(reader, xctoolEventHandler);
              testCaseSummaries = xctoolEventHandler.getTestCaseSummaries();
            }
          }
        }
        return new TestResults(
          getBuildTarget(),
          testCaseSummaries,
          contacts,
          FluentIterable.from(labels).transform(Functions.toStringFunction()).toSet());
      }
    };
  }

  @Override
  public Path getPathToTestOutputDirectory() {
    // TODO(user): Refactor the JavaTest implementation; this is identical.

    List<String> pathsList = new ArrayList<>();
    pathsList.add(getBuildTarget().getBaseNameWithSlash());
    pathsList.add(
        String.format("__apple_test_%s_output__", getBuildTarget().getShortNameAndFlavorPostfix()));

    // Putting the one-time test-sub-directory below the usual directory has the nice property that
    // doing a test run without "--one-time-output" will tidy up all the old one-time directories!
    String subdir = BuckConstant.oneTimeTestSubdirectory;
    if (subdir != null && !subdir.isEmpty()) {
      pathsList.add(subdir);
    }

    String[] pathsArray = pathsList.toArray(new String[pathsList.size()]);
    return Paths.get(BuckConstant.GEN_DIR, pathsArray);
  }

  @Override
  public boolean runTestSeparately() {
    // Tests which run in the simulator must run separately from all other tests;
    // there's a 20 second timeout hard-coded in the iOS Simulator SpringBoard which
    // is hit any time the host is overloaded.
    return runTestSeparately || testHostApp.isPresent();
  }

  // This test rule just executes the test bundle, so we need it available locally.
  @Override
  public ImmutableSortedSet<BuildRule> getRuntimeDeps() {
    ImmutableSortedSet.Builder<BuildRule> runtimeDepsBuilder =
        ImmutableSortedSet.<BuildRule>naturalOrder()
            .add(testBundle)
            .addAll(testHostApp.asSet());

    if (xctoolZipRule.isPresent()) {
      runtimeDepsBuilder.add(xctoolZipRule.get());
    }

    return runtimeDepsBuilder.build();
  }

  @Override
  public boolean supportsStreamingTests() {
    return !useXctest;
  }
}


text:
STEFANO LONGO

                EN
                IT


text:
class BodyMonitorsController < ApplicationController
  include Tubesock::Hijack

  def index
  end

  def monitor
    hijack do |tubesock|
      redis_thread = Thread.new do
        Redis.new.subscribe 'monitor' do |on|
          on.message do |channel, message|
            tubesock.send_data message
          end
        end
      end

      tubesock.onmessage do |m|
        measure, item_value, recorded_at, session_code = m.split(',')

        # NOTE: first value comes in unreasonable high for GSR
        unless item_value.to_f > 9
          object_class(measure).create(item_value: item_value,
            recorded_at: Time.at(recorded_at.to_i/1000), session_code: session_code)
          puts "#{measure},#{item_value},#{recorded_at}"
          Redis.new.publish 'monitor', "#{measure},#{item_value},#{recorded_at}"
        end
      end

      tubesock.onclose do
        redis_thread.kill
      end
    end
  end

  def gsr
  end

  def history
    @ibi_session_codes = IbiRecord.pluck(:session_code).uniq
    @gsr_session_codes = GsrRecord.pluck(:session_code).uniq
  end

  def gsr_history
    gon.gsr_records = GsrRecord.select(:item_value, :recorded_at).where(session_code: params[:session_code])
  end

  def ibi_history
    gon.ibi_records = IbiRecord.where(session_code: params[:session_code]).
      select(:item_value, :recorded_at)
  end

  private

  def object_class(measure)
    case measure
    when 'IBI'
      IbiRecord
    when 'GSR'
      GsrRecord
    end
  end
end


text:
package com.mauriciotogneri.idlerush.objects.buildings;

public class Building3 extends Building
{
	public Building3(int level)
	{
		super(level, 500, 4);
	}
}


text:
using OY.Theory.Shared;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace OY.Theory.DataStructures.Heap
{
    public class BinaryHeap<T> : IHeap<T>, IEnumerable<T>
    {
        private int count;
        private ResizableArray<T> data;
        private IComparer<T> comparer;

        /// <summary>
        /// We at most support 64M items
        /// </summary>
        public const int MaxSize = 1024 * 1024 * 64;

        private bool SafeGetAtIndex(int i, ref T item)
        {
            if (i < 0 || i >= this.count)
                return false;
            item = this.data[i];
            return true;
        }

        private bool Less(int i, int j)
        {
            if (this.comparer == null)
                return ((IComparable<T>)data[i]).CompareTo(data[j]) < 0;
            return this.comparer.Compare(data[i], data[j]) < 0;
        }

        private bool Great(int i, int j)
        {
            return !this.Less(j, i);
        }

        private void Swap(int i, int j)
        {
            T t = data[i];
            this.data[i] = this.data[j];
            this.data[j] = t;
        }

        private void Sink(int i)
        {
            while (i >= 0 && i < this.count)
            {
                int l = 2 * (i + 1) - 1;
                if (l >= this.count)
                    return;

                int min = i;
                if (this.Less(l, i))
                    min = l;

                int r = 2 * (i + 1);
                if (r < this.count && this.Less(r, min))
                    min = r;

                if (min == i)
                    return;
                Swap(i, min);
                i = min;
            }
        }

        private void Swim(int i)
        {
            while (i > 0)
            {
                int p = (i + 1) / 2 - 1;
                if (!this.Great(i, p))
                    return;
                Swap(i, p);
                i = p;
            }
        }

        private void Heapify()
        {
            for (int i = this.count / 2; i >= 0; --i)
            {
                Sink(i);
            }
        }

        public BinaryHeap(ICollection<T> source, IComparer<T> comparer = null)
        {
            this.comparer = comparer;
            if (this.comparer == null && !typeof(IComparable<T>).IsAssignableFrom(typeof(T)))
                throw new ArgumentException("The source is not comparable and there is no comparer");

            if (source == null)
            {
                this.data = new ResizableArray<T>();
                return;
            }

            this.count = source.Count;
            this.data = new ResizableArray<T>(source.Count);
            int i = 0;
            foreach (var t in source)
                this.data[i++] = t;
            this.Heapify();
        }
        public BinaryHeap(int capacity, IComparer<T> comparer = null)
        {
            this.comparer = comparer;
            if (this.comparer == null && !typeof(IComparable<T>).IsAssignableFrom(typeof(T)))
                throw new ArgumentException("The source is not comparable and there is no comparer");

            this.count = 0;
            data = new ResizableArray<T>(capacity);
        }

        public BinaryHeap(IComparer<T> comparer = null)
        {
            this.comparer = comparer;
            if (this.comparer == null && !typeof(IComparable<T>).IsAssignableFrom(typeof(T)))
                throw new ArgumentException("The source is not comparable and there is no comparer");

            this.count = 0;
            data = new ResizableArray<T>(ResizableArray<T>.DefaultCapacity);
        }
        public BinaryHeap() : this(16) { }
        public IHeap<T> Insert(T node)
        {
            ++this.count;
            if (this.count > this.data.Length)
                this.data.Expand();
            this.data[this.count - 1] = node;
            Swim(this.count - 1);

            return this;
        }

        public T Min()
        {
            if (this.count == 0)
                throw new InvalidOperationException("Empty Queue");
            return this.data[0];
        }

        public T ExtractMin()
        {
            if (this.count == 0)
                throw new InvalidOperationException("Empty Queue");

            Swap(0, --this.count);
            Sink(0);
            return this.data[count];
        }

        public int Count()
        {
            return this.count;
        }

        public IEnumerator<T> GetEnumerator()
        {
            return this.data.GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return this.data.GetEnumerator();
        }
    }
}


text:
using MapReduceDojo.Movies;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace MapReduceDojo.Test.movie
{
    [TestClass]
    public class MovieRatingByYearTest
    {
        [TestMethod]
        public void ShouldFindHighestRatedMovieFor1994()
        {
            MovieDataSource dataSource = new MovieDataSource("movies.txt");
            MapReduceJob<Movie> job = new MapReduceJob<Movie>(new MovieRatingByYear());
            job.Run(dataSource);

            Assert.AreEqual(job.GetFinalResults("1994").Name, "The Shawshank Redemption");
        }

    }
}


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

import java.sql.Array;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Types;

import org.jdbi.v3.core.argument.Argument;
import org.jdbi.v3.core.argument.Arguments;
import org.jdbi.v3.core.rule.H2DatabaseRule;
import org.jdbi.v3.core.statement.StatementContext;
import org.jdbi.v3.core.statement.StatementContextAccess;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;

import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;

public class ByteArrayTest {
    @Rule
    public H2DatabaseRule db = new H2DatabaseRule();
    @Rule
    public MockitoRule mockito = MockitoJUnit.rule();
    @Mock
    private PreparedStatement stmt;

    StatementContext ctx = StatementContextAccess.createContext();

    @Test
    public void byteArrayIsTypedAsVarbinary() throws SQLException {
        Argument nullByteArrayArg = db.getJdbi().withHandle(h -> h.getConfig(Arguments.class).findFor(byte[].class, new byte[] {1})).get();

        nullByteArrayArg.apply(0, stmt, ctx);

        verify(stmt, never()).setArray(anyInt(), any(Array.class));
        verify(stmt).setBytes(anyInt(), any(byte[].class));
    }

    @Test
    public void nullByteArrayIsTypedAsVarbinary() throws SQLException {
        Argument nullByteArrayArg = db.getJdbi().withHandle(h -> h.getConfig(Arguments.class).findFor(byte[].class, null)).get();

        nullByteArrayArg.apply(0, stmt, ctx);

        verify(stmt, never()).setNull(anyInt(), eq(Types.ARRAY));
        verify(stmt).setNull(anyInt(), eq(Types.VARBINARY));
    }
}


text:
"""Implements report, log, output XML, and xUnit file generation.

The public API of this package is the :class:`~.ResultWriter` class. It
can write result files based on XML output files on the file system,
as well as based on the result objects returned by
the :func:`~robot.result.resultbuilder.ExecutionResult` factory method or
an executed :class:`~robot.running.model.TestSuite`.

It is highly recommended to use the public API via the :mod:`robot.api` package.

This package is considered stable.
"""

from .resultwriter import ResultWriter


text:
<?php

/*
 * This file is part of the Symfony framework.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace App\AdminBundle\Command;

use Assetic\Asset\AssetCollectionInterface;
use Assetic\Asset\AssetInterface;
use Assetic\Util\VarUtils;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

/**
 * Dumps assets to the filesystem.
 *
 * @author Kris Wallsmith <kris@symfony.com>
 */
class WorkflowCommand extends ContainerAwareCommand
{
    /**
     * @var \App\AdminBundle\Compiler\Loader\AdminLoader
     */
    private $loader ;

    /**
     * @var \App\AdminBundle\Compiler\Cache\AdminCache
     */
    private $admin ;

    private $convert = array() ;

    private $force ;
    private $dev ;

    protected function configure()
    {
        $this
            ->setName('app:workflow:status')
            ->setDescription('Dumps all assets to the filesystem')
            ->addOption('admin', null, InputOption::VALUE_OPTIONAL, 'for admin')
            ->addOption('convert', null, InputOption::VALUE_OPTIONAL, 'for admin status change')
            ->addOption('force', null, InputOption::VALUE_NONE, 'run the sql')
            ->addOption('dev', null, InputOption::VALUE_NONE, 'debug')
        ;
    }

    protected function initialize(InputInterface $input, OutputInterface $output)
    {
        $this->loader   = $this->getContainer()->get('app.admin.loader') ;
        $this->force    = $input->getOption('force') ;
        $this->dev    = $input->getOption('dev') ;
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {

        $admin      = $input->getOption('admin') ;
        $convert  = $input->getOption('convert') ;
        if( $admin ) {
            if( !$this->loader->hasAdminName( $admin) ) {
                throw new \InvalidArgumentException(sprintf("`%s` is not valid admin ", $admin));
            }
            $this->admin = $this->loader->getAdminByName($admin) ;
            if( ! $this->admin->workflow ) {
                throw new \InvalidArgumentException(sprintf("admin `%s` has no workflow ", $admin));
            }
            if( $convert ) {
                $this->parse($convert, $this->admin, $input, $output) ;
            }
            $this->check( $this->admin, $input, $output);
            return ;
        }

        if( $convert ) {
            $this->parse_all($convert, $input, $output) ;
        }
        $tree   = $this->loader->getAdminTree() ;
        $this->tree($tree, $input, $output) ;
    }

    private function getWorkflowSteps(\App\AdminBundle\Compiler\Cache\AdminCache $admin){
        $steps  = array() ;
        foreach( $admin->workflow['status'] as $step_name => $step ) {
            if( $step['internal'] ) continue ;
            $steps[ $step_name ] = $step['value'] ;
        }
        return $steps ;
    }

    private function parse($convert, \App\AdminBundle\Compiler\Cache\AdminCache $admin, InputInterface $input, OutputInterface $output) {

        $steps  = $this->getWorkflowSteps($admin) ;
        $step_help  = json_encode( $steps) ;

        if( !preg_match('/^(\d+)\:(\d+)$/', $convert, $ms) ) {
            throw new \InvalidArgumentException(sprintf("admin `%s` convert `%s` invalid, steps:%s ",  $admin->getName(), $convert, $step_help ));
        }
        $from   = $ms[1] ;
        $to = $ms[2] ;
        if( $from === $to ) {
            throw new \InvalidArgumentException(sprintf("admin `%s` convert `%s` same status, steps:%s",  $admin->getName(), $convert, $step_help ));
        }
        if( isset($admin->workflow['value'][$from]) ) {
            throw new \InvalidArgumentException(sprintf("admin `%s` can not convert `%s` from exists status `%s`, steps:%s ",  $admin->getName(), $convert, $admin->workflow['value'][$from], $step_help ));
        }

        if( !isset($admin->workflow['value'][$to]) ) {
            throw new \InvalidArgumentException(sprintf("admin `%s` can not convert `%s` to unknow status `%s`, steps:%s",  $admin->getName(), $convert, $to, $step_help ));
        }
        $_to  = $admin->workflow['value'][$to] ;
        if(  $admin->workflow['status'][$_to]['internal'] ) {
            throw new \InvalidArgumentException(sprintf("admin `%s` can not convert `%s` to internal status `%s`, steps:%s",  $admin->getName(), $convert, $_to, $step_help ));
        }

        $this->convert[ $admin->getName() ][ $from ] = $to ;
    }

    private function parse_all($convert, InputInterface $input, OutputInterface $output) {
        $list   = preg_split('/\s*\,\s*/', trim($convert) ) ;

        foreach($list as $_convert){
            if( !preg_match('/^(\w+)\:(.+)$/', $_convert, $ms) ) {
                throw new \InvalidArgumentException(sprintf("invalid convert `%s` ", $_convert));
            }
            $admin_name = $ms[1] ;
            if( !$this->loader->hasAdminName($admin_name) ) {
                throw new \InvalidArgumentException(sprintf("admin `%s` is exists for convert `%s` ", $admin_name, $_convert ));
            }
            $admin  = $this->loader->getAdminByName($admin_name) ;
            if( ! $admin->workflow ) {
                throw new \InvalidArgumentException(sprintf("admin `%s` no workflow for convert `%s` ", $admin_name, $_convert ));
            }
            $config = $ms[2] ;
            $this->parse( $config, $admin, $input, $output) ;
        }
    }

    private function tree(array & $tree, InputInterface $input, OutputInterface $output){
        foreach($tree as $admin_name => $children ) {
            $admin  = $this->loader->getAdminByName($admin_name) ;
            if( $admin->workflow ) {
                $this->check($admin, $input, $output);
            }
            if( $children ) {
                $this->tree($children, $input, $output) ;
            }
        }
    }

    private function check(\App\AdminBundle\Compiler\Cache\AdminCache $admin, InputInterface $input, OutputInterface $output){

        $steps  = $this->getWorkflowSteps($admin) ;

        $dql   = sprintf("SELECT a FROM %s a WHERE a.%s NOT IN (%s)", $admin->getClassName(), $admin->workflow['property'], join(',', $steps));
        $em = $admin->getManager();
        $query = $em->createQuery($dql);
        $list = $query->getResult();
        if( empty($list) ) {
            return ;
        }
        $admin_name = $admin->getName() ;

        $output->writeln(sprintf("%s , %s count(%d) \n \t steps:%s", $admin_name , $admin->getClassName(), count($list) , json_encode($steps) ));

        if( $this->force ) {
            $em     = $admin->getManager() ;
        }

        $changed    = false ;

        foreach($list as $object) {
            $id     = $admin->getId($object) ;
            $prod = $admin->getReflectionProperty( $admin->workflow['property'] );
            $value = $prod->getValue($object) ;

            $_to    = null ;
            if( isset($this->convert[$admin_name][$value]) ) {

                $to     = $this->convert[$admin_name][$value] ;
                $_to    = $admin->workflow['value'][ $to ] ;
                $prod->setValue($object, $to ) ;
            }

            if( $_to ) {
                $output->writeln(sprintf("  id(%d) => %d  ===> %s(%d) ", $id, $value, $_to, $to ));
                if( $this->force ) {
                    $em->persist( $object ) ;
                    $changed    = true ;
                }
            } else {
                $output->writeln(sprintf("  id(%d) => %d ", $id, $value ));
            }
        }

        if( $changed ) {
            $em->flush();
        }

    }
}


text:
'use strict';

var http = require('http');

module.exports.server = http.createServer((req, res) => {
  // Send "Hello World" to every request
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end('Hello World');
});

this.server.listen(0);


text:
package org.bachelor.auth.service.impl;

import java.util.List;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import org.bachelor.auth.dao.IAuthFunctionDao;
import org.bachelor.auth.domain.AuthFunction;
import org.bachelor.auth.domain.Role;
import org.bachelor.auth.service.IAuthFunctionService;
import org.bachelor.gv.vo.GlobalEnumTvVo;
import org.bachelor.ps.domain.Function;

@Service
public class AuthFunctionServiceImpl   implements IAuthFunctionService {

	private Log log = LogFactory.getLog(this.getClass());

	@Autowired
	private IAuthFunctionDao authFunctionDao = null;

	public void saveOrUpdate(String authFuncs){
		/** 保存数据**/
		if(!StringUtils.isEmpty(authFuncs)){
				StringBuilder dSQL = new StringBuilder();
				StringBuilder aSQL = new StringBuilder();
				if(authFuncs!=null && !authFuncs.equals("")){
					String authArray[] = authFuncs.split(";");
					for(String authFunc : authArray){
						if(!StringUtils.isEmpty(authFunc)){
							String tempAuth[] = authFunc.split(",");

							if("del".equals(tempAuth[4])){
								dSQL.append(authFunc).append(";");
							} else if("add".equals(tempAuth[4])){
								aSQL.append(authFunc).append(";");
							}
						}
					}
				}
				log.info("---------------角色功能删除:要角色功能的功能ID是"+(dSQL.toString())+"---------------");
				/** 先删除所有功能权限信息 **/
				batchDelAuthFunctions(dSQL.toString());
				if(!StringUtils.isEmpty(aSQL.toString())){
					log.info("---------------角色功能新增:要新增的角色功能是"+( aSQL.toString().split(";").length)+"条---------------");
					log.info("---------------角色功能新增:要新增的角色功能的SQL:"+(aSQL.toString())+"条---------------");
					String addInfos[] = aSQL.toString().split(";");
					String addSQL[] = new String[addInfos.length];
					int index = 0;
					for(String info : addInfos){
						String infos[] = info.split(",");
						addSQL[index] = " insert into t_bchlr_auth_function(ID,ROLE_ID,FUNCTION_ID,VISIBLE,USAGE) values('"+UUID.randomUUID().toString().replace("-", "").replace("-", "")+
								"','"+infos[1]+"','"+infos[0]+"','"+infos[2]+"','"+infos[3]+"')";
						index++;
					}
					authFunctionDao.batchSaveAuthFunction(addSQL);
				}
		}
	}

	@Override
	public List<AuthFunction> findAll() {

		return authFunctionDao.findAll();
	}

	@Override
	public AuthFunction findAuthFunctionById(String id) {

		return authFunctionDao.findById(id);
	}

	@Override
	public void deleteAuthFunctionInfo(AuthFunction auth) {

		authFunctionDao.delete(auth);
	}

	@Override
	public List<AuthFunction> findAuthFunctionByFuncId(AuthFunction af) {

		return authFunctionDao.findAllAuthFuncByFuncId(af);
	}

	@Override
	public List<GlobalEnumTvVo> findTvInfo(String funcId) {

		return authFunctionDao.findTvInfo(funcId);
	}

	/**
	 * 该方法已经弃用
	 */
	@Override
	public void batchSaveAuthFunction(List<AuthFunction> afs) {
		if(afs!=null && afs.size()>0){
			String iSQL[] = new String[afs.size()];
			StringBuilder sql ;
			int index = 0;
			for(AuthFunction af : afs){
				sql = new StringBuilder();
				sql.append("insert into t_bchlr_auth_function(ID,ROLE_ID,FUNCTION_ID,VISIBLE,USAGE)");
				sql.append(" values(sys_guid(),'").append(af.getRole().getId());
				sql.append("','").append(af.getFunc().getId()).append("',");
				sql.append("'1',").append("'1')");
				iSQL[index] = sql.toString();
				index++;
			}
			authFunctionDao.batchSaveAuthFunction(iSQL);
		}
	}

	public void batchDelAuthFunctions(String batchInfo) {
		if(!StringUtils.isEmpty(batchInfo)){
			String batchInfos[] = batchInfo.split(";");
			String dSQL[] = new String[batchInfos.length];
			log.info("---------------角色功能删除:要删除的角色功能是"+(batchInfos.length)+"条---------------");
			log.info("---------------角色功能删除:要删除的角色功能的SQL:"+(batchInfo)+"条---------------");
			int index = 0;
			for(String delInfo : batchInfos){
				String delInfos[] = delInfo.split(",");
				dSQL[index] = " delete from t_bchlr_auth_function where ROLE_ID='"+delInfos[1]+"' and FUNCTION_ID='"+delInfos[0]+"'";
				index++;
			}
			authFunctionDao.batchSaveAuthFunction(dSQL);
		}

	}

	@Override
	public List<AuthFunction> findByFuncIds(String ids) {

		return authFunctionDao.findByFuncIds(ids);
	}
}


text:
/* eslint-disable comma-dangle, object-shorthand, func-names, no-param-reassign */
/* global DiscussionMixins */
/* global CommentsStore */
const Vue = require('vue');

((w) => {
  w.ResolveCount = Vue.extend({
    mixins: [DiscussionMixins],
    props: {
      loggedOut: Boolean
    },
    data: function () {
      return {
        discussions: CommentsStore.state
      };
    },
    computed: {
      allResolved: function () {
        return this.resolvedDiscussionCount === this.discussionCount;
      },
      resolvedCountText() {
        return this.discussionCount === 1 ? 'discussion' : 'discussions';
      }
    }
  });
})(window);


text:
package com.ctrip.xpipe.redis.console.healthcheck.nonredis.dbvariables.checker;

import com.ctrip.xpipe.redis.checker.alert.AlertManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class ExitActionChecker extends AbstractVariableChecker {

    @Autowired
    public ExitActionChecker(AlertManager alertManager) {
        super(alertManager);
    }

    boolean checkValue(Object value) {
        return String.valueOf(value).equalsIgnoreCase("ABORT_SERVER");
    }

    String getName() {
        return "group_replication_exit_state_action";
    }

}


text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: google/cloud/retail/v2alpha/serving_config_service.proto

package com.google.cloud.retail.v2alpha;

public interface ListServingConfigsRequestOrBuilder
    extends
    // @@protoc_insertion_point(interface_extends:google.cloud.retail.v2alpha.ListServingConfigsRequest)
    com.google.protobuf.MessageOrBuilder {

  /**
   *
   *
   *

   * Required. The catalog resource name. Format:
   * projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}
   *

   *
   *
   * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
   *
   *
   * @return The parent.
   */
  java.lang.String getParent();
  /**
   *
   *
   *

   * Required. The catalog resource name. Format:
   * projects/{project_number}/locations/{location_id}/catalogs/{catalog_id}
   *

   *
   *
   * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
   *
   *
   * @return The bytes for parent.
   */
  com.google.protobuf.ByteString getParentBytes();

  /**
   *
   *
   *

   * Optional. Maximum number of results to return. If unspecified, defaults
   * to 100. If a value greater than 100 is provided, at most 100 results are
   * returned.
   *

   *
   * int32 page_size = 2 [(.google.api.field_behavior) = OPTIONAL];
   *
   * @return The pageSize.
   */
  int getPageSize();

  /**
   *
   *
   *

   * Optional. A page token, received from a previous `ListServingConfigs` call.
   * Provide this to retrieve the subsequent page.
   *

   *
   * string page_token = 3 [(.google.api.field_behavior) = OPTIONAL];
   *
   * @return The pageToken.
   */
  java.lang.String getPageToken();
  /**
   *
   *
   *

   * Optional. A page token, received from a previous `ListServingConfigs` call.
   * Provide this to retrieve the subsequent page.
   *

   *
   * string page_token = 3 [(.google.api.field_behavior) = OPTIONAL];
   *
   * @return The bytes for pageToken.
   */
  com.google.protobuf.ByteString getPageTokenBytes();
}


text:
package uk.me.arseni.search

import org.slf4j.Logger
import org.slf4j.LoggerFactory

import uk.me.arseni.filters.{StemmerFilter, StopWordsFilter}
import uk.me.arseni.search.queries.QueryParser
import uk.me.arseni.tokenizers.TokenizerWithFilters
import uk.me.arseni.tools.FileIO
import uk.me.arseni.vectorization.{DocumentVectorizer, IdfMatrix}

import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer

/**
  * @author Arseni Anisimovich
  * @since 24/03/16
  */

class SearchIndex(directory: String, encoding: String = "CP1251") {
  var invertedTermIndex = mutable.HashMap[Int, ArrayBuffer[(Int, Double)]]()
  var documentIndex     = mutable.HashMap[Int, Vector[Int]]()
  var idToName          = mutable.HashMap[Int, String]()
  var documentCount     = 0
  val vectorizer        = indexDocuments(directory)
  val queryParser       = new QueryParser(vectorizer)

  def indexDocuments(directory: String) : DocumentVectorizer = {
    val logger    = LoggerFactory.getLogger(this.getClass.getName)
    val idfMatrix = new IdfMatrix(new TokenizerWithFilters(filters = Array(new StopWordsFilter, new StemmerFilter)), encoding)
    logger.info("Started IDF matrix calculation from " + directory)
    idfMatrix.calculateMatrixFromDirectory(directory)
    logger.info("Finished IDF matrix calculation. " + idfMatrix.matrix.size + " terms loaded.")

    val vectorizer = new DocumentVectorizer(idfMatrix)

    logger.info("Started documents indexing.")
    val filesToIndex = FileIO.listFilesFromString(directory, recursive = true)
    for (file <- filesToIndex) {
      documentCount += 1
      idToName.put(documentCount, file.toString)

      val document = io.Source.fromFile(file, encoding).mkString
      val wordVector = vectorizer.tokenizeDocument(document)
      documentIndex.put(documentCount, wordVector )
      for ((term, count) <- wordVector .toArray.groupBy(x => x).map(x => (x._1, x._2.length))) {
        val tfIdf = idfMatrix.getTermIdf(term) * count
        val array = invertedTermIndex.getOrElseUpdate(term, ArrayBuffer())
        array.append((documentCount, tfIdf))
      }
    }
    invertedTermIndex.mapValues(_.toArray)
    logger.info("Finished documents indexing: " + documentCount + " documents indexed.")
    vectorizer
  }

  def processQuery(query: String): Array[(String, Double)] = {
    val q = queryParser.getQuery(query)
    val res = q.execute(invertedTermIndex.toMap, documentIndex.toMap)
    res.map(tuple => (idToName(tuple._1), tuple._2))
  }
}


text:
package org.aludratest.service.gui.integrationtest;

import static org.junit.Assert.assertEquals;

import org.aludratest.AludraTest;
import org.aludratest.service.ComponentId;
import org.aludratest.service.gui.web.AludraWebGUI;
import org.aludratest.service.gui.web.selenium.selenium2.AludraSelenium2;
import org.aludratest.testcase.TestStatus;
import org.aludratest.testcase.event.TestStepInfo;
import org.aludratest.testcase.impl.AludraTestContextImpl;
import org.aludratest.testing.LocalTestCase;
import org.aludratest.testing.util.DirectLogTestListener;
import org.databene.commons.StringUtil;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;

/** Parent class for Selenium web GUI tests.

 * To execute a web based GUI test from within eclipse, you must serve the required resources with a Jetty server. Start the Jetty
 * server by calling mvn jetty:run from the command line, then execute the JUnit tests as usual from eclipse.
 *
 * @author YWANG
 * @author Volker Bergmann */
@SuppressWarnings("javadoc")
public abstract class GUITest extends LocalTestCase {

    private AludraTest aludraTest;

    protected AludraWebGUI aludraWebGUI;
    protected GUITestUIMap guiTestUIMap;
    protected ComponentId<AludraWebGUI> serviceId;
    protected DirectLogTestListener logListener;
    static int testMethodID = 0;

    protected static final int DEFAULT_TIMEOUT = 1000;

    @Before
    public void setUp() throws Exception {
        if (shallPerformLocalTests()) {
            initializeAludra();
        }
    }

    @After
    public void tearDown() throws Exception {
        tearDownAludra();
    }

    protected void initializeAludra() {
        logger.debug("Initializing AludraTest");
        // reset AludraTest instance, if there is already one created
        aludraTest = AludraTest.startFramework();

        // set test case instance, gives every test method a new ID
        setContext(new AludraTestContextImpl(logListener = new DirectLogTestListener(), aludraTest.getServiceManager()));

        // configure aludra service with url.of.aut
        System.setProperty("ALUDRATEST_CONFIG/webgui/_testui/url.of.aut", getTestPageUrl());

        // get aludra service
        serviceId = ComponentId.create(AludraWebGUI.class, "testui");
        aludraWebGUI = getService(serviceId);
        // open test page
        openTestPage();
        // get uimap
        guiTestUIMap = new GUITestUIMap(aludraWebGUI);
        logger.debug("AludraTest initialization finished");
    }

    private void tearDownAludra() {
        logger.debug("Closing AludraTest");
        if (aludraWebGUI != null) { // if precondition is violated, the service has not been initialized
            closeService(serviceId);
        }
        if (aludraTest != null) {
            aludraTest.stopFramework();
        }
    }

    protected static void activateSelenium2() {
        overrideImplementor(AludraWebGUI.class, AludraSelenium2.class);
    }

    /**
     * check if expected status equals to the last step status
     * @param expectedStatus expected status
     */
    protected void checkLastStepStatus(TestStatus expectedStatus) {
        // get the last test step
        TestStepInfo lastStep = logListener.getLastTestStep();
        // format the failure message
        String message = lastStep.getErrorMessage();
        if (StringUtil.isEmpty(message)) {
            message = lastStep.getErrorMessage();
        }
        message = "Last test step message: '" + StringUtil.nullToEmpty(message) + "'.";
        // assert
        assertEquals(message, expectedStatus, lastStep.getTestStatus());
    }

    /**
     * check if expected error message equals to the error message in the last test step
     * @param expectedErrorMessage expected error message
     */
    protected void checkLastStepErrorMessage(String expectedErrorMessage) {
        assertEquals(expectedErrorMessage, getLastStepErrorMessage());
    }

    /**
     * check if error message in the last test step matches the expected error message pattern
     *
     * @param expectedErrorMessagePattern
     *            expected error message pattern (regular expression)
     */
    protected void checkLastStepErrorMessageMatches(String expectedErrorMessagePattern) {
        Assert.assertTrue(getLastStepErrorMessage().matches(expectedErrorMessagePattern));
    }

    // Open test page
    private void openTestPage() {
        aludraWebGUI.perform().open();
        aludraWebGUI.perform().windowMaximize();
        //		aludraWebGUI.perform().windowFocus();
        aludraWebGUI.perform().refresh();
    }

    // Get error message of the last test step
    private String getLastStepErrorMessage() {
        return logListener.getLastTestStep().getErrorMessage();
    }

    protected String getTestPageUrl() {
        return "http://localhost:8080/index.html";
    }

    protected static void overrideImplementor(Class<?> ifaceClass, Class<?> implClass) {
        System.setProperty("ALUDRATEST_CONFIG/aludraservice/" + ifaceClass.getName(), implClass.getName());
    }

}


text:
class BuildpacksCIConfiguration
  def concourse_private_filename
    ENV.fetch('LPASS_CONCOURSE_PRIVATE_FILE', 'Shared-CF\ Buildpacks/concourse-private.yml')
  end

  def deployments_buildpacks_filename
    ENV.fetch('LPASS_DEPLOYMENTS_BUILDPACKS_FILE',  'Shared-CF\ Buildpacks/deployments-buildpacks.yml')
  end

  def repos_private_keys_filename
    ENV.fetch('LPASS_REPOS_PRIVATE_KEYS_FILE', 'Shared-CF\ Buildpacks/buildpack-repos-private-keys.yml')
  end

  def cnb_repos_private_keys_filename
    ENV.fetch('LPASS_CNB_REPOS_PRIVATE_KEYS_FILE', 'Shared-CF\ Buildpacks/buildpack-cnb-repos-private-keys.yml')
  end

  def bosh_release_private_keys_filename
    ENV.fetch('LPASS_BOSH_RELEASE_PRIVATE_KEYS_FILE', 'Shared-CF\ Buildpacks/buildpack-bosh-release-repos-private-keys.yml')
  end

  def bosh_release_private_keys_filename_2
    ENV.fetch('LPASS_BOSH_RELEASE_PRIVATE_KEYS_FILE_2', 'Shared-CF\ Buildpacks/buildpack-bosh-release-repos-private-keys-2.yml')
  end

  def bosh_release_private_keys_filename_lts
    ENV.fetch('LPASS_BOSH_RELEASE_PRIVATE_KEYS_FILE_LTS', 'Shared-CF\ Buildpacks/buildpack-bosh-release-repos-private-keys-lts.yml')
  end

  def git_repos_private_keys_filename
    ENV.fetch('LPASS_GIT_REPOS_PRIVATE_KEYS_FILE', 'Shared-CF\ Buildpacks/git-repos-private-keys.yml')
  end

  def git_repos_private_keys_two_filename
    ENV.fetch('LPASS_GIT_REPOS_PRIVATE_KEYS_TWO_FILE', 'Shared-CF\ Buildpacks/git-repos-private-keys-two.yml')
  end

  def git_repos_private_keys_three_filename
    ENV.fetch('LPASS_GIT_REPOS_PRIVATE_KEYS_THREE_FILE', 'Shared-CF\ Buildpacks/git-repos-private-keys-three.yml')
  end

  def dockerhub_cflinuxfs_credentials_filename
    ENV.fetch('LPASS_DOCKERHUB_CFLINUXFS_CREDENTIALS_FILE', 'Shared-CF\ Buildpacks/dockerhub-cflinuxfs.yml')
  end

  def organization
    YAML.load_file('public-config.yml')['buildpacks-github-org']
  end

  def run_oracle_php_tests?
    YAML.load_file('public-config.yml')['run-oracle-php-tests']
  end

  def concourse_target_name
    ENV.fetch('CONCOURSE_TARGET_NAME', 'buildpacks')
  end
end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Orleans.GrainDirectory;
using Orleans.Runtime;
using Orleans.Runtime.GrainDirectory;
using Orleans.Runtime.Scheduler;
using TestExtensions;
using UnitTests.SchedulerTests;
using UnitTests.TesterInternal;
using Xunit;
using Xunit.Abstractions;

namespace UnitTests.Directory
{
    [TestCategory("BVT"), TestCategory("Directory")]
    public class DhtGrainLocatorTests : IDisposable
    {
        private readonly DhtGrainLocator target;
        private readonly MockLocalGrainDirectory localGrainDirectory;
        private readonly ITestOutputHelper output;
        private readonly LoggerFactory loggerFactory;
        private readonly UnitTestSchedulingContext rootContext;
        private readonly OrleansTaskScheduler taskScheduler;

        public DhtGrainLocatorTests(ITestOutputHelper output)
        {
            this.output = output;
            this.loggerFactory = new LoggerFactory(new[] { new XunitLoggerProvider(output) });
            this.rootContext = new UnitTestSchedulingContext();
            this.taskScheduler = TestInternalHelper.InitializeSchedulerForTesting(this.rootContext, this.loggerFactory);
            this.localGrainDirectory = new MockLocalGrainDirectory(
                TimeSpan.FromMilliseconds(100),
                TimeSpan.FromMilliseconds(200));
            this.target = new DhtGrainLocator(this.localGrainDirectory, this.taskScheduler, this.rootContext);
        }

        [Fact]
        public async Task SingleDeactivation()
        {
            foreach (var cause in (UnregistrationCause[]) Enum.GetValues(typeof(UnregistrationCause)))
             {
                var activationAddress = GenerateActivationAddress();

                await this.target.Unregister(activationAddress, cause);

                Assert.Single(this.localGrainDirectory.UnregistrationReceived);
                Assert.Equal(cause, this.localGrainDirectory.UnregistrationReceived[0].cause);
                Assert.Equal(activationAddress, this.localGrainDirectory.UnregistrationReceived[0].activationAddress);

                this.localGrainDirectory.Reset();
            }
        }

        [Fact]
        public async Task MultipleDeactivations()
        {
            foreach (var cause in (UnregistrationCause[])Enum.GetValues(typeof(UnregistrationCause)))
            {
                var batchn = 100;
                var addresses = new List<ActivationAddress>();
                var tasks = new List<Task>();

                for (var i = 0; i < batchn; i++)
                {
                    addresses.Add(GenerateActivationAddress());
                }

                foreach (var addr in addresses)
                {
                    tasks.Add(this.target.Unregister(addr, cause));
                }

                await Task.WhenAll(tasks);

                Assert.True(batchn > this.localGrainDirectory.UnregistrationCounter);

                Assert.All(this.localGrainDirectory.UnregistrationReceived, item => Assert.Equal(cause, item.cause));
                Assert.Equal(addresses, this.localGrainDirectory.UnregistrationReceived.Select(item => item.activationAddress));

                this.localGrainDirectory.Reset();
            }
        }

        [Fact]
        public async Task MultipleMixedDeactivations()
        {
            var batchn = 12;
            var addresses = new List<ActivationAddress>();
            var tasks = new List<Task>();

            var map = new Dictionary<ActivationAddress, UnregistrationCause>();

            foreach (var cause in (UnregistrationCause[])Enum.GetValues(typeof(UnregistrationCause)))
            {
                for (var i = 0; i < batchn; i++)
                {
                    var addr = GenerateActivationAddress();
                    addresses.Add(addr);
                    map.Add(addr, cause);
                    tasks.Add(this.target.Unregister(addr, cause));
                }
            }

            await Task.WhenAll(tasks);

            Assert.All(this.localGrainDirectory.UnregistrationReceived, item => Assert.Equal(map[item.activationAddress], item.cause));
            Assert.Equal(addresses, this.localGrainDirectory.UnregistrationReceived.Select(item => item.activationAddress));

            this.localGrainDirectory.Reset();
        }

        private int generation = 0;
        private ActivationAddress GenerateActivationAddress()
        {
            var grainId = LegacyGrainId.GetGrainIdForTesting(Guid.NewGuid());
            var siloAddr = SiloAddress.New(new IPEndPoint(IPAddress.Loopback, 5000), ++generation);

            return ActivationAddress.NewActivationAddress(siloAddr, grainId);
        }

        public void Dispose()
        {
            if (this.taskScheduler != null)
            {
                this.taskScheduler.Stop();
            }
        }
    }
}


text:
These scripts are used to build RancherOS for Vagrant, Amazon and GCE.

#License
Copyright (c) 2014-2015 [Rancher Labs, Inc.](http://rancher.com)

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

[http://www.apache.org/licenses/LICENSE-2.0](http://www.apache.org/licenses/LICENSE-2.0)

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.


text:
 #pragma once

class Serialize__tagMacroAttribute : public Serialize_StructBase<_tagMacroAttribute,Serialize__tagMacroAttribute>
{
	public:
	typedef _tagMacroAttribute _MyObjectType;

	Serialize_BaseObject<BOOL> bRootMacro;
	Serialize__tagMacroAttribute(){};
	~Serialize__tagMacroAttribute(){};
	_Myt& operator=(_tagMacroAttribute & _X);
	void GetData();
	BOOL Construct(StorageObjectInterface * pOutObject);
	void SetData(_tagMacroAttribute & _X);
	BOOL LoadGetCurSerializeObject(FieldAddr & CurFieldAddr, SerializeLoadSaveInterface * * RetObj);
	BOOL Save(StorageObjectInterface * pStorageObject);
	BOOL GetObjectMap(IN OUT vector<SerializeObjectInterface *> & ObjectInterfaceMap);

};


text:
class EnableUuidOsspExtension < ActiveRecord::Migration<% if Rails::VERSION::MAJOR >= 5 %>[<%= Rails::VERSION::MAJOR %>.<%= Rails::VERSION::MINOR %>]<% end %>
  def change
    enable_extension 'uuid-ossp'
  end
end