text:
namespace syncable {
class DirectoryManager;
class ScopedDirLookup;
}
namespace browser_sync {
struct HttpResponse;
}

class MockConnectionManager : public browser_sync::ServerConnectionManager {
 public:
  class MidCommitObserver {
   public:
    virtual void Observe() = 0;

   protected:
    virtual ~MidCommitObserver() {}
  };

  MockConnectionManager(syncable::DirectoryManager* dirmgr,
                        const std::string& name);
  virtual ~MockConnectionManager();

  // Overridden ServerConnectionManager functions.
  virtual bool PostBufferToPath(
      const PostBufferParams*,
      const std::string& path,
      const std::string& auth_token,
      browser_sync::ScopedServerStatusWatcher* watcher);

  virtual bool IsServerReachable();
  virtual bool IsUserAuthenticated();

  // Control of commit response.
  void SetMidCommitCallback(Callback0::Type* callback);
  void SetMidCommitObserver(MidCommitObserver* observer);

  // Set this if you want commit to perform commit time rename. Will request
  // that the client renames all commited entries, prepending this string.
  void SetCommitTimeRename(std::string prepend);

  // Generic versions of AddUpdate functions. Tests using these function should
  // compile for both the int64 and string id based versions of the server.
  // The SyncEntity returned is only valid until the Sync is completed
  // (e.g. with SyncShare.) It allows to add further entity properties before
  // sync, using SetLastXXX() methods and/or GetMutableLastUpdate().
  sync_pb::SyncEntity* AddUpdateDirectory(syncable::Id id,
                                          syncable::Id parent_id,
                                          std::string name,
                                          int64 version,
                                          int64 sync_ts);
  sync_pb::SyncEntity* AddUpdateBookmark(syncable::Id id,
                                         syncable::Id parent_id,
                                         std::string name,
                                         int64 version,
                                         int64 sync_ts);
  // Versions of the AddUpdate functions that accept integer IDs.
  sync_pb::SyncEntity* AddUpdateDirectory(int id,
                                          int parent_id,
                                          std::string name,
                                          int64 version,
                                          int64 sync_ts);
  sync_pb::SyncEntity* AddUpdateBookmark(int id,
                                         int parent_id,
                                         std::string name,
                                         int64 version,
                                         int64 sync_ts);
  // New protocol versions of the AddUpdate functions.
  sync_pb::SyncEntity* AddUpdateDirectory(std::string id,
                                          std::string parent_id,
                                          std::string name,
                                          int64 version,
                                          int64 sync_ts);
  sync_pb::SyncEntity* AddUpdateBookmark(std::string id,
                                         std::string parent_id,
                                         std::string name,
                                         int64 version,
                                         int64 sync_ts);

  // Find the last commit sent by the client, and replay it for the next get
  // updates command.  This can be used to simulate the GetUpdates that happens
  // immediately after a successful commit.
  sync_pb::SyncEntity* AddUpdateFromLastCommit();

  // Add a deleted item.  Deletion records typically contain no
  // additional information beyond the deletion, and no specifics.
  // The server may send the originator fields.
  void AddUpdateTombstone(const syncable::Id& id);

  void SetLastUpdateDeleted();
  void SetLastUpdateServerTag(const std::string& tag);
  void SetLastUpdateClientTag(const std::string& tag);
  void SetLastUpdateOriginatorFields(const std::string& client_id,
                                     const std::string& entry_id);
  void SetLastUpdatePosition(int64 position_in_parent);
  void SetNewTimestamp(int ts);
  void SetChangesRemaining(int64 count);

  // Add a new batch of updates after the current one.  Allows multiple
  // GetUpdates responses to be buffered up, since the syncer may
  // issue multiple requests during a sync cycle.
  void NextUpdateBatch();

  // For AUTHENTICATE responses.
  void SetAuthenticationResponseInfo(const std::string& valid_auth_token,
                                     const std::string& user_display_name,
                                     const std::string& user_display_email,
                                     const std::string& user_obfuscated_id);

  void FailNextPostBufferToPathCall() { fail_next_postbuffer_ = true; }

  void SetClearUserDataResponseStatus(
      sync_pb::ClientToServerResponse::ErrorType errortype);

  // A visitor class to allow a test to change some monitoring state atomically
  // with the action of overriding the response codes sent back to the Syncer
  // (for example, so you can say "ThrottleNextRequest, and assert no more
  // requests are made once throttling is in effect" in one step.
  class ResponseCodeOverrideRequestor {
   public:
    // Called with response_code_override_lock_ acquired.
    virtual void OnOverrideComplete() = 0;

   protected:
    virtual ~ResponseCodeOverrideRequestor() {}
  };
  void ThrottleNextRequest(ResponseCodeOverrideRequestor* visitor);
  void FailWithAuthInvalid(ResponseCodeOverrideRequestor* visitor);
  void StopFailingWithAuthInvalid(ResponseCodeOverrideRequestor* visitor);
  void FailNonPeriodicGetUpdates() { fail_non_periodic_get_updates_ = true; }

  // Simple inspectors.
  bool client_stuck() const { return client_stuck_; }

  sync_pb::ClientCommand* GetNextClientCommand();

  const std::vector<syncable::Id>& committed_ids() const {
    return committed_ids_;
  }
  const std::vector<sync_pb::CommitMessage*>& commit_messages() const {
    return commit_messages_.get();
  }
  const std::vector<sync_pb::CommitResponse*>& commit_responses() const {
    return commit_responses_.get();
  }
  // Retrieve the last sent commit message.
  const sync_pb::CommitMessage& last_sent_commit() const;

  // Retrieve the last returned commit response.
  const sync_pb::CommitResponse& last_commit_response() const;

  // Retrieve the last request submitted to the server (regardless of type).
  const sync_pb::ClientToServerMessage& last_request() const {
    return last_request_;
  }

  void set_conflict_all_commits(bool value) {
    conflict_all_commits_ = value;
  }
  void set_next_new_id(int value) {
    next_new_id_ = value;
  }
  void set_conflict_n_commits(int value) {
    conflict_n_commits_ = value;
  }

  void set_use_legacy_bookmarks_protocol(bool value) {
    use_legacy_bookmarks_protocol_ = value;
  }

  void set_store_birthday(std::string new_birthday) {
    // Multiple threads can set store_birthday_ in our tests, need to lock it to
    // ensure atomic read/writes and avoid race conditions.
    base::AutoLock lock(store_birthday_lock_);
    store_birthday_ = new_birthday;
  }

  // Retrieve the number of GetUpdates requests that the mock server has
  // seen since the last time this function was called.  Can be used to
  // verify that a GetUpdates actually did or did not happen after running
  // the syncer.
  int GetAndClearNumGetUpdatesRequests() {
    int result = num_get_updates_requests_;
    num_get_updates_requests_ = 0;
    return result;
  }

  // Expect that GetUpdates will request exactly the types indicated in
  // the bitset.
  void ExpectGetUpdatesRequestTypes(
      std::bitset<syncable::MODEL_TYPE_COUNT> expected_filter) {
    expected_filter_ = expected_filter;
  }

  void ExpectGetUpdatesRequestPayloads(
      const syncable::ModelTypePayloadMap& payloads) {
    expected_payloads_ = payloads;
  }

  void SetServerReachable();

  void SetServerNotReachable();

  // Return by copy to be thread-safe.
  const std::string store_birthday() {
    base::AutoLock lock(store_birthday_lock_);
    return store_birthday_;
  }

  // Locate the most recent update message for purpose of alteration.
  sync_pb::SyncEntity* GetMutableLastUpdate();

 private:
  sync_pb::SyncEntity* AddUpdateFull(syncable::Id id, syncable::Id parentid,
                                     std::string name, int64 version,
                                     int64 sync_ts,
                                     bool is_dir);
  sync_pb::SyncEntity* AddUpdateFull(std::string id,
                                     std::string parentid, std::string name,
                                     int64 version, int64 sync_ts,
                                     bool is_dir);
  // Functions to handle the various types of server request.
  void ProcessGetUpdates(sync_pb::ClientToServerMessage* csm,
                         sync_pb::ClientToServerResponse* response);
  void ProcessAuthenticate(sync_pb::ClientToServerMessage* csm,
                           sync_pb::ClientToServerResponse* response,
                           const std::string& auth_token);
  void ProcessCommit(sync_pb::ClientToServerMessage* csm,
                     sync_pb::ClientToServerResponse* response_buffer);
  void ProcessClearData(sync_pb::ClientToServerMessage* csm,
                        sync_pb::ClientToServerResponse* response);
  void AddDefaultBookmarkData(sync_pb::SyncEntity* entity, bool is_folder);

  // Determine if one entry in a commit should be rejected with a conflict.
  bool ShouldConflictThisCommit();

  // Generate a numeric position_in_parent value.  We use a global counter
  // that only decreases; this simulates new objects always being added to the
  // front of the ordering.
  int64 GeneratePositionInParent() {
    return next_position_in_parent_--;
  }

  // Get a mutable update response which will eventually be returned to the
  // client.
  sync_pb::GetUpdatesResponse* GetUpdateResponse();
  void ApplyToken();

  // Determine whether an progress marker array (like that sent in
  // GetUpdates.from_progress_marker) indicates that a particular ModelType
  // should be included.
  bool IsModelTypePresentInSpecifics(
      const google::protobuf::RepeatedPtrField<
          sync_pb::DataTypeProgressMarker>& filter,
      syncable::ModelType value);

  sync_pb::DataTypeProgressMarker const* GetProgressMarkerForType(
      const google::protobuf::RepeatedPtrField<
          sync_pb::DataTypeProgressMarker>& filter,
      syncable::ModelType value);

  // All IDs that have been committed.
  std::vector<syncable::Id> committed_ids_;

  // Control of when/if we return conflicts.
  bool conflict_all_commits_;
  int conflict_n_commits_;

  // Commit messages we've sent, and responses we've returned.
  ScopedVector<sync_pb::CommitMessage> commit_messages_;
  ScopedVector<sync_pb::CommitResponse> commit_responses_;

  // The next id the mock will return to a commit.
  int next_new_id_;

  // The store birthday we send to the client.
  std::string store_birthday_;
  base::Lock store_birthday_lock_;
  bool store_birthday_sent_;
  bool client_stuck_;
  std::string commit_time_rename_prepended_string_;

  // Fail on the next call to PostBufferToPath().
  bool fail_next_postbuffer_;

  // Our directory.
  syncable::DirectoryManager* directory_manager_;
  std::string directory_name_;

  // The updates we'll return to the next request.
  std::list<sync_pb::GetUpdatesResponse> update_queue_;
  scoped_ptr<Callback0::Type> mid_commit_callback_;
  MidCommitObserver* mid_commit_observer_;

  // The clear data response we'll return in the next response
  sync_pb::ClientToServerResponse::ErrorType
      clear_user_data_response_errortype_;

  // The AUTHENTICATE response we'll return for auth requests.
  sync_pb::AuthenticateResponse auth_response_;
  // What we use to determine if we should return SUCCESS or BAD_AUTH_TOKEN.
  std::string valid_auth_token_;

