text:
function getFullName() {
	return this.firstName + " " + this.lastName;
}

var person1 = {
	firstName: "Bob",
	lastName: "Smith",
	// property named 'getFullName' referencing the 'getFullName' function object above
	getFullName: getFullName
};

var person2 = {
	firstName: "Tim",
	lastName: "Johnson",
	// property named 'getFullName' referencing the 'getFullName' function object above
	getFullName: getFullName
};

// outputs "Bob Smith"
console.log(person1.getFullName());

// outputs "Tim Johnson"
console.log(person2.getFullName());

// outputs "true" because both properties point to the same function
console.log(person1.getFullName === person2.getFullName);

redpajama_set_name: RedPajamaGithub


text:
import 'isomorphic-fetch'

const API_ROOT = 'http://localhost:3001/'

export function callApi(endpoint, schema) {
  const fullUrl = (endpoint.indexOf(API_ROOT) === -1) ? API_ROOT + endpoint : endpoint

  return fetch(fullUrl)
    .then(response =>
      response.json().then(json => ({ json, response }))
    ).then(({ json, response }) => {
      if (!response.ok) {
        return Promise.reject(json)
      }
      return Object.assign({}, {data: json})
    })
    .then(
      response => ({response}),
      error => ({error: error})
    )
}


text:
HealthComponent* health_component_new(Entity entity, i32 maxHealth) {
    HealthComponent* self = CALLOC(1, HealthComponent);

    component_init((Component*)self, COMPONENT_HEALTH, sizeof(HealthComponent), entity);

    self->maxHealth = maxHealth;
    self->currentHealth = maxHealth;

    return self;
}

COMPONENT_DESERIALIZE(COMPONENT_HEALTH) {
    i32 max = CONFIG_GET(int)(config, table, "max_health");
    return (Component*)health_component_new(0, max);
}

COMPONENT_FREE(COMPONENT_HEALTH) {}

COMPONENT_COPY(COMPONENT_HEALTH) {}

void health_component_on_collision_enter(Component* component, const Message msg) {
    HealthComponent* self = (HealthComponent*)component;

    self->currentHealth -= 40;
}


text:
import Utils from './utils';
import { doc } from './consts';

/**
 * Collection of event-related methods.
 */
const Events = {
  /**
   * Method for adding a callback for when the DOM has loaded.
   * @param {Function} callback Function to call when document is ready
   * @param {Boolean=} capture True or false to capture this event callback before others
   */
  ready(callback, capture) {
    doc.addEventListener('DOMContentLoaded', callback, capture || false);
  },

  /**
   * Method for triggering events on an element.
   * @param {Element} element Element on which to trigger events
   * @param {Array} types Array of strings representing event names
   */
  trigger(element, types) {
    let event;

    Utils.each(types, (type) => {
      // Create custom event
      event = doc.createEvent('Event');

      // Set properties of custom event
      event.initEvent(type, true, true);

      // Dispatch (trigger) event on element
      element.dispatchEvent(event);
    });
  },
};

// Export collection of methods
export default Events;


text:
package io.quarkus.vertx.graphql.it;

import static io.restassured.RestAssured.given;
import static java.lang.String.format;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

import org.eclipse.microprofile.config.ConfigProvider;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;

import io.quarkus.test.junit.QuarkusTest;
import io.restassured.http.ContentType;
import io.vertx.core.Vertx;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.http.HttpClient;
import io.vertx.core.http.WebSocket;
import io.vertx.core.http.WebSocketConnectOptions;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.handler.graphql.ApolloWSMessageType;

@QuarkusTest
class VertxGraphqlTest {
    private static Vertx vertx;

    public static int getPortFromConfig() {
        return ConfigProvider.getConfig().getOptionalValue("quarkus.http.test-port", Integer.class).orElse(8081);
    }

    @BeforeAll
    public static void initializeVertx() {
        vertx = Vertx.vertx();
    }

    @AfterAll
    public static void closeVertx() throws InterruptedException {
        CountDownLatch latch = new CountDownLatch(1);
        vertx.close((h) -> latch.countDown());
        latch.await();
    }

    @Test
    public void testGraphQlQuery() {
        given().contentType(ContentType.JSON).body("{ \"query\" : \"{ hello }\" }")
                .when().post("/graphql")
                .then().log().ifValidationFails().statusCode(200).body("data.hello", is("world"));
    }

    @Test
    public void testWebSocketSubProtocol() throws Exception {
        HttpClient httpClient = vertx.createHttpClient();
        WebSocketConnectOptions options = new WebSocketConnectOptions().setPort(getPortFromConfig())
                .addSubProtocol("graphql-ws").setURI("/graphql");
        JsonObject init = new JsonObject().put("type", ApolloWSMessageType.CONNECTION_INIT.getText());
        String graphql = "{\"id\" : \"2\", \"type\" : \"start\", \"payload\" : { \"query\" : \"{ hello }\" } }";
        CompletableFuture<JsonObject> wsFuture = new CompletableFuture<>();
        wsFuture.whenComplete((r, t) -> httpClient.close());

        /*
         * Protocol:
         * --> connection_init -->
         * <-- connection_ack <--
         * <-- ka (keep-alive) <--
         * -----> start ------>
         * <----- data <-------
         */

        httpClient.webSocket(options, ws -> {
            AtomicReference<String> lastReceivedType = new AtomicReference<>();
            if (ws.succeeded()) {
                WebSocket webSocket = ws.result();
                webSocket.handler(message -> {
                    if (lastReceivedType.compareAndSet(null, ApolloWSMessageType.CONNECTION_ACK.getText())) {
                        // Go ack, wait for the next message (ka)
                    } else if (lastReceivedType.compareAndSet("connection_ack",
                            ApolloWSMessageType.CONNECTION_KEEP_ALIVE.getText())) {
                        webSocket.write(Buffer.buffer(graphql));
                    } else {
                        JsonObject json = message.toJsonObject();
                        String type = json.getString("type");
                        if (ApolloWSMessageType.DATA.getText().equals(type)) {
                            wsFuture.complete(message.toJsonObject());
                        } else {
                            wsFuture.completeExceptionally(new RuntimeException(
                                    format("Unexpected message type: %s\nMessage: %s", type, message.toString())));
                        }
                    }
                });
                webSocket.write(init.toBuffer());
            } else {
                wsFuture.completeExceptionally(ws.cause());
            }
        });

        JsonObject json = wsFuture.get(1, TimeUnit.MINUTES);
        assertNotNull(json);
        assertEquals("2", json.getString("id"));
        assertEquals("data", json.getString("type"));
        assertEquals("world", json.getJsonObject("payload").getJsonObject("data").getString("hello"));
    }

}


text:
package ld

// ToRDF adds RDF triples for each graph in the current node map to an RDF dataset.
func (api *JsonLdApi) ToRDF(input interface{}, opts *JsonLdOptions) (*RDFDataset, error) {
	issuer := NewIdentifierIssuer("_:b")

	nodeMap := make(map[string]interface{})
	nodeMap["@default"] = make(map[string]interface{})
	if _, err := api.GenerateNodeMap(input, nodeMap, "@default", issuer, "", "", nil); err != nil {
		return nil, err
	}

	dataset := NewRDFDataset()

	for graphName, graphVal := range nodeMap {
		// 4.1)
		if IsRelativeIri(graphName) {
			continue
		}
		graph := graphVal.(map[string]interface{})
		dataset.GraphToRDF(graphName, graph, issuer, opts.ProduceGeneralizedRdf)
	}

	return dataset, nil
}


text:
# $Revision: 1650 $
# $Date: 2005-07-20 00:18:17 -0300 (Wed, 20 Jul 2005) $

CREATE TABLE ofUser (
  username              VARCHAR(64)     NOT NULL,
  plainPassword         VARCHAR(32),
  encryptedPassword     VARCHAR(255),
  name                  VARCHAR(100),
  email                 VARCHAR(100),
  creationDate          CHAR(15)        NOT NULL,
  modificationDate      CHAR(15)        NOT NULL,
  PRIMARY KEY (username),
  INDEX ofUser_cDate_idx (creationDate)
);

CREATE TABLE ofUserProp (
  username              VARCHAR(64)     NOT NULL,
  name                  VARCHAR(100)    NOT NULL,
  propValue             TEXT            NOT NULL,
  PRIMARY KEY (username, name)
);

CREATE TABLE ofUserFlag (
  username              VARCHAR(64)     NOT NULL,
  name                  VARCHAR(100)    NOT NULL,
  startTime             CHAR(15),
  endTime               CHAR(15),
  PRIMARY KEY (username, name),
  INDEX ofUserFlag_sTime_idx (startTime),
  INDEX ofUserFlag_eTime_idx (endTime)
);

CREATE TABLE ofPrivate (
  username              VARCHAR(64)     NOT NULL,
  name                  VARCHAR(100)    NOT NULL,
  namespace             VARCHAR(200)    NOT NULL,
  privateData           TEXT            NOT NULL,
  PRIMARY KEY (username, name, namespace(100))
);

CREATE TABLE ofOffline (
  username              VARCHAR(200)     NOT NULL,
  messageID             BIGINT          NOT NULL,
  creationDate          CHAR(15)        NOT NULL,
  messageSize           INTEGER         NOT NULL,
  packetId              VARCHAR(100)    DEFAULT NULL,
  stanza                MEDIUMTEXT      NOT NULL,
  PRIMARY KEY (username, messageID)
);

CREATE TABLE ofPresence (
  username              VARCHAR(64)     NOT NULL,
  offlinePresence       TEXT,
  offlineDate           CHAR(15)     NOT NULL,
  PRIMARY KEY (username)
);

CREATE TABLE ofRoster (
  rosterID              BIGINT          NOT NULL,
  username              VARCHAR(64)     NOT NULL,
  jid                   VARCHAR(1024)   NOT NULL,
  sub                   TINYINT         NOT NULL,
  ask                   TINYINT         NOT NULL,
  recv                  TINYINT         NOT NULL,
  nick                  VARCHAR(255),
  PRIMARY KEY (rosterID),
  INDEX ofRoster_unameid_idx (username),
  INDEX ofRoster_jid_idx (jid(255))
);

CREATE TABLE ofRosterGroups (
  rosterID              BIGINT          NOT NULL,
  rank                  TINYINT         NOT NULL,
  groupName             VARCHAR(255)    NOT NULL,
  PRIMARY KEY (rosterID, rank),
  INDEX ofRosterGroup_rosterid_idx (rosterID)
);

CREATE TABLE ofVCard (
  username              VARCHAR(64)     NOT NULL,
  vcard                 MEDIUMTEXT      NOT NULL,
  PRIMARY KEY (username)
);

CREATE TABLE ofGroup (
  groupName             VARCHAR(50)     NOT NULL,
  description           VARCHAR(255),
  PRIMARY KEY (groupName)
);

CREATE TABLE ofGroupProp (
  groupName             VARCHAR(50)     NOT NULL,
  name                  VARCHAR(100)    NOT NULL,
  propValue             TEXT            NOT NULL,
  PRIMARY KEY (groupName, name)
);

CREATE TABLE ofGroupUser (
  groupName             VARCHAR(50)     NOT NULL,
  username              VARCHAR(100)    NOT NULL,
  administrator         TINYINT         NOT NULL,
  PRIMARY KEY (groupName, username, administrator)
);

CREATE TABLE ofID (
  idType                INTEGER         NOT NULL,
  id                    BIGINT          NOT NULL,
  PRIMARY KEY (idType)
);

CREATE TABLE ofProperty (
  name        VARCHAR(100)              NOT NULL,
  propValue   TEXT                      NOT NULL,
  PRIMARY KEY (name)
);

CREATE TABLE ofVersion (
  name     VARCHAR(50)  NOT NULL,
  version  INTEGER  NOT NULL,
  PRIMARY KEY (name)
);

CREATE TABLE ofExtComponentConf (
  subdomain             VARCHAR(255)    NOT NULL,
  wildcard              TINYINT         NOT NULL,
  secret                VARCHAR(255),
  permission            VARCHAR(10)     NOT NULL,
  PRIMARY KEY (subdomain)
);

CREATE TABLE ofRemoteServerConf (
  xmppDomain            VARCHAR(255)    NOT NULL,
  remotePort            INTEGER,
  permission            VARCHAR(10)     NOT NULL,
  PRIMARY KEY (xmppDomain)
);

