text:
import unittest

import bright
from tests import settings

from bright.helpers import Forbidden, ResourceNotFound

class CollectionTests(unittest.TestCase):

    @classmethod
    def setupClass(self):
        scopes = ["collections:read", "collections:write", "collections:like",
                  "artworks:read", "user:read"]
        self.bright_api = bright.Bright(client_id=settings.client_id,
                                        client_secret=settings.client_secret,
                                        scopes=scopes,
                                        **settings.kwargs
                                        )

        self.own_collections = self.bright_api.my_collections()["collections"]
        self.own_artworks = self.bright_api.my_artworks()["artworks"]

    def test_get_collection(self):
        "Test we can get a collection"
        contents = ['slug', 'thumbnail_url', 'is_private', 'name', 'artworks',
                    'id', 'curator', 'description', 'draft']

        res = self.bright_api.get_collection(self.own_collections[0]["id"])
        self.assertIn("collection", res)

        for element in contents:
            self.assertIn(element, res["collection"])

    def test_get_all_collections(self):
        "Test we can get all collections"
        contents = ['slug', 'thumbnail_url', 'is_private', 'name', 'artworks',
                    'id', 'curator', 'description', 'draft']

        res = self.bright_api.get_all_collections()

        self.assertIn("pages", res)
        self.assertIn("collections", res)

        for collection in res["collections"]:
            for element in contents:
                self.assertIn(element, collection)

    def test_create_collection(self):
        "Test we can create a collection"
        contents = ['slug', 'thumbnail_url', 'is_private', 'name', 'artworks',
                    'id', 'curator', 'description', 'draft']
        res = self.bright_api.create_collection("test", "'tis but a test", False)

        for element in contents:
            self.assertIn(element, res["collection"])

        self.bright_api.delete_collection(res["collection"]["id"])

    def test_delete_collection(self):
        "Test we can delete a collection"
        res = self.bright_api.create_collection("test", "'tis but a test", False)["collection"]
        me = self.bright_api.my_collections()["collections"]

        self.assertIn(res, me)

        self.bright_api.delete_collection(res["id"])
        me = self.bright_api.my_collections()["collections"]

        self.assertNotIn(res, me)

    def test_update_collection(self):
        "Test we can update a collection"
        data = {
            "name": "foobar"
        }
        orig = self.bright_api.get_collection(self.own_collections[0]["id"])["collection"]
        res = self.bright_api.update_collection(orig["id"], data=data)["collection"]
        self.assertEquals(data["name"], res["name"])
        self.bright_api.update_collection(orig["id"], {"name": orig["name"]})

    def test_add_to_collection(self):
        "Test we can add artworks to collections"
        collec = self.own_collections[0]
        artworks_not_in_collec = [x for x in self.own_artworks
                                  if x in collec["artworks"]]
        artwork_id = artworks_not_in_collec[0]["id"]

        res = self.bright_api.add_to_collection(collec["id"], artwork_id)
        self.assertEquals({}, res)

        res = self.bright_api.get_collection(collec["id"])
        self.assertIn(artwork_id, res["collection"]["artworks"])

        self.bright_api.remove_from_collection(collec["id"], artwork_id)

    def remove_from_collection(self):
        "Test we can remove artworks from collections"
        collec = self.own_collections[0]
        artworks_in_collec = [x for x in self.own_artworks
                              if x in collec["artworks"]]
        artwork_id = artworks_in_collec[0]["id"]

        res = self.bright_api.remove_from_collection(collec["id"], artwork_id)
        self.assertEquals({}, res)

        res = self.bright_api.get_collection(collec["id"])
        self.assertNotIn(artwork_id, res["collection"]["artworks"])

        self.bright_api.add_to_collection(collec["id"], artwork_id)

    def test_like_collection(self):
        "Test that we can like a collection"
        own_id = self.bright_api.me()["user"]["id"]
        all_collec = self.bright_api.get_all_collections()["collections"]
        collec = list(filter(lambda c: not own_id in c["likes"], all_collec))[0]

        res = self.bright_api.like_collection(collec["id"])
        self.assertEquals({}, res)

        res = self.bright_api.get_collection(collec["id"])
        self.assertIn(own_id, res["collections"]["likes"])

        self.bright_api.unlike_collection(collec["id"])

    def test_unlike_collection(self):
        "Test that we can unlike a collection"
        own_id = self.bright_api.me()["user"]["id"]
        all_collec = self.bright_api.get_all_collections()["collections"]
        collec = list(filter(lambda c: not own_id in c["likes"], all_collec))[0]

        _ = self.bright_api.like_collection(collec["id"])
        res = self.bright_api.unlike_collection(collec["id"])
        self.assertEquals({}, res)

        res = self.bright_api.get_collection(collec["id"])
        self.assertNotIn(own_id, res["collections"]["likes"])

        self.bright_api.like_collection(collec["id"])


text:
module Locomotive
  class ContentEntryPresenter < BasePresenter

    ## properties ##

    properties  :_label, only_getter: true

    property    :_slug

    properties  :_position, :_visible, required: false

    properties  :seo_title, :meta_keywords, :meta_description, required: false

    with_options only_getter: true do |presenter|
      presenter.properties  :content_type_slug, :translated_in

      presenter.property    :errors, if: Proc.new { include_errors? }
    end

    with_options only_getter: true, if: Proc.new { html_view? } do |presenter|
      presenter.properties  :safe_attributes
      presenter.properties  :select_custom_fields, :file_custom_fields, :belongs_to_custom_fields, :has_many_custom_fields, :many_to_many_custom_fields
    end

    ## callbacks ##

    set_callback :set_attributes, :after, :set_dynamic_attributes

    ## other getters / setters ##

    def errors
      super
    end

    def content_type_slug
      self.__source.content_type.slug
    end

    def safe_attributes
      self.__source.custom_fields_safe_setters + %w(_slug _visible seo_title meta_keywords meta_description)
    end

    ## other methods ##

    def as_json_with_custom_fields
      as_json_without_custom_fields.merge(self.custom_fields_to_hash)
    end

    alias_method_chain :as_json, :custom_fields

    def as_json_for_html_view
      self.__options[:html_view] = true
      as_json_without_custom_fields.merge(self.custom_fields_to_hash)
    end

    protected

    # Build the hash representing the values of all
    # the custom fields of the content entry.
    # It also includes the ones from relationships fields
    #
    # @return [ Hash ] key the name of the custom field and value from the source
    #
    def custom_fields_to_hash
      base = self.__source.custom_fields_basic_attributes
      base.merge!(self.many_relationships_to_hash)
      base.merge!(self.belongs_to_to_hash)
    end

    # Build the hash storing for each *belongs_to* type field the target entry.
    #
    # @return [ Hash ] The hash whose name is the name of the belongs_to field
    #
    def belongs_to_to_hash
      {}.tap do |hash|
        self.__source.belongs_to_custom_fields.each do |name, _|
          if target = self.__source.send(name.to_sym)
            if self.html_view?
              hash["#{name}_id"] = target._id
            else
              hash[name.to_s]    = target._slug
            end
          end
        end
      end
    end

    # Build the hash storing for each *many* type field
    # the list of entries.
    #
    # @return [ Hash ] The hash whose name is the name of the relationhip
    #
    def many_relationships_to_hash
      {}.tap do |hash|
        (self.__source.has_many_custom_fields + self.__source.many_to_many_custom_fields).each do |name, _|
          if self.__depth == 0
            list = self.__source.send(name.to_sym).ordered
            hash[name.to_s] = list.map do |entry|
              if self.html_view?
                entry.to_presenter(depth: self.__depth + 1, html_view: true).as_json
              else
                entry._slug
              end
            end
          end
        end
      end
    end

    # Set the values of the dynamic attributes for the
    # content entry instance. This method is called automatically
    # (callback) when the attributes= is called.
    #
    def set_dynamic_attributes
      # process the basic types
      self.__source.custom_fields_basic_attributes = @_attributes

      # now the relationships
      self.__source.relationship_custom_fields.each do |rule|
        if rule['type'] == 'belongs_to'
          self.set_belongs_to_attribute(rule['name'], rule['class_name'])
        elsif rule['type'] == 'many_to_many'
          self.set_many_to_many_attribute(rule['name'], rule['class_name'])
        end
      end
    end

    def set_belongs_to_attribute(name, class_name)
      id_or_slug  = @_attributes[name] || @_attributes["#{name}_id"]

      return if id_or_slug.nil?

      entry = self.fetch_content_entries(class_name, id_or_slug).first

      if entry
        self.__source.send(:"#{name}_id=", entry._id)

        if position = @_attributes["#{name}_position"]
          self.__source.send(:"#{name}_position=", position)
        end
      end
    end

    def set_many_to_many_attribute(name, class_name)
      ids_or_slugs  = @_attributes[name] || @_attributes["#{name}_ids"]

      return if ids_or_slugs.nil?

      entries = self.fetch_content_entries(class_name, ids_or_slugs)

      unless entries.empty?
        entries = entries.sort do |a, b|
          (ids_or_slugs.index(a._id.to_s) || ids_or_slugs.index(a._permalink)) <=>
          (ids_or_slugs.index(b._id.to_s) || ids_or_slugs.index(b._permalink))
        end # keep the original order

        self.__source.send(:"#{name}=", entries.to_a)
      end
    end

    # Return all the ids of the content entries matching the ids or the slugs
    #
    # @param [ Array ] ids_or_slugs Array of ids or slugs
    #
    # @return [ Array ] The matching entries
    #
    def fetch_content_entries(class_name, ids_or_slugs)
      ids_or_slugs  = [*ids_or_slugs]
      klass         = class_name.constantize

      klass.any_of({ :_slug.in => ids_or_slugs }, { :_id.in => ids_or_slugs })
    end

  end
end

redpajama_set_name: RedPajamaGithub


text:
require 'spec_helper'

describe Chef::Resource::GemPackage, "initialize" do

  before(:each) do
    @resource = Chef::Resource::GemPackage.new("foo")
  end

  it "should return a Chef::Resource::GemPackage" do
    @resource.should be_a_kind_of(Chef::Resource::GemPackage)
  end

  it "should set the resource_name to :gem_package" do
    @resource.resource_name.should eql(:gem_package)
  end

  it "should set the provider to Chef::Provider::Package::Rubygems" do
    @resource.provider.should eql(Chef::Provider::Package::Rubygems)
  end
end

describe Chef::Resource::GemPackage, "gem_binary" do
  before(:each) do
    @resource = Chef::Resource::GemPackage.new("foo")
  end

  it "should set the gem_binary variable to whatever is passed in" do
    @resource.gem_binary("/opt/local/bin/gem")
    @resource.gem_binary.should eql("/opt/local/bin/gem")
  end
end


text:
package com.vonage.client.verify;

import com.vonage.client.VonageUnexpectedException;
import org.junit.Test;

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

public class ControlResponseTest {

    @Test
    public void testParseError() throws Exception {
        ControlResponse response = ControlResponse.fromJson("{\n" +
                "    \"error_text\": \"Missing username\",\n" +
                "    \"status\": \"2\"\n" +
                "}");
        assertEquals("2", response.getStatus());
        assertEquals("Missing username", response.getErrorText());
    }

    @Test
    public void testBadJson() throws Exception {
        try {
            ControlResponse.fromJson("blarg");
            fail("Deserializing nonsense JSON should result in a VonageUnexpectedException");
        } catch (VonageUnexpectedException nue) {
            // This is expected
        }
    }
}


text:
var method = Sensor.prototype;

var Auxiliares = require('../util/Auxiliares.js');
var hp = new Auxiliares();

var objSensor;

function Sensor()
{
 objSensor = new Object({
   IdSensor : Number
  , IdDispositivo : String
  , Descripcion : String
  , MarcaModelo : String
  , Tipo : String
  , Pin : Number
  , EsPinAnalogo : Boolean
  , Habilitado : Boolean
});
}

method.Crear = function(IdSensor,IdDispositivo, Descripcion, MarcaModelo, Tipo,Pin,EsPinAnalogo, Habilitado)
{

  objSensor.IdSensor = parseInt(IdSensor);
  objSensor.IdDispositivo = IdDispositivo;
  objSensor.Descripcion = Descripcion;
  objSensor.MarcaModelo = MarcaModelo;
  objSensor.Tipo = Tipo;
  objSensor.Pin = Pin;
  objSensor.EsPinAnalogo = hp.toBoolean(EsPinAnalogo);
  objSensor.Habilitado = hp.toBoolean(Habilitado);
};