  // Whether we are faking a server mandating clients to throttle requests.
  // Protected by |response_code_override_lock_|.
  bool throttling_;

  // Whether we are failing all requests by returning
  // ClientToServerResponse::AUTH_INVALID.
  // Protected by |response_code_override_lock_|.
  bool fail_with_auth_invalid_;

  base::Lock response_code_override_lock_;

  // True if we are only accepting GetUpdatesCallerInfo::PERIODIC requests.
  bool fail_non_periodic_get_updates_;

  scoped_ptr<sync_pb::ClientCommand> client_command_;

  // The next value to use for the position_in_parent property.
  int64 next_position_in_parent_;

  // The default is to use the newer sync_pb::BookmarkSpecifics-style protocol.
  // If this option is set to true, then the MockConnectionManager will
  // use the older sync_pb::SyncEntity_BookmarkData-style protocol.
  bool use_legacy_bookmarks_protocol_;

  std::bitset<syncable::MODEL_TYPE_COUNT> expected_filter_;

  syncable::ModelTypePayloadMap expected_payloads_;

  int num_get_updates_requests_;

  std::string next_token_;

  sync_pb::ClientToServerMessage last_request_;

  DISALLOW_COPY_AND_ASSIGN(MockConnectionManager);
};

#endif  // CHROME_TEST_SYNC_ENGINE_MOCK_CONNECTION_MANAGER_H_


text:
package com.tinkerpop.gremlin.structure.io.kryo;

import org.junit.Test;

import static org.junit.Assert.assertNotSame;

/**
 * @author Stephen Mallette (http://stephen.genoprime.com)
 */
public class GremlinKryoTest {
    @Test
    public void shouldGetMostRecentVersion() {
        final GremlinKryo.Builder b = GremlinKryo.build();
        assertNotSame(b, GremlinKryo.build());
    }
}

redpajama_set_name: RedPajamaGithub


text:
require 'spec_helper'

describe "groups/new" do
  before(:each) do
    assign(:group, stub_model(Group,
      :name => "MyString",
      :sysgroup => false
    ).as_new_record)
  end

  it "renders new group form" do
    render

    # Run the generator again with the --webrat flag if you want to use webrat matchers
    assert_select "form[action=?][method=?]", groups_path, "post" do
      assert_select "input#group_name[name=?]", "group[name]"
      assert_select "input#group_sysgroup[name=?]", "group[sysgroup]"
    end
  end
end


text:
layout: event
categories:
  - events
links:
title: "Using Urban Forestry Data to Improve Health and Quality of Life in the Chicago Region"
description: "Results from an extensive tree census conducted in the seven-county Chicago metropolitan region found that urban forests are in a state of transition with the recent loss of 13 million trees to emerald ash borer. Further, 28% of the overall forest is comprised of an exotic invasive species. This transition has significant impacts on the 8.5 million people who rely on the benefits these trees provide (US 2010 Census). The Chicago Region Trees Initiative (CRTI), founded by The Morton Arboretum, was organized to reverse this outlook and leverage collaborative efforts for a holistic approach to improve the urban forest and quality of life for Chicago region residents."
speakers:
 - Lydia Scott, Director, Chicago Region Trees Initiative, The Morton Arboretum
image: /images/events/356-Lydia-Scott.jpg
image_credit:
date: 2019-07-09T18:00:00-05:00
event_id: 356
youtube_id: bKgvjuhMJFY
agenda: https://docs.google.com/document/d/1vntIl9WhzYXibOKTlEue-EpGllybVmXamjwaf3X4ZSY/edit?usp=sharing
sponsor: CityBase
asl_provided: true
tags:
 - environment
published: true

---