CREATE TABLE ofPrivacyList (
  username              VARCHAR(64)     NOT NULL,
  name                  VARCHAR(100)    NOT NULL,
  isDefault             TINYINT         NOT NULL,
  list                  TEXT            NOT NULL,
  PRIMARY KEY (username, name),
  INDEX ofPrivacyList_default_idx (username, isDefault)
);

CREATE TABLE ofSASLAuthorized (
  username            VARCHAR(64)   NOT NULL,
  principal           TEXT          NOT NULL,
  PRIMARY KEY (username, principal(200))
);

CREATE TABLE ofSecurityAuditLog (
  msgID                 BIGINT          NOT NULL,
  username              VARCHAR(64)     NOT NULL,
  entryStamp            BIGINT          NOT NULL,
  summary               VARCHAR(255)    NOT NULL,
  node                  VARCHAR(255)    NOT NULL,
  details               TEXT,
  PRIMARY KEY (msgID),
  INDEX ofSecurityAuditLog_tstamp_idx (entryStamp),
  INDEX ofSecurityAuditLog_uname_idx (username)
);

# MUC Tables

CREATE TABLE ofMucService (
  serviceID           BIGINT        NOT NULL,
  subdomain           VARCHAR(255)  NOT NULL,
  description         VARCHAR(255),
  isHidden            TINYINT       NOT NULL,
  PRIMARY KEY (subdomain),
  INDEX ofMucService_serviceid_idx (serviceID)
);

CREATE TABLE ofMucServiceProp (
  serviceID           BIGINT        NOT NULL,
  name                VARCHAR(100)  NOT NULL,
  propValue           TEXT          NOT NULL,
  PRIMARY KEY (serviceID, name)
);

CREATE TABLE ofMucRoom (
  serviceID           BIGINT        NOT NULL,
  roomID              BIGINT        NOT NULL,
  creationDate        CHAR(15)      NOT NULL,
  modificationDate    CHAR(15)      NOT NULL,
  name                VARCHAR(50)   NOT NULL,
  naturalName         VARCHAR(255)  NOT NULL,
  description         VARCHAR(255),
  lockedDate          CHAR(15)      NOT NULL,
  emptyDate           CHAR(15)      NULL,
  canChangeSubject    TINYINT       NOT NULL,
  maxUsers            INTEGER       NOT NULL,
  publicRoom          TINYINT       NOT NULL,
  moderated           TINYINT       NOT NULL,
  membersOnly         TINYINT       NOT NULL,
  canInvite           TINYINT       NOT NULL,
  roomPassword        VARCHAR(50)   NULL,
  canDiscoverJID      TINYINT       NOT NULL,
  logEnabled          TINYINT       NOT NULL,
  subject             VARCHAR(100)  NULL,
  rolesToBroadcast    TINYINT       NOT NULL,
  useReservedNick     TINYINT       NOT NULL,
  canChangeNick       TINYINT       NOT NULL,
  canRegister         TINYINT       NOT NULL,
  PRIMARY KEY (serviceID,name),
  INDEX ofMucRoom_roomid_idx (roomID),
  INDEX ofMucRoom_serviceid_idx (serviceID)
);

CREATE TABLE ofMucRoomProp (
  roomID                BIGINT          NOT NULL,
  name                  VARCHAR(100)    NOT NULL,
  propValue             TEXT            NOT NULL,
  PRIMARY KEY (roomID, name)
);

CREATE TABLE ofMucAffiliation (
  roomID              BIGINT        NOT NULL,
  jid                 TEXT          NOT NULL,
  affiliation         TINYINT       NOT NULL,
  PRIMARY KEY (roomID,jid(70))
);

CREATE TABLE ofMucMember (
  roomID              BIGINT        NOT NULL,
  jid                 TEXT          NOT NULL,
  nickname            VARCHAR(255)  NULL,
  firstName           VARCHAR(100)  NULL,
  lastName            VARCHAR(100)  NULL,
  url                 VARCHAR(100)  NULL,
  email               VARCHAR(100)  NULL,
  faqentry            VARCHAR(100)  NULL,
  PRIMARY KEY (roomID,jid(70))
);

CREATE TABLE ofMucConversationLog (
  roomID              BIGINT        NOT NULL,
  sender              TEXT          NOT NULL,
  nickname            VARCHAR(255)  NULL,
  logTime             CHAR(15)      NOT NULL,
  subject             VARCHAR(255)  NULL,
  body                TEXT          NULL,
  INDEX ofMucConversationLog_time_idx (logTime)
);

# PubSub Tables

CREATE TABLE ofPubsubNode (
  serviceID           VARCHAR(100)  NOT NULL,
  nodeID              VARCHAR(100)  NOT NULL,
  leaf                TINYINT       NOT NULL,
  creationDate        CHAR(15)      NOT NULL,
  modificationDate    CHAR(15)      NOT NULL,
  parent              VARCHAR(100)  NULL,
  deliverPayloads     TINYINT       NOT NULL,
  maxPayloadSize      INTEGER       NULL,
  persistItems        TINYINT       NULL,
  maxItems            INTEGER       NULL,
  notifyConfigChanges TINYINT       NOT NULL,
  notifyDelete        TINYINT       NOT NULL,
  notifyRetract       TINYINT       NOT NULL,
  presenceBased       TINYINT       NOT NULL,
  sendItemSubscribe   TINYINT       NOT NULL,
  publisherModel      VARCHAR(15)   NOT NULL,
  subscriptionEnabled TINYINT       NOT NULL,
  configSubscription  TINYINT       NOT NULL,
  accessModel         VARCHAR(10)   NOT NULL,
  payloadType         VARCHAR(100)  NULL,
  bodyXSLT            VARCHAR(100)  NULL,
  dataformXSLT        VARCHAR(100)  NULL,
  creator             VARCHAR(255) NOT NULL,
  description         VARCHAR(255)  NULL,
  language            VARCHAR(255)  NULL,
  name                VARCHAR(50)   NULL,
  replyPolicy         VARCHAR(15)   NULL,
  associationPolicy   VARCHAR(15)   NULL,
  maxLeafNodes        INTEGER       NULL,
  PRIMARY KEY (serviceID, nodeID)
);

CREATE TABLE ofPubsubNodeJIDs (
  serviceID           VARCHAR(100)  NOT NULL,
  nodeID              VARCHAR(100)  NOT NULL,
  jid                 VARCHAR(255)  NOT NULL,
  associationType     VARCHAR(20)   NOT NULL,
  PRIMARY KEY (serviceID, nodeID, jid(70))
);

CREATE TABLE ofPubsubNodeGroups (
  serviceID           VARCHAR(100)  NOT NULL,
  nodeID              VARCHAR(100)  NOT NULL,
  rosterGroup         VARCHAR(100)   NOT NULL,
  INDEX ofPubsubNodeGroups_idx (serviceID, nodeID)
);

CREATE TABLE ofPubsubAffiliation (
  serviceID           VARCHAR(100)  NOT NULL,
  nodeID              VARCHAR(100)  NOT NULL,
  jid                 VARCHAR(255) NOT NULL,
  affiliation         VARCHAR(10)   NOT NULL,
  PRIMARY KEY (serviceID, nodeID, jid(70))
);

CREATE TABLE ofPubsubItem (
  serviceID           VARCHAR(100)  NOT NULL,
  nodeID              VARCHAR(100)  NOT NULL,
  id                  VARCHAR(100)  NOT NULL,
  jid                 VARCHAR(255)  NOT NULL,
  creationDate        CHAR(15)      NOT NULL,
  payload             MEDIUMTEXT    NULL,
  PRIMARY KEY (serviceID, nodeID, id)
);

CREATE TABLE ofPubsubSubscription (
  serviceID           VARCHAR(100)  NOT NULL,
  nodeID              VARCHAR(100)  NOT NULL,
  id                  VARCHAR(100)  NOT NULL,
  jid                 VARCHAR(255) NOT NULL,
  owner               VARCHAR(255) NOT NULL,
  state               VARCHAR(15)   NOT NULL,
  deliver             TINYINT       NOT NULL,
  digest              TINYINT       NOT NULL,
  digest_frequency    INT           NOT NULL,
  expire              CHAR(15)      NULL,
  includeBody         TINYINT       NOT NULL,
  showValues          VARCHAR(30)   NULL,
  subscriptionType    VARCHAR(10)   NOT NULL,
  subscriptionDepth   TINYINT       NOT NULL,
  keyword             VARCHAR(200)  NULL,
  PRIMARY KEY (serviceID, nodeID, id)
);

CREATE TABLE ofPubsubDefaultConf (
  serviceID           VARCHAR(100)  NOT NULL,
  leaf                TINYINT       NOT NULL,
  deliverPayloads     TINYINT       NOT NULL,
  maxPayloadSize      INTEGER       NOT NULL,
  persistItems        TINYINT       NOT NULL,
  maxItems            INTEGER       NOT NULL,
  notifyConfigChanges TINYINT       NOT NULL,
  notifyDelete        TINYINT       NOT NULL,
  notifyRetract       TINYINT       NOT NULL,
  presenceBased       TINYINT       NOT NULL,
  sendItemSubscribe   TINYINT       NOT NULL,
  publisherModel      VARCHAR(15)   NOT NULL,
  subscriptionEnabled TINYINT       NOT NULL,
  accessModel         VARCHAR(10)   NOT NULL,
  language            VARCHAR(255)  NULL,
  replyPolicy         VARCHAR(15)   NULL,
  associationPolicy   VARCHAR(15)   NOT NULL,
  maxLeafNodes        INTEGER       NOT NULL,
  PRIMARY KEY (serviceID, leaf)
);

# Finally, insert default table values.

INSERT INTO ofID (idType, id) VALUES (18, 1);
INSERT INTO ofID (idType, id) VALUES (19, 1);
INSERT INTO ofID (idType, id) VALUES (23, 1);
INSERT INTO ofID (idType, id) VALUES (26, 2);

INSERT INTO ofVersion (name, version) VALUES ('openfire', 21);

# Entry for admin user
INSERT INTO ofUser (username, plainPassword, name, email, creationDate, modificationDate)
    VALUES ('admin', 'admin', 'Administrator', 'admin@example.com', '0', '0');

# Entry for default conference service
INSERT INTO ofMucService (serviceID, subdomain, isHidden) VALUES (1, 'conference', 0);

insert into ofProperty values ('provider.lockout.className', 'com.magnet.mmx.lockout.MmxLockoutProvider');

insert into ofProperty values ('xmpp.parser.buffer.size', '2097152');

insert into ofProperty values('xmpp.routing.strict', 'true');

insert into ofProperty values('xmpp.client.idle', '-1');

insert into ofProperty values('xmpp.client.idle.ping', 'false');
# $Revision$
# $Date$

INSERT INTO ofVersion (name, version) VALUES ('mmxappmgmt', 0);

CREATE TABLE mmxApp (
  id                INT           NOT NULL AUTO_INCREMENT PRIMARY KEY,
  serverUserId      VARCHAR(200),
  appName           VARCHAR(100)  NOT NULL,
  appId             VARCHAR(16)   NOT NULL, /* appId is a string of 16 characters */
  apiKey            VARCHAR(100)  DEFAULT NULL,
  encryptedApiKey   VARCHAR(255)  DEFAULT NULL,
  googleApiKey      VARCHAR(100),
  googleProjectId   VARCHAR(100),
  apnsCert          VARBINARY(5000), /* in .p12 binary file format */
  apnsCertPlainPassword VARCHAR(100)      DEFAULT NULL,
  apnsCertEncryptedPassword VARCHAR(255)  DEFAULT NULL,
  creationDate      datetime      NOT NULL,
  modificationDate  datetime     NULL,
  ownerId           VARCHAR(200),
  ownerEmail        VARCHAR(255) DEFAULT NULL,
  guestUserId       VARCHAR(200),
  guestSecret       VARCHAR(255),
  UNIQUE KEY `mmxApp_appId` (`appId`)
);

CREATE INDEX mmxApp_serverUserJJID ON mmxApp(serverUserId);
CREATE INDEX mmxApp_apiKey ON mmxApp(apiKey);