method.Objeto = function()
{
  return objSensor;
};

method.Modificar = function(IdSensor,IdDispositivo, Descripcion, MarcaModelo, Tipo,Pin,EsPinAnalogo,Habilitado)
{
  //objSensor.IdSensor = IdSensor;
  objSensor.IdDispositivo = IdDispositivo;
  objSensor.Descripcion = Descripcion;
  objSensor.MarcaModelo = MarcaModelo;
  objSensor.Tipo = Tipo;
  objSensor.Pin = Pin;
  objSensor.EsPinAnalogo = hp.toBoolean(EsPinAnalogo);
  objSensor.Habilitado = hp.toBoolean(Habilitado);
};

method.Validar = function(obj)
{
  if (!obj.IdSensor)
  {
    console.log("dto.Sensor : La property IdSensor no puede ser null");
    return false;
  }
  return true;

}

module.exports = Sensor;


text:
#define RUNTIME_FUNCTION_LIST_DEBUGGER(F) \
  /* Debugger support*/ \
  F(DebugBreak, 0, 1) \
  F(SetDebugEventListener, 2, 1) \
  F(Break, 0, 1) \
  F(DebugGetPropertyDetails, 2, 1) \
  F(DebugGetProperty, 2, 1) \
  F(DebugPropertyTypeFromDetails, 1, 1) \
  F(DebugPropertyAttributesFromDetails, 1, 1) \
  F(DebugPropertyIndexFromDetails, 1, 1) \
  F(DebugNamedInterceptorPropertyValue, 2, 1) \
  F(DebugIndexedInterceptorElementValue, 2, 1) \
  F(CheckExecutionState, 1, 1) \
  F(GetFrameCount, 1, 1) \
  F(GetFrameDetails, 2, 1) \
  F(GetScopeCount, 2, 1) \
  F(GetStepInPositions, 2, 1) \
  F(GetScopeDetails, 4, 1) \
  F(GetAllScopesDetails, 4, 1) \
  F(GetFunctionScopeCount, 1, 1) \
  F(GetFunctionScopeDetails, 2, 1) \
  F(SetScopeVariableValue, 6, 1) \
  F(DebugPrintScopes, 0, 1) \
  F(GetThreadCount, 1, 1) \
  F(GetThreadDetails, 2, 1) \
  F(SetDisableBreak, 1, 1) \
  F(GetBreakLocations, 2, 1) \
  F(SetFunctionBreakPoint, 3, 1) \
  F(SetScriptBreakPoint, 4, 1) \
  F(ClearBreakPoint, 1, 1) \
  F(ChangeBreakOnException, 2, 1) \
  F(IsBreakOnException, 1, 1) \
  F(PrepareStep, 4, 1) \
  F(ClearStepping, 0, 1) \
  F(DebugEvaluate, 6, 1) \
  F(DebugEvaluateGlobal, 4, 1) \
  F(DebugGetLoadedScripts, 0, 1) \
  F(DebugReferencedBy, 3, 1) \
  F(DebugConstructedBy, 2, 1) \
  F(DebugGetPrototype, 1, 1) \
  F(DebugSetScriptSource, 2, 1) \
  F(SystemBreak, 0, 1) \
  F(DebugDisassembleFunction, 1, 1) \
  F(DebugDisassembleConstructor, 1, 1) \
  F(FunctionGetInferredName, 1, 1) \
  F(LiveEditFindSharedFunctionInfosForScript, 1, 1) \
  F(LiveEditGatherCompileInfo, 2, 1) \
  F(LiveEditReplaceScript, 3, 1) \
  F(LiveEditReplaceFunctionCode, 2, 1) \
  F(LiveEditFunctionSourceUpdated, 1, 1) \
  F(LiveEditFunctionSetScript, 2, 1) \
  F(LiveEditReplaceRefToNestedFunction, 3, 1) \
  F(LiveEditPatchFunctionPositions, 2, 1) \
  F(LiveEditCheckAndDropActivations, 2, 1) \
  F(LiveEditCompareStrings, 2, 1) \
  F(LiveEditRestartFrame, 2, 1) \
  F(GetFunctionCodePositionFromSource, 2, 1) \
  F(ExecuteInDebugContext, 2, 1) \
  \
  F(SetFlags, 1, 1) \
  F(CollectGarbage, 1, 1) \
  F(GetHeapUsage, 0, 1) \


text:
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/. */