Results from an extensive tree census conducted in the seven-county Chicago metropolitan region found that urban forests are in a state of transition with the recent loss of 13 million trees to emerald ash borer. Further, 28% of the overall forest is comprised of an exotic invasive species. This transition has significant impacts on the 8.5 million people who rely on the benefits these trees provide (US 2010 Census). The [Chicago Region Trees Initiative (CRTI)](http://chicagorti.org/), founded by The Morton Arboretum, was organized to reverse this outlook and leverage collaborative efforts for a holistic approach to improve the urban forest and quality of life for Chicago region residents.

To understand the dynamic nature of the forest and develop a data driven strategy, the CRTI collected and combined extensive datasets. These datasets included LiDAR, aerial imagery, land cover, forest inventories (private and public), forest management capacity, socio-economic data, pre-settlement ecosystem mapping, human and tree health data, among others. The resulting analyses help identify a community's unique list of challenges (low canopy cover, high poverty, poor health, etc.) and opportunities (strong forestry program, remnant woodlands, community engagement, etc.). By recognizing challenges and opportunities at varying scales, strategies can be successfully tailored to improve the urban forest.

For outreach purposes, a scientific literature review was conducted on the benefits trees provide to people. The CRTI develops programs and outreach for people and organizations that make land use decisions and manage trees. By expanding knowledge and skills to improve the urban forest, the quality of life will be improved in this region. This integrated program based on urban forest research serves as a strong case study.

---

**RSVP required** Braintree now requires all attendees to [RSVP beforehand]({{site.rsvp_url}}) by 12:00 PM (noon). Walk-ins will not be allowed!

**ASL** This event will {% unless page.asl_provided %} not {% endunless %}have an American Sign Language interpreter.

**Food** Food and drinks will be provided. We encourage attendees to bring their own water bottles to reduce waste.


text:
import unittest
from .views import retrieve_list, delete_document, update_document
from pyramid.httpexceptions import HTTPBadRequest
import json
from couchdbkit import *
from pyramid import testing
from pprint import pformat
import iso8601

class ViewTests(unittest.TestCase):

    def add_couchdb(self, request):
        s = Server(uri="http://localhost:5984")
        db = s.get_or_create_db("resource_data")
        return db

    def setUp(self):
        config = testing.setUp()
        self.config = config
        self.config.add_route('userkey', '/user/:username/key')

    def tearDown(self):
        testing.tearDown()

    def _prepare_request(self, params):
        request = testing.DummyRequest()
        request.db = self.add_couchdb(request)
        s = Server(uri="http://admin:password@localhost:5984")
        request.users = s.get_db("_users")
        request.username = "wegrata3"
        request.node_id = "abc123"
        request.GET['include_docs'] = json.dumps(True)
        request.GET.update(params)
        return request

    def _list_test_generic(self, params, comparer):
        request = self._prepare_request(params)
        data = retrieve_list(request)
        for envelope in data.json.get('response', []):
            date = iso8601.parse_date(envelope.get("node_timestamp"))
            self.assertTrue(comparer(date))

    def test_get_list_from(self):
        params = {"from": "2012-10-26T15:14:02.972834Z"}
        from_date = iso8601.parse_date(params["from"])
        self._list_test_generic(params, lambda date: date >= from_date)

    def test_get_list_until(self):
        params = {"until": "2012-10-26T15:14:02.972834Z"}
        until_date = iso8601.parse_date(params["until"])
        self._list_test_generic(params, lambda date: date <= until_date)

    def test_get_list_from_until(self):
        params = {"until": "2012-11-26T15:14:02.972834Z",
                  "from": "2012-10-26T15:14:02.972834Z"}
        until_date = iso8601.parse_date(params["until"])
        from_date = iso8601.parse_date(params["from"])
        self._list_test_generic(
            params, lambda date: date <= until_date and date >= from_date)

    def test_get_list_until_from(self):
        params = {"from": "2012-11-26T15:14:02.972834Z",
                  "until": "2012-10-26T15:14:02.972834Z"}
        until_date = iso8601.parse_date(params["until"])
        from_date = iso8601.parse_date(params["from"])
        request = self._prepare_request(params)
        self.assertRaises(HTTPBadRequest, retrieve_list, request)

    def test_get_list_bad_from(self):
        params = {"from": "2012-11-"}
        request = self._prepare_request(params)
        self.assertRaises(HTTPBadRequest, retrieve_list, request)

    def test_get_list_bad_until(self):
        params = {"until": "2012-11-"}
        request = self._prepare_request(params)
        self.assertRaises(HTTPBadRequest, retrieve_list, request)

    def test_get_list_bad_include_docs(self):
        params = {"include_docs": "2012-11-"}
        request = self._prepare_request(params)
        self.assertRaises(HTTPBadRequest, retrieve_list, request)

    def test_add_envelope_lrmi(self):
        from .views import add_envelope
        from requests import post
        request = self._prepare_request({})
        resp = post("http://localhost:5984/_session", data={"name": 'user', "password": 'password'})
        request.auth_cookie = resp.headers['set-cookie']
        request.body = json.dumps({
            "doc_type": "resource_data",
            "resource_locator": "",
            "digital_signature":            {
                "key_location": ["http://lrnode.inbloom.org/pubkey"],
                "key_owner": "Learning Registry SLC Node <lrnode@inbloom.org>",
                "signing_method": "LR-PGP.1.0",
                "signature": "-----BEGIN PGP SIGNED MESSAGE-----\nHash: SHA1\n\nf01a16e10c15da435049150a1f8fe2b327b75055f0435412ad704f20c263336e\n-----BEGIN PGP SIGNATURE-----\nVersion: GnuPG v1.4.11 (GNU/Linux)\n\niQEcBAEBAgAGBQJTAxNjAAoJEGNQ+N81sWR7TckIAKlaqlv0JPQxUOUxG4Ra3pXz\nl5nTxCzNAczOo/M3oODWERNvZbVaEsm7DtGlb41yHG6lTNm0ue3MMC2C0cfLCMjy\nLtYbi81t9GZG8qFpDEGpNsf+EUG7a25K8OE8NNwis1S66BL4Gb8fgEhUEfmlHNK2\npgaYcVSg15Yg6wCRb6C/at6U6z0ab1pVQ6lltet50RPsftJ3WabDEoHCem5255jl\nn4yHY7jmEP3Vkx7EvuHwa1MuBzTtB8q/GLRqY2+KrwKdaS8t4Igj/xgwxfUxGrKm\nGKEZc8t4N6CJ3KHwUPgaeSnGcgxLOsdktEunnbtGvanBszYWlo36T1WyDaKGWsI=\n=/tzy\n-----END PGP SIGNATURE-----\n"
            },
            "resource_data": {
                "items": [
                    {
                        "type": ["http://schema.org/CreativeWork"],
                        "id": "a4e87e49-b549-4499-ada5-9ec700226c2d",
                        "properties": {
                            "timeRequired": ["P0Y0M0W0DT0H0M0S"],
                            "inLanguage": ["es-ES"],
                            "educationalAlignment": [],
                            "name": ["Recurso 2"]
                        }
                    }
                ]
            },
            "keys": [],
            "TOS": {
                "submission_TOS": "http://www.learningregistry.org/information-assurances/open-information-assurances-1-0"
            },
            "resource_data_type": "metadata",
            "payload_schema_locator": "http://www.w3.org/TR/2012/WD-microdata-20121025/#converting-html-to-other-formats",
            "payload_placement": "inline",
            "payload_schema": [
                "schema.org",
                "LRMI",
                "application/microdata+json"],
            "doc_version": "0.23.0",
            "active": True,
            "identity": {
                "submitter": "inBloom Tagger Application <tagger@inbloom.org>",
                "signer": "Learning Registry SLC Node <lrnode@inbloom.org>",
                "submitter_type": "user",
                "curator": "5a4bfe96-1724-4565-9db1-35b3796e3ce1:jordi.juarez@udl.cat@null"
            }
        })
        info = add_envelope(request)
        assert info['OK']

    def test_add_envelope_str(self):
        from .views import add_envelope
        from requests import post
        request = self._prepare_request({})
        resp = post("http://localhost:5984/_session", data={"name": 'user', "password": 'password'})
        request.auth_cookie = resp.headers['set-cookie']
        request.body = json.dumps({
            "doc_type": "resource_data",
            "resource_locator": "",
            "resource_data": "test",
            "keys": [],
            "TOS": {
                "submission_TOS": "http://www.learningregistry.org/information-assurances/open-information-assurances-1-0"
            },
            "resource_data_type": "metadata",
            "payload_schema_locator": "http://www.w3.org/TR/2012/WD-microdata-20121025/#converting-html-to-other-formats",
            "payload_placement": "inline",
            "payload_schema": ["plain text"],
            "doc_version": "0.23.0",
            "active": True,
            "identity": {
                "submitter": "inBloom Tagger Application <tagger@inbloom.org>",
                "signer": "Learning Registry SLC Node <lrnode@inbloom.org>",
                "submitter_type": "user",
                "curator": "5a4bfe96-1724-4565-9db1-35b3796e3ce1:jordi.juarez@udl.cat@null"
            }
        })
        info = add_envelope(request)
        assert info['OK'], pformat(info)

    def test_add_envelope_auto_sign(self):
        from .views import add_envelope
        from requests import post
        request = self._prepare_request({})
        resp = post("http://localhost:5984/_session", data={"name": 'user', "password": 'password'})
        request.auth_cookie = resp.headers['set-cookie']
        request.body = json.dumps({
            "doc_type": "resource_data",
            "resource_locator": "http://test",
            "resource_data": "test",
            "keys": [],
            "TOS": {
                "submission_TOS": "http://www.learningregistry.org/information-assurances/open-information-assurances-1-0"
            },
            "resource_data_type": "metadata",
            "payload_schema_locator": "http://www.w3.org/TR/2012/WD-microdata-20121025/#converting-html-to-other-formats",
            "payload_placement": "inline",
            "payload_schema": ["plain text"],
            "doc_version": "0.23.0",
            "active": True,
            "identity": {
                "submitter": "inBloom Tagger Application <tagger@inbloom.org>",
                "signer": "Learning Registry SLC Node <lrnode@inbloom.org>",
                "submitter_type": "user",
                "curator": "5a4bfe96-1724-4565-9db1-35b3796e3ce1:jordi.juarez@udl.cat@null"
            }
        })
        info = add_envelope(request)
        assert info['OK'], pformat(info)
        doc = request.db[info["doc_ID"]]
        assert "digital_signature" in doc

    def test_add_envelope_linked_fail(self):
        from .views import add_envelope
        from requests import post
        request = self._prepare_request({})
        resp = post("http://localhost:5984/_session", data={"name": 'user', "password": 'password'})
        request.auth_cookie = resp.headers['set-cookie']
        request.node_id = "abc123"
        request.body = json.dumps({
            "doc_type": "resource_data",
            "resource_locator": "",
            "resource_data": "test",
            "keys": [],
            "TOS": {
                "submission_TOS": "http://www.learningregistry.org/information-assurances/open-information-assurances-1-0"
            },
            "resource_data_type": "metadata",
            "payload_schema_locator": "http://www.w3.org/TR/2012/WD-microdata-20121025/#converting-html-to-other-formats",
            "payload_placement": "linked",
            "payload_schema": ["plain text"],
            "doc_version": "0.23.0",
            "active": True,
            "identity": {
                "submitter": "inBloom Tagger Application <tagger@inbloom.org>",
                "signer": "Learning Registry SLC Node <lrnode@inbloom.org>",
                "submitter_type": "user",
                "curator": "5a4bfe96-1724-4565-9db1-35b3796e3ce1:jordi.juarez@udl.cat@null"
            }
        })
        info = add_envelope(request)
        assert not info['OK']

    def test_add_envelope_inline_fail(self):
        from .views import add_envelope
        from requests import post
        request = self._prepare_request({})
        resp = post("http://localhost:5984/_session", data={"name": 'user', "password": 'password'})
        request.auth_cookie = resp.headers['set-cookie']
        request.body = json.dumps({
            "doc_type": "resource_data",
            "resource_locator": "",
            "keys": [],
            "TOS": {
                "submission_TOS": "http://www.learningregistry.org/information-assurances/open-information-assurances-1-0"
            },
            "resource_data_type": "metadata",
            "payload_schema_locator": "http://www.w3.org/TR/2012/WD-microdata-20121025/#converting-html-to-other-formats",
            "payload_placement": "inline",
            "payload_schema": ["plain text"],
            "doc_version": "0.23.0",
            "active": True,
            "identity": {
                "submitter": "inBloom Tagger Application <tagger@inbloom.org>",
                "signer": "Learning Registry SLC Node <lrnode@inbloom.org>",
                "submitter_type": "user",
                "curator": "5a4bfe96-1724-4565-9db1-35b3796e3ce1:jordi.juarez@udl.cat@null"
            }
        })
        info = add_envelope(request)
        assert not info['OK'], pformat(info)

    def test_delete(self):
        import base64
        import gnupg
        from .views import add_envelope
        from requests import post
        request = self._prepare_request({})
        resp = post("http://localhost:5984/_session", data={"name": 'wegrata3', "password": 'password'})
        request.auth_cookie = resp.headers['set-cookie']
        request.body = json.dumps({
            "doc_type": "resource_data",
            "resource_locator": "http://test",
            "resource_data": "test",
            "keys": [],
            "TOS": {
                "submission_TOS": "http://www.learningregistry.org/information-assurances/open-information-assurances-1-0"
            },
            "resource_data_type": "metadata",
            "payload_schema_locator": "http://www.w3.org/TR/2012/WD-microdata-20121025/#converting-html-to-other-formats",
            "payload_placement": "inline",
            "payload_schema": ["plain text"],
            "doc_version": "0.23.0",
            "active": True,
            "identity": {
                "submitter": "inBloom Tagger Application <tagger@inbloom.org>",
                "signer": "Learning Registry SLC Node <lrnode@inbloom.org>",
                "submitter_type": "user",
                "curator": "5a4bfe96-1724-4565-9db1-35b3796e3ce1:jordi.juarez@udl.cat@null"
            }
        })
        info = add_envelope(request)
        assert info["OK"]
        request = testing.DummyRequest()
        request.matchdict['doc_id'] = info['doc_ID']
        request.db = self.add_couchdb(request)
        s = Server(uri="http://admin:password@localhost:5984")
        request.users = s.get_db("_users")
        request.username = "wegrata3"
        result = delete_document(request)
        assert result["OK"]
        assert request.db[info['doc_ID']].get('doc_type') == "tombstone"

    def test_update(self):
        import base64
        import gnupg
        from .views import add_envelope
        from requests import post
        request = self._prepare_request({})
        resp = post("http://localhost:5984/_session", data={"name": 'wegrata3', "password": 'password'})
        request.auth_cookie = resp.headers['set-cookie']
        request.body = json.dumps({
            "doc_type": "resource_data",
            "resource_locator": "http://test",
            "resource_data": "test",
            "keys": [],
            "TOS": {
                "submission_TOS": "http://www.learningregistry.org/information-assurances/open-information-assurances-1-0"
            },
            "resource_data_type": "metadata",
            "payload_schema_locator": "http://www.w3.org/TR/2012/WD-microdata-20121025/#converting-html-to-other-formats",
            "payload_placement": "inline",
            "payload_schema": ["plain text"],
            "doc_version": "0.23.0",
            "active": True,
            "identity": {
                "submitter": "inBloom Tagger Application <tagger@inbloom.org>",
                "signer": "Learning Registry SLC Node <lrnode@inbloom.org>",
                "submitter_type": "user",
                "curator": "5a4bfe96-1724-4565-9db1-35b3796e3ce1:jordi.juarez@udl.cat@null"
            }
        })
        info = add_envelope(request)
        assert info["OK"]
        request = testing.DummyRequest()
        request.matchdict['doc_id'] = info['doc_ID']
        request.body = json.dumps({
            "doc_type": "resource_data",
            "resource_locator": "http://test123",
            "resource_data": "test",
            "keys": [],
            "TOS": {
                "submission_TOS": "http://www.learningregistry.org/information-assurances/open-information-assurances-1-0"
            },
            "resource_data_type": "metadata",
            "payload_schema_locator": "http://www.w3.org/TR/2012/WD-microdata-20121025/#converting-html-to-other-formats",
            "payload_placement": "inline",
            "payload_schema": ["plain text"],
            "doc_version": "0.23.0",
            "active": True,
            "identity": {
                "submitter": "inBloom Tagger Application <tagger@inbloom.org>",
                "signer": "Learning Registry SLC Node <lrnode@inbloom.org>",
                "submitter_type": "user",
                "curator": "5a4bfe96-1724-4565-9db1-35b3796e3ce1:jordi.juarez@udl.cat@null"
            }
        })
        request.db = self.add_couchdb(request)
        s = Server(uri="http://admin:password@localhost:5984")
        request.users = s.get_db("_users")
        request.username = "wegrata3"
        request.node_id = "abc123"
        request.auth_cookie = resp.headers['set-cookie']
        result = update_document(request)
        assert result["OK"]
        print(result)
        assert request.db[info['doc_ID']].get('doc_type') == "tombstone"
        assert result['doc_ID'] in request.db


text:
package com.futurice.freesound.test.assertion.rx;

import com.futurice.freesound.common.InstantiationForbiddenError;

import android.support.annotation.NonNull;

import io.reactivex.functions.Function;
import io.reactivex.functions.Predicate;
import polanski.option.Option;

/**
 * Helpers for testing {@link Option} values using RxJava2's {@link io.reactivex.Observable#test()}
 */
public final class RxJava2OptionAssertions {

    @NonNull
    public static <T> Predicate<Option<T>> isNone() {
        return Option::isNone;
    }

    @NonNull
    public static <T, R> Predicate<T> isNone(@NonNull final Function<T, Option<R>> selector) {
        return v -> selector.apply(v).isNone();
    }

    @NonNull
    public static <T> Predicate<Option<T>> isSome() {
        return Option::isSome;
    }

    @NonNull
    public static <T, R> Predicate<T> isSome(@NonNull final Function<T, Option<R>> selector) {
        return v -> selector.apply(v).isSome();
    }

    @NonNull
    public static <T> Predicate<Option<T>> hasOptionValue(@NonNull final T expected) {
        return t -> t.filter(actual -> actual.equals(expected)).isSome();
    }

    private RxJava2OptionAssertions() {
        throw new InstantiationForbiddenError();
    }
}


text:
@interface UIView (BILoadXib)

+ (nonnull instancetype)viewFromXib;

@end


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Encyclop. Mycol. (Paris), <b>1</b> Le Genre Inocybe 1: 163 (1931)

#### Original name
Inocybe malenconii R. Heim, 1931

### Remarks
null


text:
<template name="examTest">

 {{question.question}}

    <form>
    	{{#each question.options}}

            {{#if selecting}}
	  		   <input type="radio" name="{{question._id}}" value="{{@index}}" class="option"  checked="checked">
            {{else}}
                <input type="radio" name="{{question._id}}" value="{{@index}}" class="option">
            {{/if}}
	  		{{text}}

	  	{{/each}}
        {{#if validQuestion}}

            {{#if backEnable}}
	  		<button type="button" data-total-question="{{totalQuestion}}" data-target-question="{{previousQuestion}}" data-current-question="{{currentQuestion}}" class="btn btn-danger questionBtn">Back
                        </button>
            {{/if}}
            {{#if nextEnable}}
            <button type="button" data-total-question="{{totalQuestion}}" data-target-question="{{nextQuestion}}" data-current-question="{{currentQuestion}}" class="btn btn-danger questionBtn">Next
                        </button>
            {{/if}}
            {{#if finishEnable}}
	  		<button type="button" data-total-question="{{totalQuestion}}" data-target-question="{{nextQuestion}}" data-current-question="{{currentQuestion}}" class="btn btn-danger finishBtn">Finish
                        </button>
            {{/if}}
            <button type="button" data-total-question="{{totalQuestion}}" data-target-question="{{nextQuestion}}" data-current-question="{{currentQuestion}}" class=" hidden btn btn-danger forceFinishBtn">Finish
                        </button>

        {{/if}}
	</form>

</template>


text:
var assign = require('object-assign');
var pathFn = require('path');

var config = hexo.config.feed = assign({
  type: 'atom',
  limit: 20,
  hub: '',
  content: true
}, hexo.config.feed);

var type = config.type.toLowerCase();

// Check feed type
if (type !== 'atom' && type !== 'rss2') {
  config.type = 'atom';
} else {
  config.type = type;
}

// Set default feed path
if (!config.path) {
  config.path = config.type + '.xml';
}

// Add extension name if don't have
if (!pathFn.extname(config.path)) {
  config.path += '.xml';
}

hexo.extend.generator.register('feed', require('./lib/generator'));


text:
import gameHelper from "./game_helper";
export const getBoard = (localState) => localState.board;
export const getCurrentPlayer = (localState) => localState.currentPlayer;
export const getTheWinner = (localState) => localState.theWinner;
export const getWinnerCells = (localState) => localState.winnerCells;
export const getIsBoardFull = (localState) => gameHelper.isBoardFull(localState.board);


text:
import * as Jungle from '../../../jungle'

let Membrane = Jungle.Membrane;
import TestHost from '../../helpers/testHost'
import {Input, Output} from '../../helpers/testContacts'

describe('basic membrane', function(){

    let memb, host;

    beforeEach(function(){
        host =  new TestHost([])
        memb = host.primary
    })

    afterEach(function(){
    })

    it('should allow addition and removal of ports', function(){
        let newb = Input()
        let new2 = Output()

        memb.addContact( newb, 'calledA');
        memb.addContact( new2, 'caller1');

        expect(memb.contacts.calledA).toBe(newb);
        expect(memb.contacts.caller1).toBe(new2);

        memb.removeContact("calledA");
        memb.removeContact("caller1");

        expect(memb.contacts.calledA).toBeUndefined();
        expect(memb.contacts.caller1).toBeUndefined();
    })
    describe('designation', function(){
        beforeEach(function(){
            host.populate(['_a', '_b', 'y_', 'x_'])
        })

        it('populate works', function(){
            expect(memb.contacts.a).not.toBeUndefined();
            expect(memb.contacts.b).not.toBeUndefined();
            expect(memb.contacts.y).not.toBeUndefined();
            expect(memb.contacts.x).not.toBeUndefined();

        })
    })
    describe('inversion', function(){
        let invert;
        beforeEach(function(){
            host.populate(['_a', '_b', 'y_', 'x_'])
            invert = memb.invert();
        })

        it('should have inverted those contactes already present', function(){
            let desall = invert.scan(":*");

            expect(desall[':y']).not.toBeUndefined();
            expect(desall[':x']).not.toBeUndefined();
        })

        it('should invert further contactes added', function(){
            memb.addContact(Output(), 'lame-o');

           //
            let desall = invert.scan(":*");

            expect(desall[':lame-o']).not.toBeUndefined();

            //a caller in the inversion is a called in the original
            invert.addContact(Output(), 'cool-cat');
            let desallop = memb.scan(":*");
            expect(desallop[':cool-cat']).not.toBeUndefined();
        })

        it('should remove from both sides', function(){
            let desiga = invert.scan(':a', false);

            invert.removeContact(desiga[0]);
            expect(invert.scan(':a',  false)[0]).toBeUndefined();
        })

    })
    describe('nested membranes', function(){
        let subhost, submemb

        beforeEach(function(){
            subhost = new TestHost([])

            submemb = subhost.primary;
            memb.addSubrane(submemb, 'sub')

            subhost.populate(['_a','x_']);
            host.populate(['_a', '_b', 'y_', 'x_'])
        })

        it('should allow designation at depth', function(){

            let desig = memb.scan('sub:a')
            expect(desig['sub:a']).toBe(submemb.contacts.a)
        })

        it('globbing should collect at many depths',function(){
            let sub2 = new Membrane()

            sub2.addContact(Input() , 'a');
            submemb.addSubrane(sub2, 'sub')

            let desig = memb.scan('sub.sub:a')
            //
            expect(desig['sub.sub:a']).toBe(sub2.contacts.a)

            let desigAll = memb.scan('**.sub:a')
            expect(desigAll['sub.sub:a']).toBe(sub2.contacts.a)
            expect(desigAll['sub:a']).toBe(submemb.contacts.a)

        })

    })
    describe('- membrane change notifications', function(){

        beforeEach(function(){

        })

        //when ports are added the host of the membrane and all parent membranes is informed
        it('should notify host when membrane has a contact added',function(){
            //all additions reported
            host.populate(['_door']);
            expect(host.addspy.calls.allArgs()[0][1]).toBe(memb.contacts.door)
            expect(host.addspy.calls.allArgs()[0][0]).toEqual([[],'door'])
        });

        it('should notify when a sub membrane has a contact added',function(){
            let sub = new Membrane()
            memb.addSubrane(sub, 'sub')

            sub.addContact(Input(), 'piwi')

            expect(host.addspy.calls.allArgs()[0][1]).toBe(sub.contacts.piwi)
            expect(host.addspy.calls.allArgs()[0][0]).toEqual([['sub'], 'piwi'])
        });

        it('should notify me when a contact is removed from my membrane',function(){
            host.populate(['_door']);
            let removed = memb.contacts.door
            memb.removeContact('door');

            expect(memb.contacts.door).toBeUndefined()
            expect(host.remspy.calls.allArgs()[0][0]).toEqual([[],'door'])
        })

        it('should notify me when a contact is removed from a sub membrane',function(){
            let sub = new Membrane()
            memb.addSubrane(sub, 'sub')

            sub.addContact(Input(),'piwi')

            let removed = sub.removeContact('piwi')

            expect(memb.contacts.door).toBeUndefined()
            expect(host.remspy.calls.allArgs()[0][0]).toEqual([['sub'], 'piwi'])
        })

        it('should notify contact additions of an added sub membrane', function(){
            let sub = new Membrane()
            memb.addSubrane(sub, 'sub')

            let sub2 = new Membrane()
            sub2.addContact(Output(),'fogle')

            sub.addSubrane(sub2, 'sub2')

            expect(host.addspy.calls.allArgs()[0][1]).toBe(sub2.contacts.fogle)
            expect(host.addspy.calls.allArgs()[0][0]).toEqual([['sub','sub2'],'fogle'])
        })
    })

    describe('with anonymity', function(){

        it('should allow anonymous watch with numeric indicies',function(){

            let memb = new Membrane()

            function check(ev, ct, token){//console.log('change occurred with token ', token)
            }

            let changeSpy = jasmine.createSpy('change on anon').and.callFake(check)
            let indexSpy = jasmine.createSpy('change on index').and.callFake(check)

            memb.addWatch({
                contactChange:changeSpy
            })

            memb.addWatch({
                contactChange:indexSpy
            }, 0)

            let contact = Input()
            memb.addContact(contact, 'twice')

            expect(changeSpy.calls.allArgs()[0][0]).toEqual([[],'twice'], "because anonymous wipes the front")

            expect(indexSpy.calls.allArgs()[0][0]).toEqual([['0'],'twice'], "because numeric designation is allowed")

        })
    })

})


text:
package net.ssehub.easy.instantiation.serializer.xml;

import java.io.File;
import java.io.IOException;
import java.util.Collection;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.FileFilterUtils;
import org.apache.commons.io.filefilter.IOFileFilter;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;

import net.ssehub.easy.basics.Environment;
import net.ssehub.easy.basics.modelManagement.ModelManagementException;
import net.ssehub.easy.basics.progress.ProgressObserver;
import net.ssehub.easy.instantiation.core.model.BuiltIn;
import net.ssehub.easy.instantiation.core.model.buildlangModel.BuildModel;
import net.ssehub.easy.instantiation.core.model.common.VilException;
import net.ssehub.easy.instantiation.core.model.execution.Executor;
import net.ssehub.easy.instantiation.core.model.execution.TracerFactory;
import net.ssehub.easy.instantiation.core.model.templateModel.TemplateModel;
import net.ssehub.easy.instantiation.core.model.tracing.ConsoleTracerFactory;
import net.ssehub.easy.reasoning.core.frontend.ReasonerFrontend;
import net.ssehub.easy.reasoning.core.impl.ReasonerRegistry;
import net.ssehub.easy.reasoning.core.reasoner.ReasonerConfiguration;
import net.ssehub.easy.reasoning.core.reasoner.ReasonerDescriptor;
import net.ssehub.easy.reasoning.core.reasoner.ReasoningResult;
import net.ssehub.easy.reasoning.sseReasoner.Reasoner;
import net.ssehub.easy.varModel.confModel.Configuration;
import net.ssehub.easy.varModel.management.VarModel;
import net.ssehub.easy.varModel.model.Project;

/**
 * Test case for executing the QM2 model from a XML file.
 *
 * @author Sass
 *
 */
public class ExecuteQM2ModelFromXMLTest extends AbstractUtil {

    protected static final ProgressObserver OBSERVER = ProgressObserver.NO_OBSERVER;

    private static final File TMP_DIR = new File(TEMPDATA, "gen");

    private static final File VIL = new File(XMLDATA, "qm2.xml");

//    private static final File IVML = new File(XMLDATA, "qm2ivml.xml");

    /**
     * Load properties and register types.
     */
    @BeforeClass
    public static void setUpBeforeClass() {
        if (!Environment.runsInEclipse()) {
            loadProperties();
            Registration.register();
            BuiltIn.initialize();
            net.ssehub.easy.instantiation.maven.Registration.register();

            // Ensure correct reasoner is used
            while (ReasonerRegistry.getInstance().getReasonerCount() > 0) {
                // Unregister all reasoners
                ReasonerRegistry.getInstance().unregister(ReasonerRegistry.getInstance().getReasoner(0));
            }
            // register desired reasoner: SSE-Reasoner
            ReasonerRegistry.getInstance().register(new Reasoner());
        }
        // Remove all possible locations
        int locationCount = VarModel.INSTANCE.locations().getLocationCount();
        for (int i = 0; i < locationCount; i++) {
            try {
                File varModelLocation = VarModel.INSTANCE.locations().getLocation(i).getLocation();
                File buildModelLocation = BuildModel.INSTANCE.locations().getLocation(i).getLocation();
                File tempModelLocation = TemplateModel.INSTANCE.locations().getLocation(i).getLocation();
                VarModel.INSTANCE.locations().removeLocation(varModelLocation, OBSERVER);
                BuildModel.INSTANCE.locations().removeLocation(buildModelLocation, OBSERVER);
                TemplateModel.INSTANCE.locations().removeLocation(tempModelLocation, OBSERVER);
            } catch (ModelManagementException e) {
                Assert.fail(e.getMessage());
            }
        }
        Assert.assertEquals(0, VarModel.INSTANCE.loaders().getLoaderCount());
        Assert.assertEquals(0, BuildModel.INSTANCE.loaders().getLoaderCount());
        Assert.assertEquals(0, TemplateModel.INSTANCE.loaders().getLoaderCount());
        Assert.assertEquals(0, VarModel.INSTANCE.locations().getLocationCount());
        Assert.assertEquals(0, BuildModel.INSTANCE.locations().getLocationCount());
        Assert.assertEquals(0, TemplateModel.INSTANCE.locations().getLocationCount());
    }

    /**
     * Clean up after test.
     */
    @AfterClass
    public static void tearDownAfterClass() {
        FileUtils.deleteQuietly(TMP_DIR);
        // TODO: WHY ARE THERE 2 LOADERS AFTER THE TEST ON JENKINS?
//        Assert.assertEquals(1, VarModel.INSTANCE.loaders().getLoaderCount());
//        Assert.assertEquals(1, BuildModel.INSTANCE.loaders().getLoaderCount());
//        Assert.assertEquals(1, TemplateModel.INSTANCE.loaders().getLoaderCount());
//        Assert.assertEquals(1, VarModel.INSTANCE.locations().getLocationCount());
//        Assert.assertEquals(1, BuildModel.INSTANCE.locations().getLocationCount());
//        Assert.assertEquals(1, TemplateModel.INSTANCE.locations().getLocationCount());
        // Remove locations
//        try {
//            VarModel.INSTANCE.locations().removeLocation(VIL, OBSERVER);
//            VarModel.INSTANCE.locations().removeLocation(IVML, OBSERVER);
//            BuildModel.INSTANCE.locations().removeLocation(VIL, OBSERVER);
//            TemplateModel.INSTANCE.locations().removeLocation(VIL, OBSERVER);
//        } catch (ModelManagementException e) {
//            Assert.fail(e.getMessage());
//        }
        // Unregister Loader
//        VarModel.INSTANCE.loaders().unregisterLoader(IVMLModelLoader.INSTANCE, OBSERVER);
//        BuildModel.INSTANCE.loaders().unregisterLoader(VILModelLoader.INSTANCE, OBSERVER);
//        TemplateModel.INSTANCE.loaders().unregisterLoader(VTLModelLoader.INSTANCE, OBSERVER);
        // Check if all loaders and locations were removed
//        Assert.assertEquals(0, VarModel.INSTANCE.loaders().getLoaderCount());
//        Assert.assertEquals(0, BuildModel.INSTANCE.loaders().getLoaderCount());
//        Assert.assertEquals(0, TemplateModel.INSTANCE.loaders().getLoaderCount());
//        Assert.assertEquals(0, VarModel.INSTANCE.locations().getLocationCount());
//        Assert.assertEquals(0, BuildModel.INSTANCE.locations().getLocationCount());
//        Assert.assertEquals(0, TemplateModel.INSTANCE.locations().getLocationCount());
    }

    /**
     * Test if the QM2 model can be loaded.
     *
     * @throws ModelManagementException
     */
    @Ignore("SE: Currently, the maven execution crashes")
    @Test
    public void testExecuteVil() throws ModelManagementException {
        Assert.assertTrue("File does not exist: " + VIL.getAbsolutePath(), VIL.exists());
        ModelDeserializer.deserializeModel(VIL);
        // execute
        try {
            ProjectDescriptor source = new ProjectDescriptor("qm2.xml", "QM");
            ProjectDescriptor target = new ProjectDescriptor(source, TMP_DIR);
            TracerFactory.setDefaultInstance(ConsoleTracerFactory.INSTANCE);
            Executor executor = new Executor(source.getMainVilScript()).addSource(target).addTarget(target)
                    .addConfiguration(ProjectDescriptor.getConfiguration("QM"));
            executor.execute();
        } catch (ModelManagementException e) {
            Assert.fail(e.getMessage());
        } catch (VilException e) {
            Assert.fail(e.getMessage());
        }
        checkEquality();
    }

    /**
     * Check the equality of the generated files with the original files.
     */
    private void checkEquality() {
        // Exclude jar and class files
        IOFileFilter jarFileFilter = FileFilterUtils.notFileFilter(FileFilterUtils.suffixFileFilter(".jar"));
        IOFileFilter classFileFilter = FileFilterUtils.notFileFilter(FileFilterUtils.suffixFileFilter(".class"));
        IOFileFilter targetFolderFilter = FileFilterUtils.notFileFilter(FileFilterUtils.nameFileFilter("target"));
        IOFileFilter fileFilter = FileFilterUtils.and(jarFileFilter, classFileFilter, targetFolderFilter);
        Collection<File> allfiles = FileUtils.listFiles(TEMPDATA, fileFilter,
                fileFilter);
        // Check if the right amount of files were generated
        File ifGen = new File(MODELDATA, "if-gen");
        File pipelines = new File(MODELDATA, "pipelines");
        Collection<File> ifGenFiles = FileUtils.listFiles(ifGen, fileFilter, fileFilter);
        Collection<File> pipelineFiles = FileUtils.listFiles(pipelines, fileFilter, fileFilter);
        Collection<File> allOriginalFiles = ifGenFiles;
        allOriginalFiles.addAll(pipelineFiles);
        if (allOriginalFiles.size() != allfiles.size()) {
            for (File file : allOriginalFiles) {
                String newPath = file.getPath();
                newPath = newPath.replaceAll("QM2.devel", "tmp/gen");
                File tmp = new File(newPath);
                if (!allfiles.contains(tmp)) {
                    Assert.fail("Not generated: " + tmp);
                }
            }
        }
        // Compare generated files with original files from the testdata folder
        String gen = "";
        String origin = "";
        for (File file : allfiles) {
            try {
                String generatedFile = readFile(file.toString());
                String path = file.toString().replaceAll("tmp/gen", "QM2.devel");
                String originalFile = readFile(path);
                Assert.assertEquals("Comparison failure in \""+ path + "\" (original) and \""+ file.getAbsolutePath()
                    +"\" (generated)", originalFile, generatedFile);
//                if (!generatedFile.equals(originalFile)) {
//                    Assert.fail("Not equals: " + file);
//                    gen += generatedFile + "\n";
//                    origin += originalFile + "\n";
//                }
            } catch (IOException e) {
                Assert.fail(e.getMessage());
            }
        }
        Assert.assertEquals(origin, gen);
    }

    /**
     * Test for reasoning.
     */
    @Test
    public void testExecuteIVML() {
        Assert.assertTrue("File does not exist: " + VIL.getAbsolutePath(), VIL.exists());
        // if Model does not work due to changes, copy testdata/tmp/qm2.* to testdata/serializedModel.
        // the serializedModel is intentionaly not taken over automatically. it is written during the prequisite tests
        ModelDeserializer.deserializeModel(VIL);
        ReasonerConfiguration configuration = new ReasonerConfiguration();
        configuration.enableCustomMessages();
        Project project = VarModel.INSTANCE.availableModels().getModelInfo("QM").get(0).getResolved();
        Configuration cfg = new Configuration(project);

        ReasonerFrontend rFrontend = ReasonerFrontend.getInstance();
        ReasonerDescriptor desc = rFrontend.setPreferredReasoner();
        System.out.println("Using reasoner: " + desc.getName());
        ReasoningResult result = ReasonerFrontend.getInstance().check(cfg, configuration, ProgressObserver.NO_OBSERVER);
        Assert.assertEquals("Reasoning encountered problems", 0, result.getMessageCount());
    }

}


text:
# node-webcrypto-ossl

[![License](https://img.shields.io/badge/license-MIT-green.svg?style=flat)](https://raw.githubusercontent.com/PeculiarVentures/node-webcrypto-ossl/master/LICENSE)
![test](https://github.com/PeculiarVentures/node-webcrypto-ossl/workflows/test/badge.svg)
[![Coverage Status](https://coveralls.io/repos/github/PeculiarVentures/node-webcrypto-ossl/badge.svg?branch=master)](https://coveralls.io/github/PeculiarVentures/node-webcrypto-ossl?branch=master)
[![npm version](https://badge.fury.io/js/node-webcrypto-ossl.svg)](https://badge.fury.io/js/node-webcrypto-ossl)

[![NPM](https://nodei.co/npm/node-webcrypto-ossl.png)](https://nodei.co/npm/node-webcrypto-ossl/)

## Deprecated

__`node-webcrypto-ossl` was created in 2015 because at the time the Node team did not feel the need to have two crypto interfaces and they already had one before WebCrypto was defined.__

__That position has since changed since Node16.x (2021-10-26) there is a LTS build of Node that supports the WebCrypto interface.__

__We have also since created [@peculiar/webcrypto](https://www.npmjs.com/package/@peculiar/webcrypto) which no longer has the direct dependency on OpenSSL which makes it much easier to support in the wild. This package supports a number of algorithms that are not supported by standards compliant webcrypto implementations.__

__This allows applications to retain maximal code compatibility with standards while maintaining interoperability with systems that rely on these other algorithms. For those who have this requirement we recommend moving to [@peculiar/webcrypto](https://www.npmjs.com/package/@peculiar/webcrypto).__

## About

We wanted to be able to write Javascript that used crypto on both the client and the server but we did not want to rely on Javascript implementations of crypto. The only native cryptography available in browser is [Web Crypto](http://caniuse.com/#search=cryptography), this resulted in us creating a `node-webcrypto-ossl` a native polyfill for WebCrypto based on OpenSSL since at the time Node did not have a native WebCrypto implementation. As of [Node 15](https://nodejs.org/api/webcrypto.html) however they have added such a interface so you may not need this module any longer.

## Table Of Contents

* [WARNING](#warning)
* [Installing](#installing)
  * [Clone Repo](#clone-repo)
  * [Install Dependencies](#install-dependencies)
  * [Install](#install)
  * [Test](#test)
* [Threat Model](#threat-model)
  * [Assumptions](#assumptions)
  * [Threats From Weak Cryptography](#threats-from-weak-cryptography)
  * [Threats From Improper Use Of Cryptography](#threats-from-improper-use-of-cryptography)
* [Bug Reporting](#bug-reporting)
* [Related](#related)

## WARNING

**At this time this solution should be considered suitable for research and experimentation, further code and security review is needed before utilization in a production application.**

## Installation

### npm

```
npm install node-webcrypto-ossl
```

### Clone Repo

```
git clone https://github.com/PeculiarVentures/node-webcrypto-ossl
cd node-webcrypto-ossl
```

### Install

```
npm install
```

### Test

```
mocha
```

## Supported algorithms

| Algorithm name    | generateKey | digest  | export/import | sign/verify | encrypt/decrypt | wrapKey/unwrapKey | derive  |
|-------------------|-------------|---------|---------------|-------------|-----------------|-------------------|---------|
| SHA-1             |             |    X    |               |             |                 |                   |         |
| SHA-256           |             |    X    |               |             |                 |                   |         |
| SHA-384           |             |    X    |               |             |                 |                   |         |
| SHA-512           |             |    X    |               |             |                 |                   |         |
| RSASSA-PKCS1-v1_5 |      X      |         |       X       |      X      |                 |                   |         |
| RSA-PSS           |      X      |         |       X       |      X      |                 |                   |         |
| RSA-OAEP          |      X      |         |       X       |             |        X        |         X         |         |
| AES-CBC           |      X      |         |       X       |             |        X        |         X         |         |
| AES-CTR           |      X      |         |       X       |             |        X        |         X         |         |
| AES-ECB 2 |      X      |         |       X       |             |        X        |         X         |         |
| AES-GCM           |      X      |         |       X       |             |        X        |         X         |         |
| AES-KW            |      X      |         |       X       |             |                 |         X         |         |
| AES-CMAC          |      X      |         |       X       |      X      |                 |                   |         |
| ECDSA             |      X      |         |       X       |      X      |                 |                   |         |
| ECDH              |      X      |         |       X       |             |                 |                   |    X    |
| HMAC              |      X      |         |       X       |      X      |                 |                   |         |
| PBKDF2            |             |         |       X       |             |                 |                   |    X    |
| DES-CBC           |      X      |         |       X       |             |        X        |         X         |         |
| DES-EDE3-CBC      |      X      |         |       X       |             |        X        |         X         |         |

2 ECB support is not defined by the WebCrypto specifications. Use of ECB in a safe way is hard, it was added for the purpose of enabling interoperability with an existing system. We recommend against its use unless needed for interoperability.

## Using

```js
import { Crypto } from "node-webcrypto-ossl";

const crypto = new Crypto();
```

## Elliptic curve secp256k1

`secp256k1` curve is not defined by the WebCrypto specifications. This module implements `K-256` curve for ECDSA algorithm.

[K-256 curve examples](https://github.com/PeculiarVentures/webcrypto-core/blob/master/spec/EC_K_256.md)

## KeyStorage

To use KeyStorage you should init WebCrypto with `directory` option. If `directory` option is missing then `keyStorage` is `null`

```javascript
const { Crypto } = require("node-webcrypto-ossl");

const crypto = new Crypto({
  directory: "key_storage"
})
```

KeyStorage implements interface of [W3 Storage](https://developer.mozilla.org/en-US/docs/Web/API/Storage)

```js
// generating RSA key
const keys = await crypto.subtle.generateKey({
    name: "RSASSA-PKCS1-v1_5",
    modulusLength: 1024,
    publicExponent: new Uint8Array([1, 0, 1]),
    hash: {
      name: "SHA-1"
    }
  },
    false,
    ["sign", "verify"]
  );

/**
 * saving private RSA key to KeyStorage
 * creates file ./key_storage/prvRSA-1024
 */
await crypto.keyStorage.setItem(keyPairs.privateKey, "prvRSA-1024");
```

To get key from KeyStorage
```js
var rsaKey = await webcrypto.keyStorage.getItem("prvRSA-1024");
```

## Threat Model

The threat model is defined in terms of what each possible attacker can achieve.

### Assumptions

TODO: ADD ASSUMPTIONS

### Threats From A node-webcrypto-ossl Defect

TODO: ADD THREATS FROM NODE-WEBCRYPTO-OSSL DEFECT

### Threats From Weak Cryptography

TODO: ADD THREATS FROM WEAK CRYPTOGRAPHY

### Threats From Improper Use Of Cryptography

TODO: ADD THREATS FOR IMPROPER USE OF CRYPTOGRAPHY

## Bug Reporting
Please report bugs either as pull requests or as issues in the issue tracker. node-webcrypto-ossl has a full disclosure vulnerability policy. Please do NOT attempt to report any security vulnerability in this code privately to anybody.

## Related
 - [node-webcrypto-p11](https://github.com/PeculiarVentures/node-webcrypto-p11)
 - [webcrypto-liner](https://github.com/PeculiarVentures/webcrypto-liner)
 - [WebCrypto Examples](https://github.com/diafygi/webcrypto-examples)
 - [OpenSSL](https://github.com/openssl/openssl)
 - [OpenSSL AES GCM encrypt/decrypt](https://wiki.openssl.org/index.php/EVP_Authenticated_Encryption_and_Decryption)


text:
Tema do Trabalho: eSUS-AB

Descrição do trabalho: [eSUS-AB](https://github.com/kyriosdata/db/wiki/e-SUS-AB)

[Wiki do Projeto](https://github.com/Eddyosos/integracao201701/wiki)


text:
package com.carlos.luke.communication.interthread.interrupt;
public class MyThread2 extends Thread{
    @Override
    public void run() {
        super.run();
        while (true){
            if (this.isInterrupted()){
                System.out.println("The thread is stop!");
                return;
            }
            System.out.println("timer="+System.currentTimeMillis());
        }
    }
}


text:
package com.icegreen.greenmail.test;

import com.icegreen.greenmail.util.GreenMail;
import com.icegreen.greenmail.util.ServerSetup;
import com.icegreen.greenmail.util.ServerSetupTest;
import org.junit.Test;

import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

/**
 * Test that checks if greenmail start, stop and reset works correctly
 */
public class ServerStartStopTest {
    @Test
    public void testStartStop() {
        GreenMail service = new GreenMail(ServerSetupTest.ALL);
        try {
            // Try to stop before start: Nothing happens
            service.stop();
            service.start();
            service.stop();
            // Now the server is stopped, should be started by reset command
            service.reset();
            // Start again
            service.reset();
        } finally {
            // And finally stop
            service.stop();
        }
    }

    @Test
    public void testServerStartupTimeout() {
        // Create a few setups
        ServerSetup setups[] = new ServerSetup[ServerSetupTest.ALL.length];

        // Set too low startup timeout
        for(int i=0;i<ServerSetupTest.ALL.length;i++) {
            setups[i] = ServerSetupTest.ALL[i].createCopy();
            setups[i].setServerStartupTimeout(0L);
        }

        // Will fail, as timeouts are set to 0.
        GreenMail service = new GreenMail(setups);
        try {
            service.start();
            fail("Expected timeout");
        } catch (IllegalStateException ex) {
            assertTrue(ex.getMessage().contains("try to set server startup timeout > "));
        } finally {
            service.stop();
        }

        // Set large startup timeout
        for(ServerSetup s: setups) {
            s.setServerStartupTimeout(3000L);
        }
        service = new GreenMail(setups);
        try {
            service.start(); // Should work with large timeout
        } finally {
            service.stop();
        }
    }
}


text:
package intdataplane

import (
	log "github.com/sirupsen/logrus"

	"github.com/projectcalico/felix/iptables"
	"github.com/projectcalico/felix/proto"
	"github.com/projectcalico/felix/rules"
)

type policyManagerCallbacks struct {
	updatePolicy *UpdatePolicyDataFuncs
	removePolicy *RemovePolicyDataFuncs
}

func newPolicyManagerCallbacks(callbacks *callbacks, ipVersion uint8) policyManagerCallbacks {
	if ipVersion == 4 {
		return policyManagerCallbacks{
			updatePolicy: callbacks.UpdatePolicyV4,
			removePolicy: callbacks.RemovePolicyV4,
		}
	} else {
		return policyManagerCallbacks{
			updatePolicy: &UpdatePolicyDataFuncs{},
			removePolicy: &RemovePolicyDataFuncs{},
		}
	}
}

func (c *policyManagerCallbacks) InvokeUpdatePolicy(policyID proto.PolicyID, policy *proto.Policy) {
	c.updatePolicy.Invoke(policyID, policy)
}

func (c *policyManagerCallbacks) InvokeRemovePolicy(policyID proto.PolicyID) {
	c.removePolicy.Invoke(policyID)
}

// policyManager simply renders policy/profile updates into iptables.Chain objects and sends
// them to the dataplane layer.
type policyManager struct {
	rawTable     iptablesTable
	mangleTable  iptablesTable
	filterTable  iptablesTable
	ruleRenderer policyRenderer
	ipVersion    uint8
	callbacks    policyManagerCallbacks
}

type policyRenderer interface {
	PolicyToIptablesChains(policyID *proto.PolicyID, policy *proto.Policy, ipVersion uint8) []*iptables.Chain
	ProfileToIptablesChains(profileID *proto.ProfileID, policy *proto.Profile, ipVersion uint8) (inbound, outbound *iptables.Chain)
}

func newPolicyManager(rawTable, mangleTable, filterTable iptablesTable, ruleRenderer policyRenderer, ipVersion uint8, callbacks *callbacks) *policyManager {
	return &policyManager{
		rawTable:     rawTable,
		mangleTable:  mangleTable,
		filterTable:  filterTable,
		ruleRenderer: ruleRenderer,
		ipVersion:    ipVersion,
		callbacks:    newPolicyManagerCallbacks(callbacks, ipVersion),
	}
}

func (m *policyManager) OnUpdate(msg interface{}) {
	switch msg := msg.(type) {
	case *proto.ActivePolicyUpdate:
		log.WithField("id", msg.Id).Debug("Updating policy chains")
		chains := m.ruleRenderer.PolicyToIptablesChains(msg.Id, msg.Policy, m.ipVersion)
		// We can't easily tell whether the policy is in use in a particular table, and, if the policy
		// type gets changed it may move between tables.  Hence, we put the policy into all tables.
		// The iptables layer will avoid programming it if it is not actually used.
		m.rawTable.UpdateChains(chains)
		m.mangleTable.UpdateChains(chains)
		m.filterTable.UpdateChains(chains)
		m.callbacks.InvokeUpdatePolicy(*msg.Id, msg.Policy)
	case *proto.ActivePolicyRemove:
		log.WithField("id", msg.Id).Debug("Removing policy chains")
		inName := rules.PolicyChainName(rules.PolicyInboundPfx, msg.Id)
		outName := rules.PolicyChainName(rules.PolicyOutboundPfx, msg.Id)
		// As above, we need to clean up in all the tables.
		m.filterTable.RemoveChainByName(inName)
		m.filterTable.RemoveChainByName(outName)
		m.mangleTable.RemoveChainByName(inName)
		m.mangleTable.RemoveChainByName(outName)
		m.rawTable.RemoveChainByName(inName)
		m.rawTable.RemoveChainByName(outName)
		m.callbacks.InvokeRemovePolicy(*msg.Id)
	case *proto.ActiveProfileUpdate:
		log.WithField("id", msg.Id).Debug("Updating profile chains")
		inbound, outbound := m.ruleRenderer.ProfileToIptablesChains(msg.Id, msg.Profile, m.ipVersion)
		m.filterTable.UpdateChains([]*iptables.Chain{inbound, outbound})
		m.mangleTable.UpdateChains([]*iptables.Chain{outbound})
	case *proto.ActiveProfileRemove:
		log.WithField("id", msg.Id).Debug("Removing profile chains")
		inName := rules.ProfileChainName(rules.ProfileInboundPfx, msg.Id)
		outName := rules.ProfileChainName(rules.ProfileOutboundPfx, msg.Id)
		m.filterTable.RemoveChainByName(inName)
		m.filterTable.RemoveChainByName(outName)
		m.mangleTable.RemoveChainByName(outName)
	}
}

func (m *policyManager) CompleteDeferredWork() error {
	// Nothing to do, we don't defer any work.
	return nil
}


text:
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;

namespace Microsoft.VisualStudio.LanguageServices.Implementation.Library.FindResults
{
    internal class SourceDefinitionTreeItem : AbstractSourceTreeItem
    {
        private readonly bool _canGoToDefinition;
        private readonly string _symbolDisplay;

        public SourceDefinitionTreeItem(Document document, TextSpan sourceSpan, ISymbol symbol, ushort glyphIndex)
            : base(document, sourceSpan, glyphIndex)
        {
            _symbolDisplay = symbol.ToDisplayString(definitionDisplayFormat);
            this.DisplayText = $"{GetProjectNameString()}{_symbolDisplay}";

            _canGoToDefinition = symbol.Kind != SymbolKind.Namespace;
        }

        public override bool CanGoToDefinition()
        {
            return _canGoToDefinition;
        }

        internal override void SetReferenceCount(int referenceCount)
        {
            var referenceCountDisplay = referenceCount == 1
                ? ServicesVSResources._1_reference
                : string.Format(ServicesVSResources._0_references, referenceCount);

            this.DisplayText = $"{GetProjectNameString()}{_symbolDisplay} ({referenceCountDisplay})";
        }

        private string GetProjectNameString()
        {
            return (_projectName != null && _canGoToDefinition) ? $"[{_projectName}] " : string.Empty;
        }
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <link rel="stylesheet" href="style.css">


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE chapter PUBLIC "-//OASIS//DTD DocBook XML V4.4//EN"
"http://www.oasis-open.org/docbook/xml/4.4/docbookx.dtd">
<glossary id="Glossary">
  <glossdiv>
    <title>A</title>

    <glossentry>
      <glossterm>ACPI</glossterm>

      <glossdef>
        <para>Advanced Configuration and Power Interface, une
        spécification de l'industrie pour BIOS et extensions matérielles pour configurer
        le matériel PC et gérer l'alimentation. Windows 2000 et ultérieur ainsi que
        Linux 2.4 et ultérieur supportent ACPI. Windows ne peut activer/désactiver
        le support ACPI qu'à l'installation.</para>
      </glossdef>
    </glossentry>

    <glossentry>
      <glossterm>AHCI</glossterm>

      <glossdef>
        <para>Advanced Host Controller Interface, l'interface qui supporte
        les périphériques SATA tel que les disques durs. Voir <xref
        linkend="harddiskcontrollers" />.</para>
      </glossdef>
    </glossentry>

    <glossentry>
      <glossterm>AMD-V</glossterm>

      <glossdef>
        <para>La capacité de virtualisation matérielle implémentée dans les
        processeurs AMD récents. Voir <xref linkend="hwvirt" />.</para>
      </glossdef>
    </glossentry>

    <glossentry>
      <glossterm>API</glossterm>

      <glossdef>
        <para>Application Programming Interface.</para>
      </glossdef>
    </glossentry>

    <glossentry>
      <glossterm>APIC</glossterm>

      <glossdef>
        <para>Advanced Programmable Interrupt Controller, une version plus récente
        de l'ancienne PIC (programmable interrupt controller). La plupart des
        CPUs récents incorporent un APIC ("local APIC"). Beaucoup de systèmes intègrent
        aussi un I/O APIC (input output APIC) dans une puce à part qui fournit plus de
        16 IRQs. Windows 2000 et ultérieur utilise un noyau différent si il est
        détecté un I/O APIC à l'installation. De ce fait un I/O APIC ne doit pas être
        supprimé après l'installation.</para>
      </glossdef>
    </glossentry>

    <glossentry>
      <glossterm>ATA</glossterm>

      <glossdef>
        <para>Advanced Technology Attachment, un standard de l'industrie pour les
        interfaces de disques durs (synonyme de IDE). Voir <xref
        linkend="harddiskcontrollers" />.</para>
      </glossdef>
    </glossentry>
  </glossdiv>

  <glossdiv>
    <title>B</title>

    <glossentry>
      <glossterm>BIOS</glossterm>

      <glossdef>
        <para>Basic Input/Output System, le firmware intégré à la plupart des ordinateurs
        personnels qui est chargé d'initialiser le matériel après que la machine
        ait été allumée et qui alors démarre le système d'exploitation.
        VirtualBox est livré avec son propre BIOS virtuel qui se lance quand une
        machine est démarrée.</para>
      </glossdef>
    </glossentry>
  </glossdiv>

  <glossdiv>
    <title>C</title>

    <glossentry>
      <glossterm>COM</glossterm>

      <glossdef>
        <para>Microsoft Component Object Model, une infrastructure de programmation
        pour logiciels modulaires. COM permet aux applications de fournir une interface
        de programmation qui peut être accédée depuis divers autres langages de
        programmation et applications. VirtualBox utilise COM en interne et
        en externe pour fournir une API complète aux développeurs externes
        .</para>
      </glossdef>
    </glossentry>
  </glossdiv>

  <glossdiv>
    <title>D</title>

    <glossentry>
      <glossterm>DHCP</glossterm>

      <glossdef>
        <para>Dynamic Host Configuration Protocol. Ceci donne la faculté à un périphérique
        de réseau d'obtenir automatiquement son adresse IP (et autres informations du réseau)
        , afin d'éviter d'avoir à configurer tous les périphériques
        d'un réseau avec des adresses IP fixes. VirtualBox a un serveur
        DHCP incorporé qui octroie une adresse IP à une machine virtuelle
        quand le réseau est configuré en mode NAT ; voir <xref
        linkend="networkingdetails" />.</para>
      </glossdef>
    </glossentry>

    <glossentry>
      <glossterm>DKMS</glossterm>

      <glossdef>
        <para>Dynamic Kernel Module Support. Un environnement qui simplifie
        l'installation et la mise à jour des modules externes de noyau sur les machines Linux ; voir
        <xref linkend="externalkernelmodules" />.</para>
      </glossdef>
    </glossentry>
  </glossdiv>

  <glossdiv>
    <title>E</title>

    <glossentry>
      <glossterm>EFI</glossterm>

      <glossdef>
        <para>Extensible Firmware Interface, un firmware intégré aux ordinateurs
        qui a pour but de remplacer le BIOS dépassé. À l'origine conçu par
        Intel, la plupart des systèmes peuvent maintenant démarrer une machine qui
        a EFI au lieu de BIOS ; voir <xref
        linkend="efi" />.</para>
      </glossdef>
    </glossentry>

    <glossentry>
      <glossterm>EHCI</glossterm>

      <glossdef>
        <para>Enhanced Host Controller Interface, l'interface qui
        implémente l'USB 2.0 standard.</para>
      </glossdef>
    </glossentry>
  </glossdiv>

  <glossdiv>
    <title>G</title>

    <glossentry>
      <glossterm>GUI</glossterm>

      <glossdef>
        <para>Graphical User Interface. Communément employé en opposition à
        "interface en ligne de commande", dans le contexte VirtualBox, nous nous
        référons au programme graphique principal de
        <computeroutput>VirtualBox</computeroutput> en tant que "GUI", pour le
        différencier de l'interface <computeroutput>VBoxManage</computeroutput>
        .</para>
      </glossdef>
    </glossentry>

    <glossentry>
      <glossterm>GUID</glossterm>

      <glossdef>
        <para>Voir UUID.</para>
      </glossdef>
    </glossentry>
  </glossdiv>

  <glossdiv>
    <title>I</title>

    <glossentry>
      <glossterm>IDE</glossterm>

      <glossdef>
        <para>Integrated Drive Electronics, un standard de l'industrie pour une interface
        de disque dur. Voir <xref linkend="harddiskcontrollers" />.</para>
      </glossdef>
    </glossentry>

    <glossentry>
      <glossterm>I/O APIC</glossterm>

      <glossdef>
        <para>Voir APIC.</para>
      </glossdef>
    </glossentry>

    <glossentry>
      <glossterm>iSCSI</glossterm>

      <glossdef>
        <para>Internet SCSI; voir <xref linkend="storage-iscsi" />.</para>
      </glossdef>
    </glossentry>
  </glossdiv>

  <glossdiv>
    <title>M</title>

    <glossentry>
      <glossterm>MAC</glossterm>

      <glossdef>
        <para>Media Access Control, un élément d'une carte Ethernet. Une adresse MAC
        est un nombre de 6 octets qui identifie une carte réseau. C'est typiquement
        écrit en héxadecimal où les octets sont séparés par ":", tel que
        <computeroutput>00:17:3A:5E:CB:08</computeroutput>.</para>
      </glossdef>
    </glossentry>

    <glossentry>
      <glossterm>MSI</glossterm>

      <glossdef>
        <para>Message Signaled Interrupts, supporté par les circuits récents
        tel que le ICH9; voir <xref linkend="settings-motherboard" />.
        Contrairement aux traditionnelles interruptions pin-based, avec MSI, une petite
        quantité de données peut accompagner le véritable message d'interruption. Ceci réduit la
        quantité requise de broches sur le matériel, permet plus d'interruptions avec de
        meilleures performances.</para>
      </glossdef>
    </glossentry>
  </glossdiv>

  <glossdiv>
    <title>N</title>

    <glossentry>
      <glossterm>NAT</glossterm>

      <glossdef>
        <para>Network Address Translation. Une technique pour partager les interfaces
        réseau par laquelle une interface modifie l'adresse IP source et/ou cible
        des paquets réseau selon des règles spécifiques. Couramment
        employé par routeurs et pare-feux pour séparer un réseau interne
        de l'Internet, VirtualBox peut utiliser NAT pour facilement partager un équipement réseau
        physique de l'hôte avec ses machines virtuelles. Voir <xref
        linkend="network_nat" />.</para>
      </glossdef>
    </glossentry>
  </glossdiv>

  <glossdiv>
    <title>O</title>

    <glossentry>
      <glossterm>OVF</glossterm>

      <glossdef>
        <para>Open Virtualization Format, un standard de l'industrie inter-platforme
        pour échanger des briques logicielles virtuelles entre produits de virtualisation; voir
        <xref linkend="ovf" />.</para>
      </glossdef>
    </glossentry>
  </glossdiv>

  <glossdiv>
    <title>P</title>

    <glossentry>
      <glossterm>PAE</glossterm>

      <glossdef>
        <para>Physical Address Extension. Ceci permet l'accès à plus de 4 GB
        de RAM même en environnement 32-bit ; voir <xref
        linkend="settings-general-advanced" />.</para>
      </glossdef>
    </glossentry>

    <glossentry>
      <glossterm>PIC</glossterm>

      <glossdef>
        <para>Voir APIC.</para>
      </glossdef>
    </glossentry>

    <glossentry>
      <glossterm>PXE</glossterm>

      <glossdef>
        <para>Preboot Execution Environment, un standard de l'industrie pour démarrer
        des systèmes PC à distance. Cela inclue DHCP pour la configuration IP
        et TFTP pour le transfert de fichier. Avec UNDI, est disponible une pile de pilote de matériel
        indépendant pour accéder la carte réseau par le code d'amorce
        .</para>
      </glossdef>
    </glossentry>
  </glossdiv>

  <glossdiv>
    <title>R</title>

    <glossentry>
      <glossterm>RDP</glossterm>

      <glossdef>
        <para>Remote Desktop Protocol, un protocole développé par Microsoft en
        extension des protocoles ITU T.128 et T.124 de vidéo conference. Avec
        RDP, un système PC peut être contrôllé à distance en utilisant une connection
        réseau à travers laquelle les données sont transférées dans les 2 directions.
        Typiquement les événements graphiques et audio sont envoyés depuis la machine à distance
        et les événements clavier et souris sont envoyés depuis le client. Un paquet d'extension
        VirtualBox d'Oracle fournit VRDP, une implementation améliorée du standard approprié qui est
        largement compatible avec le RDP Microsoft. Voir <xref linkend="vrde" /> pour le
        detail.</para>
      </glossdef>
    </glossentry>
  </glossdiv>

  <glossdiv>
    <title>S</title>

    <glossentry>
      <glossterm>SAS</glossterm>

      <glossdef>
        <para>Serial Attached SCSI, un standard de l'industrie pour les interfaces
        de disques durs. Voir <xref linkend="harddiskcontrollers" />.</para>
      </glossdef>
    </glossentry>

    <glossentry>
      <glossterm>SATA</glossterm>

      <glossdef>
        <para>Serial ATA, un standard de l'industrie pour les interfaces de disques durs. Voir
        <xref linkend="harddiskcontrollers" />.</para>
      </glossdef>
    </glossentry>

    <glossentry>
      <glossterm>SCSI</glossterm>

      <glossdef>
        <para>Small Computer System Interface. Un standard de l'industrie pour
        le transfer de données entre périphériques, de stockage particulièrement. Voir <xref
        linkend="harddiskcontrollers" />.</para>
      </glossdef>
    </glossentry>

    <glossentry>
      <glossterm>SMP</glossterm>

      <glossdef>
        <para>Symmetrical Multiprocessing, indique que les ressources d'une
        machine sont partagées entre différents processeurs. Ceci peut être soit
        plusieurs puces processeur ou, le plus courant dans le matériel récent,
        plusieurs coeurs CPU dans le processeur.</para>
      </glossdef>
    </glossentry>

    <glossentry>
      <glossterm>SSD</glossterm>

      <glossdef>
        <para>Solid-state drive, utilise des micropuces pour stocker les données système d'une
        machine. Comparé aux classiquex disques durs ils n'ont pas de composants mécaniques
        comme les plateaux tournants.
        </para>
      </glossdef>
    </glossentry>
  </glossdiv>

  <glossdiv>
    <title>T</title>

    <glossentry>
      <glossterm>TAR</glossterm>

      <glossdef>
        <para>Un format de fichier largement répandu pour l'archivage. À l'origine
        pour "Tape ARchive", était déjà supporté par les premières versions d'Unix
        pour sauvegarder les données sur bande. Le format de fichier est toujours largement
        utilisé, par exemple, avec les archives OVF (avec l'extension de fichier
        <computeroutput>.ova</computeroutput>) ; voir <xref
        linkend="ovf" />.</para>
      </glossdef>
    </glossentry>
  </glossdiv>

  <glossdiv>
    <title>U</title>

    <glossentry>
      <glossterm>UUID</glossterm>

      <glossdef>
        <para>Un identifiant unique universel (Universally Unique Identifier) -- souvent aussi appelé GUID
        (Globally Unique Identifier) -- est une chaîne de nombres et lettres
        qui peut être calculée dynamiquement et qui garantie son unicité.
        En général, c'est utilisé comme un identifiant global d'un composant.
        VirtualBox emploie les UUIDs pour identifier les VMs, les images de disque virtuel
        (fichiers VDI) et autres composants.</para>
      </glossdef>
    </glossentry>
  </glossdiv>

  <glossdiv>
    <title>V</title>

    <glossentry>
      <glossterm>VM</glossterm>

      <glossdef>
        <para>Machine virtuelle -- un ordinateur virtuel que VirtualBox fait tourner
        dans la véritable machine. Voir <xref
        linkend="virtintro" /> pour le detail.</para>
      </glossdef>
    </glossentry>

    <glossentry>
      <glossterm>VMM</glossterm>

      <glossdef>
        <para>Virtual Machine Manager -- le composant de VirtualBox qui
        contrôle l'exécution des VMs. Voir <xref linkend="technical-components" /> pour
        une liste de composants VirtualBox.</para>
      </glossdef>
    </glossentry>

    <glossentry>
      <glossterm>VRDE</glossterm>

      <glossdef>
        <para>VirtualBox Remote Desktop Extension. Cette interface est intégrée
        à VirtualBox pour permettre aux paquets d'extension VirtualBox de fournir
        aux machines virtuelles un accès à distance. Un paquet d'extension de VirtualBox
        d'Oracle implémente VRDP; voir <xref linkend="vrde" /> pour le
        detail.</para>
      </glossdef>
    </glossentry>

    <glossentry>
      <glossterm>VRDP</glossterm>

      <glossdef>
        <para>Voir RDP.</para>
      </glossdef>
    </glossentry>

    <glossentry>
      <glossterm>VT-x</glossterm>

      <glossdef>
        <para>La capacité de virtualisation matérielle implémentée dans les processeurs Intel
        récents. Voir <xref linkend="hwvirt" />.</para>
      </glossdef>
    </glossentry>
  </glossdiv>

  <glossdiv>
    <title>X</title>

    <glossentry>
      <glossterm>XML</glossterm>

      <glossdef>
        <para>eXtensible Markup Language, un métastandard pour toute sorte
        d'information textuelle. XML spécifie seulement comment les données dans un document sont
        organisées en général et ne préscrit pas la manière d'organiser
        le contenu sémantiquement.</para>
      </glossdef>
    </glossentry>

    <glossentry>
      <glossterm>XPCOM</glossterm>

      <glossdef>
        <para>Mozilla Cross Platform Component Object Model, un environnement
        de programmation développé par le projet de navigateur Mozilla qui est
        similaire au COM de Microsoft et permet aux applications de fournir une interface
        de programmation modulaire. VirtualBox emploie XPCOM sur Linux à la fois
        en interne et en externe pour fournir une API complète aux développeurs
        externes.</para>
      </glossdef>
    </glossentry>
  </glossdiv>
</glossary>


text:
class CamaleonCms::Theme < CamaleonCms::TermTaxonomy
  # attrs:
  #   slug => plugin key
  cama_define_common_relationships('Theme')
  belongs_to :site, class_name: "CamaleonCms::Site", foreign_key: :parent_id

  default_scope { where(taxonomy: :theme) }

  before_validation :fix_name
  before_destroy :destroy_custom_fields

  # return theme settings configured in config.json
  def settings
    PluginRoutes.theme_info(self.slug)
  end

  # return the path to the settings file for current theme
  def settings_file
    File.join(self.settings["path"], "views/admin/settings.html.erb").to_s
  end

  private
  def fix_name
    self.name = self.slug unless self.name.present?
  end

  def destroy_custom_fields
    self.get_field_groups.destroy_all
  end

end


text:
import { Box, Clickable, HTML, Text } from "@artsy/palette"
import React from "react"
import PropTypes from "prop-types"
import { ArtworkCaption } from "./ArtworkCaption"
import { Media } from "Utils/Responsive"

interface CaptionProps {
  section?: any // TODO: What am I?
  total: number
  index: number
  open: boolean
}

export const Caption: React.FC<CaptionProps> = (
  { index, open, section, total },
  context
) => {
  const isArtwork = section.type === "artwork"

  return (
    <>
      <Media lessThan="sm">
        <Box p={2} bg="black5">
          <Clickable
            display="flex"
            width="100%"
            onClick={context.onToggleCaption}
          >
            <Text
              flex="1"
              variant="caption"
              textAlign="left"
              style={{ textDecoration: "underline" }}
            >
              {open ? "Hide" : "View Caption"}
            </Text>

            <Text variant="caption">
              {index} of {total}
            </Text>
          </Clickable>

          {open && (
            <Box pt={2}>
              {isArtwork ? (
                <ArtworkCaption display="flex" flex="1" section={section} />
              ) : (
                <HTML variant="caption" html={section.caption} />
              )}
            </Box>
          )}
        </Box>
      </Media>

      <Media greaterThanOrEqual="sm">
        <Box
          position="relative"
          zIndex={2}
          display="flex"
          px={6}
          py={3}
          bg="black5"
        >
          <Box flex="1">
            {isArtwork ? (
              <ArtworkCaption display="flex" flex="1" section={section} />
            ) : (
              <HTML variant="caption" html={section.caption} />
            )}
          </Box>

          <Text variant="caption" pl={2}>
            {index} of {total}
          </Text>
        </Box>
      </Media>
    </>
  )
}

Caption.contextTypes = {
  onToggleCaption: PropTypes.func,
}