CREATE TABLE mmxDevice (
  id            int(11)        NOT NULL AUTO_INCREMENT,
  name          varchar(100)   NOT NULL,           /* display name of the device */
  ownerJid     varchar(200)    NOT NULL,           /* bare user identifier       */
  appId        varchar(16)    NOT NULL,
  osType       varchar(20)     NOT NULL,           /* os type of the device (iOS,ANDRIOD) */
  deviceId     varchar(50)     NOT NULL,           /* deviceId                            */
  tokenType    varchar(10),           /* token type */
  clientToken  varchar(500),          /* client token for push notifications */
  versionInfo  varchar(20),           /* version string for the OS */
  modelInfo    varchar(200),          /* model info */
  phoneNumber  varchar(20),           /* phoneNumber */
  phoneNumberRev  varchar(20),        /* phoneNumber reversed */
  carrierInfo  varchar(20),           /* carrier information */
  dateCreated  datetime     NOT NULL,
  dateUpdated  datetime     NULL,
  status        varchar(20) NOT NULL DEFAULT 'ACTIVE',
  PRIMARY KEY (id),
  UNIQUE KEY `devicid_type_osType_appid` (`deviceId`,`osType`, `appId`)
);

CREATE TABLE mmxMessage (
  id               int(11)         NOT NULL AUTO_INCREMENT,
  messageId        varchar(100)    NOT NULL,
  deviceId         varchar(50)     NOT NULL, /* deviceId */
  fromJID          varchar(200)    NOT NULL, /* from JID */
  toJID            varchar(200)    NOT NULL, /* to JID   */
  dateQueued       datetime        NOT NULL,
  state            varchar(50)     NOT NULL,
  appId            varchar(16)     NOT NULL,
  dateAcknowledged datetime,
  sourceMessageId  varchar(100),
  messageType      varchar(50),
  PRIMARY KEY (id)
  );

CREATE INDEX mmxMessage_messageId ON mmxMessage(messageId);

 CREATE TABLE mmxWakeupQueue (
    id              int(11)        NOT NULL AUTO_INCREMENT,
    deviceId        varchar(50)    NOT NULL, /* deviceId */
    clientToken     varchar(500),            /* client token for push notifications */
    tokenType       varchar(10),
    googleApiKey    varchar(100),
    payload         varchar(400)   NOT NULL,
    messageId       varchar(100)   NOT NULL,
    dateCreated     datetime,
    dateSent        datetime,     /* date when we sent the wakeup */
    PRIMARY KEY (id)
 );

CREATE INDEX mmxWakeupQueue_dateCreated ON mmxWakeupQueue(dateCreated);

CREATE INDEX mmxWakeupQueue_dateSent ON mmxWakeupQueue(dateSent);

/* TABLE for maintaining the push messages */
 CREATE TABLE mmxPushMessage (
    messageId   varchar(50)     NOT NULL,
    deviceId    varchar(50)     NOT NULL,   /* deviceId that is target for this push message */
    appId       varchar(16)     NOT NULL,   /* appId */
    dateSent    datetime        NOT NULL,   /* date when sent */
    dateAcknowledged    datetime,           /* date when receiver acknowledged the message */
    type        varchar(16)     NOT NULL,   /* type : consoleping, ping, pingpong, other */
    state       varchar(50)     NOT NULL,   /* PUSHED and ACKNOWLEDGED */
    PRIMARY KEY (messageId)
 );

 /* Table for mapping topics to roles that are allowed access to the topic */
 CREATE TABLE mmxTopicRole (
     id           INT             NOT NULL AUTO_INCREMENT PRIMARY KEY,
     serviceID    VARCHAR(100)    NOT NULL,
     nodeID       VARCHAR(100)    NOT NULL,
     role         VARCHAR(100)    NOT NULL,
     creationDate datetime        NOT NULL,
     FOREIGN KEY (serviceID, nodeID) REFERENCES ofPubsubNode(serviceID, nodeID) ON DELETE CASCADE
 );

 ALTER TABLE mmxTopicRole ADD UNIQUE KEY `mmxTopicRole_uk` (serviceID, nodeID, role);

 INSERT INTO mmxTopicRole (serviceID, nodeID, role, creationDate)
 SELECT serviceID,nodeID,'PUBLIC', now() FROM ofPubsubNode WHERE nodeID IS NOT NULL;


text:
/* This is a patched version of a file from pocketsphinx.js */

#include "psRecognizer.h"
#include "pocketsphinx.h"
#include "pocketsphinxjs-config.h"

#define MAX_NUM_GRAMMARS 1000

namespace pocketsphinxjs {
  typedef std::map<std::string, std::string> StringsMapType;
  typedef std::map<std::string, std::string>::iterator StringsMapIterator;

  // Implemented later in this file
  ReturnType parseStringList(const std::string &, StringsSetType*, std::string*);

  Recognizer::Recognizer(): grammar_names(MAX_NUM_GRAMMARS), is_fsg(true), is_recording(false), current_hyp(""), grammar_index(0) {
    Config c;
    if (init(c) != SUCCESS) cleanup();
  }

  Recognizer::Recognizer(const Config& config) : grammar_names(MAX_NUM_GRAMMARS), is_fsg(true), is_recording(false), current_hyp(""), grammar_index(0) {
    if (init(config) != SUCCESS) cleanup();
  }

  ReturnType Recognizer::reInit(const Config& config) {
    ReturnType r = init(config);
    if (r != SUCCESS) cleanup();
    return r;
  }

  ReturnType Recognizer::addWords(const std::vector<Word>& words) {
    if (decoder == NULL) return BAD_STATE;
    for (int i=0 ; i<words.size() ; ++i) {
      // This case is not properly handeled by ps_add_word, so we treat it separately
      if (words.at(i).pronunciation.size() == 0) return RUNTIME_ERROR;
      if (ps_add_word(decoder, words.at(i).word.c_str(), words.at(i).pronunciation.c_str(), 1) < 0) return RUNTIME_ERROR;
    }
    return SUCCESS;
  }

  ReturnType Recognizer::addGrammar(Integers& id, const Grammar& grammar) {
    if (decoder == NULL) return BAD_STATE;
    std::ostringstream grammar_name;
    grammar_name << grammar_index;
    grammar_names.push_back(grammar_name.str());
    current_grammar = fsg_model_init(grammar_names.back().c_str(), logmath, 1.0, grammar.numStates);
    if (current_grammar == NULL)
      return RUNTIME_ERROR;
    current_grammar->start_state = grammar.start;
    current_grammar->final_state = grammar.end;
    for (int i=0;i<grammar.transitions.size();i++) {
      if (grammar.transitions.at(i).word.size() == 0)
	fsg_model_null_trans_add(current_grammar, grammar.transitions.at(i).from, grammar.transitions.at(i).to, grammar.transitions.at(i).logp);
      else
	fsg_model_trans_add(current_grammar, grammar.transitions.at(i).from, grammar.transitions.at(i).to, grammar.transitions.at(i).logp, fsg_model_word_add(current_grammar, grammar.transitions.at(i).word.c_str()));
    }
    fsg_model_add_silence(current_grammar, "<sil>", -1, 1.0);

    if(ps_set_fsg(decoder, grammar_names.back().c_str(), current_grammar)) {
      return RUNTIME_ERROR;
    }
    if (id.size() == 0) id.push_back(grammar_index);
    else id.at(0) = grammar_index;
    grammar_index++;
    // We switch to the newly added grammar right away
    if (ps_set_search(decoder, grammar_names.back().c_str())) {
      return RUNTIME_ERROR;
    }
    return SUCCESS;
  }

  ReturnType Recognizer::addKeyword(Integers& id, const std::string& keyphrase) {
    if (decoder == NULL) return BAD_STATE;
    std::ostringstream search_name;
    search_name << grammar_index;
    grammar_names.push_back(search_name.str());
    if(ps_set_keyphrase(decoder, grammar_names.back().c_str(), keyphrase.c_str())) {
      return RUNTIME_ERROR;
    }
    if (id.size() == 0) id.push_back(grammar_index);
    else id.at(0) = grammar_index;
    grammar_index++;
    // We switch to the newly added search right away
    if (ps_set_search(decoder, grammar_names.back().c_str())) {
      return RUNTIME_ERROR;
    }
    return SUCCESS;

    return SUCCESS;
  }

  ReturnType Recognizer::switchGrammar(int id) {
    return switchSearch(id);
  }

  ReturnType Recognizer::switchSearch(int id) {
    if (decoder == NULL) return BAD_STATE;
    std::ostringstream search_name;
    search_name << id;
    if(ps_set_search(decoder, search_name.str().c_str())) {
      return RUNTIME_ERROR;
    }
    return SUCCESS;
  }

  ReturnType Recognizer::start() {
    if ((decoder == NULL) || (is_recording)) return BAD_STATE;
    if (ps_start_utt(decoder, NULL) < 0) {
      return RUNTIME_ERROR;
    }
    current_hyp = "";
    is_recording = true;
    return SUCCESS;
  }

  ReturnType Recognizer::stop() {
    if ((decoder == NULL) || (!is_recording)) return BAD_STATE;
    if (ps_end_utt(decoder) < 0) {
      return RUNTIME_ERROR;
    }
    const char* h = ps_get_hyp(decoder, NULL, &sentence_id);
    current_hyp = (h == NULL) ? "" : h;
    is_recording = false;
    return SUCCESS;
  }

  ReturnType Recognizer::process(const std::vector<int16_t>& buffer) {
    if ((decoder == NULL) || (!is_recording)) return BAD_STATE;
    if (buffer.size() == 0)
      return RUNTIME_ERROR;
    ps_process_raw(decoder, (short int *) &buffer[0], buffer.size(), 0, 0);
    const char* h = ps_get_hyp(decoder, NULL, &sentence_id);
    current_hyp = (h == NULL) ? "" : h;
    return SUCCESS;
  }

  Recognizer::~Recognizer() {
    cleanup();
  }

  std::string Recognizer::getHyp() {
    return current_hyp;
  }

  ReturnType Recognizer::getHypseg(Segmentation& seg) {
    if ((decoder == NULL) || (is_recording)) return BAD_STATE;
    seg.clear();
    int32 scoreh=0, sfh=0, efh=0;
    std::string hseg;
    ps_seg_t *itor = ps_seg_iter(decoder, &scoreh);
    while (itor) {
      SegItem segItem;
      segItem.word = ps_seg_word(itor);
      ps_seg_frames(itor, &sfh, &efh);
      segItem.start = sfh;
      segItem.end = efh;
      seg.push_back(segItem);
      itor = ps_seg_next(itor);
    }
    return SUCCESS;
  }

  void Recognizer::cleanup() {
    if (decoder) ps_free(decoder);
    if (logmath) logmath_free(logmath);
    decoder = NULL;
    logmath = NULL;
  }

  ReturnType Recognizer::init(const Config& config) {
#ifdef HMM_FOLDERS
    parseStringList(HMM_FOLDERS, &acoustic_models, &default_acoustic_model);
#endif /* HMM_FOLDERS */
#ifdef LM_FILES
    parseStringList(LM_FILES, &language_models, &default_language_model);
#endif /* LM_FILES */
#ifdef DICT_FILES
    parseStringList(DICT_FILES, &dictionaries, &default_dictionary);
#endif /* DICT_FILES */

    const arg_t cont_args_def[] = {
      POCKETSPHINX_OPTIONS,
      { "-argfile",
	ARG_STRING,
	NULL,
	"Argument file giving extra arguments." },
      { "-adcdev",
	ARG_STRING,
	NULL,
	"Name of audio device to use for input." },
      { "-infile",
	ARG_STRING,
	NULL,
	"Audio file to transcribe." },
      { "-time",
	ARG_BOOLEAN,
	"no",
	"Print word times in file transcription." },
      CMDLN_EMPTY_OPTION
    };

    std::map<std::string, std::string> parameters;
    for (int i=0 ; i< config.size() ; ++i)
      parameters[config[i].key] = config[i].value;

    if (parameters.find("-hmm") == parameters.end())
      parameters["-hmm"] = default_acoustic_model;
    if (parameters.find("-bestpath") == parameters.end())
      parameters["-bestpath"] = "no";
    if (parameters.find("-remove_noise") == parameters.end())
      parameters["-remove_noise"] = "no";

    int argc = 2 * parameters.size();
    char ** argv = new char*[argc];
    int index = 0;
    for (StringsMapIterator i = parameters.begin() ; i != parameters.end(); ++i) {
      if (i->first == "-lm") is_fsg = false;
      argv[index++] = (char*) i->first.c_str();
      argv[index++] = (char*) i->second.c_str();
    }

    cmd_ln_t * cmd_line = cmd_ln_parse_r(NULL, cont_args_def, argc, argv, FALSE);
    if (cmd_line == NULL) {
      delete [] argv;
      return RUNTIME_ERROR;
    }
    decoder = ps_init(cmd_line);
    delete [] argv;
    if (decoder == NULL) {
      return RUNTIME_ERROR;
    }
    logmath = logmath_init(1.0001, 0, 0);
    if (logmath == NULL) {
      return RUNTIME_ERROR;
    }
    return SUCCESS;
  }