define(["require", "util", "channels", "jquery", "storage"], function (require, util, channels, $, storage) {

  var DEBUG = true;

  // This is the amount of time in which a hello-back must be received after a hello
  // for us to respect a URL change:
  var HELLO_BACK_CUTOFF = 1500;

  var session = util.mixinEvents(util.Module("session"));
  var assert = util.assert;

  // We will load this module later (there's a circular import):
  var peers;

  // This is the hub we connect to:
  session.shareId = null;
  // This is the ID that identifies this client:
  session.clientId = null;
  session.router = channels.Router();
  // Indicates if TogetherJS has just started (not continuing from a saved session):
  session.firstRun = false;

  // This is the key we use for localStorage:
  var localStoragePrefix = "togetherjs.";
  // This is the channel to the hub:
  var channel = null;

  // Setting, essentially global:
  session.AVATAR_SIZE = 90;

  var MAX_SESSION_AGE = 30*24*60*60*1000; // 30 days

  /****************************************
   * URLs
   */
  var includeHashInUrl = TogetherJS.config.get("includeHashInUrl");
  TogetherJS.config.close("includeHashInUrl");
  var currentUrl = (location.href + "").replace(/\#.*$/, "");
  if (includeHashInUrl) {
    currentUrl = location.href;
  }

  session.hubUrl = function (id) {
    id = id || session.shareId;
    assert(id, "URL cannot be resolved before TogetherJS.shareId has been initialized");
    TogetherJS.config.close("hubBase");
    var hubBase = TogetherJS.config.get("hubBase");
    return hubBase.replace(/\/*$/, "") + "/hub/" + id;
  };

  session.shareUrl = function () {
    assert(session.shareId, "Attempted to access shareUrl() before shareId is set");
    var hash = location.hash;
    var m = /\?[^#]*/.exec(location.href);
    var query = "";
    if (m) {
      query = m[0];
    }
    hash = hash.replace(/&?togetherjs-[a-zA-Z0-9]+/, "");
    hash = hash || "#";
    return location.protocol + "//" + location.host + location.pathname + query +
           hash + "&togetherjs=" + session.shareId;
  };

  session.recordUrl = function () {
    assert(session.shareId);
    var url = TogetherJS.baseUrl.replace(/\/*$/, "") + "/togetherjs/recorder.html";
    url += "#&togetherjs=" + session.shareId + "&hubBase=" + TogetherJS.config.get("hubBase");
    return url;
  };

  /* location.href without the hash */
  session.currentUrl = function () {
    if (includeHashInUrl) {
      return location.href;
    } else {
      return location.href.replace(/#.*/, "");
    }
  };

  /****************************************
   * Message handling/dispatching
   */

  session.hub = util.mixinEvents({});

  var IGNORE_MESSAGES = TogetherJS.config.get("ignoreMessages");
  if (IGNORE_MESSAGES === true) {
    DEBUG = false;
    IGNORE_MESSAGES = [];
  }
  // These are messages sent by clients who aren't "part" of the TogetherJS session:
  var MESSAGES_WITHOUT_CLIENTID = ["who", "invite", "init-connection"];

  // We ignore incoming messages from the channel until this is true:
  var readyForMessages = false;

  function openChannel() {
    assert(! channel, "Attempt to re-open channel");
    console.info("Connecting to", session.hubUrl(), location.href);
    var c = channels.WebSocketChannel(session.hubUrl());
    c.onmessage = function (msg) {
      if (! readyForMessages) {
        if (DEBUG) {
          console.info("In (but ignored for being early):", msg);
        }
        return;
      }
      if (DEBUG && IGNORE_MESSAGES.indexOf(msg.type) == -1) {
        console.info("In:", msg);
      }
      if (! peers) {
        // We're getting messages before everything is fully initialized
        console.warn("Message received before all modules loaded (ignoring):", msg);
        return;
      }
      if ((! msg.clientId) && MESSAGES_WITHOUT_CLIENTID.indexOf(msg.type) == -1) {
        console.warn("Got message without clientId, where clientId is required", msg);
        return;
      }
      if (msg.clientId) {
        msg.peer = peers.getPeer(msg.clientId, msg);
      }
      if (msg.type == "hello" || msg.type == "hello-back" || msg.type == "peer-update") {
        // We do this here to make sure this is run before any other
        // hello handlers:
        msg.peer.updateFromHello(msg);
      }
      if (msg.peer) {
        msg.sameUrl = msg.peer.url == currentUrl;
        if (!msg.peer.isSelf) {
          msg.peer.updateMessageDate(msg);
        }
      }
      session.hub.emit(msg.type, msg);
      TogetherJS._onmessage(msg);
    };
    channel = c;
    session.router.bindChannel(channel);
  }

  session.send = function (msg) {
    if (DEBUG && IGNORE_MESSAGES.indexOf(msg.type) == -1) {
      console.info("Send:", msg);
    }
    msg.clientId = session.clientId;
    channel.send(msg);
  };

  session.appSend = function (msg) {
    var type = msg.type;
    if (type.search(/^togetherjs\./) === 0) {
      type = type.substr("togetherjs.".length);
    } else if (type.search(/^app\./) === -1) {
      type = "app." + type;
    }
    msg.type = type;
    session.send(msg);
  };

  /****************************************
   * Standard message responses
   */

  /* Always say hello back, and keep track of peers: */
  session.hub.on("hello hello-back", function (msg) {
    if (msg.type == "hello") {
      sendHello(true);
    }
    if (session.isClient && (! msg.isClient) &&
        session.firstRun && session.timeHelloSent &&
        Date.now() - session.timeHelloSent < HELLO_BACK_CUTOFF) {
      processFirstHello(msg);
    }
  });

  session.hub.on("who", function (msg) {
    sendHello(true);
  });

  function processFirstHello(msg) {
    if (! msg.sameUrl) {
      var url = msg.url;
      if (msg.urlHash) {
        url += msg.urlHash;
      }
      require("ui").showUrlChangeMessage(msg.peer, url);
      location.href = url;
    }
  }

  session.timeHelloSent = null;

  function sendHello(helloBack) {
    var msg = session.makeHelloMessage(helloBack);
    if (! helloBack) {
      session.timeHelloSent = Date.now();
      peers.Self.url = msg.url;
    }
    session.send(msg);
  }

  session.makeHelloMessage = function (helloBack) {
    var msg = {
      name: peers.Self.name || peers.Self.defaultName,
      avatar: peers.Self.avatar,
      color: peers.Self.color,
      url: session.currentUrl(),
      urlHash: location.hash,
      // FIXME: titles update, we should track those changes:
      title: document.title,
      rtcSupported: session.RTCSupported,
      isClient: session.isClient
    };
    if (helloBack) {
      msg.type = "hello-back";
    } else {
      msg.type = "hello";
      msg.clientVersion = TogetherJS.version;
    }
    if (! TogetherJS.startup.continued) {
      msg.starting = true;
    }
    // This is a chance for other modules to effect the hello message:
    session.emit("prepare-hello", msg);
    return msg;
  };
  /****************************************
   * Lifecycle (start and end)
   */

  // These are Javascript files that implement features, and so must
  // be injected at runtime because they aren't pulled in naturally
  // via define().
  // ui must be the first item:
  var features = ["peers", "ui", "chat", "webrtc", "cursor", "startup", "videos", "forms", "visibilityApi", "youtubeVideos"];

  function getRoomName(prefix, maxSize) {
    var findRoom = TogetherJS.config.get("hubBase").replace(/\/*$/, "") + "/findroom";
    return $.ajax({
      url: findRoom,
      dataType: "json",
      data: {prefix: prefix, max: maxSize}
    }).then(function (resp) {
      return resp.name;
    });
  }

  function initIdentityId() {
    return util.Deferred(function (def) {
      if (session.identityId) {
        def.resolve();
        return;
      }
      storage.get("identityId").then(function (identityId) {
        if (! identityId) {
          identityId = util.generateId();
          storage.set("identityId", identityId);
        }
        session.identityId = identityId;
        // We don't actually have to wait for the set to succede, so
        // long as session.identityId is set
        def.resolve();
      });
    });
  }

  initIdentityId.done = initIdentityId();

  function initShareId() {
    return util.Deferred(function (def) {
      var hash = location.hash;
      var shareId = session.shareId;
      var isClient = true;
      var set = true;
      var sessionId;
      session.firstRun = ! TogetherJS.startup.continued;
      if (! shareId) {
        if (TogetherJS.startup._joinShareId) {
          // Like, below, this *also* means we got the shareId from the hash
          // (in togetherjs.js):
          shareId = TogetherJS.startup._joinShareId;
        }
      }
      if (! shareId) {
        // FIXME: I'm not sure if this will ever happen, because togetherjs.js should
        // handle it
        var m = /&?togetherjs=([^&]*)/.exec(hash);
        if (m) {
          isClient = ! m[1];
          shareId = m[2];
          var newHash = hash.substr(0, m.index) + hash.substr(m.index + m[0].length);
          location.hash = newHash;
        }
      }
      return storage.tab.get("status").then(function (saved) {
        var findRoom = TogetherJS.config.get("findRoom");
        TogetherJS.config.close("findRoom");
        if (findRoom && saved && findRoom != saved.shareId) {
          console.info("Ignoring findRoom in lieu of continued session");
        } else if (findRoom && TogetherJS.startup._joinShareId) {
          console.info("Ignoring findRoom in lieu of explicit invite to session");
        }
        if (findRoom && typeof findRoom == "string" && (! saved) && (! TogetherJS.startup._joinShareId)) {
          isClient = true;
          shareId = findRoom;
          sessionId = util.generateId();
        } else if (findRoom && (! saved) && (! TogetherJS.startup._joinShareId)) {
          assert(findRoom.prefix && typeof findRoom.prefix == "string", "Bad findRoom.prefix", findRoom);
          assert(findRoom.max && typeof findRoom.max == "number" && findRoom.max > 0,
                 "Bad findRoom.max", findRoom);
          sessionId = util.generateId();
          if (findRoom.prefix.search(/[^a-zA-Z0-9]/) != -1) {
            console.warn("Bad value for findRoom.prefix:", JSON.stringify(findRoom.prefix));
          }
          getRoomName(findRoom.prefix, findRoom.max).then(function (shareId) {
            // FIXME: duplicates code below:
            session.clientId = session.identityId + "." + sessionId;
            storage.tab.set("status", {reason: "joined", shareId: shareId, running: true, date: Date.now(), sessionId: sessionId});
            session.isClient = true;
            session.shareId = shareId;
            session.emit("shareId");
            def.resolve(session.shareId);
          });
          return;
        } else if (TogetherJS.startup._launch) {
          if (saved) {
            isClient = saved.reason == "joined";
            if (! shareId) {
              shareId = saved.shareId;
            }
            sessionId = saved.sessionId;
          } else {
            isClient = TogetherJS.startup.reason == "joined";
            assert(! sessionId);
            sessionId = util.generateId();
          }
          if (! shareId) {
            shareId = util.generateId();
          }
        } else if (saved) {
          isClient = saved.reason == "joined";
          TogetherJS.startup.reason = saved.reason;
          TogetherJS.startup.continued = true;
          shareId = saved.shareId;
          sessionId = saved.sessionId;
          // The only case when we don't need to set the storage status again is when
          // we're already set to be running
          set = ! saved.running;
        } else {
          throw new util.AssertionError("No saved status, and no startup._launch request; why did TogetherJS start?");
        }
        assert(session.identityId);
        session.clientId = session.identityId + "." + sessionId;
        if (set) {
          storage.tab.set("status", {reason: TogetherJS.startup.reason, shareId: shareId, running: true, date: Date.now(), sessionId: sessionId});
        }
        session.isClient = isClient;
        session.shareId = shareId;
        session.emit("shareId");
        def.resolve(session.shareId);
      });
    });
  }

  function initStartTarget() {
    var id;
    if (TogetherJS.startup.button) {
      id = TogetherJS.startup.button.id;
      if (id) {
        storage.set("startTarget", id);
      }
      return;
    }
    storage.get("startTarget").then(function (id) {
      var el = document.getElementById(id);
      if (el) {
        TogetherJS.startup.button = el;
      }
    });
  }
  session.start = function () {
    initStartTarget();
    initIdentityId().then(function () {
      initShareId().then(function () {
        readyForMessages = false;
        openChannel();
        require(["ui"], function (ui) {
          TogetherJS.running = true;
          ui.prepareUI();
          require(features, function () {
            $(function () {
              peers = require("peers");
              var startup = require("startup");
              session.emit("start");
              session.once("ui-ready", function () {
                readyForMessages = true;
                startup.start();
              });
              ui.activateUI();
              TogetherJS.config.close("enableAnalytics");
              if (TogetherJS.config.get("enableAnalytics")) {
                require(["analytics"], function (analytics) {
                  analytics.activate();
                });
              }
              peers._SelfLoaded.then(function () {
                sendHello(false);
              });
              TogetherJS.emit("ready");
            });
          });
        });
      });
    });
  };

  session.close = function (reason) {
    TogetherJS.running = false;
    var msg = {type: "bye"};
    if (reason) {
      msg.reason = reason;
    }
    session.send(msg);
    session.emit("close");
    var name = window.name;
    storage.tab.get("status").then(function (saved) {
      if (! saved) {
        console.warn("No session information saved in", "status." + name);
      } else {
        saved.running = false;
        saved.date = Date.now();
        storage.tab.set("status", saved);
      }
      channel.close();
      channel = null;
      session.shareId = null;
      session.emit("shareId");
      TogetherJS.emit("close");
      TogetherJS._teardown();
    });
  };

  session.on("start", function () {
    $(window).on("resize", resizeEvent);
    if (includeHashInUrl) {
      $(window).on("hashchange", hashchangeEvent);
    }
  });

  session.on("close", function () {
    $(window).off("resize", resizeEvent);
    if (includeHashInUrl) {
      $(window).off("hashchange", hashchangeEvent);
    }
  });

  function hashchangeEvent() {
    // needed because when message arives from peer this variable will be checked to
    // decide weather to show actions or not
    sendHello(false);
  }

  function resizeEvent() {
    session.emit("resize");
  }

  if (TogetherJS.startup._launch) {
    setTimeout(session.start);
  }

  util.testExpose({
    getChannel: function () {
      return channel;
    }
  });

  return session;
});


text:
require "uri"

class Doubleshot
  class Resolver
    def initialize(*repositories)
      @repositories = repositories.map do |repository|
        URI.parse repository.to_s
      end
      raise ArgumentError.new("no repositories specified") if @repositories.empty?
    end

    def fetch(dependencies)
      raise NotImplementedError.new
    end

    def repositories
      ReadonlyCollection.new(@repositories)
    end
  end
end

require "doubleshot/resolver/gem_resolver"
require "doubleshot/resolver/jar_resolver"


text:
const _ = require("lodash"),
      debug = require("debug")("clusterluck:lib:chash"),
      rbt = require("functional-red-black-tree"),
      LRU = require("lru-cache"),
      crypto = require("crypto"),
      Node = require("./node"),
      utils = require("./utils"),
      consts = require("./consts");

const chashOpts = consts.chashOpts;

class CHash {
  /**
   *
   * Consistent hash implementation. Maintains a red-black tree containing the hash ring (for ordering), with keys as hashes of node names and values as the nodes themselves. This implementation also contains an `rfactor` (replication factor) and `pfactor` (persistence factor). `rfactor` dictates how many times an element is inserted into the ring, while `pfactor` dictates how many nodes will be used for redundancy.
   *
   * @class CHash CHash
   * @memberof Clusterluck
   *
   * @param {Number} rfactor - Replication factor for node insertion.
   * @param {Number} pfactor - Persistence factor for redundancy in node-neighbor calculations.
   * @param {RBTree} [tree] - Existing red-black tree to instantiate local tree from.
   * @param {Object} [opts] - Options object for hash ring.
   * @param {Number} [opts.maxCacheSize] - Maximum cache size for caching hash values in hash ring. Defaults to 5000.
   *
   */
  constructor(rfactor, pfactor, tree, opts=chashOpts) {
    opts = _.defaults(opts, chashOpts);
    this._rfactor = rfactor;
    this._pfactor = pfactor;
    this._tree = tree || rbt();
    this._cache = new LRU({max: opts.maxCacheSize});
    this._calculateWeights();
  }

  /**
   * Inserts `node` into this ring, repeating this process `rfactor` number of times. Ignores insertions if `node` is already present in the hash ring.
   *
   * @method insert
   * @memberof Clusterluck.CHash
   * @instance
   *
   * @param {Node} node - Node to insert into this instance.
   * @param {Number} [weight] - Number of times to insert this node. Defaults to `rfactor`.
   *
   * @return {Clusterluck.CHash} This instance.
   *
   */
  insert(node, weight) {
    if (this._weights.has(node.id())) return this;
    weight = weight !== undefined ? weight : this._rfactor;
    _.times(weight, (n) => {
      this._tree = this._tree.insert(this._nodeName(node, n+1), node);
    });
    this._weights.set(node.id(), weight);
    return this;
  }

  /**
   * Removes `node` from this ring, repeating this process `rfactor` number of times. Ignores removals `node` doesn't exist in the ring.
   *
   * @method remove
   * @memberof Clusterluck.CHash
   * @instance
   *
   * @param {Node} node - Node to remove from this instance.
   *
   * @return {Clusterluck.CHash} This instance.
   *
   */
  remove(node) {
    if (this._weights.has(node.id()) === false) return this;
    const weight = this._weights.get(node.id());
    _.times(weight, (n) => {
      this._tree = this._tree.remove(this._nodeName(node, n+1));
    });
    this._weights.delete(node.id());
    return this;
  }

  /**
   * Gets `node` from the hash ring by class. Useful if the id is known but host and port need to be queried.
   *
   * @method get
   * @memberof Clusterluck.CHash
   * @instance
   *
   * @param {Node} node - Node to access.
   * @param {Node} def - Default value to return if `node` doesn't exist in the hash ring.
   *
   * @return {Node} Node with matching id.
   *
   */
  get(node, def) {
    const res = this._tree.get(this._nodeName(node, 1));
    return res === undefined ? def : res;
  }

  /**
   * Update the weight of `node` in the hash ring.
   *
   * @method update
   * @memberof Clusterluck.CHash
   * @instance
   *
   * @param {Node} node - Node to add state to.
   * @param {Number} weight - Weight to change `node` to in the ring.
   *
   * @return {Clusterluck.CHash} This instance.
   *
   */
  update(node, weight) {
    this.remove(node);
    this._weights.set(node.id(), weight);
    _.times(weight, (n) => {
      this._tree = this._tree.insert(this._nodeName(node, n+1), node);
    });
    return this;
  }

  /**
   * Finds the next node in the hash ring based on the bucket placement of `data`. If no succeeding node exists, loops around to the beginning of the hash ring and picks the first node.
   *
   * @method find
   * @memberof Clusterluck.CHash
   * @instance
   *
   * @param {String} data - Data to find the next node off of.
   *
   * @return {Node} Next node in the hash ring.
   *
   */
  find(data) {
    const hash = this._findHash(data);
    const iter = this._tree.gt(hash);
    if (iter.valid === false) return this._tree.begin.value;
    return iter.value;
  }

  /**
   * Returns a list of neighbors of `node` in the hash ring. This is bounded by `pfactor`, which dictates the maximum number of neighbors a node can have (barring size limitations).
   *
   * @method next
   * @memberof Clusterluck.CHash
   * @instance
   *
   * @param {Node} node - Node to find neighbors of.
   *
   * @return {Array} Neighbors of `node` in the hash ring.
   *
   */
  next(node, range) {
    if (this._weights.size <= 1 || this._weights.has(node.id()) === false) return [];

    range = Math.min(range !== undefined ? range : this._pfactor, this._weights.size-1);
    const result = new Map();
    const name = this._nodeName(node, 1);
    const iter = this._tree.gt(name);
    this._successors(node, iter, result, range);
    return utils.mapValues(result);
  }

  /**
   * Returns a bucket of nodes including and following the hash slot corresponding to `data`. This is bounded by `range`, which dictates the size of the bucket returned).
   *
   * @method rangeNext
   * @memberof Clusterluck.CHash
   * @instance
   *
   * @param {String} data - Data to calculate hash of and find following nodes.
   * @param {Number} [range] - Number of nodes to return. Defaults to `rfactor`.
   *
   * @return {Array} Bucket of nodes with size `range` associated with key `data`.
   *
   */
  rangeNext(data, range) {
    if (this.size() === 0) return [];

    range = Math.min(range !== undefined ? range : (this._pfactor+1), this._weights.size);
    const hash = this._findHash(data);
    const result = new Map();

    let iter = this._tree.gt(hash);
    if (iter.valid === false) iter = this._tree.begin;

    const node = iter.value;
    result.set(node.id(), node);
    iter.next();
    this._successors(node, iter, result, range);
    return utils.mapValues(result);
  }

  /**
   * Returns a list of preceding neighbors of `node` in the hash ring. This is bounded by `pfactor`, which dictates the maximum number of neighbors a node can have (barring size limitations).
   *
   * @method prev
   * @memberof Clusterluck.CHash
   * @instance
   *
   * @param {Node} node - Node to find neighbors of.
   *
   * @return {Array} Neighbors of `node` in the hash ring.
   *
   */
  prev(node, range) {
    if (this.size() <= 1 || this._weights.has(node.id()) === false) return [];

    range = Math.min(range !== undefined ? range : this._pfactor, this._weights.size-1);
    const result = new Map();
    const name = this._nodeName(node, 1);
    const iter = this._tree.lt(name);
    this._precursors(node, iter, result, range);
    return utils.mapValues(result);
  }

  /**
   * Returns a bucket of nodes preceding the hash slot corresponding to `data`. This is bounded by `range`, which dictates the size of the bucket returned).
   *
   * @method rangePrev
   * @memberof Clusterluck.CHash
   * @instance
   *
   * @param {String} data - Data to calculate hash of and find following nodes.
   * @param {Number} [range] - Number of nodes to return. Defaults to `rfactor`.
   *
   * @return {Array} Bucket of nodes with size `range` preceding key `data`.
   *
   */
  rangePrev(data, range) {
    if (this.size() === 0) return [];

    range = Math.min(range !== undefined ? range : (this._pfactor+1), this._weights.size);
    const hash = this._findHash(data);
    const result = new Map();

    let iter = this._tree.lt(hash);
    if (iter.valid === false) iter = this._tree.end;

    const node = iter.value;
    result.set(node.id(), node);
    iter.prev();
    this._precursors(node, iter, result, range);
    return utils.mapValues(result);
  }

  /**
   * Computes a set-union on two hash rings, inserting any nodes present in `chash` that aren't in this hash ring.
   *
   * @method merge
   * @memberof Clusterluck.CHash
   * @instance
   *
   * @param {Clusterluck.CHash} chash - Hash ring to merge with.
   *
   * @return {Clusterluck.CHash} This instance.
   *
   */
  merge(chash) {
    chash.tree().forEach((key, value) => {
      if (this._tree.get(key) === undefined) {
        this._tree = this._tree.insert(key, value);
        if (this._weights.has(value.id())) {
          const weight = this._weights.get(value.id());
          this._weights.set(value.id(), weight+1);
        } else {
          this._weights.set(value.id(), 1);
        }
      }
    });
    return this;
  }

  /**
   * Computes a set-intersection on two hash rings, removing any nodes not found in both rings.
   *
   * @method intersect
   * @memberof Clusterluck.CHash
   * @instance
   *
   * @param {Clusterluck.CHash} chash - Hash ring to intersect with.
   *
   * @return {Clusterluck.CHash} This instance.
   *
   */
  intersect(chash) {
    let tree = rbt();
    this._weights.clear();
    chash.tree().forEach((key, value) => {
      if (this._tree.get(key) !== undefined) {
        tree = tree.insert(key, value);
        if (this._weights.has(value.id())) {
          const weight = this._weights.get(value.id());
          this._weights.set(value.id(), weight+1);
        } else {
          this._weights.set(value.id(), 1);
        }
      }
    });
    this._tree = tree;
    return this;
  }

  /**
   * Acts as a getter for the number of elements in this hash ring.
   *
   * @method size
   * @memberof Clusterluck.CHash
   * @instance
   *
   * @return {Number} Number of elements in this hash ring.
   *
   */
  size() {
    return this._tree.length;
  }

  /**
   * Returns the number of nodes in the ring.
   *
   * @method numberNodes
   * @memberof Clusterluck.CHash
   * @instance
   *
   * @return {Number} Number of nodes in this hash ring.
   *
   */
  numberNodes() {
    return this._weights.size;
  }

  /**
   * Returns the weight map from node IDs to weights in the hash ring.
   *
   * @method weights
   * @memberof Clusterluck.CHash
   * @instance
   *
   * @return {Map} Weight map from node IDs to weights
   *
   */
  weights() {
    return this._weights;
  }

  /**
   * Acts as a getter for the nodes in this hash ring.
   *
   * @method nodes
   * @memberof Clusterluck.CHash
   * @instance
   *
   * @return {Array} List of nodes in this hash ring.
   *
   */
  nodes() {
    const memo = {};
    this._tree.forEach((key, node) => {
      memo[node.id()] = node;
    });
    return _.values(memo);
  }

  /**
   * Checks `node` is defined in this hash ring.
   *
   * @method isDefined
   * @memberof Clusterluck.CHash
   * @instance
   *
   * @return {Boolean} Whether `node` is defined.
   *
   */
  isDefined(node) {
    return this._weights.has(node.id());
  }

  /**
   * Acts as a getter/setter for the red-black tree of this hash ring.
   *
   * @method tree
   * @memberof Clusterluck.CHash
   * @instance
   *
   * @param {RBTree} [tree] - Tree to set on this instance.
   *
   * @return {RBTree} Red-black tree of this instance.
   *
   */
  tree(t) {
    if (t !== undefined) {
      this._tree = t;
    }
    return this._tree;
  }

  /**
   * Acts as a getter/setter for the rfactor of this hash ring.
   *
   * @method rfactor
   * @memberof Clusterluck.CHash
   * @instance
   *
   * @param {Number} [r] - rfactor to set on this ring.
   *
   * @return {Number} rfactor of this instance.
   *
   */
  rfactor(r) {
    if (typeof r === "number") {
      this._rfactor = r;
    }
    return this._rfactor;
  }

  /**
   * Acts as a getter/setter for the pfactor of this hash ring.
   *
   * @method pfactor
   * @memberof Clusterluck.CHash
   * @instance
   *
   * @param {Number} [p] - pfactor to set on this ring.
   *
   * @return {Number} pfactor of this instance.
   *
   */
  pfactor(p) {
    if (typeof p === "number") {
      this._pfactor = p;
    }
    return this._pfactor;
  }

  /**
   *
   * Returns whether two consistent hash rings are equal. This involves checking the following:
   *  - The hash rings have the same size
   *  - For every entry in this instance's RBT, the corresponding entry exists in the RBT of `chash`
   *
   * @method equals
   * @memberof Clusterluck.CHash
   * @instance
   *
   * @param {Clusterluck.CHash} chash - CHash to derive equality against.
   *
   * @return {Boolean} Whether this chash instance equals `chash`.
   *
   */
  equals(chash) {
    if (this._tree.length !== chash.tree().length) return false;
    const tree = chash.tree();
    const it = this.begin();
    let out;
    while (it.valid) {
      out = tree.get(it.key);
      if (!out) return false;
      if (!it.value.equals(out)) return false;
      it.next();
    }
    return true;
  }

  /**
   * Computes the JSON serialization of this instance. Useful when periodically flushing this ring to disk.
   *
   * @method toJSON
   * @memberof Clusterluck.CHash
   * @instance
   *
   * @param {Boolean} [fast] - Whether to compute the JSON serialization of this instance using a copy of internal state.
   *
   * @return {Object} JSON serialization of this instance.
   *
   */
  toJSON(fast) {
    const tree = [];
    this._tree.forEach((key, val) => {
      tree.push({key: key, value: val.toJSON(fast)});
    });
    const out = {
      rfactor: this._rfactor,
      pfactor: this._pfactor,
      tree: tree
    };
    return fast === true ? out : _.cloneDeep(out);
  }

  /**
   * Instantiates state from a JSON object.
   *
   * @method fromJSON
   * @memberof Clusterluck.CHash
   * @instance
   *
   * @param {Object} ent - JSON object to instantiate state from.
   *
   * @return {Clusterluck.CHash} This instance.
   *
   */
  fromJSON(ent) {
    this._rfactor = ent.rfactor;
    this._pfactor = ent.pfactor;
    this._tree = rbt();
    ent.tree.forEach((val) => {
      const node = new Node(val.value.id, val.value.host, val.value.port);
      this._tree = this._tree.insert(val.key, node);
    });
    this._calculateWeights();
    return this;
  }

  /**
   * Generates an iterator on this hash ring, starting at the first (smallest hash) node.
   *
   * @method begin
   * @memberof Clusterluck.CHash
   * @instance
   *
   * @return {Iterator} Iterator over this instance.
   *
   */
  begin() {
    return this._tree.begin;
  }

  /**
   * Generates an iterator on this hash ring, starting at the last (largest hash) node.
   *
   * @method end
   * @memberof Clusterluck.CHash
   * @instance
   *
   * @return {Iterator} Iterator over this instance.
   *
   */
  end() {
    return this._tree.end;
  }

  /**
   * Generates an iterator on this hash ring, starting at `node`.
   *
   * @method iterator
   * @memberof Clusterluck.CHash
   * @instance
   *
   * @param {Node} node - Node to start iteration on.
   *
   * @return {Iterator} Iterator over this instance.
   *
   */
  iterator(node) {
    return this._tree.find(node);
  }

  /**
   *
   * @method _successors
   * @memberof Clusterluck.CHash
   * @private
   * @instance
   *
   */
  _successors(node, iter, memo, range) {
    // if we have more nodes than pfactor, pfactor will be number of elements returned
    // otherwise, return number of nodes other than node
    if (memo.size === range) {
      return memo;
    }
    if (iter.valid === false) {
      return this._successors(node, this._tree.begin, memo, range);
    }
    if (iter.value.id() === node.id()) {
      iter.next();
      return this._successors(node, iter, memo, range);
    }

    const val = iter.value;
    memo.set(val.id(), val);
    iter.next();
    return this._successors(node, iter, memo, range);
  }

  /**
   *
   * @method _precursors
   * @memberof Clusterluck.CHash
   * @private
   * @instance
   *
   */
  _precursors(node, iter, memo, range) {
    if (memo.size === range) {
      return memo;
    }
    if (iter.valid === false) {
      return this._precursors(node, this._tree.end, memo, range);
    }
    if (iter.value.id() === node.id()) {
      iter.prev();
      return this._precursors(node, iter, memo, range);
    }

    const val = iter.value;
    memo.set(val.id(), iter.value);
    iter.prev();
    return this._precursors(node, iter, memo, range);
  }

  /**
   *
   * @method _nodeName
   * @memberof Clusterluck.CHash
   * @instance
   * @private
   *
   */
  _nodeName(node, index) {
    return this._findHash(node.id() + "_" + index);
  }

  /**
   *
   * @method _findHash
   * @memberof Clusterluck.CHash
   * @instance
   * @private
   *
   */
  _findHash(data) {
    if (this._cache.has(data)) return this._cache.get(data);
    const value = crypto.createHash("sha256").update(data).digest("base64");
    this._cache.set(data, value);
    return value;
  }

  /**
   *
   * @method _calculateWeights
   * @memberof Clusterluck.CHash
   * @instance
   * @private
   *
   */
  _calculateWeights() {
    const memo = new Map();
    this._tree.forEach((key, val) => {
      if (memo.has(val.id())) {
        const weight = memo.get(val.id());
        memo.set(val.id(), weight+1);
      } else {
        memo.set(val.id(), 1);
      }
    });
    this._weights = memo;
    return memo;
  }
}

module.exports = CHash;


text:
package dao;

import entity.TradeEntity;

public interface TradeDao {
	public boolean save(TradeEntity trade);
}


text:
cask 'logmein-hamachi' do
  version :latest
  sha256 :no_check

  # logmein.com is the official download host per the vendor homepage
  url 'https://secure.logmein.com/LogMeInHamachi.zip'
  name 'LogMeIn Hamachi'
  homepage 'https://vpn.net'
  license :freemium

  installer script: 'LogMeInHamachiInstaller.app/Contents/MacOS/Lili',
            args:   ['-s'],
            sudo:   true

  uninstall script: {
                      executable: '/Applications/LogMeIn Hamachi/HamachiUninstaller.app/Contents/Resources/uninstaller.sh',
                      sudo:       true,
                    }
end


text:
using base::android::ScopedJavaGlobalRef;
using base::android::ScopedJavaLocalRef;
using base::android::AttachCurrentThread;
using base::android::ConvertJavaStringToUTF16;
using base::android::ConvertJavaStringToUTF8;
using base::android::ConvertUTF8ToJavaString;

namespace {

void OnLocalFaviconAvailable(
    ScopedJavaGlobalRef<jobject>* j_favicon_image_callback,
    const favicon_base::FaviconRawBitmapResult& result) {
  JNIEnv* env = AttachCurrentThread();

  // Convert favicon_image_result to java objects.
  ScopedJavaLocalRef<jstring> j_icon_url =
      ConvertUTF8ToJavaString(env, result.icon_url.spec());
  ScopedJavaLocalRef<jobject> j_favicon_bitmap;
  if (result.is_valid()) {
    SkBitmap favicon_bitmap;
    gfx::PNGCodec::Decode(result.bitmap_data->front(),
                          result.bitmap_data->size(),
                          &favicon_bitmap);
    if (!favicon_bitmap.isNull())
      j_favicon_bitmap = gfx::ConvertToJavaBitmap(&favicon_bitmap);
  }

  // Call java side OnLocalFaviconAvailable method.
  Java_FaviconImageCallback_onFaviconAvailable(env,
                                               j_favicon_image_callback->obj(),
                                               j_favicon_bitmap.obj(),
                                               j_icon_url.obj());
}

void OnFaviconRawBitmapResultAvailable(
    ScopedJavaGlobalRef<jobject>* j_favicon_image_callback,
    const favicon_base::FaviconRawBitmapResult& favicon_bitmap_result) {
  JNIEnv* env = AttachCurrentThread();

  // Convert favicon_image_result to java objects.
  ScopedJavaLocalRef<jstring> j_icon_url =
      ConvertUTF8ToJavaString(env, favicon_bitmap_result.icon_url.spec());

  SkBitmap favicon_bitmap;
  if (favicon_bitmap_result.is_valid()) {
    gfx::PNGCodec::Decode(favicon_bitmap_result.bitmap_data->front(),
                          favicon_bitmap_result.bitmap_data->size(),
                          &favicon_bitmap);
  }
  ScopedJavaLocalRef<jobject> j_favicon_bitmap;
  if (!favicon_bitmap.isNull())
    j_favicon_bitmap = gfx::ConvertToJavaBitmap(&favicon_bitmap);

  // Call java side OnLocalFaviconAvailable method.
  Java_FaviconImageCallback_onFaviconAvailable(env,
                                               j_favicon_image_callback->obj(),
                                               j_favicon_bitmap.obj(),
                                               j_icon_url.obj());
}

}  // namespace

static jlong Init(JNIEnv* env, jclass clazz) {
  return reinterpret_cast<intptr_t>(new FaviconHelper());
}

FaviconHelper::FaviconHelper() {
  cancelable_task_tracker_.reset(new base::CancelableTaskTracker());
}

void FaviconHelper::Destroy(JNIEnv* env, jobject obj) {
  delete this;
}

jboolean FaviconHelper::GetLocalFaviconImageForURL(
    JNIEnv* env,
    jobject obj,
    jobject j_profile,
    jstring j_page_url,
    jint j_icon_types,
    jint j_desired_size_in_pixel,
    jobject j_favicon_image_callback) {
  Profile* profile = ProfileAndroid::FromProfileAndroid(j_profile);
  DCHECK(profile);
  if (!profile)
    return false;

  FaviconService* favicon_service = FaviconServiceFactory::GetForProfile(
      profile, Profile::EXPLICIT_ACCESS);
  DCHECK(favicon_service);
  if (!favicon_service)
    return false;

  ScopedJavaGlobalRef<jobject>* j_scoped_favicon_callback =
      new ScopedJavaGlobalRef<jobject>();
  j_scoped_favicon_callback->Reset(env, j_favicon_image_callback);

  favicon_base::FaviconRawBitmapCallback callback_runner = base::Bind(
      &OnLocalFaviconAvailable, base::Owned(j_scoped_favicon_callback));

  favicon_service->GetRawFaviconForPageURL(
      GURL(ConvertJavaStringToUTF16(env, j_page_url)),
      static_cast<int>(j_icon_types),
      static_cast<int>(j_desired_size_in_pixel),
      callback_runner,
      cancelable_task_tracker_.get());

  return true;
}

void FaviconHelper::GetLargestRawFaviconForUrl(
    JNIEnv* env,
    jobject obj,
    jobject j_profile,
    jstring j_page_url,
    jintArray j_icon_types,
    jint j_min_size_threshold_px,
    jobject j_favicon_image_callback) {
  Profile* profile = ProfileAndroid::FromProfileAndroid(j_profile);
  DCHECK(profile);
  if (!profile)
    return;

  FaviconService* favicon_service = FaviconServiceFactory::GetForProfile(
      profile, Profile::EXPLICIT_ACCESS);
  DCHECK(favicon_service);
  if (!favicon_service)
    return;

  std::vector<int> icon_types;
  base::android::JavaIntArrayToIntVector(env, j_icon_types, &icon_types);

  ScopedJavaGlobalRef<jobject>* j_scoped_favicon_callback =
      new ScopedJavaGlobalRef<jobject>();
  j_scoped_favicon_callback->Reset(env, j_favicon_image_callback);

  favicon_base::FaviconRawBitmapCallback callback_runner =
      base::Bind(&OnFaviconRawBitmapResultAvailable,
                 base::Owned(j_scoped_favicon_callback));
  favicon_service->GetLargestRawFaviconForPageURL(
      GURL(ConvertJavaStringToUTF16(env, j_page_url)),
      icon_types,
      static_cast<int>(j_min_size_threshold_px),
      callback_runner,
      cancelable_task_tracker_.get());
}

ScopedJavaLocalRef<jobject> FaviconHelper::GetSyncedFaviconImageForURL(
    JNIEnv* env,
    jobject obj,
    jobject jprofile,
    jstring j_page_url) {
  Profile* profile = ProfileAndroid::FromProfileAndroid(jprofile);
  DCHECK(profile);

  std::string page_url = ConvertJavaStringToUTF8(env, j_page_url);

  ProfileSyncService* sync_service =
      ProfileSyncServiceFactory::GetInstance()->GetForProfile(profile);
  DCHECK(sync_service);

  scoped_refptr<base::RefCountedMemory> favicon_png;
  browser_sync::OpenTabsUIDelegate* open_tabs =
      sync_service->GetOpenTabsUIDelegate();
  DCHECK(open_tabs);

  if (!open_tabs->GetSyncedFaviconForPageURL(page_url, &favicon_png))
    return ScopedJavaLocalRef<jobject>();

  // Convert favicon_image_result to java objects.
  gfx::Image favicon_image = gfx::Image::CreateFrom1xPNGBytes(favicon_png);
  SkBitmap favicon_bitmap = favicon_image.AsBitmap();

  ScopedJavaLocalRef<jobject> j_favicon_bitmap;
  if (favicon_bitmap.isNull())
    return ScopedJavaLocalRef<jobject>();

  return gfx::ConvertToJavaBitmap(&favicon_bitmap);
}

FaviconHelper::~FaviconHelper() {}

static jint GetDominantColorForBitmap(JNIEnv* env,
                                      jclass clazz,
                                      jobject bitmap) {
  if (!bitmap)
    return 0;

    gfx::JavaBitmap bitmap_lock(bitmap);
    SkBitmap skbitmap = gfx::CreateSkBitmapFromJavaBitmap(bitmap_lock);
    return color_utils::CalculateKMeanColorOfBitmap(skbitmap);
}

// static
bool FaviconHelper::RegisterFaviconHelper(JNIEnv* env) {
  return RegisterNativesImpl(env);
}


text:
from telemetry.page import page as page
from telemetry import story

archive_data_file_path = 'data/service_worker_micro_benchmark.json'

class ServiceWorkerBenchmarkPage(page.Page):
  """Page for workload to measure some specific functions in JS"""

  def RunNavigateSteps(self, action_runner):
    super(ServiceWorkerBenchmarkPage, self).RunNavigateSteps(action_runner)
    action_runner.WaitForJavaScriptCondition('window.done')

class ServiceWorkerMicroBenchmarkPageSet(story.StorySet):
  """Page set for micro benchmarking of each functions with ServiceWorker"""

  def __init__(self):
    super(ServiceWorkerMicroBenchmarkPageSet, self).__init__(
        archive_data_file=archive_data_file_path,
        cloud_storage_bucket=story.PUBLIC_BUCKET)

    # pylint: disable=line-too-long
    # The latest code of localhost:8091 is from:
    # https://github.com/horo-t/Service-Worker-Performance/tree/fix-flakyness
    # (rev: 0cc35c2398526665399ca99fe53147ff81101408)
    # TODO(falken): House the code in GoogleChrome's GitHub repository.
    # pylint: enable=C0301
    # Why: to measure performance of many concurrent fetches
    self.AddStory(ServiceWorkerBenchmarkPage(
        'http://localhost:8091/index.html', self,
        make_javascript_deterministic=False))


text:
<!-- IMPORTANT: Please do not create a Pull Request without creating an issue first -->
<!-- Any change needs to be discussed before proceeding. Failure to do so may result in the rejection of the pull request. -->

**Close issues**
List the issues solved.(e.g. 'close #xxx, close #xxx and close #xxx')

**Please check if the PR fulfills these requirements**

- [ ] Have you followed the guidelines in our [Contributing document](https://github.com/mili-project-manager/mili/blob/master/.github/CODE_OF_CONDUCT.md)?
- [ ] Have you written new tests for your core changes, as applicable?
- [ ] Have you written or modified docs for your core changes, as applicable?


text:
import { Component, OnInit, ChangeDetectorRef, Input } from '@angular/core';
import {MatSnackBar} from '@angular/material';

declare var chrome:any;

@Component({
  selector: 'app-transfer',
  templateUrl: './transfer.component.html',
  styleUrls: ['./transfer.component.css', '../_app.general.scss']
})
export class TransferComponent implements OnInit {

  settings:any;
  settingsText;

  constructor(public snackBar: MatSnackBar, private cdr: ChangeDetectorRef) {}
  ngOnInit() {}

  fn_initialize(settings) {
    this.settings=settings;
    this.settingsText=JSON.stringify(this.settings, null, "    ");
    this.cdr.detectChanges();
  }

  fn_refresh(){
    this.settingsText=JSON.stringify(this.settings, null, "    ");
    this.snackBar.open('The settings JSON is changed to current value!', '', {duration: 5000});
  }
  fn_clear(){
    this.settingsText="";
  }

  fn_copy(){
    this.copyToClipboard(this.settingsText);
  }
  copyToClipboard(text) {
      if (document.queryCommandSupported && document.queryCommandSupported("copy")) {
          var textarea = document.createElement("textarea");
          textarea.textContent = text;
          textarea.style.position = "fixed";  // Prevent scrolling to bottom of page in MS Edge.
          document.body.appendChild(textarea);
          textarea.select();
          try {
              document.execCommand("copy");  // Security exception may be thrown by some browsers.
              this.snackBar.open('Copied to clipboard!', '', {duration: 5000});
          } catch (ex) {
              this.snackBar.open('Please use CTRL-C to copy!', '', {duration: 8000});
              return false;
          } finally {
              document.body.removeChild(textarea);
          }
      }
      else
      {
          this.snackBar.open('Please use CTRL-C to copy!', '', {duration: 8000});
      }
  }

  fn_save(){
      this.download(this.settingsText, "PageFormatter.settings.json", "application/json");
  }
  download(data, filename, type) {
      var file = new Blob([data], {type: type});
      var a = document.createElement("a"),
              url = URL.createObjectURL(file);
      a.href = url;
      a.download = filename;
      document.body.appendChild(a);
      a.click();
      setTimeout(function() {
          document.body.removeChild(a);
          window.URL.revokeObjectURL(url);
      }, 0);
  }

  fn_default(){
      var p=JSON.parse(JSON.stringify(this.settings));
      p.favlinks.customlinks=[
        {title:'Facebook', value:'https://www.facebook.com'},
        {title:'Google', value:'https://www.google.com'},
        {title:'Yahoo', value:'https://www.yahoo.com'}
      ];
      p.autorun.customcodes =
      [
      ];
      this.settingsText=JSON.stringify(p, null, "    ");
      this.snackBar.open('The settings JSON is changed to default value!', '', {duration: 5000});
  }

  fn_set(){
      try{
          var p=JSON.parse(this.settingsText);
          if(!p.clicktohide || !p.favlinks || !p.autorun || !p.imagehoving)
          {
              throw "Not a valid setting!";
          }

          this.settings.running=p.running;
          this.settings.clicktohide=p.clicktohide;
          this.settings.favlinks=p.favlinks;
          this.settings.autorun=p.autorun;
          this.cdr.detectChanges();

	        chrome.runtime.sendMessage({messageType: "saveSettings", value:this.settings});
          this.snackBar.open('The settings JSON has been applied!', '', {duration: 5000});
      }
      catch(error)
      {
          this.snackBar.open('Error: '+error, '', {duration: 8000});
      }
  }

}


text:
import unittest

from slack_sdk.errors import SlackTokenRotationError
from slack_sdk.oauth.installation_store import Installation
from slack_sdk.oauth.token_rotation.async_rotator import AsyncTokenRotator
from slack_sdk.web.async_client import AsyncWebClient
from tests.helpers import async_test
from tests.slack_sdk.web.mock_web_api_server import (
    setup_mock_web_api_server,
    cleanup_mock_web_api_server,
)

class TestTokenRotator(unittest.TestCase):
    def setUp(self):
        setup_mock_web_api_server(self)
        self.token_rotator = AsyncTokenRotator(
            client=AsyncWebClient(base_url="http://localhost:8888", token=None),
            client_id="111.222",
            client_secret="token_rotation_secret",
        )

    def tearDown(self):
        cleanup_mock_web_api_server(self)

    @async_test
    async def test_refresh(self):
        installation = Installation(
            app_id="A111",
            enterprise_id="E111",
            team_id="T111",
            user_id="U111",
            bot_id="B111",
            bot_token="xoxe.xoxp-1-initial",
            bot_scopes=["chat:write"],
            bot_user_id="U222",
            bot_refresh_token="xoxe-1-initial",
            bot_token_expires_in=43200,
        )
        refreshed = await self.token_rotator.perform_token_rotation(
            installation=installation, minutes_before_expiration=60 * 24 * 365
        )
        self.assertIsNotNone(refreshed)

        should_not_be_refreshed = await self.token_rotator.perform_token_rotation(
            installation=installation, minutes_before_expiration=1
        )
        self.assertIsNone(should_not_be_refreshed)

    @async_test
    async def test_token_rotation_disabled(self):
        installation = Installation(
            app_id="A111",
            enterprise_id="E111",
            team_id="T111",
            user_id="U111",
            bot_id="B111",
            bot_token="xoxe.xoxp-1-initial",
            bot_scopes=["chat:write"],
            bot_user_id="U222",
        )
        should_not_be_refreshed = await self.token_rotator.perform_token_rotation(
            installation=installation, minutes_before_expiration=60 * 24 * 365
        )
        self.assertIsNone(should_not_be_refreshed)

        should_not_be_refreshed = await self.token_rotator.perform_token_rotation(
            installation=installation, minutes_before_expiration=1
        )
        self.assertIsNone(should_not_be_refreshed)

    @async_test
    async def test_refresh_error(self):
        token_rotator = AsyncTokenRotator(
            client=AsyncWebClient(base_url="http://localhost:8888", token=None),
            client_id="111.222",
            client_secret="invalid_value",
        )

        installation = Installation(
            app_id="A111",
            enterprise_id="E111",
            team_id="T111",
            user_id="U111",
            bot_id="B111",
            bot_token="xoxe.xoxp-1-initial",
            bot_scopes=["chat:write"],
            bot_user_id="U222",
            bot_refresh_token="xoxe-1-initial",
            bot_token_expires_in=43200,
        )
        with self.assertRaises(SlackTokenRotationError):
            await token_rotator.perform_token_rotation(
                installation=installation, minutes_before_expiration=60 * 24 * 365
            )


text:
progetto costruito a partire da
http://www.domitable.com/content/getting-started-symfony-23-sonata-admin-user-bundles

una volta effettuato il clone del repository e parametrizzato l'accesso al db da parameters.yml
eseguire

composer update
(e risolvere eventuali problemi sulle dipendenze)

php app/console doctrine:schema:create
php app/console fos:user:create admin paolo.cazzitti@cogitoweb.it --super-admin
php app/console init:acl
(di solito tira errore ma e ok)
php app/console sonata:admin:setup-acl
php app/console sonata:admin:generate-object-acl
php app/console cache:clear
php app/console cache:warmup

+ https://github.com/genemu/GenemuFormBundle

per altri modelli da gestire vedi
http://sonata-project.org/bundles/doctrine-orm-admin/master/doc/tutorial/creating_your_first_admin_class/introduction.html:

genera le classi a partire da db con doctrine (http://symfony.com/it/doc/current/cookbook/doctrine/reverse_engineering.html)
	php app/console doctrine:mapping:convert xml ./src/Application/LavAdr/CRUDBundle/Resources/config/doctrine --from-database --force --namespace=Application/LavAdr/CRUDBundle/Entity/
	php app/console doctrine:mapping:convert annotation ./src ## ?? serve?
	php app/console doctrine:mapping:import AcmeBlogBundle ## ?? serve?
	php app/console doctrine:generate:entities AcmeBlogBundle

genera l'admin con
	sonata:admin:generate (controller compreso)


text:
import { GraphQLList, GraphQLNonNull, GraphQLID, GraphQLInt, GraphQLString } from 'graphql'
import jsonResult from './../../helpers/utils/jsonResult'
import { GraphQLUUID } from './../scalars'
import Article from './../../models/article'
import ArticleType from './articleType'

export default {
  articles: {
    type: new GraphQLList(ArticleType),
    name: 'GetArticlesQuery',
    description: 'A paginated query for all the articles.',
    args: {
      offset: {
        type: new GraphQLNonNull(GraphQLInt),
        description: 'The number of articles to offset',
      },
      limit: {
        type: new GraphQLNonNull(GraphQLInt),
        description: 'The maximum number of articles to return at a time.',
      },
    },
    async resolve(source, { offset, limit }, context) {
      const articles = await Article.getArticles(offset, limit).then(jsonResult)
      return articles
    },
  },
  getArticlesForTag: {
    type: new GraphQLList(ArticleType),
    description: 'Return all articles matching the given tag.',
    args: {
      name: { type: GraphQLString },
      offset: { type: GraphQLInt },
      limit: { type: GraphQLInt },
    },
    async resolve(source, { name, offset, limit }, context) {
      const articles = await Article.getArticlesByTag(name, offset, limit).then(jsonResult)
      if (!articles) {
        throw errorObj({ _error: 'Project ID not found' })
      }
      return articles
    },
  },

  getArticleBySlug: {
    type: ArticleType,
    description: 'Return a specific article using its slug',
    args: {
      slug: { type: GraphQLString },
    },
    async resolve(_, { slug }, context) {
      const article = await Article.getArticleBySlug(slug)
      if (!article) {
        throw errorObj({ _error: 'Project ID not found' })
      }
      return article
    },
  },
}


text:
<!-- Do not edit this file. It is automatically generated by API Documenter. -->

[Home](./index.md) > [@snowplow/node-tracker](./node-tracker.md) > [EcommerceTransactionEvent](./node-tracker.ecommercetransactionevent.md) > [currency](./node-tracker.ecommercetransactionevent.currency.md)

## EcommerceTransactionEvent.currency property

Currency of the transaction

<b>Signature:</b>

```typescript
currency?: string;
```


text:
These instructions will cover RHEL and CentOS. Some sections will be limited to a specific distribution and will be marked as such. Screenshots provided show RHEL 7.1.

HI

Install your VM

Create a new VM and point VMware to the RHEL 7.1 Server ISO, choose to customize it at the end.

Remove the built in camera by choosing camera from the settings and clicking remove.

Adjust any other settings as desired (RAM, vCPU, etc).

Start the VM.

Select Install and press enter (I usually skip the installation source verfication as I always check the ISO with the hash). HELLO

Select your language.

Click Installation Destination and then just press Done in the upper left.

Click Network & Host Name.

Click Configure.

Click the General tab.

Tick Automatically connect to this network when it is available.

Click Save.

Click Done.

Click Begin Installation.

Click Root Password

Enter vagrant for the root password and verify it.

Click Done twice.

Click User Creation.

Enter vagrant for the full name, username, password and confirm password.

Tick Make this user administrator.

Click Done twice.

When the installation finishes, click on Reboot.

Connect to your VM

Log into the console under the user vagrant after it reboots.

Find the name of your network connection:

sudo nmcli con show

Find the IP of your network connection using the device name from the above command:

sudo nmcli con show eno16777736 | grep IP4.ADD

Use SSH on your host machine to connect to your VM.

Configure your VM

Red Hat Specific Subscription and Repo Config (RHEL Only)

Since we need to update the VM and also add some packages, we will need to register it with Red Hat so it can connect to the RH repos. After everything is done, we will unregister it to clean up everything nicely. When you use the box in Vagrant you can then register each VM independently as needed. There is some information in the notes at the end for how to handle this.

Register Red Hat Subscription

sudo subscription-manager register --username <red hat account username>

Then enter your password when prompted.

Attach Red Hat Subscription

sudo subscription-manager attach --auto

Install Prereq files

sudo yum update -y
sudo yum install yum-utils net-tools gcc make open-vm-tools kernel-headers kernel-devel perl -y

The packages gcc, make, kernel-headers, kernel-devel, and perl are for building the HGFS driver that enables folder sharing in VMware.

The package net-tools is for Vagrant to configure the network adapters.

The package open-vm-tools is for the preferred method of adding VMware Tools (aside from the HGFS driver).

The package yum-utils is for bootstrap installers (like SaltStack) which need to add additional repos. If you have Vagrant install Salt-Master or Salt-Minion on the VM, this will be required as it will need to add the epel-release repository. You will also need to register your subscription before having salt installed (see notes below for an option on how to register subscriptions on vagrant up).

Configure Sudoers

Vagrant requires the vagrant user to be able to run sudo without a password. To do this we configure a group named admin to be able to access sudo without a password. Then we add the vagrant user to this group.

In addition to this, Vagrant will not work correctly if sudo requires a tty. So we comment out the line requiring this in the /etc/sudoers file. This line exists by default on CentOS and RHEL.

sudo sed -i 's/^Defaults\s*requiretty/# Defaults requiretty/g' /etc/sudoers
echo "%admin  ALL=NOPASSWD: ALL" | sudo tee -a /etc/sudoers
sudo groupadd admin
sudo usermod -G admin vagrant

Configure SSH

Vagrant needs a generic SSH key to have access to the vagrant user. Once it connects the first time it will then replace this with a randomly generated key for security. To grant this initial access we create the .ssh folder and download the public key into the authorized_keys file for the SSH key Vagrant has built in. Then we configure the permissions so openSSH will correctly authenticate with the key.

cd ~/
mkdir .ssh
curl https://raw.githubusercontent.com/mitchellh/vagrant/master/keys/vagrant.pub > .ssh/authorized_keys
chmod 700 .ssh/
sudo chmod 600 .ssh/authorized_keys
sudo chown -R vagrant:vagrant .ssh/

Reboot

Because of the kernel update, you will need to reboot the VM. The HGFS driver will not compile otherwise and Vagrant will fail when it tries to mount shared folders.

sudo reboot

Install HGFS Driver

Insert the VMware Tools installation CD via VMware Fusion or Workstation. It will be listed as Reinstall VMware Tools in the menu since the open-vm-tools driver is running. This is normal. We need this part to get the HGFS driver that open-vm-tools does not come with.

cd ~/
sudo mount /dev/cdrom /media
tar xvf /media/VMwareTools-*.tar.gz
sudo ./vmware-tools-distrib/vmware-install.pl --default
rm -rf  vmware-tools-distrib/

Cleanup

Clear Red Hat Subscription (RHEL Only)

Because you may not want the box file associated with your RHEL account, we will unregister it here. Then whomever uses the box file in the future can reregister it on vagrant up.

sudo yum clean all
sudo subscription-manager remove --all
sudo subscription-manager unregister

Remove Temp Data and Shutdown

This is just to clear out temporary files and anything else unnecessary for the packaging of the VM as a box file. This information can be regenerated by the system when needed (i.e. yum cache).

sudo yum clean all
sudo rm -rf /tmp/*
rm ~/.bash_history
history -c
sudo poweroff

Convert VM to Vagrant Box

These commands are from OS X. You will need to modify them appropriately for your host OS if it is not OS X.

Open terminal and go to the directory of your VM (example is a VM named vagrant-centos7-1503-x64):

cd ~/Documents/Virtual\ Machines.localized/Source_Images/vagrant-centos7-1503-x64.vmwarevm/

Defragment the disk:

/Applications/VMware\ Fusion.app/Contents/Library/vmware-vdiskmanager -d Virtual\ Disk.vmdk

Shrink the disk:

/Applications/VMware\ Fusion.app/Contents/Library/vmware-vdiskmanager -k Virtual\ Disk.vmdk

Clear any logs:

rm *.log

Add required metadata (change appropriately if using VMware Workstation):

echo '{' > metadata.json
echo '    "provider": "vmware_fusion"' >> metadata.json
echo '}' >> metadata.json

Create box file for import:

tar cvzf ../vagrant-centos7-1503-x64.box ./*

Import the box file:

vagrant box add vagrant-centos7-1503-x64 ../vagrant-centos7-1503-x64.box

Remove the box file (you can save if desired):

rm vagrant-centos7-1503-x64.box

Notes

Saving the VM

Optionally you can delete your VM after you're done. However I recommend saving it to speed up adding or changing things on it later on. You can just boot it up, make the changes and rerun the cleanup and conversion to a Vagrant box steps.

Network Changes During Provisioning

Because of the way Vagrant handles network settings, if you need to add or change network settings you will want to reboot the NetworkManager and network services when the box is provisioned and after the changes. Example shell provisioning:

config.vm.provision "shell", inline: <<-SHELL
  sudo systemctl restart NetworkManager
  sudo systemctl restart network
SHELL

Without this, it will still work but if, for example, you add a new NIC, it won't have an IP until after you reboot. This quick provisioning script resolves that issue.

Fedora

I originally wrote this with Fedora 22 as one of the distributions however I could not get the networking to work correctly. These instructions do cover Fedora 22 but when you run vagrant up you will get a failure due to the networking configuration. I am unsure of what the fix is at the moment. When I resolve the issue I will add in Fedora 22 to this post with the few differences needed.

Example error:
```
Bringing machine 'fedora22test' up with 'vmware_fusion' provider…
==> fedora22test: Cloning VMware VM: 'vagrant-fedora22-x64'. This can take some time…
==> fedora22test: Verifying vmnet devices are healthy…
==> fedora22test: Preparing network adapters…
==> fedora22test: Starting the VMware VM…
==> fedora22test: Waiting for machine to boot. This may take a few minutes…
    fedora22test: SSH address: 192.168.226.134:22
    fedora22test: SSH username: vagrant
    fedora22test: SSH auth method: private key
    fedora22test:
    fedora22test: Vagrant insecure key detected. Vagrant will automatically replace
    fedora22test: this with a newly generated keypair for better security.
    fedora22test:
    fedora22test: Inserting generated public key within guest…
    fedora22test: Removing insecure key from the guest if its present…
    fedora22test: Key inserted! Disconnecting and reconnecting using new SSH key…
==> fedora22test: Machine booted and ready!
==> fedora22test: Forwarding ports…
    fedora22test: – 22 => 2222
==> fedora22test: Setting hostname…
The following SSH command responded with a non-zero exit status.
Vagrant assumes that this means the command failed!</p>

<p>service network restart</p>

<p>Stdout from the command:</p>

<p>Restarting network (via systemctl):  [FAILED]</p>

<p>Stderr from the command:</p>

<p>Job for network.service failed. See "systemctl status network.service" and "journalctl -xe" for details.
```

Managing RHEL Subscription Registration (RHEL Only)

I recommend installing the vagrant-registration plugin for managing your RHEL subscriptions. You can install this via vagrant plugin install vagrant-registration. Once installed you can create a file in your home directory to always register your RHEL subscription on vagrant up and remove it on vagrant halt and vagrant destroy.

From the GitHub documentation linked above:

mkdir ~/.vagrant.d/
cat >> ~/.vagrant.d/Vagrantfile << EOF
if Vagrant.has_plugin?('vagrant-registration')
  config.registration.username = 'foo'
  config.registration.password = 'bar'
end
EOF

Additionally you'll need to add in any required repos via a SHELL script. Example that covers repos needed for bootstrapping SaltStack:

config.vm.provision "shell", run: "always", inline: <<-SHELL
  sudo subscription-manager repos --enable rhel-7-server-optional-rpms
  sudo subscription-manager repos --enable rhel-7-server-extras-rpms
SHELL

There are some caveats I've come across using this method so far:

Your RH creds are stored in plaintext. There may be a better way using a built in keychain package or something else to encrypt/obfuscate the creds. I highly recommend not having shared passwords in your accounts in general and this highlights one of the reasons for this.

On vagrant halt it will unregister your VM. Well, it seems silly to have to reregister every time you vagrant up. It really needs an option to only unregister on vagrant destroy.

If you vagrant halt and then vagrant up it asks you if you want to register it and if you answer yes it will then ask you for your RH username and password even though it already has them.

It has no support for adding repos so you have to use a shell provisioner to add repos and make sure it runs anytime it reregisters because it unregisters on halt.

Closing

This is one of my first complete tutorials. I hope everything has been covered adequately from start to finish. I found a lot of them missed chunks, made assumptions or were outdated when looking for help building my own clean box files for Linux distros.

As mentioned, Fedora 22 will be added once I work out a few kinks. I also have a Debian 8.1 in the works as well that has a few issues that need to be resolved.

CB


text:
<?php

/**
 * @file
 * Contains \Drupal\webprofiler\Compiler\EventPass.
 */

namespace Drupal\webprofiler\Compiler;

use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;

/**
 * Class EventPass.
 */
class EventPass implements CompilerPassInterface {

  /**
   * {@inheritdoc}
   */
  public function process(ContainerBuilder $container) {
    $definition = $container->findDefinition('http_kernel.basic');
    $definition->replaceArgument(1, new Reference('webprofiler.debug.controller_resolver'));

    // Replace the regular event_dispatcher service with the debug one.
    $definition = $container->findDefinition('event_dispatcher');
    $definition->setPublic(FALSE);
    $container->setDefinition('webprofiler.debug.event_dispatcher.default', $definition);
    $container->register('event_dispatcher', 'Drupal\webprofiler\TraceableEventDispatcher')
      ->addArgument(new Reference('webprofiler.debug.event_dispatcher.default'))
      ->addArgument(new Reference('stopwatch'))
      ->setProperty('_serviceId', 'event_dispatcher');
  }
}


text:
module.exports = function(options)
{
  var element = extract("element", options);
  var steps = extract("steps", options);
  var id = extract("id", options);
  var status = extract("status", options);
  var message = extract("message", options);
  var link = extract("link", options);

  steps = $.map(steps, function(x){
    if(x.id == id)
    {
      x.status = status;
      x.message = message || "";
      x.link = link || "";
    }
    return x;
  })

  geodash.bootloader.ui.update({ "element": element, "steps": steps });

  return steps;
};


text:
package com.rtg.util.array;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import com.rtg.util.array.longindex.LongIndex;
import com.rtg.util.io.ByteArrayIOUtils;
import com.rtg.util.io.FileUtils;

/**
 * Array utility functions.
 *
 */
public final class ArrayUtils {

  private ArrayUtils() { }

  /**
   * Sum an array of doubles.
   *
   * @param a array
   * @return sum
   */
  public static double sum(final double... a) {
    double s = 0;
    for (final double v : a) {
      s += v;
    }
    return s;
  }

  /**
   * Sum an array of longs.
   *
   * @param a array
   * @return sum
   */
  public static long sum(final long... a) {
    long sum = 0;
    for (final long x : a) {
      sum += x;
    }
    return sum;
  }

  /**
   * Sum an array of ints.  Returns a long in order to minimise changes of overflow.
   *
   * @param a array
   * @return sum
   */
  public static long sum(final int... a) {
    long sum = 0;
    for (final int x : a) {
      sum += x;
    }
    return sum;
  }

  /**
   * Read an array of longs from a file.
   *
   * @param f file
   * @return array
   * @exception IOException if an I/O error occurs
   */
  public static long[] readLongArray(final File f) throws IOException {
    final byte[] b = new byte[(int) f.length()];
    try (InputStream stream = new FileInputStream(f)) {
      final int length = stream.read(b);
      if (length != b.length) {
        throw new IOException();
      }
    }
    return ByteArrayIOUtils.convertToLongArray(b);
  }

  /**
   * Read an array of longs from a file.
   *
   * @param f file
   * @param a index to read into
   * @param offset in the array.
   * @param addend amount to add to each entry
   * @return length
   * @exception IOException if an I/O error occurs
   */
  public static int readInts(final File f, final LongIndex a, final long offset, final long addend) throws IOException {
    return readInts(f, 0, (int) f.length() / 4, a, offset, addend);
  }

  /**
   * Read an array of longs from a file.
   *
   * @param f file
   * @param fileOffset offset into the file to start reading at
   * @param fileEnd position in the file to finish
   * @param a index to read into
   * @param offset in the array.
   * @param addend amount to add to each entry
   * @return length
   * @exception IOException if an I/O error occurs
   */
  public static int readInts(final File f, final int fileOffset, final int fileEnd, final CommonIndex a, final long offset, final long addend) throws IOException {
    final int length = (fileEnd - fileOffset) * 4;
    final byte[] b = new byte[length];
    try (InputStream stream = new FileInputStream(f)) {

      // Skip has failed lets attempt to use read to fix things up.
      int remaining = fileOffset * 4;
      long skipped;
      while (remaining > 0 && (skipped = FileUtils.streamSkip(stream, remaining)) > 0) {
        remaining -= (int) skipped;
      }
      if (remaining > 0) {
        throw new IOException();
      }
      int soFar = 0;
      int read;
      while (soFar < length && (read = stream.read(b, soFar, length - soFar)) > 0) {
        soFar += read;
      }
      if (soFar < length) {
        throw new IOException();
      }
    }
    for (int i = 0; i < b.length; i += 4) {
      a.set(offset + i / 4, ByteArrayIOUtils.bytesToIntBigEndian(b, i) + addend);
    }
    return b.length / 4;
  }

  /**
   * Return list of boxed bytes as a primitive array.
   *
   * @param l list
   * @return byte array
   */
  public static byte[] asByteArray(final List<Byte> l) {
    final byte[] a = new byte[l.size()];
    for (int i = 0; i < a.length; ++i) {
      a[i] = l.get(i);
    }
    return a;
  }

  /**
   * Return list of boxed longs as a primitive array.
   *
   * @param l list
   * @return long array
   */
  public static long[] asLongArray(final List<Long> l) {
    final long[] a = new long[l.size()];
    for (int i = 0; i < a.length; ++i) {
      a[i] = l.get(i);
    }
    return a;
  }

  /**
   * @param input list of integers represented as decimals separated by comma.
   * @return the values separated into an array
   * @throws NumberFormatException if the string format is invalid
   */
  public static int[] parseIntArray(final String input) {
    final String[] strings = input.split(", *");
    final int[] values = new int[strings.length];
    for (int i = 0; i < strings.length; ++i) {
      values[i] = Integer.parseInt(strings[i]);
    }
    return values;
  }

  /**
   * Checks that a segment of an array is sorted.
   * @param arr1 primary array
   * @param start the first position to check (inclusive)
   * @param end one past the last position to check (exclusive)
   * @return true if the array is sorted, false
   *         otherwise
   */
  public static boolean isSorted(final CommonIndex arr1, final long start, final long end) {
    assert 0 <= start;
    assert start <= end;
    assert end <= arr1.length();
    for (long ii = start; ii < end - 1; ++ii) {
      if (arr1.get(ii) > arr1.get(ii + 1)) {
        return false;
      }
    }
    return true;
  }

  /**
   * Checks that an array is sorted.
   * @param arr1 primary array
   * @param len the length to check
   * @return true if the array is sorted, false
   *         otherwise
   */
  public static boolean isSorted(final CommonIndex arr1, final long len) {
    assert len <= arr1.length();
    for (long ii = 0; ii < len - 1; ++ii) {
      if (arr1.get(ii) > arr1.get(ii + 1)) {
        return false;
      }
    }
    return true;
  }

  /**
   * Checks that an array is sorted (strictly increasing).
   * @param arr1 primary array
   * @param len the length to check
   * @return true if the array is sorted, false otherwise
   */
  public static boolean isSortedStrict(final CommonIndex arr1, final long len) {
    assert len <= arr1.length();
    for (long ii = 0; ii < len - 1; ++ii) {
      if (arr1.get(ii) >= arr1.get(ii + 1)) {
        return false;
      }
    }
    return true;
  }

  /**
   * Make the array an identity map up to entry n.
   * @param a array
   * @param n maximum entry
   * @return the array
   */
  public static int[] identity(final int[] a, final int n) {
    for (int k = 0; k < n; ++k) {
      a[k] = k;
    }
    return a;
  }

  /**
   * Make the array an identity map up to entry n.
   * @param length length of array
   * @return the array
   */
  public static int[] identity(final int length) {
    return identity(new int[length], length);
  }

}


text:
@interface AllTest1TableViewHeaderFooterView()

@property(nonatomic, strong) UIView *underLineView;
@property(nonatomic, copy) void(^action)(NSInteger index);

@end

@implementation AllTest1TableViewHeaderFooterView

-(instancetype)initWithReuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithReuseIdentifier:reuseIdentifier];
    if (self != nil)
    {
        MyFrameLayout *rootLayout = [MyFrameLayout new];
        rootLayout.widthSize.equalTo(self.contentView.widthSize);
        rootLayout.heightSize.equalTo(self.contentView.heightSize);
        [self.contentView addSubview:rootLayout];

        MyFrameLayout *leftItemLayout = [self createItemLayout:NSLocalizedString(@"Show", @"") withTag:0];
        leftItemLayout.widthSize.equalTo(rootLayout.widthSize).multiply(1/3.0);
        leftItemLayout.heightSize.equalTo(rootLayout.heightSize);
        leftItemLayout.highlightedOpacity = 0.5;
        [rootLayout addSubview:leftItemLayout];

        MyBorderline *bld = [[MyBorderline alloc] initWithColor:[UIColor lightGrayColor]];
        bld.tailIndent = bld.headIndent = 5;

        MyFrameLayout *centerItemLayout = [self createItemLayout:NSLocalizedString(@"Topic", @"") withTag:1];
        centerItemLayout.widthSize.equalTo(rootLayout.widthSize).multiply(1/3.0);
        centerItemLayout.heightSize.equalTo(rootLayout.heightSize);
        centerItemLayout.centerXPos.equalTo(@0);
        centerItemLayout.leadingBorderline = bld;
        centerItemLayout.highlightedOpacity = 0.5;
        [rootLayout addSubview:centerItemLayout];

        MyFrameLayout *rightItemLayout = [self createItemLayout:NSLocalizedString(@"Follow", @"") withTag:2];
        rightItemLayout.widthSize.equalTo(rootLayout.widthSize).multiply(1/3.0);
        rightItemLayout.heightSize.equalTo(rootLayout.heightSize);
        rightItemLayout.trailingPos.equalTo(@0);
        rightItemLayout.leadingBorderline = bld;
        rightItemLayout.highlightedOpacity = 0.5;
        [rootLayout addSubview:rightItemLayout];

        //底部的横线
        _underLineView = [UIView new];
        _underLineView.backgroundColor = [UIColor redColor];
        _underLineView.widthSize.equalTo(rootLayout.widthSize).multiply(1/3.0);
        _underLineView.heightSize.equalTo(@2);
        _underLineView.bottomPos.equalTo(@0);
        _underLineView.leadingPos.equalTo(@0).active = YES;   //设置左边位置有效
        _underLineView.centerXPos.equalTo(@0).active = NO;  //设置水平中间位置无效
        _underLineView.trailingPos.equalTo(@0).active = NO;    //设置右边位置无效
        [rootLayout addSubview:_underLineView];

        MyBorderline *rootLayoutBld = [[MyBorderline alloc] initWithColor:[UIColor lightGrayColor]];
        rootLayout.bottomBorderline = rootLayoutBld;
        rootLayout.topBorderline = rootLayoutBld;

    }

    return self;
}

-(void)setItemChangedAction:(void(^)(NSInteger index))action
{
    self.action = [action copy];
}

#pragma mark -- Layout Construction

-(MyFrameLayout*)createItemLayout:(NSString*)title withTag:(NSInteger)tag
{
    //创建一个框架条目布局,并设置触摸处理事件
    MyFrameLayout *itemLayout = [MyFrameLayout new];
    itemLayout.tag = tag;
    [itemLayout setTarget:self action:@selector(handleTap:)];

    UILabel *titleLabel = [UILabel new];
    titleLabel.text = title;
    titleLabel.font = [UIFont systemFontOfSize:15];
    [titleLabel sizeToFit];
    titleLabel.centerXPos.equalTo(@0);
    titleLabel.centerYPos.equalTo(@0); //标题尺寸由内容包裹,位置在布局视图中居中。
    [itemLayout addSubview:titleLabel];

    return itemLayout;
}

#pragma mark -- Handle Method

-(void)handleTap:(MyBaseLayout*)sender
{
    //调整underLineView的位置的有效值来实现位置移动。对于位置MyLayoutPos对象和尺寸对象MyLayoutSize来说有一个active属性来设置是否这个约束有效。
    switch (sender.tag) {
        case 0:
            self.underLineView.leadingPos.active = YES;
            self.underLineView.centerXPos.active = NO;
            self.underLineView.trailingPos.active = NO;
            break;
        case 1:
            self.underLineView.leadingPos.active = NO;
            self.underLineView.centerXPos.active = YES;
            self.underLineView.trailingPos.active = NO;
            break;
        case 2:
            self.underLineView.leadingPos.active = NO;
            self.underLineView.centerXPos.active = NO;
            self.underLineView.trailingPos.active = YES;
            break;
        default:
            NSAssert(0, @"oops!");
            break;
    }

    MyBaseLayout *layout = (MyBaseLayout*)sender.superview;
    [layout layoutAnimationWithDuration:0.2];

    if (self.action != nil)
        self.action(sender.tag);
}

@end


text:
@extends('pages.public.master')

@section('page')

            @if($children)

                @foreach ($children as $child)
                @include('pages.public._listItem', array('child' => $child))
                @endforeach

            @endif

            {{ $model->body }}
            @include('galleries.public._galleries')

@stop


text:
To download the latest version of Plaso you'll need to install the git tools:
```
sudo apt-get install git
```

Checkout the Plaso source from the git repo:
```
git clone https://github.com/log2timeline/plaso.git
```

## Dependencies

Install the dependencies, using either:
* A [virtualenv](Developing-Virtualenv.html#Ubuntu)
* The [prepackaged dependencies](Development-Dependencies.html#Ubuntu).

Check if you have all the dependencies installed and have the right minimum
versions:
```
python utils/check_dependencies.py
```

**Note that some dependencies are actively under development and can be
frequently updated, therefore we recommend checking the status of the
 dependencies regularly.**

## Updating your environment.

If you are using a github fork your origin is pointing to your fork and not
the main Plaso git repository. When you run `git remote -v` you might see
something like:
```
origin	https://github.com/Onager/plaso (fetch)
origin	https://github.com/Onager/plaso (push)
```

Add a git remote called 'upstream' that you can use to sync your fork:
```
git remote add upstream https://github.com/log2timeline/plaso.git
git pull --rebase upstream master
```

We provide packaged versions of the dependencies via the [l2tbinaries project](https://github.com/log2timeline/l2tbinaries/blob/master/README.md).
However it is possible that the dependencies are not fully up to date therefore
we also provide a build script as part of [l2tdevtools project](https://github.com/log2timeline/l2tdevtools)
to do unattended bulk builds.

## Development tools
If you intend to do development on Plaso you'll also need to install some
development tools:

* PyLint
* Python Mock

### PyLint
Currently plaso development uses PyLint version 1.9.x.

Remove any older version of PyLint.
```bash
sudo apt-get remove pylint
```

For pylint 1.9.x the following additional dependencies are required:
* [astroid](https://pypi.python.org/pypi/astroid)
* [lazy-object-proxy](https://pypi.python.org/pypi/lazy-object-proxy)
* [logilab-common](https://pypi.python.org/pypi/logilab-common)
* [wrapt](https://pypi.python.org/pypi/wrapt)

Download and build the python-wrapt Debian package:
**TODO describe**

Download and build the python-lazy-object-proxy Debian package:
**TODO describe**

Download and build the python-logilab-common Debian package:
```bash
hg clone http://hg.logilab.org/logilab/common
cd common
dpkg-buildpackage -rfakeroot
cd ..
```

Since you're building from development branch it can be possible that you need
to disable any failing tests.
Either report these as bugs to the PyLint project or fix them yourself.

Download and build the python-astroid Debian package:
```bash
hg clone https://bitbucket.org/logilab/astroid
cd astroid
dpkg-buildpackage -rfakeroot
cd ..
```

Download and build the pylint Debian package:
```bash
hg clone https://bitbucket.org/logilab/pylint
cd pylint
dpkg-buildpackage -rfakeroot
cd ..
```

Install the python-wrapt, python-lazy-object-proxy, python-logilab-common,
python-astroid and pylint Debian packages:
```bash
sudo dpkg -i python-wrapt python-lazy-object-proxy python-logilab-common_0.60.0-1_all.deb python-astroid_1.0.1-1_all.deb pylint_1.6.5-1_all.deb
```

### Python Mock
To install Python Mock run:
```bash
sudo apt-get install python-mock
```


text:
package internal

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/url"
)

// HTTPGetByURL make Get request
func HTTPGetByURL(url string, collection interface{}) error {

	client := &http.Client{
		Transport: http.DefaultTransport,
	}

	response, err := client.Get(url)

	if err != nil {
		return err
	}

	err = readResponse(response, &collection)

	return err
}

// HTTPGet make Get request
func HTTPGet(host string, path string, qp map[string]string, collection interface{}) error {

	baseURL, _ := url.Parse(host)
	endpoint, _ := baseURL.Parse(baseURL.RequestURI() + "/" + path)
	query := endpoint.Query()

	for key, value := range qp {
		query.Set(key, value)
	}

	endpoint.RawQuery = query.Encode()

	client := &http.Client{
		Transport: http.DefaultTransport,
	}

	response, err := client.Get(endpoint.String())

	if err != nil {
		return err
	}

	err = readResponse(response, &collection)

	return err
}

// ReadResponse the response from http.Response
func readResponse(response *http.Response, result interface{}) error {
	// close the body when done reading
	defer response.Body.Close()

	bytes, err := ioutil.ReadAll(response.Body)

	if err != nil {
		return err
	}

	err = json.Unmarshal(bytes, result)

	if err != nil {
		return err
	}

	if response.StatusCode == 400 {
		return fmt.Errorf("Bad Request: %s", string(bytes))
	}

	return nil
}