  /*******************************************
   *
   * Parses the string with available models and fills in
   * the default model and the available models
   * @param string to parse, the models are separated with ";"
   * @return 0 if successful, always successful
   *
   *****************************************/
  ReturnType parseStringList(const std::string & list, StringsSetType* strings_set, std::string* default_string = NULL) {
    if ((strings_set == NULL) || (list.size() == 0))
      return BAD_ARGUMENT;
    std::string separator = ";";
    std::string::size_type index;
    std::string first_string = list.substr(0, index = list.find(separator));
    if (default_string != NULL)
      *default_string = first_string;
    strings_set->insert(first_string);
    while((index != std::string::npos) && (index != list.size() -1))
      strings_set->insert(list.substr(index+1, -1 -index +(index = list.find(separator, index + 1))));
    return SUCCESS;
  }
} // namespace pocketsphinxjs


text:
ALTER TABLE [dbo].[SpecialNeeds]
    ADD CONSTRAINT [PK_SpecialNeeds] PRIMARY KEY CLUSTERED ([id] ASC) WITH (ALLOW_PAGE_LOCKS = ON, ALLOW_ROW_LOCKS = ON, PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF, STATISTICS_NORECOMPUTE = OFF);


text:
#ifndef INCLUDED_openfl__legacy_net_URLLoader
#define INCLUDED_openfl__legacy_net_URLLoader

#ifndef HXCPP_H
#include <hxcpp.h>
#endif

#ifndef INCLUDED_openfl__legacy_events_EventDispatcher
#include <openfl/_legacy/events/EventDispatcher.h>
#endif
HX_DECLARE_CLASS3(openfl,_legacy,events,Event)
HX_DECLARE_CLASS3(openfl,_legacy,events,EventDispatcher)
HX_DECLARE_CLASS3(openfl,_legacy,events,IEventDispatcher)
HX_DECLARE_CLASS3(openfl,_legacy,net,URLLoader)
HX_DECLARE_CLASS3(openfl,_legacy,net,URLRequest)
namespace openfl{
namespace _legacy{
namespace net{

class HXCPP_CLASS_ATTRIBUTES  URLLoader_obj : public ::openfl::_legacy::events::EventDispatcher_obj{
	public:
		typedef ::openfl::_legacy::events::EventDispatcher_obj super;
		typedef URLLoader_obj OBJ_;
		URLLoader_obj();
		Void __construct(::openfl::_legacy::net::URLRequest request);

	public:
		inline void *operator new( size_t inSize, bool inContainer=true,const char *inName="openfl._legacy.net.URLLoader")
			{ return hx::Object::operator new(inSize,inContainer,inName); }
		static hx::ObjectPtr< URLLoader_obj > __new(::openfl::_legacy::net::URLRequest request);
		static Dynamic __CreateEmpty();
		static Dynamic __Create(hx::DynamicArray inArgs);
		//~URLLoader_obj();

		HX_DO_RTTI_ALL;
		Dynamic __Field(const ::String &inString, hx::PropertyAccess inCallProp);
		static bool __GetStatic(const ::String &inString, Dynamic &outValue, hx::PropertyAccess inCallProp);
		Dynamic __SetField(const ::String &inString,const Dynamic &inValue, hx::PropertyAccess inCallProp);
		static bool __SetStatic(const ::String &inString, Dynamic &ioValue, hx::PropertyAccess inCallProp);
		void __GetFields(Array< ::String> &outFields);
		static void __register();
		void __Mark(HX_MARK_PARAMS);
		void __Visit(HX_VISIT_PARAMS);
		::String __ToString() const { return HX_HCSTRING("URLLoader","\xc2","\x68","\xb3","\x41"); }

		static void __boot();
		static int urlInvalid;
		static int urlInit;
		static int urlLoading;
		static int urlComplete;
		static int urlError;
		static cpp::ArrayBase eventsQueue;
		static bool hasActive( );
		static Dynamic hasActive_dyn();

		static Void initialize( ::String caCertFilePath);
		static Dynamic initialize_dyn();

		static bool __loadPending( );
		static Dynamic __loadPending_dyn();

		static Void enqueueEvent( ::openfl::_legacy::net::URLLoader loader,::openfl::_legacy::events::Event event);
		static Dynamic enqueueEvent_dyn();

		static Void __pollData( );
		static Dynamic __pollData_dyn();

		int bytesLoaded;
		int bytesTotal;
		Dynamic data;
		Dynamic dataFormat;
		int state;
		Dynamic __handle;
		Dynamic __onComplete;
		Dynamic &__onComplete_dyn() { return __onComplete;}
		virtual Void close( );
		Dynamic close_dyn();

		virtual Void dispatchHTTPStatus( int code);
		Dynamic dispatchHTTPStatus_dyn();

		virtual Array< ::String > getCookies( );
		Dynamic getCookies_dyn();

		virtual Void load( ::openfl::_legacy::net::URLRequest request);
		Dynamic load_dyn();

		virtual Void loadInCURLThread( ::openfl::_legacy::net::URLRequest request);
		Dynamic loadInCURLThread_dyn();

		virtual Void onError( ::String msg);
		Dynamic onError_dyn();

		virtual Void update( );
		Dynamic update_dyn();

		virtual Void __dataComplete( );
		Dynamic __dataComplete_dyn();

};

} // end namespace openfl
} // end namespace _legacy
} // end namespace net

#endif /* INCLUDED_openfl__legacy_net_URLLoader */


text:
require 'socket'

MAX_MESSAGE_LENGTH = 8192 unless defined?(MAX_MESSAGE_LENGTH)# < 10K
$testwise_support = true

module RWebSpec
  module TestWisePlugin

    def debug(message)
      Thread.pass
			if $RUN_IN_TESTWISE && message
				the_sent_msg = message.to_s
				if the_sent_msg.size > MAX_MESSAGE_LENGTH
					the_sent_msg = the_sent_msg[0..MAX_MESSAGE_LENGTH] + "..."
				end
	      connect_to_testwise(" DEBUG",  the_sent_msg + "\r\n")
			end

    end

    # Support of iTest to ajust the intervals between keystroke/mouse operations
    def operation_delay
      begin

				if $TESTWISE_OPERATION_DELAY && $TESTWISE_OPERATION_DELAY > 0 &&
                $TESTWISE_OPERATION_DELAY < 30000  then # max 30 seconds
          Thread.pass
          sleep($TESTWISE_OPERATION_DELAY / 1000)
        end

        while $TESTWISE_PAUSE
          Thread.pass
          debug("Paused, waiting ...")
          sleep 1
        end
      rescue => e
        puts "Error on delaying: #{e}"
        # ignore
      end
    end

			def check_for_pause

        if $TESTWISE_READY_TO_PAUSE
          # Already executed the the line immedately above,
          # give some buffer time for TW to set $TESTWISE_PAUSE flag
          sleep 0.5
        end

				# If the executed line no change, ignore
	      while $TESTWISE_PAUSE
	          Thread.pass
	          debug("[selenium_webdriver_extension] Paused, waiting ...")
	          sleep 1
	      end
			end

    def notify_screenshot_location(image_file_path)
      begin
        connect_to_testwise("  SHOT", image_file_path)
      rescue => e
        puts "[DEBUG] failed to notify TestWise a screenshot"
      end
    end

    # find out the line (and file) the execution is on, and notify iTest via Socket
    def dump_caller_stack
      return unless ($TESTWISE_TRACE_EXECUTION)
      begin
        trace_lines = []
        trace_file = nil
        found_first_spec_reference = false
        caller.each_with_index do |position, idx|
          next unless position =~ /\A(.*?):(\d+)/
          trace_file = $1
          if trace_file =~ /(_spec|_test|_rwebspec)\.rb\s*$/ || trace_file =~ /\.feature$/
            found_first_spec_reference = true
            trace_lines << position
            break
          end
          trace_lines << position
          break if trace_file =~ /example\/example_methods\.rb$/ or trace_file =~ /example\/example_group_methods\.rb$/
          break if trace_lines.size > 10
          # TODO: send multiple trace to be parse with pages.rb
          # break if trace_file =~ /example\/example_methods\.rb$/ or trace_file =~ /example\/example_group_methods\.rb$/ or trace_file =~ /driver\.rb$/ or trace_file =~ /timeout\.rb$/ # don't include rspec or ruby trace
        end

        #  (trace_file.include?("_spec.rb") || trace_file.include?("_rwebspec.rb") || trace_file.include?("_test.rb") || trace_file.include?("_cmd.rb"))
        if !trace_lines.empty?
          connect_to_testwise(" TRACE", trace_lines.reverse.join("|"))
        end

      rescue => e
        puts "failed to capture log: #{e}"
      end
    end

    def connect_to_testwise (message_type, body)
      Thread.pass
      begin
        the_message = message_type + "|" + body
        if @last_message == the_message then # ignore the message same as preivous one
          return
        end
        itest_port = $TESTWISE_TRACE_PORT || 7025
        itest_socket = Socket.new(Socket::AF_INET, Socket::SOCK_STREAM, 0)
        itest_socket.connect(Socket.pack_sockaddr_in(itest_port, '127.0.0.1'))
        itest_socket.puts(the_message)
        @last_message = the_message
        itest_socket.close
      rescue => e
      end
    end

  end
end


text:
require 'spec_helper'

describe "cms/pages", type: :feature, dbscope: :example do
  subject(:site) { cms_site }
  subject(:index_path) { cms_pages_path site.id }
  let!(:item2) { create(:cms_page) }
  let!(:html) { "
関連記事リンク1
" }
  let!(:item3) { create(:cms_page, html: html) }
  subject(:delete_path2) { delete_cms_page_path site.id, item2 }
  subject(:delete_path3) { delete_cms_page_path site.id, item3 }

  describe "basic crud" do
    before { login_cms_user }

    it do
      #
      # new
      #
      visit new_cms_page_path(site.id)
      within "form#item-form" do
        fill_in "item[name]", with: "sample"
        fill_in "item[basename]", with: "sample"
        click_button I18n.t("ss.buttons.save")
      end
      expect(status_code).to eq 200

      item = Cms::Page.last
      expect(item.name).to eq "sample"
      expect(item.filename).to eq "sample.html"

      #
      # show
      #
      visit cms_page_path(site.id, item)
      expect(status_code).to eq 200
      expect(page).to have_content("sample.html")

      #
      # edit
      #
      visit edit_cms_page_path(site.id, item)
      within "form#item-form" do
        fill_in "item[name]", with: "modify"
        click_button I18n.t("ss.buttons.save")
      end
      expect(status_code).to eq 200

      item.reload
      expect(item.name).to eq "modify"
      expect(item.filename).to eq "sample.html"

      #
      # move
      #
      visit move_cms_page_path(site.id, item)
      within "form" do
        fill_in "destination", with: "destination"
        click_button I18n.t("ss.buttons.move")
      end
      expect(status_code).to eq 200
      expect(page).to have_css("form#item-form h2", text: "destination.html")

      item.reload
      expect(item.name).to eq "modify"
      expect(item.filename).to eq "destination.html"

      visit move_cms_page_path(site.id, item)
      within "form" do
        fill_in "destination", with: "sample"
        click_button I18n.t("ss.buttons.move")
      end
      expect(status_code).to eq 200
      expect(page).to have_css("form#item-form h2", text: "sample.html")

      item.reload
      expect(item.name).to eq "modify"
      expect(item.filename).to eq "sample.html"

      #
      # copy
      #
      visit copy_cms_page_path(site.id, item)
      within "form" do
        click_button I18n.t("ss.buttons.save")
      end
      expect(status_code).to eq 200
      expect(page).to have_css("a", text: "[複製] modify")
      expect(page).to have_css(".state", text: "非公開")

      expect(Cms::Page.count).to eq 4

      #
      # contains_urls
      #
      visit contains_urls_cms_page_path(site.id, item)
      expect(status_code).to eq 200

      #
      # delete
      #
      visit delete_cms_page_path(site.id, item)
      within "form" do
        click_button I18n.t("ss.buttons.delete")
      end
      expect(current_path).to eq index_path
    end

    context "other delete pattern" do
      let(:user) { cms_user }

      it "permited and contains_urls" do
        visit delete_path2
        expect(page).to have_css(".delete")
        within "form" do
          click_on I18n.t("ss.buttons.delete")
        end
        expect(current_path).to eq index_path
        expect(page).to have_css('#notice', text: I18n.t('ss.notice.deleted'))
      end

      it "not permited and contains_urls" do
        role = user.cms_roles[0]
        role.update(permissions: %w(delete_private_cms_pages delete_other_cms_pages))
        visit delete_path2
        expect(page).not_to have_css(".delete")
        expect(page).to have_css(".addon-head", text: I18n.t('ss.confirm.contains_url_expect'))
      end

      it "not permited and not contains_urls" do
        role = user.cms_roles[0]
        role.update(permissions: %w(delete_private_cms_pages delete_other_cms_pages))
        visit delete_path3
        expect(page).to have_css(".delete")
        within "form" do
          click_on I18n.t("ss.buttons.delete")
        end
        expect(current_path).to eq index_path
        expect(page).to have_css('#notice', text: I18n.t('ss.notice.deleted'))
      end
    end
  end
end

describe "cms/pages", type: :feature, dbscope: :example, js: true do
  subject(:site) { cms_site }
  let!(:item2) { create(:cms_page) }
  let!(:html) { "
関連記事リンク1
" }
  let!(:item3) { create(:cms_page, html: html) }
  subject(:edit_path2) { edit_cms_page_path site.id, item2 }
  subject(:edit_path3) { edit_cms_page_path site.id, item3 }

  describe "basic crud" do
    before { login_cms_user }
    context "#draft_save" do
      let(:user) { cms_user }

      it "permited and contains_urls" do
        visit edit_path2
        within "form" do
          click_on I18n.t("ss.buttons.withdraw")
        end
        expect(page).to have_css('.save', text: I18n.t('ss.buttons.ignore_alert'))
      end

      it "permited and not contains_urls" do
        visit edit_path3
        within "form" do
          click_on I18n.t("ss.buttons.withdraw")
        end
        expect(page).to have_css('.save', text: I18n.t('ss.buttons.ignore_alert'))
      end

      it "not permited and contains_urls" do
        role = user.cms_roles[0]
        role.update(permissions: %w(edit_private_cms_pages edit_other_cms_pages
                                    release_private_cms_pages release_other_cms_pages))
        visit edit_path2
        within "form" do
          click_on I18n.t("ss.buttons.withdraw")
        end
        expect(page).not_to have_css('.save', text: I18n.t('ss.buttons.ignore_alert'))
        expect(page).to have_css(".errorExplanation", text: I18n.t('ss.confirm.contains_url_expect'))
      end

      it "not permited and not contains_urls" do
        role = user.cms_roles[0]
        role.update(permissions: %w(edit_private_cms_pages edit_other_cms_pages
                                    release_private_cms_pages release_other_cms_pages))
        visit edit_path3
        within "form" do
          click_on I18n.t("ss.buttons.withdraw")
        end
        expect(page).to have_css('.save', text: I18n.t('ss.buttons.ignore_alert'))
      end
    end
  end
end


text:
package net.mybluemix.entity;

import java.util.LinkedList;
import java.util.List;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.xml.bind.annotation.XmlRootElement;

@Entity
@XmlRootElement

public class Produto {

	@Id
	@GeneratedValue(strategy=GenerationType.TABLE)
    private Long sku;

	@ManyToMany
	  @JoinTable(
	      name="LOTE_PRODUTO",
	      joinColumns=@JoinColumn(name="LOTE_ID", referencedColumnName="sku")
	      )
	List<Lote> lotes = new LinkedList<Lote>();

	@ManyToOne
	Receita receita;

	String status;
	float preco;

	public long quantidadeProduzida;

	public long getQuantidadeProduzida() {
		return quantidadeProduzida;
	}

	public void setQuantidadeProduzida(long quantidadeProduzida) {
		this.quantidadeProduzida = quantidadeProduzida;
	}

	public Produto() {

	}

	public Long getSku() {
		return sku;
	}

	public void setSku(Long sku) {
		this.sku = sku;
	}

	public List<Lote> getLotes() {
		return lotes;
	}

	public void setLotes(List<Lote> lotes) {
		this.lotes = lotes;
	}

	public Receita getReceita() {
		return receita;
	}

	public void setReceita(Receita receita) {
		this.receita = receita;
	}

	public String getStatus() {
		return status;
	}

	public void setStatus(String status) {
		this.status = status;
	}

	public float getPreco() {
		return preco;
	}

	public void setPreco(float preco) {
		this.preco = preco;
	}

	public Produto(List<Lote> lotes, Receita receita, String status, float preco) {
		super();
		this.lotes = lotes;
		this.receita = receita;
		this.status = status;
		this.preco = preco;
	}

	public void update(Produto p) {
		this.lotes = p.lotes;
		this.receita = p.receita;
		this.status = p.status;
		this.preco = p.preco;
	}

}


text:
using System;
using System.Collections.Concurrent;
using System.Reflection;
using System.Threading;
using log4net;
using OpenSim.Framework;

namespace OpenSim.Framework.Monitoring
{
    public class JobEngine
    {
        private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

        public int LogLevel { get; set; }

        private object JobLock = new object();

        public string Name { get; private set; }

        public string LoggingName { get; private set; }

        /// <summary>
        /// Is this engine running?
        /// </summary>
        public bool IsRunning { get; private set; }

        /// <summary>
        /// The current job that the engine is running.
        /// </summary>
        /// <remarks>
        /// Will be null if no job is currently running.
        /// </remarks>
        public Job CurrentJob { get; private set; }

        /// <summary>
        /// Number of jobs waiting to be processed.
        /// </summary>
        public int JobsWaiting { get { return m_jobQueue.Count; } }

        /// <summary>
        /// The timeout in milliseconds to wait for at least one event to be written when the recorder is stopping.
        /// </summary>
        public int RequestProcessTimeoutOnStop { get; set; }

        /// <summary>
        /// Controls whether we need to warn in the log about exceeding the max queue size.
        /// </summary>
        /// <remarks>
        /// This is flipped to false once queue max has been exceeded and back to true when it falls below max, in
        /// order to avoid spamming the log with lots of warnings.
        /// </remarks>
        private bool m_warnOverMaxQueue = true;

        private BlockingCollection<Job> m_jobQueue = new BlockingCollection<Job>(new ConcurrentQueue<Job>(), 5000);

        private CancellationTokenSource m_cancelSource;

        /// <summary>
        /// Used to signal that we are ready to complete stop.
        /// </summary>
        private ManualResetEvent m_finishedProcessingAfterStop = new ManualResetEvent(false);

        public JobEngine(string name, string loggingName)
        {
            Name = name;
            LoggingName = loggingName;

            RequestProcessTimeoutOnStop = 5000;
        }

        public void Start()
        {
            lock (JobLock)
            {
                if (IsRunning)
                    return;

                IsRunning = true;

                m_finishedProcessingAfterStop.Reset();

                m_cancelSource = new CancellationTokenSource();

                WorkManager.StartThread(
                    ProcessRequests,
                    Name,
                    ThreadPriority.Normal,
                    false,
                    true,
                    null,
                    int.MaxValue);
            }
        }

        public void Stop()
        {
            lock (JobLock)
            {
                try
                {
                    if (!IsRunning)
                        return;

                    m_log.DebugFormat("[JobEngine] Stopping {0}", Name);

                    IsRunning = false;

                    m_finishedProcessingAfterStop.Reset();
                    if(m_jobQueue.Count <= 0)
                        m_cancelSource.Cancel();

                    if(m_finishedProcessingAfterStop.WaitOne(RequestProcessTimeoutOnStop))
                        m_finishedProcessingAfterStop.Close();
                }
                finally
                {
                    m_cancelSource.Dispose();
                }
            }
        }

        /// <summary>
        /// Make a job.
        /// </summary>
        /// <remarks>
        /// We provide this method to replace the constructor so that we can later pool job objects if necessary to
        /// reduce memory churn.  Normally one would directly call QueueJob() with parameters anyway.
        /// </remarks>
        /// <returns></returns>
        /// <param name="name">Name.</param>
        /// <param name="action">Action.</param>
        /// <param name="commonId">Common identifier.</param>
        public static Job MakeJob(string name, Action action, string commonId = null)
        {
            return Job.MakeJob(name, action, commonId);
        }

        /// <summary>
        /// Remove the next job queued for processing.
        /// </summary>
        /// <remarks>
        /// Returns null if there is no next job.
        /// Will not remove a job currently being performed.
        /// </remarks>
        public Job RemoveNextJob()
        {
            Job nextJob;
            m_jobQueue.TryTake(out nextJob);

            return nextJob;
        }

        /// <summary>
        /// Queue the job for processing.
        /// </summary>
        /// <returns><c>true</c>, if job was queued, <c>false</c> otherwise.</returns>
        /// <param name="name">Name of job.  This appears on the console and in logging.</param>
        /// <param name="action">Action to perform.</param>
        /// <param name="commonId">
        /// Common identifier for a set of jobs.  This is allows a set of jobs to be removed
        /// if required (e.g. all jobs for a given agent.  Optional.
        /// </param>
        public bool QueueJob(string name, Action action, string commonId = null)
        {
            return QueueJob(MakeJob(name, action, commonId));
        }

        /// <summary>
        /// Queue the job for processing.
        /// </summary>
        /// <returns><c>true</c>, if job was queued, <c>false</c> otherwise.</returns>
        /// <param name="job">The job</param>
        /// </param>
        public bool QueueJob(Job job)
        {
            if (m_jobQueue.Count < m_jobQueue.BoundedCapacity)
            {
                m_jobQueue.Add(job);

                if (!m_warnOverMaxQueue)
                    m_warnOverMaxQueue = true;

                return true;
            }
            else
            {
                if (m_warnOverMaxQueue)
                {
                    m_log.WarnFormat(
                        "[{0}]: Job queue at maximum capacity, not recording job from {1} in {2}",
                        LoggingName, job.Name, Name);

                    m_warnOverMaxQueue = false;
                }

                return false;
            }
        }

        private void ProcessRequests()
        {
            while(IsRunning || m_jobQueue.Count > 0)
            {
                try
                {
                    CurrentJob = m_jobQueue.Take(m_cancelSource.Token);
                }
                catch(ObjectDisposedException e)
                {
                    // If we see this whilst not running then it may be due to a race where this thread checks
                    // IsRunning after the stopping thread sets it to false and disposes of the cancellation source.
                    if(IsRunning)
                        throw e;
                    else
                    {
                        m_log.DebugFormat("[JobEngine] {0} stopping ignoring {1} jobs in queue",
                                Name,m_jobQueue.Count);
                        break;
                    }
                }
                catch(OperationCanceledException)
                {
                    break;
                }

                if(LogLevel >= 1)
                    m_log.DebugFormat("[{0}]: Processing job {1}",LoggingName,CurrentJob.Name);

                try
                {
                    CurrentJob.Action();
                }
                catch(Exception e)
                {
                    m_log.Error(
                        string.Format(
                        "[{0}]: Job {1} failed, continuing.  Exception  ",LoggingName,CurrentJob.Name),e);
                }

                if(LogLevel >= 1)
                    m_log.DebugFormat("[{0}]: Processed job {1}",LoggingName,CurrentJob.Name);

                CurrentJob = null;
            }

            Watchdog.RemoveThread(false);
            m_finishedProcessingAfterStop.Set();
        }

        public class Job
        {
            /// <summary>
            /// Name of the job.
            /// </summary>
            /// <remarks>
            /// This appears on console and debug output.
            /// </remarks>
            public string Name { get; private set; }

            /// <summary>
            /// Common ID for this job.
            /// </summary>
            /// <remarks>
            /// This allows all jobs with a certain common ID (e.g. a client UUID) to be removed en-masse if required.
            /// Can be null if this is not required.
            /// </remarks>
            public string CommonId { get; private set; }

            /// <summary>
            /// Action to perform when this job is processed.
            /// </summary>
            public Action Action { get; private set; }

            private Job(string name, string commonId, Action action)
            {
                Name = name;
                CommonId = commonId;
                Action = action;
            }

            /// <summary>
            /// Make a job.  It needs to be separately queued.
            /// </summary>
            /// <remarks>
            /// We provide this method to replace the constructor so that we can pool job objects if necessary to
            /// to reduce memory churn.  Normally one would directly call JobEngine.QueueJob() with parameters anyway.
            /// </remarks>
            /// <returns></returns>
            /// <param name="name">Name.</param>
            /// <param name="action">Action.</param>
            /// <param name="commonId">Common identifier.</param>
            public static Job MakeJob(string name, Action action, string commonId = null)
            {
                return new Job(name, commonId, action);
            }
        }
    }
}


text:
package org.apache.commons.lang3.function;

import java.util.Objects;
import java.util.function.LongConsumer;

/**
 * A functional interface like {@link LongConsumer} that declares a {@code Throwable}.
 *
 * @param <E> Thrown exception.
 * @since 3.11
 */
@FunctionalInterface
public interface FailableLongConsumer<E extends Throwable> {

    /** NOP singleton */
    @SuppressWarnings("rawtypes")
    FailableLongConsumer NOP = t -> {/* NOP */};

    /**
     * Returns The NOP singleton.
     *
     * @param <E> Thrown exception.
     * @return The NOP singleton.
     */
    static <E extends Throwable> FailableLongConsumer<E> nop() {
        return NOP;
    }

    /**
     * Accepts the consumer.
     *
     * @param object the parameter for the consumable to accept
     * @throws E Thrown when the consumer fails.
     */
    void accept(long object) throws E;

    /**
     * Returns a composed {@code FailableLongConsumer} like {@link LongConsumer#andThen(LongConsumer)}.
     *
     * @param after the operation to perform after this one.
     * @return a composed {@code FailableLongConsumer} like {@link LongConsumer#andThen(LongConsumer)}.
     * @throws NullPointerException if {@code after} is null
     */
    default FailableLongConsumer<E> andThen(final FailableLongConsumer<E> after) {
        Objects.requireNonNull(after);
        return (final long t) -> {
            accept(t);
            after.accept(t);
        };
    }
}


text:
(function ($) {
    // number aliases
  $.extend($.inputmask.defaults.aliases, {
    'decimal': {
      mask: '~',
      placeholder: '',
      repeat: '*',
      greedy: false,
      numericInput: false,
      isNumeric: true,
      digits: '*', // number of fractionalDigits
      groupSeparator: '', // ",", // | "."
      radixPoint: '.',
      groupSize: 3,
      autoGroup: false,
      allowPlus: true,
      allowMinus: true,
            // todo
      integerDigits: '*', // number of integerDigits
      defaultValue: '',
      prefix: '',
      suffix: '',

            // todo
      getMaskLength: function (buffer, greedy, repeat, currentBuffer, opts) { // custom getMaskLength to take the groupSeparator into account
        var calculatedLength = buffer.length

        if (!greedy) {
          if (repeat == '*') {
            calculatedLength = currentBuffer.length + 1
          } else if (repeat > 1) {
            calculatedLength += (buffer.length * (repeat - 1))
          }
        }

        var escapedGroupSeparator = $.inputmask.escapeRegex.call(this, opts.groupSeparator)
        var escapedRadixPoint = $.inputmask.escapeRegex.call(this, opts.radixPoint)
        var currentBufferStr = currentBuffer.join(''), strippedBufferStr = currentBufferStr.replace(new RegExp(escapedGroupSeparator, 'g'), '').replace(new RegExp(escapedRadixPoint), ''),
          groupOffset = currentBufferStr.length - strippedBufferStr.length
        return calculatedLength + groupOffset
      },
      postFormat: function (buffer, pos, reformatOnly, opts) {
        if (opts.groupSeparator == '') return pos
        var cbuf = buffer.slice(),
          radixPos = $.inArray(opts.radixPoint, buffer)
        if (!reformatOnly) {
          cbuf.splice(pos, 0, '?') // set position indicator
        }
        var bufVal = cbuf.join('')
        if (opts.autoGroup || (reformatOnly && bufVal.indexOf(opts.groupSeparator) != -1)) {
          var escapedGroupSeparator = $.inputmask.escapeRegex.call(this, opts.groupSeparator)
          bufVal = bufVal.replace(new RegExp(escapedGroupSeparator, 'g'), '')
          var radixSplit = bufVal.split(opts.radixPoint)
          bufVal = radixSplit[0]
          var reg = new RegExp('([-\+]?[\\d\?]+)([\\d\?]{' + opts.groupSize + '})')
          while (reg.test(bufVal)) {
            bufVal = bufVal.replace(reg, '$1' + opts.groupSeparator + '$2')
            bufVal = bufVal.replace(opts.groupSeparator + opts.groupSeparator, opts.groupSeparator)
          }
          if (radixSplit.length > 1) { bufVal += opts.radixPoint + radixSplit[1] }
        }
        buffer.length = bufVal.length // align the length
        for (var i = 0, l = bufVal.length; i < l; i++) {
          buffer[i] = bufVal.charAt(i)
        }
        var newPos = $.inArray('?', buffer)
        if (!reformatOnly) buffer.splice(newPos, 1)

        return reformatOnly ? pos : newPos
      },
      regex: {
        number: function (opts) {
          var escapedGroupSeparator = $.inputmask.escapeRegex.call(this, opts.groupSeparator)
          var escapedRadixPoint = $.inputmask.escapeRegex.call(this, opts.radixPoint)
          var digitExpression = isNaN(opts.digits) ? opts.digits : '{0,' + opts.digits + '}'
          var signedExpression = opts.allowPlus || opts.allowMinus ? '[' + (opts.allowPlus ? '\+' : '') + (opts.allowMinus ? '-' : '') + ']?' : ''
          return new RegExp('^' + signedExpression + '(\\d+|\\d{1,' + opts.groupSize + '}((' + escapedGroupSeparator + '\\d{' + opts.groupSize + '})?)+)(' + escapedRadixPoint + '\\d' + digitExpression + ')?$')
        }
      },
      onKeyDown: function (e, buffer, opts) {
        var $input = $(this), input = this
        if (e.keyCode == opts.keyCode.TAB) {
          var radixPosition = $.inArray(opts.radixPoint, buffer)
          if (radixPosition != -1) {
            var masksets = $input.data('_inputmask')['masksets']
            var activeMasksetIndex = $input.data('_inputmask')['activeMasksetIndex']
            for (var i = 1; i <= opts.digits && i < opts.getMaskLength(masksets[activeMasksetIndex]['_buffer'], masksets[activeMasksetIndex]['greedy'], masksets[activeMasksetIndex]['repeat'], buffer, opts); i++) {
              if (buffer[radixPosition + i] == undefined || buffer[radixPosition + i] == '') buffer[radixPosition + i] = '0'
            }
            input._valueSet(buffer.join(''))
          }
        } else if (e.keyCode == opts.keyCode.DELETE || e.keyCode == opts.keyCode.BACKSPACE) {
          opts.postFormat(buffer, 0, true, opts)
          input._valueSet(buffer.join(''))
          return true
        }
      },
      definitions: {
        '~': { // real number
          validator: function (chrs, buffer, pos, strict, opts) {
            if (chrs == '') return false
            if (!strict && pos <= 1 && buffer[0] === '0' && new RegExp('[\\d-]').test(chrs) && buffer.join('').length == 1) { // handle first char
              buffer[0] = ''
              return { 'pos': 0 }
            }

            var cbuf = strict ? buffer.slice(0, pos) : buffer.slice()

            cbuf.splice(pos, 0, chrs)
            var bufferStr = cbuf.join('')

                        // strip groupseparator
            var escapedGroupSeparator = $.inputmask.escapeRegex.call(this, opts.groupSeparator)
            bufferStr = bufferStr.replace(new RegExp(escapedGroupSeparator, 'g'), '')

            var isValid = opts.regex.number(opts).test(bufferStr)
            if (!isValid) {
                            // let's help the regex a bit
              bufferStr += '0'
              isValid = opts.regex.number(opts).test(bufferStr)
              if (!isValid) {
                                // make a valid group
                var lastGroupSeparator = bufferStr.lastIndexOf(opts.groupSeparator)
                for (var i = bufferStr.length - lastGroupSeparator; i <= 3; i++) {
                  bufferStr += '0'
                }

                isValid = opts.regex.number(opts).test(bufferStr)
                if (!isValid && !strict) {
                  if (chrs == opts.radixPoint) {
                    isValid = opts.regex.number(opts).test('0' + bufferStr + '0')
                    if (isValid) {
                      buffer[pos] = '0'
                      pos++
                      return { 'pos': pos }
                    }
                  }
                }
              }
            }

            if (isValid != false && !strict && chrs != opts.radixPoint) {
              var newPos = opts.postFormat(buffer, pos, false, opts)
              return { 'pos': newPos }
            }

            return isValid
          },
          cardinality: 1,
          prevalidator: null
        }
      },
      insertMode: true,
      autoUnmask: false
    },
    'integer': {
      regex: {
        number: function (opts) {
          var escapedGroupSeparator = $.inputmask.escapeRegex.call(this, opts.groupSeparator)
          var signedExpression = opts.allowPlus || opts.allowMinus ? '[' + (opts.allowPlus ? '\+' : '') + (opts.allowMinus ? '-' : '') + ']?' : ''
          return new RegExp('^' + signedExpression + '(\\d+|\\d{1,' + opts.groupSize + '}((' + escapedGroupSeparator + '\\d{' + opts.groupSize + '})?)+)$')
        }
      },
      alias: 'decimal'
    }
  })
})(jQuery)


text:
class PurgeMemoryIOHelper
    : public base::RefCountedThreadSafe<PurgeMemoryIOHelper> {
 public:
  explicit PurgeMemoryIOHelper(SafeBrowsingService* safe_browsing_service)
      : safe_browsing_service_(safe_browsing_service) {
  }

  void AddRequestContextGetter(
      scoped_refptr<net::URLRequestContextGetter> request_context_getter);

  void PurgeMemoryOnIOThread();

 private:
  typedef scoped_refptr<net::URLRequestContextGetter> RequestContextGetter;
  typedef std::set<RequestContextGetter> RequestContextGetters;

  RequestContextGetters request_context_getters_;
  scoped_refptr<SafeBrowsingService> safe_browsing_service_;

  DISALLOW_COPY_AND_ASSIGN(PurgeMemoryIOHelper);
};

void PurgeMemoryIOHelper::AddRequestContextGetter(
    scoped_refptr<net::URLRequestContextGetter> request_context_getter) {
  request_context_getters_.insert(request_context_getter);
}

void PurgeMemoryIOHelper::PurgeMemoryOnIOThread() {
  // Ask ProxyServices to purge any memory they can (generally garbage in the
  // wrapped ProxyResolver's JS engine).
  for (RequestContextGetters::const_iterator i(
           request_context_getters_.begin());
       i != request_context_getters_.end(); ++i)
    (*i)->GetURLRequestContext()->proxy_service()->PurgeMemory();

  // Close the Safe Browsing database, freeing memory used to cache sqlite as
  // well as a number of in-memory structures.
  safe_browsing_service_->CloseDatabase();

  // The appcache service listens for this notification.
  NotificationService::current()->Notify(
      NotificationType::PURGE_MEMORY,
      Source<void>(NULL),
      NotificationService::NoDetails());
}

// -----------------------------------------------------------------------------

// static
void MemoryPurger::PurgeAll() {
  PurgeBrowser();
  PurgeRenderers();

  // TODO(pkasting):
  // * Tell the plugin processes to release their free memory?  Other stuff?
  // * Enumerate what other processes exist and what to do for them.
}

// static
void MemoryPurger::PurgeBrowser() {
  // Dump the backing stores.
  BackingStoreManager::RemoveAllBackingStores();

  // Per-profile cleanup.
  scoped_refptr<PurgeMemoryIOHelper> purge_memory_io_helper(
      new PurgeMemoryIOHelper(g_browser_process->resource_dispatcher_host()->
          safe_browsing_service()));
  ProfileManager* profile_manager = g_browser_process->profile_manager();
  std::vector<Profile*> profiles(profile_manager->GetLoadedProfiles());
  for (size_t i = 0; i < profiles.size(); ++i) {
    purge_memory_io_helper->AddRequestContextGetter(
        make_scoped_refptr(profiles[i]->GetRequestContext()));

    // NOTE: Some objects below may be duplicates across profiles.  We could
    // conceivably put all these in sets and then iterate over the sets.

    // Unload all history backends (freeing memory used to cache sqlite).
    // Spinning up the history service is expensive, so we avoid doing it if it
    // hasn't been done already.
    HistoryService* history_service =
        profiles[i]->GetHistoryServiceWithoutCreating();
    if (history_service)
      history_service->UnloadBackend();

    // Unload all web databases (freeing memory used to cache sqlite).
    WebDataService* web_data_service =
        profiles[i]->GetWebDataServiceWithoutCreating();
    if (web_data_service)
      web_data_service->UnloadDatabase();

    // Ask all WebKitContexts to purge memory (freeing memory used to cache
    // the LocalStorage sqlite DB).  WebKitContext creation is basically free so
    // we don't bother with a "...WithoutCreating()" function.
    profiles[i]->GetWebKitContext()->PurgeMemory();
  }

  BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
      NewRunnableMethod(purge_memory_io_helper.get(),
                        &PurgeMemoryIOHelper::PurgeMemoryOnIOThread));

  // TODO(pkasting):
  // * Purge AppCache memory.  Not yet implemented sufficiently.
  // * Browser-side DatabaseTracker.  Not implemented sufficiently.

#if (defined(OS_WIN) || defined(OS_LINUX)) && defined(USE_TCMALLOC)
  // Tell tcmalloc to release any free pages it's still holding.
  //
  // TODO(pkasting): A lot of the above calls kick off actions on other threads.
  // Maybe we should find a way to avoid calling this until those actions
  // complete?
  MallocExtension::instance()->ReleaseFreeMemory();
#endif
}

// static
void MemoryPurger::PurgeRenderers() {
  // Direct all renderers to free everything they can.
  //
  // Concern: Telling a bunch of renderer processes to destroy their data may
  // cause them to page everything in to do it, which could take a lot of time/
  // cause jank.
  for (RenderProcessHost::iterator i(RenderProcessHost::AllHostsIterator());
       !i.IsAtEnd(); i.Advance())
    PurgeRendererForHost(i.GetCurrentValue());
}

// static
void MemoryPurger::PurgeRendererForHost(RenderProcessHost* host) {
  // Direct the renderer to free everything it can.
  host->Send(new ViewMsg_PurgeMemory());
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

  <meta name="generator" content=
  "HTML Tidy for Linux/x86 (vers 1 September 2005), see www.w3.org">

  <title>copy_n</title>
  <link href="../cppreference.css" rel="stylesheet" type="text/css">
  <link href="../prettify.css" type="text/css" rel="stylesheet" />

    cppreference.com > C++ Algorithms > copy_n

    copy_n

    Syntax:

  #include <algorithm>
  iterator copy_n( iterator from, size_t num, iterator to );

The copy_n() function copies num elements starting at
  from to the destination pointed at by to. To put it
  another way, copy_n() performs num assignments and
  duplicates a subrange.

The return value of copy_n() is an iterator that points to the
  last element that was copied, i.e. (to + num).

This function runs in linear
  time.

    Related topics:

    copy

    copy_backward

    swap


text:
<?php

namespace Sylius\Component\Grid;

/**
 * @author Paweł Jędrzejewski <pawel@sylius.org>
 */
final class Parameters
{
    /**
     * @var array
     */
    private $parameters;

    /**
     * @param array $parameters
     */
    public function __construct(array $parameters = [])
    {
        $this->parameters = $parameters;
    }

    /**
     * @return array
     */
    public function all()
    {
        return $this->parameters;
    }

    /**
     * @return array
     */
    public function keys()
    {
        return array_keys($this->parameters);
    }

    /**
     * @param string $key
     * @param mixed $default
     *
     * @return mixed
     */
    public function get($key, $default = null)
    {
        return $this->has($key) ? $this->parameters[$key] : $default;
    }

    /**
     * @param string $key
     *
     * @return bool
     */
    public function has($key)
    {
        return array_key_exists($key, $this->parameters);
    }
}


text:
@interface ZYLuckyViewController ()

@property (weak, nonatomic) IBOutlet UIImageView *lightImage;

@end

@implementation ZYLuckyViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    //image动画组,可以实现简单额动画,原理就是来回切换图片
    UIImage *image = [UIImage imageNamed:@"lucky_entry_light0"];
    UIImage *image1 =[UIImage imageNamed:@"lucky_entry_light1"];
    self.lightImage.animationImages = @[image,image1];
    self.lightImage.animationDuration = 1;
    [self.lightImage startAnimating];

}

- (IBAction)rotaryButton:(UIButton *)button {

}

@end


text:
The [modern build](https://github.com/lodash/lodash/wiki/Build-Differences) of [lodash's](https://lodash.com/) internal `createPadding` exported as a [Node.js](http://nodejs.org/)/[io.js](https://iojs.org/) module.

## Installation

Using npm:

```bash
$ {sudo -H} npm i -g npm
$ npm i --save lodash._createpadding
```

In Node.js/io.js:

```js
var createPadding = require('lodash._createpadding');
```

See the [package source](https://github.com/lodash/lodash/blob/3.6.1-npm-packages/lodash._createpadding) for more details.


text:
<?php

use yii\db\Migration;

class m170103_052416_work_item_table extends Migration
{

    // Use safeUp/safeDown to run migration code within a transaction
    public function safeUp()
    {
        $this->createTable('work_item', [
            'id' => $this->primaryKey()." COMMENT 'ID'",
            'title_en' => $this->string(128)->notNull()." COMMENT '标题(英文)'",
            'title_zh' => $this->string(128)->notNull()." COMMENT '标题(中文)'",
            'lead_photo' => $this->string(500)." COMMENT '图片'",
            'content_en' => $this->text()->notNull()." COMMENT '内容(英文)'",
            'content_zh' => $this->text()->notNull()." COMMENT '内容(中文)'",
            'created_at' => $this->datetime()." COMMENT '创建时间'",
            'updated_at' => $this->datetime()." COMMENT '更新时间'",
            'category_id' => $this->integer()->notNull()." COMMENT '分类'",
            'view_count'=> $this->integer()->defaultValue(1)." COMMENT '查看次数'",
            'on_top'=> $this->integer()->defaultValue(0)." COMMENT '置顶'",
            'comments_count'=> $this->integer()->defaultValue(0)." COMMENT '评论数量'",
            'status'=> $this->integer()->defaultValue(0)." COMMENT '状态'",
            'sort'=> $this->integer()->defaultValue(0)." COMMENT '排序'",
        ]);

        $this->addForeignKey('fk_work_item_category', 'work_item', 'category_id', 'work_category', 'id', 'CASCADE');
    }

    public function safeDown()
    {
        $this->dropForeignKey('fk_work_item_category','work_item');
        $this->dropTable('work_item');
    }
}


text:
package de.jdynameta.testcommon.testdata;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;

import de.jdynameta.base.metainfo.AttributeHandler;
import de.jdynameta.base.metainfo.AttributeInfo;
import de.jdynameta.base.metainfo.ClassInfo;
import de.jdynameta.base.metainfo.ClassRepository;
import de.jdynameta.base.metainfo.ObjectReferenceAttributeInfo;
import de.jdynameta.base.metainfo.PrimitiveAttributeInfo;
import de.jdynameta.base.metainfo.filter.ClassInfoQuery;
import de.jdynameta.base.metainfo.impl.DefaultClassRepositoryValidator;
import de.jdynameta.base.metainfo.impl.JdyClassInfoModel;
import de.jdynameta.base.metainfo.impl.JdyRepositoryModel;
import de.jdynameta.base.metainfo.primitive.BlobByteArrayHolder;
import de.jdynameta.base.metainfo.primitive.BlobType;
import de.jdynameta.base.metainfo.primitive.BooleanType;
import de.jdynameta.base.metainfo.primitive.CurrencyType;
import de.jdynameta.base.metainfo.primitive.FloatType;
import de.jdynameta.base.metainfo.primitive.LongType;
import de.jdynameta.base.metainfo.primitive.PrimitiveTypeGetVisitor;
import de.jdynameta.base.metainfo.primitive.TextType;
import de.jdynameta.base.metainfo.primitive.TimeStampType;
import de.jdynameta.base.metainfo.primitive.VarCharType;
import de.jdynameta.base.objectlist.DefaultObjectListModel;
import de.jdynameta.base.objectlist.ObjectListModel;
import de.jdynameta.base.value.ChangeableValueObject;
import de.jdynameta.base.value.JdyPersistentException;
import de.jdynameta.base.value.ValueObject;

/**
 * Class to create a list of random data for a given {@link ClassInfo}
 *
 * @author rs
 *
 * @param <TResult>
 */
public abstract class TestDataCreator<TResult extends ChangeableValueObject>
{
    private ArrayList<String> wordList;

    public TestDataCreator()
    {
        this.wordList = new ArrayList<>();

        TestDataCreator.class.getResourceAsStream("wordlist.txt");

        try
        {
            BufferedReader input = new BufferedReader(new InputStreamReader(TestDataCreator.class.getResourceAsStream("wordlist.txt"), "ISO-8859-1"));

            try
            {
                String line;
                while ((line = input.readLine()) != null)
                {
                    wordList.add(line);
                }
            } catch (IOException e)
            {
                // ignore
            } finally
            {
                if (null != input)
                {
                    try
                    {
                        input.close();
                    } catch (IOException e)
                    {
                        // ignore
                    }
                }
            }
        } catch (UnsupportedEncodingException e)
        {
            // ignore
        }

    }

    /**
     * Create a list of ValueObjects for the given ClassInfo
     *
     * @param aClassInfo
     * @param objToCreateCount count of objects that are created
     * @param query
     * @return
     */
    public ObjectListModel<TResult> createTestData(ClassInfo aClassInfo, int objToCreateCount, ClassInfoQuery query)
    {
        ArrayList<TResult> allData = new ArrayList<>();
        for (int i = 0; i < objToCreateCount; i++)
        {

            TResult model = createValueModelForClassInfo(aClassInfo);

            try
            {
                if (query == null || query.matchesObject(model))
                {
                    allData.add(model);
                }
            } catch (JdyPersistentException e)
            {
                e.printStackTrace();
            }
        }

        return new DefaultObjectListModel<>(allData);
    }

    /**
     * @param aClassInfo
     * @return
     */
    protected TResult createValueModelForClassInfo(ClassInfo aClassInfo)
    {
        TResult model = createEmptyResult(aClassInfo);

        for (AttributeInfo curAttr : aClassInfo.getAttributeInfoIterator())
        {

            try
            {
                setCellValueForAttribute(model, curAttr);
            } catch (JdyPersistentException e)
            {
                e.printStackTrace();
            }
        }
        return model;
    }

    protected abstract TResult createEmptyResult(ClassInfo aClassInfo);

    protected void setCellValueForAttribute(final ChangeableValueObject curValueObj, AttributeInfo curAttr) throws JdyPersistentException
    {
        final PrimitiveTypeGetVisitor typeVisitor = new PrimitiveTypeGetVisitor()
        {

            @Override
            public BlobByteArrayHolder handleValue(BlobType aType) throws JdyPersistentException
            {
                return null;
            }

            @Override
            public String handleValue(VarCharType aType) throws JdyPersistentException
            {
                int charCount = (int) (Math.random() * aType.getLength());

                StringBuilder buffer = new StringBuilder(charCount);
                // use wordlist when it is filled
                if (wordList.size() > 50)
                {

                    while (buffer.length() < charCount)
                    {

                        int wordPos = (int) (Math.random() * wordList.size());
                        String word = wordList.get(wordPos);
                        buffer.append(word).append(' ');
                    }
                    buffer.setLength(charCount);
                } else
                {

                    for (int i = 0; i < charCount; i++)
                    {

                        int asciiRange = (int) 'z' - (int) 'a';
                        buffer.append(new Character((char) ('a' + Math.random() * asciiRange)));
                    }
                }

                return buffer.toString();
            }

            @Override
            public String handleValue(TextType aType) throws JdyPersistentException
            {
                int charCount = (int) (Math.random() * aType.getLength());
                StringBuilder buffer = new StringBuilder(charCount);
                for (int i = 0; i < charCount; i++)
                {
                    int asciiRange = (int) 'Z' - (int) 'A';
                    buffer.append(new Character((char) ('A' + Math.random() * asciiRange)));
                }
                return buffer.toString();
            }

            @Override
            public BigDecimal handleValue(CurrencyType aType) throws JdyPersistentException
            {
                return new BigDecimal(Math.random() * aType.getMaxValue().doubleValue()).setScale((int) aType.getScale(), BigDecimal.ROUND_HALF_UP);
            }

            @Override
            public Date handleValue(TimeStampType aType) throws JdyPersistentException
            {
                return new Date(System.currentTimeMillis() + (long) (Math.random() * 24 * 60 * 60 * 1000));
            }

            @Override
            public Double handleValue(FloatType aType) throws JdyPersistentException
            {
                return Math.random() * 1000000.0;
            }

            @Override
            public Boolean handleValue(BooleanType aType) throws JdyPersistentException
            {
                return Math.random() > 0.5;
            }

            @Override
            public Long handleValue(LongType aType) throws JdyPersistentException
            {
                return (long) (Math.random() * aType.getMaxValue());
            }
        };

        curAttr.handleAttribute(new AttributeHandler()
        {

            @Override
            public void handlePrimitiveAttribute(PrimitiveAttributeInfo aInfo, Object objToHandle) throws JdyPersistentException
            {
                curValueObj.setValue(aInfo, aInfo.getType().handlePrimitiveKey(typeVisitor));
            }

            @Override
            public void handleObjectReference(ObjectReferenceAttributeInfo aInfo, ValueObject objToHandle) throws JdyPersistentException
            {
                curValueObj.setValue(aInfo, createValueModelForClassInfo(aInfo.getReferencedClass()));

            }
        }, curValueObj.getValue(curAttr));

    }

    public static JdyClassInfoModel createSmallClassInfo()
    {
        JdyClassInfoModel classInfo = new JdyClassInfoModel().setInternalName("SmallClassInfo");
        classInfo.addLongAttr("LongAttribute", 0, 500).setIsKey(true);
        classInfo.addTextAttr("TextAttribute", 50).setNotNull(true);
        classInfo.addBooleanAttr("BooleanAttribute");

        return classInfo;
    }

    public static JdyClassInfoModel createMediumClassInfo()
    {
        JdyClassInfoModel classInfo = new JdyClassInfoModel().setInternalName("MediumClassInfo");
        classInfo.addLongAttr("LongAttribute", 0, 500).setIsKey(true);
        classInfo.addTextAttr("TextAttribute", 50).setNotNull(true);
        classInfo.addDecimalAttr("DecimalAttribute", new BigDecimal(-100.00), new BigDecimal(100.00), 2).setNotNull(true);
        classInfo.addBooleanAttr("BooleanAttribute");
        classInfo.addFloatAttr("FloatAttribute").setNotNull(true);
        classInfo.addTimestampAttr("TimestampAttribute").setNotNull(true);
        classInfo.addVarCharAttr("VarcharAttribute", 1000).setNotNull(true);

        return classInfo;
    }

    public static JdyClassInfoModel createLongClassInfo()
    {
        JdyClassInfoModel classInfo = new JdyClassInfoModel().setInternalName("LargeClassInfo");
        classInfo.addLongAttr("LongAttribute", 0, 500).setIsKey(true);
        classInfo.addTextAttr("TextAttribute", 50).setNotNull(true);
        classInfo.addDecimalAttr("DecimalAttribute", new BigDecimal(-100.00), new BigDecimal(100.00), 2).setNotNull(true);
        classInfo.addBooleanAttr("BooleanAttribute");
        classInfo.addFloatAttr("FloatAttribute").setNotNull(true);
        classInfo.addTimestampAttr("TimestampAttribute").setNotNull(true);
        classInfo.addVarCharAttr("VarcharAttribute", 1000).setNotNull(true);
        classInfo.addTimestampAttr("TimeAttr", false, true);
        classInfo.addTimestampAttr("DateAttr", true, false);
        classInfo.addDecimalAttr("DecimalAttribute2", new BigDecimal(-1000000.00), new BigDecimal(1000000.00), 2).setNotNull(true);
        classInfo.addLongAttr("LongAttribute5", -500, 500);
        classInfo.addLongAttr("LongAttribute6", 0, 500);

        return classInfo;
    }

    public static JdyClassInfoModel createClassWithReference()
    {
        JdyClassInfoModel referencedInfo = new JdyClassInfoModel().setInternalName("ReferencedClass");
        referencedInfo.addLongAttr("RefKeyLongAttr", 0, 500).setIsKey(true);
        referencedInfo.addTextAttr("RefKeyTextAttr", 50).setIsKey(true);
        referencedInfo.addDecimalAttr("RefKeyDecimalAttr", new BigDecimal(-100000000), new BigDecimal(100000000), 3).setIsKey(true);
        referencedInfo.addTimestampAttr("RefKeyTimeStampAttr").setIsKey(true);
        referencedInfo.addTextAttr("RefTextAttr", 100).setIsKey(false);

        JdyClassInfoModel classInfo = new JdyClassInfoModel().setInternalName("ClassWithReference");
        classInfo.addLongAttr("LongAttribute", -500, 500).setIsKey(true);
        classInfo.addTextAttr("TextAttribute", 50).setNotNull(true);
        classInfo.addBooleanAttr("BooleanAttribute");
        classInfo.addReference("Reference", referencedInfo);

        return classInfo;
    }

    public static JdyClassInfoModel createClassWithDeepReference()
    {
        JdyClassInfoModel deepReferencedInfo = new JdyClassInfoModel().setInternalName("DeepReferencedClass");
        deepReferencedInfo.addLongAttr("DeepRefKeyLongAttr", -500, 500).setIsKey(true);
        deepReferencedInfo.addTextAttr("DeepRefKeyTextAttr", 50).setIsKey(true);
        deepReferencedInfo.addTimestampAttr("DeepRefKeyTimeStampAttr");

        JdyClassInfoModel referencedInfo = new JdyClassInfoModel().setInternalName("ReferencedClass");
        referencedInfo.addReference("DeepReference", deepReferencedInfo).setIsKey(true);
        referencedInfo.addLongAttr("RefKeyLongAttr", -500, 500).setIsKey(true);
        referencedInfo.addTextAttr("RefKeyTextAttr", 50).setIsKey(true);
        referencedInfo.addDecimalAttr("RefKeyDecimalAttr", new BigDecimal(100000000.000), new BigDecimal(100000000.000), 3).setIsKey(true);
        referencedInfo.addTimestampAttr("RefKeyTimeStampAttr").setIsKey(true);
        referencedInfo.addTextAttr("RefTextAttr", 100).setIsKey(false);

        JdyClassInfoModel classInfo = new JdyClassInfoModel().setInternalName("ClassWithReference");
        classInfo.addLongAttr("LongAttribute", 0, 500).setIsKey(true);
        classInfo.addTextAttr("TextAttribute", 50).setNotNull(true);
        classInfo.addBooleanAttr("BooleanAttribute");
        classInfo.addReference("Reference", referencedInfo);

        return classInfo;
    }

    public static ClassRepository createRepository()
    {
        JdyRepositoryModel repository = new JdyRepositoryModel("MetaData");
        repository.addListener(new DefaultClassRepositoryValidator());
        repository.addClassInfo(createSmallClassInfo());
        repository.addClassInfo(createMediumClassInfo());
        repository.addClassInfo(createLongClassInfo());

        return repository;
    }

}


text:
.class public Landroid/net/http/X509TrustManagerExtensions;
.super Ljava/lang/Object;
.source "X509TrustManagerExtensions.java"

# instance fields
.field mDelegate:Lorg/apache/harmony/xnet/provider/jsse/TrustManagerImpl;

# direct methods
.method public constructor <init>(Ljavax/net/ssl/X509TrustManager;)V
    .locals 2
    .parameter "tm"
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Ljava/lang/IllegalArgumentException;
        }
    .end annotation

    .prologue
    .line 44
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    .line 45
    instance-of v0, p1, Lorg/apache/harmony/xnet/provider/jsse/TrustManagerImpl;

    if-eqz v0, :cond_0

    .line 46
    check-cast p1, Lorg/apache/harmony/xnet/provider/jsse/TrustManagerImpl;

    .end local p1
    iput-object p1, p0, Landroid/net/http/X509TrustManagerExtensions;->mDelegate:Lorg/apache/harmony/xnet/provider/jsse/TrustManagerImpl;

    .line 50
    return-void

    .line 48
    .restart local p1
    :cond_0
    new-instance v0, Ljava/lang/IllegalArgumentException;

    const-string/jumbo v1, "tm is not a supported type of X509TrustManager"

    invoke-direct {v0, v1}, Ljava/lang/IllegalArgumentException;-><init>(Ljava/lang/String;)V

    throw v0
.end method

# virtual methods
.method public checkServerTrusted([Ljava/security/cert/X509Certificate;Ljava/lang/String;Ljava/lang/String;)Ljava/util/List;
    .locals 1
    .parameter "chain"
    .parameter "authType"
    .parameter "host"
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "([",
            "Ljava/security/cert/X509Certificate;",
            "Ljava/lang/String;",
            "Ljava/lang/String;",
            ")",
            "Ljava/util/List",
            "<",
            "Ljava/security/cert/X509Certificate;",
            ">;"
        }
    .end annotation

    .annotation system Ldalvik/annotation/Throws;
        value = {
            Ljava/security/cert/CertificateException;
        }
    .end annotation

    .prologue
    .line 64
    iget-object v0, p0, Landroid/net/http/X509TrustManagerExtensions;->mDelegate:Lorg/apache/harmony/xnet/provider/jsse/TrustManagerImpl;

    invoke-virtual {v0, p1, p2, p3}, Lorg/apache/harmony/xnet/provider/jsse/TrustManagerImpl;->checkServerTrusted([Ljava/security/cert/X509Certificate;Ljava/lang/String;Ljava/lang/String;)Ljava/util/List;

    move-result-object v0

    return-object v0
.end method


text:
package net.anotheria.moskito.webui.util.offlinecharts;

import java.util.LinkedList;
import java.util.List;

/**
 * Represents a chart for generation.
 */
public class OfflineChart {
    /**
     * Caption of the chart.
     */
    private String caption;

    /**
     * Definition of chart lines.
     */
    private List<OfflineChartLineDefinition> lineDefinitions = new LinkedList<>();
    /**
     * Points with values for all lines.
     */
    private List<OfflineChartPoint> points = new LinkedList<>();

    public String getCaption() {
        return caption;
    }

    public void setCaption(String caption) {
        this.caption = caption;
    }

    public List<OfflineChartLineDefinition> getLineDefinitions() {
        return lineDefinitions;
    }

    public void setLineDefinitions(List<OfflineChartLineDefinition> lineDefinitions) {
        this.lineDefinitions = lineDefinitions;
    }

    public List<OfflineChartPoint> getPoints() {
        return points;
    }

    public void setPoints(List<OfflineChartPoint> points) {
        this.points = points;
    }

    @Override public String toString(){
        return "Chart "+getCaption()+", LineDefinitions: "+getLineDefinitions()+", Points: "+getPoints();
    }

    public void addLineDefinition(OfflineChartLineDefinition offlineChartLineDefinition) {
        lineDefinitions.add(offlineChartLineDefinition);
    }

    public void addPoint(OfflineChartPoint ocp) {
        points.add(ocp);
    }
}