text:
<!DOCTYPE html>
<title>IndexedDB: Test IDBObjectStore.getAllKeys.</title>
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script src="support.js"></script>
<script>

var alphabet = 'abcdefghijklmnopqrstuvwxyz'.split('');

function getall_test(func, name) {
  indexeddb_test(
    function(t, connection, tx) {
      var store = connection.createObjectStore('generated',
            {autoIncrement: true, keyPath: 'id'});
      alphabet.forEach(function(letter) {
        store.put({ch: letter});
      });

      store = connection.createObjectStore('out-of-line', null);
      alphabet.forEach(function(letter) {
        store.put('value-' + letter, letter);
      });

      store = connection.createObjectStore('empty', null);
    },
    func,
    name
  );
}

function createGetAllKeysRequest(t, storeName, connection, range, maxCount) {
    var transaction = connection.transaction(storeName, 'readonly');
    var store = transaction.objectStore(storeName);
    var req = store.getAllKeys(range, maxCount);
    req.onerror = t.unreached_func('getAllKeys request should succeed');
    return req;
}

getall_test(function(t, connection) {
      var req = createGetAllKeysRequest(t, 'out-of-line', connection, 'c');
      req.onsuccess = t.step_func(function(evt) {
          assert_array_equals(evt.target.result, ['c']);
          t.done();
      });
    }, 'Single item get');

getall_test(function(t, connection) {
      var req = createGetAllKeysRequest(t, 'generated', connection, 3);
      req.onsuccess = t.step_func(function(evt) {
          var data = evt.target.result;
          assert_true(Array.isArray(data));
          assert_array_equals(data, [3]);
          t.done();
      });
    }, 'Single item get (generated key)');

getall_test(function(t, connection) {
      var req = createGetAllKeysRequest(t, 'empty', connection);
      req.onsuccess = t.step_func(function(evt) {
          assert_array_equals(evt.target.result, [],
              'getAllKeys() on empty object store should return an empty ' +
                  'array');
          t.done();
      });
    }, 'getAllKeys on empty object store');

getall_test(function(t, connection) {
      var req = createGetAllKeysRequest(t, 'out-of-line', connection);
      req.onsuccess = t.step_func(function(evt) {
          assert_array_equals(evt.target.result, alphabet);
          t.done();
      });
    }, 'Get all values');

getall_test(function(t, connection) {
      var req = createGetAllKeysRequest(t, 'out-of-line', connection, undefined,
                                    10);
      req.onsuccess = t.step_func(function(evt) {
          assert_array_equals(evt.target.result, 'abcdefghij'.split(''));
          t.done();
      });
    }, 'Test maxCount');

getall_test(function(t, connection) {
      var req = createGetAllKeysRequest(t, 'out-of-line', connection,
                                    IDBKeyRange.bound('g', 'm'));
      req.onsuccess = t.step_func(function(evt) {
          assert_array_equals(evt.target.result, 'ghijklm'.split(''));
          t.done();
      });
    }, 'Get bound range');

getall_test(function(t, connection) {
      var req = createGetAllKeysRequest(t, 'out-of-line', connection,
                                    IDBKeyRange.bound('g', 'm'), 3);
      req.onsuccess = t.step_func(function(evt) {
          assert_array_equals(evt.target.result, ['g', 'h', 'i']);
          t.done();
      });
    }, 'Get bound range with maxCount');

getall_test(function(t, connection) {
      var req = createGetAllKeysRequest(t, 'out-of-line', connection,
                                    IDBKeyRange.bound('g', 'k', false, true));
      req.onsuccess = t.step_func(function(evt) {
          assert_array_equals(evt.target.result, ['g', 'h', 'i', 'j']);
          t.done();
      });
    }, 'Get upper excluded');

getall_test(function(t, connection) {
      var req = createGetAllKeysRequest(t, 'out-of-line', connection,
                                    IDBKeyRange.bound('g', 'k', true, false));
      req.onsuccess = t.step_func(function(evt) {
          assert_array_equals(evt.target.result, ['h', 'i', 'j', 'k']);
          t.done();
      });
    }, 'Get lower excluded');

getall_test(function(t, connection) {
      var req = createGetAllKeysRequest(t, 'generated', connection,
                                    IDBKeyRange.bound(4, 15), 3);
      req.onsuccess = t.step_func(function(evt) {
          var data = evt.target.result;
          assert_true(Array.isArray(data));
          assert_array_equals(data, [4, 5, 6]);
          t.done();
      });
    }, 'Get bound range (generated) with maxCount');

getall_test(function(t, connection) {
      var req = createGetAllKeysRequest(t, 'out-of-line', connection,
                                    "Doesn't exist");
      req.onsuccess = t.step_func(function(evt) {
          assert_array_equals(evt.target.result, [],
              'getAllKeys() using a nonexistent key should return an ' +
                  'empty array');
          t.done();
      });
      req.onerror = t.unreached_func('getAllKeys request should succeed');
    }, 'Non existent key');

getall_test(function(t, connection) {
      var req = createGetAllKeysRequest(t, 'out-of-line', connection, undefined,
          0);
      req.onsuccess = t.step_func(function(evt) {
          assert_array_equals(evt.target.result, alphabet);
          t.done();
      });
    }, 'zero maxCount');

</script>


text:
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Lifx.Lib.Enums;
using Lifx.Lib.Packets;

namespace Lifx.Lib
{
    public static class LifxNetworkGroupExtensions
    {
        public static void AddBulbToGroup(this ILifxNetwork network, IBulbGroup bulbGroup, IBulb bulb)
        {
            var n = (LifxNetwork) network;
            var group = (BulbGroup)bulbGroup;

            if (group.Contains(bulb))
            {
                return;
            }

            group.Add(bulb);

            var groups = n.Groups.Where(g => g.Contains(bulb)).ToList();
            SetGroups(n, bulb, groups);

            UpdateGroupName(n, group, bulb);
        }

        public static void RemoveBulbFromGroup(this ILifxNetwork network, IBulbGroup bulbGroup, IBulb bulb)
        {
            var n = (LifxNetwork) network;
            var group = (BulbGroup) bulbGroup;
            group.Remove(bulb);

            var groups = n.Groups.Where(g => g.Contains(bulb)).ToList();
            SetGroups(n, bulb, groups);
        }

        public static void RemoveGroup(this ILifxNetwork network, IBulbGroup bulbGroup)
        {
            var n = (LifxNetwork)network;
            var group = (BulbGroup)bulbGroup;
            n.Remove(group);

            var allGroups = n.Groups.ToList();
            foreach (var bulb in group.GetBulbs())
            {
                var groups = allGroups.Where(g => g.Contains(bulb) && !Equals(g, group)).ToList();
                SetGroups(n, bulb, groups);
            }
        }

        public static IBulbGroup AddGroup(this ILifxNetwork network, string name)
        {
            var n = (LifxNetwork) network;
            var group = n.CreateGroup();
            group.Name = name;
            return group;
        }

        public static void RenameGroup(this ILifxNetwork network, IBulbGroup bulbGroup, string name)
        {
            var n = (LifxNetwork) network;
            var group = (BulbGroup) bulbGroup;
            group.Name = name;

            foreach (var bulb in group.GetBulbs())
            {
                UpdateGroupName(n, group, bulb);
            }
        }

        private static void UpdateGroupName(LifxNetwork network, BulbGroup group, IBulb bulb)
        {
            var command = (SetTagLabels)PacketFactory.GetCommand(CommandType.SetTagLabels);
            command.Init(group.Bitmask, Encoding.UTF8.GetBytes(group.Name));
            network.SendCommand(bulb, command);
        }

        private static void SetGroups(LifxNetwork network, IBulb bulb, IEnumerable<BulbGroup> groups)
        {
            var command = (SetTags) PacketFactory.GetCommand(CommandType.SetTags);
            command.Init(GetBitmask(groups));

            network.SendCommand(bulb, command);
        }

        private static ulong GetBitmask(IEnumerable<BulbGroup> groups)
        {
            ulong bitmask = 0;
            foreach (var group in groups)
            {
                bitmask |= group.Bitmask;
            }
            return bitmask;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package gnu.xml.validation.datatype;

import java.math.BigInteger;
import javax.xml.XMLConstants;
import javax.xml.namespace.QName;
import org.relaxng.datatype.DatatypeException;
import org.relaxng.datatype.ValidationContext;

/**
 * The XML Schema nonPositiveInteger type.
 *
 * @author Chris Burdess
 */
final class NonPositiveIntegerType
  extends AtomicSimpleType
{

  static final int[] CONSTRAINING_FACETS = {
    Facet.TOTAL_DIGITS,
    Facet.FRACTION_DIGITS,
    Facet.PATTERN,
    Facet.WHITESPACE,
    Facet.ENUMERATION,
    Facet.MAX_INCLUSIVE,
    Facet.MAX_EXCLUSIVE,
    Facet.MIN_INCLUSIVE,
    Facet.MIN_EXCLUSIVE
  };

  NonPositiveIntegerType()
  {
    super(new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "nonPositiveInteger"),
          TypeLibrary.INTEGER);
  }

  public int[] getConstrainingFacets()
  {
    return CONSTRAINING_FACETS;
  }

  public void checkValid(String value, ValidationContext context)
    throws DatatypeException
  {
    super.checkValid(value, context);
    int len = value.length();
    if (len == 0)
      throw new DatatypeException(0, "invalid non-positive integer value");
    boolean positive = true;
    for (int i = 0; i < len; i++)
      {
        char c = value.charAt(i);
        if (c == 0x30)
          continue;
        else if (c >= 0x31 && c <= 0x39)
          {
            if (positive)
              throw new DatatypeException(i,
                                          "invalid non-positive integer value");
            continue;
          }
        else if (c == '+' && i == 0)
          continue;
        else if (c == '-' && i == 0)
          {
            positive = false;
            continue;
          }
        throw new DatatypeException(i, "invalid non-positive integer value");
      }
  }

  public Object createValue(String literal, ValidationContext context) {
    try
      {
        return new BigInteger(literal);
      }
    catch (NumberFormatException e)
      {
        return null;
      }
  }

}


text:
ActiveRecord::Schema.define(version: 20160621010334) do

  # These are extensions that must be enabled in order to support this database
  enable_extension "plpgsql"

  create_table "users", force: :cascade do |t|
    t.string   "name"
    t.string   "encrypted_ssn"
    t.string   "encrypted_ssn_iv"
    t.datetime "created_at",       null: false
    t.datetime "updated_at",       null: false
  end

end


text:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Installer extends MX_Controller{

    public function __construct(){
        parent::__construct();
        if(ENVIRONMENT != 'first-time'){
            show_404();
        }
        $this->load->helper('url');
        $this->load->helper('html');
        $this->load->helper('form');
        $this->load->model('install_model');
    }

    protected function get_input(){
        $this->install_model->db_protocol                  = (string)$this->input->post('db_protocol');
        $this->install_model->db_host                      = (string)$this->input->post('db_host');
        $this->install_model->db_name                      = (string)$this->input->post('db_name');
        $this->install_model->db_port                      = (string)$this->input->post('db_port');
        $this->install_model->db_username                  = (string)$this->input->post('db_username');
        $this->install_model->db_password                  = (string)$this->input->post('db_password');
        $this->install_model->db_table_prefix              = (string)$this->input->post('db_table_prefix');
        $this->install_model->admin_email                  = (string)$this->input->post('admin_email');
        $this->install_model->admin_real_name              = (string)$this->input->post('admin_real_name');
        $this->install_model->admin_user_name              = (string)$this->input->post('admin_user_name');
        $this->install_model->admin_password               = (string)$this->input->post('admin_password');
        $this->install_model->admin_confirm_password       = (string)$this->input->post('admin_confirm_password');
        $this->install_model->hide_index                   = $this->input->post('hide_index')=='true';
        $this->install_model->gzip_compression             = $this->input->post('gzip_compression')=='true';
        $this->install_model->auth_enable_facebook         = $this->input->post('auth_enable_facebook')=='true';
        $this->install_model->auth_facebook_app_id         = (string)$this->input->post('auth_facebook_app_id');
        $this->install_model->auth_facebook_app_secret     = $this->input->post('auth_facebook_app_secret');
        $this->install_model->auth_enable_twitter          = $this->input->post('auth_enable_twitter')=='true';
        $this->install_model->auth_twitter_app_key         = (string)$this->input->post('auth_twitter_app_key');
        $this->install_model->auth_twitter_app_secret      = (string)$this->input->post('auth_twitter_app_secret');
        $this->install_model->auth_enable_google           = $this->input->post('auth_enable_google')=='true';
        $this->install_model->auth_google_app_id           = (string)$this->input->post('auth_google_app_id');
        $this->install_model->auth_google_app_secret       = $this->input->post('auth_google_app_secret');
        $this->install_model->auth_enable_yahoo            = $this->input->post('auth_enable_yahoo')=='true';
        $this->install_model->auth_yahoo_app_id            = (string)$this->input->post('auth_yahoo_app_id');
        $this->install_model->auth_yahoo_app_secret        = (string)$this->input->post('auth_yahoo_app_secret');
        $this->install_model->auth_enable_linkedin         = $this->input->post('auth_enable_linkedin')=='true';
        $this->install_model->auth_linkedin_app_key        = (string)$this->input->post('auth_linkedin_app_key');
        $this->install_model->auth_linkedin_app_secret     = $this->input->post('auth_linkedin_app_secret');
        $this->install_model->auth_enable_myspace          = $this->input->post('auth_enable_myspace')=='true';
        $this->install_model->auth_myspace_app_key         = (string)$this->input->post('auth_myspace_app_key');
        $this->install_model->auth_myspace_app_secret      = (string)$this->input->post('auth_myspace_app_secret');
        $this->install_model->auth_enable_foursquare       = $this->input->post('auth_enable_foursquare')=='true';
        $this->install_model->auth_foursquare_app_id       = (string)$this->input->post('auth_foursquare_app_id');
        $this->install_model->auth_foursquare_app_secret   = (string)$this->input->post('auth_foursquare_app_secret');
        $this->install_model->auth_enable_windows_live     = $this->input->post('auth_enable_windows_live')=='true';
        $this->install_model->auth_windows_live_app_id     = (string)$this->input->post('auth_windows_live_app_id');
        $this->install_model->auth_windows_live_app_secret = (string)$this->input->post('auth_windows_live_app_secret');
        $this->install_model->auth_enable_open_id          = $this->input->post('auth_enable_open_id')=='true';
        $this->install_model->auth_enable_aol              = $this->input->post('auth_enable_aol')=='true';
    }

    public function check(){
        $this->get_input();
        echo json_encode($this->install_model->check_installation());
    }

    public function index(){
        $this->load->view('installer/installer_index');
    }

    public function install(){
        $this->get_input();
        $check_installation = $this->install_model->check_installation();
        $success = $check_installation['success'];
        $module_installed = FALSE;
        if($success){
            $this->install_model->build_configuration();
            $this->install_model->build_database();
            $module_installed = $this->install_model->install_modules();
        }
        $data['module_installed'] = $module_installed;
        $data['success'] = $success;
        $data['admin_user_name'] = $this->install_model->admin_user_name;
        $data['admin_password'] = $this->install_model->admin_password;
        $this->load->view('installer/installer_install', $data);
    }

}


text:
import logging
import pygame
import os
C_SOUNDS_DIR = '/home/pi/mopidy-rstation/audio/'
C_SOUND_REC_START = C_SOUNDS_DIR + 'start_rec.wav'
C_SOUND_REC_END = C_SOUNDS_DIR + 'stop_rec.wav'
C_SOUND_START_UP = C_SOUNDS_DIR + 'newbuntu.wav'
C_SOUND_BEEP = C_SOUNDS_DIR + 'alert.wav'
C_SOUND_PLUG_IN = C_SOUNDS_DIR + 'plugin.wav'
C_SOUND_PLUG_OUT = C_SOUNDS_DIR + 'plugout.wav'

logger = logging.getLogger('mopidy_Rstation')
logger = logging.getLogger(__name__)
channel = None

# The problem is that in some soundcards/configurations
# pygame takes exclusive use of the soundcard at init
# and mopidy is not able to use the soundcard.
# os.environ["SDL_AUDIODRIVER"] = "none"

def beep():
    # print('\a')
    play_file(C_SOUND_BEEP)

def play_file(f, async=False):
    global channel
    if not pygame.mixer.get_init():
        pygame.mixer.init(
            frequency=44100, size=-16, channels=1, buffer=2**12)
    #     channel = pygame.mixer.Channel(5)
    # else:
    #     channel = pygame.mixer.find_channel()
    #     if channel is None:
    #         pygame.mixer.set_num_channels(
    #             pygame.mixer.get_num_channels()+1)
    #         channel = pygame.mixer.find_channel()
    if type(f) is str or isinstance(f, unicode):
        sound = pygame.mixer.Sound(f)
    else:
        sound = pygame.mixer.Sound(f.name)

    if channel is not None and channel.get_busy():
        channel.stop()

    channel = pygame.mixer.find_channel()
    channel.play(sound)

    if async is False:
        while channel.get_busy():
            pass

# def play_file(f, async=False):
#     pygame.init()
#     pygame.mixer.music.load(f)
#     pygame.mixer.music.play()
#     if async is False:
#         while pygame.mixer.music.get_busy():
#             pygame.time.Clock().tick(10)


text:
 package com.indeed.flamdex.lucene;

import com.indeed.flamdex.api.DocIdStream;
import com.indeed.flamdex.api.TermIterator;
import org.apache.lucene.index.TermDocs;

import java.io.IOException;

public class LuceneDocIdStream implements DocIdStream {
    private final TermDocs termDocs;
    private boolean valid = false;

    public LuceneDocIdStream(final TermDocs termDocs) {
        this.termDocs = termDocs;
    }

    @Override
    public void reset(final TermIterator term) {
        if (!(term instanceof LuceneTermIterator)) throw new IllegalArgumentException("This DocIdStream can only function with LuceneTermIterator");
        internalReset((LuceneTermIterator)term);
    }

    private void internalReset(final LuceneTermIterator term) {
        try {
            termDocs.seek(term.termEnum());
        } catch (final IOException e) {
            throw e(e);
        }
        valid = true;
    }

    @Override
    public int fillDocIdBuffer(final int[] docIdBuffer) {
        if (!valid) throw new IllegalArgumentException("DocIdStream is not in a valid state");
        try {
            return internalFillDocIdBuffer(docIdBuffer);
        } catch (IOException e) {
            throw e(e);
        }
    }

    private int internalFillDocIdBuffer(final int[] docIdBuffer) throws IOException {
        int i = 0;
        for (; i < docIdBuffer.length; i++) {
            if (!termDocs.next()) break; // todo: think about setting valid = false
            docIdBuffer[i] = termDocs.doc();
        }
        return i;
    }

    @Override
    public void close() {
        try {
            termDocs.close();
        } catch (IOException e) {
            throw e(e);
        }
    }

    private RuntimeException e(final IOException e) {
        valid = false;
        throw LuceneUtils.ioRuntimeException(e);
    }
}


text:
function u = unit(a, dim)
%UNIT   Normalizing vectors with respect to their magnitude.
%   If A is a vector (e.g. a P×1, 1×P, or 1×1×P array):
%
%      U = UNIT(A) returns A normalized for magnitude (see function MAGN).
%      If A represents a vectorial quantity, such as the position of a
%      point, U = UNIT(A) can be described as a unit vector aligned with A.
%
%      U = UNIT(A, DIM) is equivalent to UNIT (A) if DIM is the
%      non-singleton dimension of vector A; it returns a vector of ones
%      if DIM is a singleton dimension.
%
%   If A is an N-D array containing more than one vector:
%
%      U = UNIT(A) contains the elements, normalized for magnitude, of the
%      vectors constructed along the first non-singleton dimension of A.
%
%      U = UNIT(A, DIM) contains the elements, normalized for magnitude,
%      of the vectors constructed along the dimension DIM of A.
%
%   Example:
%   A 5×3×2 array may be considered to be a block array containing ten
%   3-element vectors along dimension 2. In this case, its size is denoted
%   by 5×(3)×2. If A is a 5×(3)×2 array, U = UNIT(A, 2) is an array of the
%   same size containing unit vectors.
%
%   See also MAGN, DOT2, CROSS2, CROSSDIV, OUTER, PROJECTION, REJECTION.

% $ Version: 2.0 $
% CODE      by:                 Paolo de Leva (IUSM, Rome, IT) 2009 Jan 24
% COMMENTS  by:                 Code author                    2009 Feb 6
% OUTPUT    tested by:          Code author                    2009 Feb 6
% -------------------------------------------------------------------------

% Coping with empty input arrays
if isempty(a), u = a; return, end

% Setting DIM if not supplied.
if nargin == 1
   firstNS = find(size(a)>1, 1, 'first'); % First non-singleton dimension
                                          % (empty matrix if A is a scalar)
   dim = max([firstNS, 1]);               % DIM = 1 if A is a scalar
end

% 1 - Computing magnitude of A
mag = magn(a, dim);

% 2 - Normalizing A.
%     (BSXFUN replicates MAG SIZE(A,DIM) times along its singleton dim. DIM)
u = bsxfun(@rdivide, a, mag);

% NOTE: For vectors with null magnitude, the latter divison (by zero) will
% cause MATLAB to issue a warning. The respective normalized vector will be
% composed of NaNs.


text:
package com.libqa.web.service.space;

import com.libqa.application.enums.ActivityType;
import com.libqa.web.domain.Keyword;
import com.libqa.web.domain.Space;
import com.libqa.web.domain.User;
import com.libqa.web.view.space.SpaceMain;
import com.libqa.web.view.space.SpaceMainList;
import com.libqa.web.view.space.SpaceWikiList;

import java.util.List;

/**
 * Created by yion on 2015. 3. 1..
 */
public interface SpaceService {

    Space save(Space space);

    /**
     * 삭제되지 않은 공간 목록 조회
     *
     * @param isDeleted
     * @return
     */
    List<Space> findAllByCondition(boolean isDeleted);

    /**
     * 페이징
     *
     * @param isDeleted
     * @param startIdx
     * @param endIdx
     * @return
     */
    List<Space> findAllByCondition(boolean isDeleted, Integer startIdx, Integer endIdx);

    /**
     * 페이징 및 정렬 조건
     *
     * @param isDeleted
     * @param startIdx
     * @param endIdx
     * @param sortCondition
     * @return
     */
    SpaceMainList findPageBySort(boolean isDeleted, Integer startIdx, Integer endIdx, String sortCondition);

    Space findOne(Integer spaceId);

    Space saveWithKeyword(Space space, Keyword keyword, ActivityType activityType);

    /**
     * 사용자가 추가한 즐겨찾기 공간 목록 조회
     *
     * @param userId
     * @return
     */
    List<Space> findUserFavoriteSpace(Integer userId, boolean isDeleted);

    /**
     * 즐겨 찾기 추가 (삭제)
     *
     * @param spaceId
     * @param userId
     * @param isDeleted
     * @return
     */
    Integer addSpaceFavorite(Integer spaceId, Integer userId, boolean isDeleted);

    Integer cancelSpaceFavorite(Integer spaceId, Integer userId, boolean isDeleted);

    /**
     * 삭제
     *
     * @param space
     * @param user
     * @return
     */
    Space delete(Space space, User user);

    List<SpaceMain> convertSpaceMain(List<Space> spaces);

    SpaceWikiList findWikiPageBySort(boolean isDeleted, Integer startIdx, Integer endIdx, String sortCondition);
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>statsmodels.tsa.arima_process.lpol_fiar — statsmodels 0.6.1 documentation</title>

    <link rel="stylesheet" href="../_static/nature.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />

    <link rel="shortcut icon" href="../_static/statsmodels_hybi_favico.ico"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="top" title="statsmodels 0.6.1 documentation" href="../index.html" />
    <link rel="up" title="Time Series analysis tsa" href="../tsa.html" />
    <link rel="next" title="statsmodels.tsa.arima_process.lpol_fima" href="statsmodels.tsa.arima_process.lpol_fima.html" />
    <link rel="prev" title="statsmodels.tsa.arima_process.lpol2index" href="statsmodels.tsa.arima_process.lpol2index.html" />
<link rel="stylesheet" href="../../_static/facebox.css" type="text/css" />
<link rel="stylesheet" href="../_static/examples.css" type="text/css" />

Navigation

          index

          next |

          previous |

Install
  |

Support
  |

Bugs
  |

Develop
  |

Examples
  |

FAQ
  |

Time Series analysis tsa |

statsmodels.tsa.arima_process.lpol_fiar¶

statsmodels.tsa.arima_process.lpol_fiar(d, n=20)[source]¶

AR representation of fractional integration

<col class="field-name" />
<col class="field-body" />

Parameters:
d : float

fractional power

n : int

number of terms to calculate, including lag zero

Returns:
ar : array

coefficients of lag polynomial

Notes:

first coefficient is 1, negative signs except for first term,

ar(L)*x_t

Previous topic

statsmodels.tsa.arima_process.lpol2index

Next topic

statsmodels.tsa.arima_process.lpol_fima

This Page

Show Source

Quick search

    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

    Enter search terms or a module, class or function name.

        © Copyright 2009-2013, Josef Perktold, Skipper Seabold, Jonathan Taylor, statsmodels-developers.
      Created using Sphinx 1.3.1.


text:
package com.intellij.extapi.psi;

import com.intellij.lang.ASTNode;
import com.intellij.psi.PsiElement;
import com.intellij.psi.impl.source.tree.SharedImplUtil;
import javax.annotation.Nonnull;

/**
 * @author max
 */
public class ASTWrapperPsiElement extends ASTDelegatePsiElement {
  private final ASTNode myNode;

  public ASTWrapperPsiElement(@Nonnull final ASTNode node) {
    myNode = node;
  }

  @Override
  public PsiElement getParent() {
    return SharedImplUtil.getParent(getNode());
  }

  @Override
  @Nonnull
  public ASTNode getNode() {
    return myNode;
  }

  @Override
  public String toString() {
    return getClass().getSimpleName() + "(" + myNode.getElementType().toString() + ")";
  }
}


text:
#ifndef SimTK_SIMBODY_SMOOTH_SPHERE_HALFSPACE_FORCE_IMPL_H_
#define SimTK_SIMBODY_SMOOTH_SPHERE_HALFSPACE_FORCE_IMPL_H_

#include "SimTKcommon.h"
#include "simbody/internal/common.h"
#include "simbody/internal/SmoothSphereHalfSpaceForce.h"
#include "ForceImpl.h"

namespace SimTK {

class SmoothSphereHalfSpaceForceImpl : public ForceImpl {
public:
    class Parameters {
    public:
        Parameters() : stiffness(1), dissipation(0), staticFriction(0),
            dynamicFriction(0), viscousFriction(0), transitionVelocity(0.01),
            cf(1e-5), bd(300), bv(50) {
        }
        Parameters(Real stiffness, Real dissipation, Real staticFriction,
            Real dynamicFriction, Real viscousFriction,
            Real transitionVelocity, Real cf, Real bd, Real bv) :
            stiffness(stiffness), dissipation(dissipation),
            staticFriction(staticFriction), dynamicFriction(dynamicFriction),
            viscousFriction(viscousFriction),
            transitionVelocity(transitionVelocity), cf(cf), bd(bd), bv(bv) {
        }
        Real stiffness, dissipation, staticFriction, dynamicFriction,
            viscousFriction, transitionVelocity, cf, bd, bv;
    };

    Real            contactSphereRadius;
    Vec3            contactSphereLocation;
    Transform       contactHalfSpaceFrame;
    MobilizedBody   bodySphere;
    MobilizedBody   bodyHalfSpace;
    Parameters      parameters;

    SmoothSphereHalfSpaceForceImpl(GeneralForceSubsystem& subsystem);

    SmoothSphereHalfSpaceForceImpl* clone() const override {
        return new SmoothSphereHalfSpaceForceImpl(*this);
    }
    // Set the contact material parameters.
    void setParameters(Real stiffness, Real dissipation, Real staticFriction,
        Real dynamicFriction, Real viscousFriction, Real transitionVelocity,
        Real cf, Real bd, Real bv);
    // Get parameters.
    const Parameters& getParameters() const;
    // Update parameters.
    Parameters& updParameters();
    // Set the stiffness constant (i.e., plain strain modulus), default is 1
    // N/m^2.
    void setStiffness(Real stiffness);
    // Set the dissipation coefficient, default is 0 s/m.
    void setDissipation(Real dissipation);
    // Set the coefficient of static friction, default is 0.
    void setStaticFriction(Real staticFriction);
    // Set the coefficient of dynamic friction, default is 0.
    void setDynamicFriction(Real dynamicFriction);
    // Set the coefficient of viscous friction, default is 0.
    void setViscousFriction(Real viscousFriction);
    // Set the transition velocity, default is 0.01 m/s.
    void setTransitionVelocity(Real transitionVelocity);
    // Set the constant that enforces non-null derivatives, default is 1e-5.
    void setConstantContactForce(Real cf);
    // Set the parameter that determines the smoothness of the transition
    // of the tanh used to smooth the Hertz force. The larger the steeper the
    // transition but also the more discontinuous, default is 300.
    void setHertzSmoothing(Real bd);
    // Set the parameter that determines the smoothness of the transition of
    // the tanh used to smooth the Hunt-Crossley force. The larger the steeper
    // the transition but also the more discontinuous, default is 50.
    void setHuntCrossleySmoothing(Real bv);
    // Set the MobilizedBody to which the contact sphere is attached.
    void setContactSphereBody(MobilizedBody bodyInput1);
    // Set the location of the contact sphere in the body frame.
    void setContactSphereLocationInBody(Vec3 locationContactSphere);
    // Set the radius of the contact sphere.
    void setContactSphereRadius(Real radius);
    // Set the MobilizedBody to which the contact half space is attached.
    void setContactHalfSpaceBody(MobilizedBody bodyInput2);
    // Set the transform of the contact half space in the body frame.
    void setContactHalfSpaceFrame(Transform halfSpaceFrame);
    // Get the MobilizedBody to which the contact sphere is attached.
    MobilizedBody getBodySphere();
    // Get the MobilizedBody to which the contact half space is attached.
    MobilizedBody getBodyHalfSpace();
    // Get the location of the contact sphere in the body frame.
    Vec3 getContactSphereLocationInBody();
    // Get the radius of the contact sphere.
    Real getContactSphereRadius();
    // Get the transform of the contact half space.
    Transform getContactHalfSpaceTransform();
    // Get the normal to the contact half space.
    void getNormalContactHalfSpace(const State& state,
        UnitVec3& normalContactHalfSpace) const;
    // Get the location of the contact sphere origin in the ground frame.
    void getContactSphereOrigin(const State& state,Vec3& contactPointPos)const;
    // Calculate contact force.
    void calcForce(const State& state, Vector_<SpatialVec>& bodyForces,
        Vector_<Vec3>& particleForces, Vector& mobilityForces) const override;
    // Calculate potential energy.
    Real calcPotentialEnergy(const State& state) const override;
    void realizeTopology(State& state) const override;
private:
    const GeneralForceSubsystem&          subsystem;
    mutable CacheEntryIndex               energyCacheIndex;
};

} // namespace SimTK

#endif // SimTK_SIMBODY_SMOOTH_SPHERE_HALFSPACE_FORCE_IMPL_H_


text:
workers Integer(ENV['WEB_CONCURRENCY'] || 2)
threads_count = Integer(ENV['MAX_THREADS'] || 5)
threads threads_count, threads_count

preload_app!

rackup      DefaultRackup
port        ENV['PORT']     || 3000
environment ENV['RACK_ENV'] || 'development'

on_worker_boot do
  ::TraceView.reconnect! if defined?(::TraceView)
end

on_worker_shutdown do
  ::TraceView.disconnect! if defined?(::TraceView)
end


text:
using NuGet;

namespace NuSelfUpdate
{
    public interface IExtendedFileSystem : IFileSystem
    {
        string AppDirectory { get; }
        void MoveFile(string sourcePath, string destinationPath);
    }
}


text:
package org.mrgeo.hdfs.vector;

import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.mapreduce.RecordReader;
import org.apache.hadoop.mapreduce.RecordWriter;
import org.mrgeo.core.MrGeoConstants;
import org.mrgeo.core.MrGeoProperties;
import org.mrgeo.data.ProviderProperties;
import org.mrgeo.data.vector.*;
import org.mrgeo.geometry.Geometry;
import org.mrgeo.hdfs.utils.HadoopFileUtils;
import org.mrgeo.hdfs.vector.ShpInputFormat.ShpRecordReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

public class HdfsVectorDataProvider extends VectorDataProvider
{
private static Logger log = LoggerFactory.getLogger(HdfsVectorDataProvider.class);

private Configuration conf;
private Path resourcePath;
private ProviderProperties providerProperties;

public HdfsVectorDataProvider(Configuration conf,
    String prefix, String resourceName, ProviderProperties providerProperties)
{
  super(prefix, resourceName);

  this.conf = conf;
  this.providerProperties = providerProperties;
}

public static boolean isSourceDelimited(Path source, boolean mustExist,
    Configuration conf) throws IOException
{
  if (source != null)
  {
    String lowerPath = source.toString().toLowerCase();
    if (lowerPath.endsWith(".tsv") || lowerPath.endsWith(".csv"))
    {
      if (mustExist)
      {
        FileSystem fs = HadoopFileUtils.getFileSystem(conf, source);
        return fs.exists(source);
      }
      return true;
    }
  }
  return false;
}

public static boolean isSourceShapefile(Path source)
{
  if (source != null)
  {
    String lowerPath = source.toString().toLowerCase();
    return lowerPath.endsWith(".shp");
  }
  return false;
}

@SuppressWarnings("squid:S1166") // Exception caught and handled
public static boolean canOpen(Configuration conf, String input,
    ProviderProperties providerProperties) throws IOException
{
  Path p;
  try
  {
    p = resolveName(conf, input, providerProperties, false);
    if (isSourceDelimited(p, true, conf))
    {
      return true;
    }
    if (isSourceShapefile(p))
    {
      return true;
    }
  }
  catch (IOException ignored)
  {
  }
  return false;
}

public static boolean exists(Configuration conf, String input,
    ProviderProperties providerProperties) throws IOException
{
  return resolveNameToPath(conf, input, providerProperties, true) != null;
}

public static void delete(Configuration conf, String input,
    ProviderProperties providerProperties) throws IOException
{
  Path p = resolveNameToPath(conf, input, providerProperties, false);
  if (p != null)
  {
    if (isSourceDelimited(p, false, conf))
    {
      HadoopFileUtils.delete(conf, p);
      Path columns = new Path(p + ".columns");
      if (HadoopFileUtils.exists(conf, columns))
      {
        HadoopFileUtils.delete(conf, columns);
      }
    }
    else if (isSourceShapefile(p))
    {
      HadoopFileUtils.delete(conf, p);
      String fileName = p.toString();
      // We know the file ends in ".shp"
      String fileWithoutExt = fileName.substring(0, fileName.length() - 3);
      String[] subExts = {"shx", "idx", "dbf", "prj", "shp.xml", "sbn", "sbx", "avl"};
      for (String ext : subExts)
      {
        Path subFile = new Path(fileWithoutExt + ext);
        if (HadoopFileUtils.exists(conf, subFile))
        {
          HadoopFileUtils.delete(conf, subFile);
        }
      }
    }
  }
}

public static boolean canWrite(Configuration conf, String input,
    ProviderProperties providerProperties) throws IOException
{
  // The return value of resolveNameToPath will be null if the input
  // path does not exist. It wil throw an exception if there is a problem
  // with building the path.
  Path p = resolveNameToPath(conf, input, providerProperties, true);
  return (p == null);
}

static Path getBasePath(Configuration conf)
{
  String basePathKey = "hdfs." + MrGeoConstants.MRGEO_HDFS_VECTOR;
  Path basePath = null;
  String strBasePath = null;
  // First check to see if the vector base path is defined in the configuration.
  // This happens when it's being called from within code that runs on a
  // Hadoop data node.
  // If it's not there, then check for the base path definition in the mrgeo conf,
  // which will only work when it's called from the name node.
  if (conf != null)
  {
    strBasePath = conf.get(basePathKey);
  }
  if (strBasePath == null)
  {
    strBasePath = MrGeoProperties.getInstance().getProperty(MrGeoConstants.MRGEO_HDFS_VECTOR);
  }
  if (strBasePath != null)
  {
    try
    {
      basePath = new Path(new URI(strBasePath));
    }
    catch (URISyntaxException e)
    {
      log.error("Invalid HDFS base path for vectors: " + strBasePath, e);
    }
  }
  // Use default if we couldn't get the base path
  if (basePath == null)
  {
    basePath = new Path("/mrgeo/vectors");
  }
  return basePath;
}

private static Path resolveName(Configuration conf, String input,
    ProviderProperties providerProperties, boolean mustExist) throws IOException
{
  Path result = resolveNameToPath(conf, input, providerProperties, mustExist);
  // Check to see if the source is one of the supported formats
  if (result != null && (isSourceDelimited(result, mustExist, conf) || isSourceShapefile(result)))
  {
    return result;
  }

  throw new IOException("Invalid image: " + input);
}

@SuppressWarnings("squid:S1166") // Exception caught and handled
@SuppressFBWarnings(value = "PATH_TRAVERSAL_IN", justification = "method only makes complete URI out of the name")
public static Path resolveNameToPath(Configuration conf, String input,
    ProviderProperties providerProperties, boolean mustExist) throws IOException
{
  if (input.indexOf('/') >= 0)
  {
    // The requested input is absolute. If it exists in the local file
    // system, then return that path. Otherwise, check HDFS, and if it
    // doesn't exist there either, but mustExist is false, return the
    // HDFS path (this resource is being created). We never create resources
    // in the local file system.
    File f = new File(input);
    if (f.exists())
    {
      try
      {
        return new Path(new URI("file://" + input));
      }
      catch (URISyntaxException e)
      {
        // The URI is invalid, so let's continue to try to open it in HDFS
      }
    }
    Path p = null;
    try
    {
      p = new Path(input);
    }
    catch (IllegalArgumentException e)
    {
      // If the path is a bad URI (which can happen if this is not an HDFS resource),
      // then an IllegalArgumentException is thrown.
      return null;
    }
    if (mustExist)
    {
      FileSystem fs = HadoopFileUtils.getFileSystem(conf, p);
      if (fs.exists(p))
      {
        return p;
      }
    }
    else
    {
      return p;
    }
    return null;
  }
  else
  {
    // The input is relative, check it using the image base path.
    Path p = null;
    try
    {
      p = new Path(getBasePath(conf), input);
    }
    catch (IllegalArgumentException e)
    {
      // If the path is a bad URI (which can happen if this is not an HDFS resource),
      // then an IllegalArgumentException is thrown.
      return null;
    }
    if (mustExist)
    {
      FileSystem fs = HadoopFileUtils.getFileSystem(conf, p);
      if (fs.exists(p))
      {
        return p;
      }
    }
    else
    {
      return p;
    }
    return null;
  }
}

public String getResolvedResourceName(boolean mustExist) throws IOException
{
  return resolveNameToPath(conf, getResourceName(), providerProperties, mustExist).toUri().toString();
  //return new Path(getImageBasePath(), getResourceName()).toUri().toString();
}

public Path getResourcePath(boolean mustExist) throws IOException
{
  if (resourcePath == null)
  {
    resourcePath = resolveName(getConfiguration(), getResourceName(),
        providerProperties, mustExist);
  }
  return resourcePath;
}

@Override
public VectorMetadataReader getMetadataReader()
{
  // TODO Auto-generated method stub
  return null;
}

@Override
public VectorMetadataWriter getMetadataWriter()
{
  // TODO Auto-generated method stub
  return null;
}

@Override
public VectorReader getVectorReader() throws IOException
{
  String resourceName = getResolvedResourceName(true);

  Path resourcePath = new Path(resourceName);
  if (isSourceDelimited(resourcePath, true, getConfiguration()))
  {
    return new DelimitedVectorReader(this, new VectorReaderContext(), conf);
  }
  else if (isSourceShapefile(resourcePath))
  {
    return new ShapefileVectorReader(this, new VectorReaderContext(), conf);
  }
  throw new IOException("Unable to create vector reader for " + resourceName);
}

@Override
public VectorReader getVectorReader(VectorReaderContext context) throws IOException
{
  String resourceName = getResolvedResourceName(true);
  Path resourcePath = new Path(resourceName);
  if (isSourceDelimited(resourcePath, true, getConfiguration()))
  {
    return new DelimitedVectorReader(this, context, conf);
  }
  else if (isSourceShapefile(resourcePath))
  {
    return new ShapefileVectorReader(this, context, conf);
  }
  throw new IOException("Unable to create vector reader for " + resourceName);
}

@Override
public VectorWriter getVectorWriter() throws IOException
{
  String resourceName = getResolvedResourceName(false);
  Path resourcePath = new Path(resourceName);
  if (isSourceDelimited(resourcePath, false, getConfiguration()))
  {
    return new DelimitedVectorWriter(this, conf);
  }
  // TODO:
//    else if (isSourceShapefile(resourcePath))
//    {
//      return new ShapefileVectorWriter(context);
//    }
  throw new IOException("Unable to create vector output format provider for " + resourceName);
}

@Override
public RecordReader<FeatureIdWritable, Geometry> getRecordReader() throws IOException
{
  String resourceName = getResolvedResourceName(true);
  Path resourcePath = new Path(resourceName);
  if (isSourceDelimited(resourcePath, true, getConfiguration()))
  {
    return new DelimitedVectorRecordReader();
  }
  else if (isSourceShapefile(resourcePath))
  {
    return new ShpRecordReader();
  }
  throw new IOException("Unable to create vector reader for " + resourceName);
}

@Override
public RecordWriter<FeatureIdWritable, Geometry> getRecordWriter()
{
  // TODO Auto-generated method stub
  return null;
}

@Override
public VectorInputFormatProvider getVectorInputFormatProvider(VectorInputFormatContext context) throws IOException
{
  String resourceName = getResolvedResourceName(true);
  Path resourcePath = new Path(resourceName);
  if (isSourceDelimited(resourcePath, true, getConfiguration()))
  {
    return new DelimitedVectorInputFormatProvider(context);
  }
  else if (isSourceShapefile(resourcePath))
  {
    return new ShapefileVectorInputFormatProvider(context);
  }
  throw new IOException("Unable to create vector input format provider for " + resourceName);
}

@Override
public VectorOutputFormatProvider getVectorOutputFormatProvider(VectorOutputFormatContext context) throws IOException
{
  String resourceName = getResolvedResourceName(false);
  Path resourcePath = new Path(resourceName);
  if (isSourceDelimited(resourcePath, false, getConfiguration()))
  {
    return new DelimitedVectorOutputFormatProvider(this, context);
  }
//    else if (isSourceShapefile(resourcePath))
//    {
//      return new ShapefileVectorInputFormatProvider(context);
//    }
  throw new IOException("Unable to create vector output format provider for " + resourceName);
}

@Override
public void delete() throws IOException
{
  // TODO Auto-generated method stub

}

@Override
public void move(String toResource) throws IOException
{
  // TODO Auto-generated method stub

}

private Configuration getConfiguration()
{
  return conf;
}
}


text:
#pragma once

#ifndef GEODE_CLIENTMETADATASERVICE_H_
#define GEODE_CLIENTMETADATASERVICE_H_

#include <ace/Task.h>
#include "ClientMetadata.hpp"
#include "ServerLocation.hpp"
#include "BucketServerLocation.hpp"
#include <geode/HashMapT.hpp>
#include <geode/SharedPtr.hpp>
#include <geode/CacheableKey.hpp>
#include <geode/Cacheable.hpp>
#include <geode/Region.hpp>
#include "Queue.hpp"
#include <string>
#include "DistributedSystemImpl.hpp"
#include "NonCopyable.hpp"

namespace apache {
namespace geode {
namespace client {

class ClienMetadata;

typedef std::map<std::string, ClientMetadataPtr> RegionMetadataMapType;

class BucketStatus {
 private:
  ACE_Time_Value m_lastTimeout;

 public:
  BucketStatus() : m_lastTimeout(ACE_Time_Value::zero) {}
  bool isTimedoutAndReset(uint32_t millis) {
    if (m_lastTimeout == ACE_Time_Value::zero) {
      return false;
    } else {
      ACE_Time_Value to(0, millis * 1000);
      to += m_lastTimeout;
      if (to > ACE_OS::gettimeofday()) {
        return true;  // timeout as buckste not recovered yet
      } else {
        // reset to zero as we waited enough to recover bucket
        m_lastTimeout = ACE_Time_Value::zero;
        return false;
      }
    }
  }

  void setTimeout() {
    if (m_lastTimeout == ACE_Time_Value::zero) {
      m_lastTimeout = ACE_OS::gettimeofday();  // set once only for timeout
    }
  }
};

class PRbuckets {
 private:
  BucketStatus* m_buckets;

 public:
  PRbuckets(int32_t nBuckets) { m_buckets = new BucketStatus[nBuckets]; }
  ~PRbuckets() { delete[] m_buckets; }

  bool isBucketTimedOut(int32_t bucketId, uint32_t millis) {
    return m_buckets[bucketId].isTimedoutAndReset(millis);
  }

  void setBucketTimeout(int32_t bucketId) { m_buckets[bucketId].setTimeout(); }
};

/* adongre
 * CID 28726: Other violation (MISSING_COPY)
 * Class "apache::geode::client::ClientMetadataService" owns resources that are
 * managed
 * in its constructor and destructor but has no user-written copy constructor.
 *
 * CID 28712: Other violation (MISSING_ASSIGN)
 * Class "apache::geode::client::ClientMetadataService" owns resources that are
 * managed
 * in its constructor and destructor but has no user-written assignment
 * operator.
 *
 * FIX : Make the class NonCopyabl3
 */

class ClientMetadataService : public ACE_Task_Base,
                              private NonCopyable,
                              private NonAssignable {
 public:
  ~ClientMetadataService();
  ClientMetadataService(PoolPtr pool);

  inline void start() {
    m_run = true;
    this->activate();
  }

  inline void stop() {
    m_run = false;
    m_regionQueueSema.release();
    this->wait();
  }

  int svc(void);

  void getClientPRMetadata(const char* regionFullPath);

  void getBucketServerLocation(
      const RegionPtr& region, const CacheableKeyPtr& key,
      const CacheablePtr& value, const UserDataPtr& aCallbackArgument,
      bool isPrimary, BucketServerLocationPtr& serverLocation, int8_t& version);

  void removeBucketServerLocation(BucketServerLocation serverLocation);

  ClientMetadataPtr getClientMetadata(const char* regionFullPath);

  void populateDummyServers(const char* regionName,
                            ClientMetadataPtr clientmetadata);

  void enqueueForMetadataRefresh(const char* regionFullPath,
                                 int8_t serverGroupFlag);

  HashMapT<BucketServerLocationPtr, VectorOfCacheableKeyPtr>*
  getServerToFilterMap(const VectorOfCacheableKey* keys,
                       const RegionPtr& region, bool isPrimary);

  void markPrimaryBucketForTimeout(
      const RegionPtr& region, const CacheableKeyPtr& key,
      const CacheablePtr& value, const UserDataPtr& aCallbackArgument,
      bool isPrimary, BucketServerLocationPtr& serverLocation, int8_t& version);

  void markPrimaryBucketForTimeoutButLookSecondaryBucket(
      const RegionPtr& region, const CacheableKeyPtr& key,
      const CacheablePtr& value, const UserDataPtr& aCallbackArgument,
      bool isPrimary, BucketServerLocationPtr& serverLocation, int8_t& version);

  bool isBucketMarkedForTimeout(const char* regionFullPath, int32_t bucketid);

  bool AreBucketSetsEqual(CacheableHashSetPtr& currentBucketSet,
                          CacheableHashSetPtr& bucketSet);

  BucketServerLocationPtr findNextServer(
      HashMapT<BucketServerLocationPtr, CacheableHashSetPtr>*
          serverToBucketsMap,
      CacheableHashSetPtr& currentBucketSet);

  HashMapT<CacheableInt32Ptr, CacheableHashSetPtr>* groupByBucketOnClientSide(
      const RegionPtr& region, CacheableVectorPtr* keySet,
      ClientMetadataPtr& metadata);

  HashMapT<BucketServerLocationPtr, CacheableHashSetPtr>*
  getServerToFilterMapFESHOP(CacheableVectorPtr* keySet,
                             const RegionPtr& region, bool isPrimary);

  HashMapT<BucketServerLocationPtr, CacheableHashSetPtr>*
  groupByServerToAllBuckets(const RegionPtr& region, bool optimizeForWrite);

  HashMapT<BucketServerLocationPtr, CacheableHashSetPtr>*
  groupByServerToBuckets(ClientMetadataPtr& metadata,
                         CacheableHashSetPtr& bucketSet, bool optimizeForWrite);

  HashMapT<BucketServerLocationPtr, CacheableHashSetPtr>* pruneNodes(
      ClientMetadataPtr& metadata, CacheableHashSetPtr& totalBuckets);

 private:
  // const PartitionResolverPtr& getResolver(const RegionPtr& region, const
  // CacheableKeyPtr& key,
  // const UserDataPtr& aCallbackArgument);

  // BucketServerLocation getServerLocation(ClientMetadataPtr cptr, int
  // bucketId, bool isPrimary);

  ClientMetadataPtr SendClientPRMetadata(const char* regionPath,
                                         ClientMetadataPtr cptr);

 private:
  // ACE_Recursive_Thread_Mutex m_regionMetadataLock;
  ACE_RW_Thread_Mutex m_regionMetadataLock;
  ClientMetadataService();
  ACE_Semaphore m_regionQueueSema;
  RegionMetadataMapType m_regionMetaDataMap;
  volatile bool m_run;
  PoolPtr m_pool;
  Queue<std::string>* m_regionQueue;

  ACE_RW_Thread_Mutex m_PRbucketStatusLock;
  std::map<std::string, PRbuckets*> m_bucketStatus;
  uint32_t m_bucketWaitTimeout;
  static const char* NC_CMDSvcThread;
};
}  // namespace client
}  // namespace geode
}  // namespace apache

#endif  // GEODE_CLIENTMETADATASERVICE_H_


text:
    padding: 11px 16px 11px !important;
    font-size: 12px;
    border: none;
    color: #fff;
    margin-top: 10px;
    height: auto!important;
    -webkit-transition: 0.1s linear all;
    -moz-transition: 0.1s linear all;
    -ms-transition: 0.1s linear all;
    -o-transition: 0.1s linear all;
    transition: 0.1s linear all;
    -webkit-border-radius: 2px;
    -moz-border-radius: 2px;
    border-radius: 2px;
    text-shadow: 0px 0px 0px!important;
    background-color: rgba(255,255,255,0.25)!important;
    background-image: none!important;
}

#redux-opts-header .button:hover {
    background-color: rgba(255,255,255,0.2)!important;
}

#redux-opts-header .button-primary {
    background-color: #77cc6d!important;
    background-image: none!important;
    border: none!important;
    padding: 11px 16px 11px !important;
    height: auto!important;
    color: #fff!important;
    font-size: 12px;
    line-height: normal;
    -webkit-border-radius: 2px;
    -moz-border-radius: 2px;
    border-radius: 2px;
    -webkit-transition: 0.1s linear all;
    -moz-transition: 0.1s linear all;
    -ms-transition: 0.1s linear all;
    -o-transition: 0.1s linear all;
    transition: 0.1s linear all;
    text-shadow: 0px 0px 0px!important;
}

#redux-opts-header .button-primary:hover {
    text-shadow: 0px 0px 0px!important;
    background-color: #77cc6d!important;
    opacity: 0.9;
}

.add-remove-controls .button-primary {
    background-color: #77cc6d!important;
    background-image: none!important;
    border: none!important;
    width: 32px;
    text-align: center;
    padding: 5px 10px!important;
    height: auto!important;
    color: #fff!important;
    font-weight: normal!important;
    font-size: 18px;
    line-height: normal;
    -webkit-border-radius: 2px;
    -moz-border-radius: 2px;
    border-radius: 2px;
    -webkit-transition: 0.1s linear all;
    -moz-transition: 0.1s linear all;
    -ms-transition: 0.1s linear all;
    -o-transition: 0.1s linear all;
    transition: 0.1s linear all;
    text-shadow: 0px 0px 0px transparent!important;
}

.add-remove-controls .button-primary:hover {
    text-shadow: 0px 0px 0px!important;
    background-color: #77cc6d!important;
    opacity: 0.9;
}
.add-remove-controls .button-primary:focus {
    box-shadow: 0px 0px 0px!important;
}

tr.font-option {
    float: left;
    position: relative;
}

tr.font-option th {
    display: none;
}

tr.font-family {
    float: left;
    clear: both;
}

tr.font-family td, tr.font-family {
    position: relative;
}

tr.font-family td span {
    top: -22px;
    right: 32px;
    display: block;
    width: 100px!important;
    position: absolute;
    padding-top: 25px!important;
    padding-bottom:0px!important;
    padding-left: 7px!important;
    padding-right: 7px!important;
    font-size: 12px!important;
    font-weight: normal!important;
}

.redux-opts-group-tab {
    position: relative;
}

.typography-table {
    padding-top: 30px!important;
    display: block;
    position: relative;
    z-index: 1;
}

tr.the-toggle {
    width: 100%!important;
    clear: both;
    display: block!important;
}

.the-toggle td {
    padding-left: 84px!important;
}

.the-toggle {
    margin-top: 43px;
    padding-bottom: 20px;
}

tr.the-toggle th {
    width: 141px!important;
}

tr.font-family th {
    padding-top: 29px!important;
    padding-bottom: 25px!important;
    width: 150px!important;
}

tr.font-option td, tr.font-family td {
    padding-left: 7px!important;
    padding-right: 7px!important;
    padding-top: 25px!important;
    padding-bottom: 25px!important;
}

tr.font-family, tr.font-family, tr.font-option  {
    border-bottom: 0px!important;
}

.webuza-debug textarea {
    height: 400px;
    width: 800px;
}
.webuza-metabox-table tr {
    border-top: 1px solid #EEEEEE;
}
.webuza-metabox-table th {
    width: 25%;
}
.webuza-metabox-table label span {
    color: #999999;
    display: block;
    line-height: 20px;
    margin: 5px 0 0;
}
.webuza-metabox-table input, .webuza-metabox-table textarea {
    float: left;
    margin-right: 20px;
    width: 100%;
    transition: all 0.2s linear;
    -moz-transition: all 0.2s linear;
    -webkit-transition: all 0.2s linear;
    -o-transition: all 0.2s linear;
}

.webuza-metabox-table input[type=checkbox] {
    width: 20px;
}

.webuza-metabox-table input.file {
    width: 85%;
}
.webuza-metabox-table input.button {
    margin-right: 0;
    width: auto;
}
.webuza-metabox-table input.radio {
    float: none;
    margin-right: 3px;
    width: auto;
}
.webuza-metabox-table .radio-label {
    margin-right: 10px;
}

.webuza-metabox-table img {
    width: 50%;
    display: block;
}

.slider-thumb {
    width: 85%;
    margin-right: 15%;
}

td.caption.column-caption, td.actions.column-actions, td.menu_order.column-menu_order, .type-home_slider td.column-title, .type-home_slider td.column-date {
    vertical-align: middle;
}

.type-home_slider td.column-title strong {
    display: none;
}

.type-home_slider td.column-title .row-actions {
    visibility: visible;
}

td.remove.column-remove, td.menu_order.column-menu_order, .manage-column.column-remove, .manage-column.column-menu_order {
    width: 9%!important;
}

td.caption.column-caption, .manage-column.column-caption {
    width: 40%;
}

td.thumbnail.column-thumbnail, .manage-column.column-thumbnail {
    width: 20%;
    padding: 10px;
}

td.menu_order.column-menu_order {
    font-size: 34px;
    line-height: 34px;
}

td.caption.column-caption {
    font-size: 24px;
    padding-right: 20px;
    line-height: 28px;
}

#sortable-table .column-order {
    width: 6%!important;
    padding-right: 0px!important;
}

#sortable-table .ui-sortable tr.ui-sortable-helper {
    background-color: #fff;
    box-shadow: 0px 0px 8px rgba(0,0,0,0.4);
}

#sortable-table .ui-sortable tr.ui-sortable-helper td {
    border: 0px!important;
}

#sortable-table .ui-sortable tr.ui-sortable-helper td.column-order {
    width: 6%!important;
}

#sortable-table .ui-sortable tr.ui-sortable-helper td.thumbnail.column-thumbnail {
    width: 22%!important;
}

#sortable-table .ui-sortable tr.ui-sortable-helper .td.caption.column-caption {
    width: 72%!important;
}

#sortable-table .column-order { padding: 3px 10px; width: 50px; }
#sortable-table .column-order img { cursor: move; }
#sortable-table td.column-order { vertical-align: middle; text-align: center; }

#webuza-framework .main-layout label {
    border: 3px solid #FFFFFF;
    display: inline-block;
    height: 36px;
    margin: 0 0 5px 5px;
    text-indent: -99999px;
    width: 45px;
}

#redux-opts-screenshot-_webuza_slide_ico_img,
#redux-opts-screenshot-_webuza_slide_ico_hover_img {
    width: 48px;
    height: 48px;
}


text:
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

# Get the command line arguments.
CONTAINER_TYPE=$( echo "$1" | tr '[:upper:]' '[:lower:]' )
shift 1

# Dockerfile to be used in docker build
DOCKERFILE_PATH="${SCRIPT_DIR}/Dockerfile.${CONTAINER_TYPE}"

if [[ "$1" == "--tag" ]]; then
    DOCKER_IMAGE_TAG="$2"
    echo "Using custom Docker tag: ${DOCKER_IMAGE_TAG}"
    shift 2
fi

if [[ "$1" == "--dockerfile" ]]; then
    DOCKERFILE_PATH="$2"
    echo "Using custom Dockerfile path: ${DOCKERFILE_PATH}"
    shift 2
fi

if [[ "$1" == "-it" ]]; then
    CI_DOCKER_EXTRA_PARAMS+=('-it')
    shift 1
fi

if [[ "$1" == "--net=host" ]]; then
    CI_DOCKER_EXTRA_PARAMS+=('--net=host')
    CI_DOCKER_BUILD_EXTRA_PARAMS+=("--network=host")
    shift 1
fi

DOCKER_NO_CACHE_ARG=--no-cache

if [[ "$1" == "--cache-from" ]]; then
    shift 1
    cached_image="$1"
    DOCKER_NO_CACHE_ARG=
    CI_DOCKER_BUILD_EXTRA_PARAMS+=("--cache-from tvm.$CONTAINER_TYPE:$DOCKER_IMAGE_TAG")
    CI_DOCKER_BUILD_EXTRA_PARAMS+=("--cache-from $cached_image")
    shift 1
fi

if [[ "$1" == "--context-path" ]]; then
    DOCKER_CONTEXT_PATH="$2"
    echo "Using custom context path: ${DOCKER_CONTEXT_PATH}"
    shift 2
else
    DOCKER_CONTEXT_PATH=$(dirname "${DOCKERFILE_PATH}")
    echo "Using default context path: ${DOCKER_CONTEXT_PATH}"
fi

if [[ "$1" == "--name" ]]; then
    CI_DOCKER_EXTRA_PARAMS+=("--name ${2} --hostname ${2}")
    echo "Using container name ${2}"
    shift 2
fi

if [[ ! -f "${DOCKERFILE_PATH}" ]]; then
    echo "Invalid Dockerfile path: \"${DOCKERFILE_PATH}\""
    exit 1
fi

COMMAND=("$@")

# Validate command line arguments.
if [ ! -e "${SCRIPT_DIR}/Dockerfile.${CONTAINER_TYPE}" ]; then
    supported_container_types=$( ls -1 ${SCRIPT_DIR}/Dockerfile.* | \
        sed -n 's/.*Dockerfile\.\([^\/]*\)/\1/p' | tr '\n' ' ' )
      echo "Usage: $(basename $0) CONTAINER_TYPE COMMAND"
      echo "       CONTAINER_TYPE can be one of [${supported_container_types}]"
      echo "       COMMAND (optional) is a command (with arguments) to run inside"
      echo "               the container."
      exit 1
fi

# Use nvidia-docker if the container is GPU.
if [[ "${CONTAINER_TYPE}" == *"gpu"* || "${CONTAINER_TYPE}" == *"cuda"* ]]; then
    if ! type "nvidia-docker" 1> /dev/null 2> /dev/null
    then
        DOCKER_BINARY="docker"
        CUDA_ENV=" --gpus all "${CUDA_ENV}
    else
        DOCKER_BINARY="nvidia-docker"
    fi
else
    DOCKER_BINARY="docker"
fi

# Helper function to traverse directories up until given file is found.
function upsearch () {
    test / == "$PWD" && return || \
        test -e "$1" && echo "$PWD" && return || \
        cd .. && upsearch "$1"
}

# Set up WORKSPACE and BUILD_TAG. Jenkins will set them for you or we pick
# reasonable defaults if you run it outside of Jenkins.
WORKSPACE="${WORKSPACE:-${SCRIPT_DIR}/../}"
BUILD_TAG="${BUILD_TAG:-tvm}"
DOCKER_IMAGE_TAG="${DOCKER_IMAGE_TAG:-latest}"

# Determine the docker image name
DOCKER_IMG_NAME="${BUILD_TAG}.${CONTAINER_TYPE}"

# Under Jenkins matrix build, the build tag may contain characters such as
# commas (,) and equal signs (=), which are not valid inside docker image names.
DOCKER_IMG_NAME=$(echo "${DOCKER_IMG_NAME}" | sed -e 's/=/_/g' -e 's/,/-/g')

# Convert to all lower-case, as per requirement of Docker image names
DOCKER_IMG_NAME=$(echo "${DOCKER_IMG_NAME}" | tr '[:upper:]' '[:lower:]')

# Compose the full image spec with "name:tag" e.g. "tvm.ci_cpu:v0.03"
DOCKER_IMG_SPEC="${DOCKER_IMG_NAME}:${DOCKER_IMAGE_TAG}"

# Print arguments.
echo "WORKSPACE: ${WORKSPACE}"
echo "CI_DOCKER_EXTRA_PARAMS: ${CI_DOCKER_EXTRA_PARAMS[@]}"
echo "COMMAND: ${COMMAND[@]}"
echo "CONTAINER_TYPE: ${CONTAINER_TYPE}"
echo "BUILD_TAG: ${BUILD_TAG}"
echo "DOCKER CONTAINER NAME: ${DOCKER_IMG_NAME}"
echo "DOCKER_IMAGE_TAG: ${DOCKER_IMAGE_TAG}"
echo "DOCKER_IMG_SPEC: ${DOCKER_IMG_SPEC}"
echo ""

# Build the docker container.
echo "Building container (${DOCKER_IMG_NAME})..."
docker build -t ${DOCKER_IMG_SPEC} \
    ${DOCKER_NO_CACHE_ARG} \
    -f "${DOCKERFILE_PATH}" \
    ${CI_DOCKER_BUILD_EXTRA_PARAMS[@]} \
    "${DOCKER_CONTEXT_PATH}"

# Check docker build status
if [[ $? != "0" ]]; then
    echo "ERROR: docker build failed."
    exit 1
fi

if [[ -n ${COMMAND} ]]; then

    # Run the command inside the container.
    echo "Running '${COMMAND[@]}' inside ${DOCKER_IMG_SPEC}..."

    # By default we cleanup - remove the container once it finish running (--rm)
    # and share the PID namespace (--pid=host) so the process inside does not have
    # pid 1 and SIGKILL is propagated to the process inside (jenkins can kill it).
    echo ${DOCKER_BINARY}
    ${DOCKER_BINARY} run --rm --pid=host \
        -v ${WORKSPACE}:/workspace \
        -w /workspace \
        -e "CI_BUILD_HOME=/workspace" \
        -e "CI_BUILD_USER=$(id -u -n)" \
        -e "CI_BUILD_UID=$(id -u)" \
        -e "CI_BUILD_GROUP=$(id -g -n)" \
        -e "CI_BUILD_GID=$(id -g)" \
        -e "CI_PYTEST_ADD_OPTIONS=$CI_PYTEST_ADD_OPTIONS" \
        -e "CI_IMAGE_NAME=${DOCKER_IMAGE_NAME}" \
        ${CUDA_ENV}\
        ${CI_DOCKER_EXTRA_PARAMS[@]} \
        ${DOCKER_IMG_SPEC} \
        bash --login docker/with_the_same_user \
        ${COMMAND[@]}

fi


text:
export enum UpdateAction {
    CellUpdate,
    ColumnFill,
    CopyPaste,
    CellDrag
}


text:
title: Installing Weave Scope
menu_order: 20
search_type: Documentation
---

Weave Scope consists of three parts: the probe, the app and the user interface.

 * [Installing on Docker](#docker)
   * [Single-node](#docker-single-node)
   * [Cluster](#docker-cluster)
   * [Cluster with Weave Net](#docker-cluster-net)
   * [Using Docker Compose](#docker-compose)
 * [Installing on Orchestrators](#orchestrators)
   * [Kubernetes](#k8s)
   * [OpenShift](#ose)
   * [Amazon ECS](#ecs)
   * [minimesos](#minimesos)
   * [Mesosphere DC/OS](#dcos)

## Installing on Docker

### Single-node

To install Scope on a single node, run the following commands:

    sudo curl -L git.io/scope -o /usr/local/bin/scope
    sudo chmod a+x /usr/local/bin/scope
    scope launch

This script downloads and runs a recent Scope image from Docker Hub. Scope needs to be installed onto every machine that you want to monitor.

After Scope is installed, open your browser to `http://localhost:4040`.

If you are using docker-machine, you can find the IP by running, `docker-machine ip <VM name>`.

Where,

 * `<VM name>` is the name you gave to your virtual machine with docker-machine.

>**Note:** Scope allows anyone with access to the user interface, control over your containers. As such, the Scope app endpoint (port 4040) should not be made accessible on the Internet.  Also traffic between the app and the probe is insecure and should not traverse the Internet. This means that you should either use the private / internal IP addresses of your nodes when setting it up, or route this traffic through Weave Net.  Put Scope behind a password, by using an application like [Caddy](https://github.com/mholt/caddy) to protect the endpoint and by making port 4040 available to localhost with Caddy proxying it.

### Cluster

This example assumes a local cluster that is not networked with Weave Net, and also has no special hostnames or DNS settings. You will launch Scope with the IP addresses of all of the nodes in the cluster.

Suppose you have the following nodes in a cluster:

    192.168.100.16
    192.168.100.17
    192.168.100.18
    192.168.100.19
    192.168.100.20

Using the above IP addresses, you will manually peer each node with all of the other nodes during Scope launch:

**1. To begin run the following on each node:**

    sudo curl -L git.io/scope -o /usr/local/bin/scope
    sudo chmod a+x /usr/local/bin/scope

 **2. Then on the first node launch scope with:**

    scope launch 192.168.100.18 192.168.100.19 192.168.100.20

 **3. And do the same for all of the other nodes in your cluster:**

    scope launch 192.168.100.17 192.168.100.20 192.168.100.21
    scope launch 192.168.100.17 192.168.100.18 192.168.100.21
    scope launch 192.168.100.17 192.198.100.19 192.168.100.20

### Cluster with Weave Net

If Scope is running on the same machine as the Weave Network, then the probe uses weaveDNS to automatically discover any other apps on the network. Scope does this by registering itself under the address `scope.weave.local`.

Each probe sends its reports to every app registered at this address. If you have weaveDNS set up and running, no further steps are required.

If you don't want to use weaveDNS, then Scope can be instructed to cluster with other Scope instances on the command line. Hostnames and IP addresses are acceptable, both with and without ports, for example:

    scope launch scope1:4030 192.168.0.12 192.168.0.11:4030

Hostnames will be regularly resolved as A records, and each answer used as a target.

### Using Docker Compose

To install Scope on your local Docker machine using Docker Compose, copy the contents of one of the two fragments below into a file `docker-compose.yml` and run

    docker-compose up -d

Scope needs to be installed onto every machine that you want to monitor. Once launched, Scope doesn't require any other configuration and it also doesn't depend on Weave Net.

After it's been launched, open your browser to `http://localhost:4040`.

**Docker Compose Format Version 1:**

    scope:
      image: weaveworks/scope:1.13.2
      net: "host"
      pid: "host"
      privileged: true
      labels:
        - "works.weave.role=system"
      volumes:
        - "/var/run/docker.sock:/var/run/docker.sock:rw"
      command:
        - "--probe.docker=true"

**Docker Compose Format Version 2:**

    version: '2'
    services:
      scope:
        image: weaveworks/scope:1.13.2
        network_mode: "host"
        pid: "host"
        privileged: true
        labels:
          - "works.weave.role=system"
        volumes:
          - "/var/run/docker.sock:/var/run/docker.sock:rw"
        command:
          - "--probe.docker=true"

Version 2 of this YAML file supports networks and volumes as defined by any plugins you might be using. See [Compose File Reference](https://docs.docker.com/compose/compose-file/) for more information.

## Installing on Orchestrators

### Kubernetes

> If your cluster is on GKE, first you need to grant permissions for the
> installation with:
>
>     kubectl create clusterrolebinding "cluster-admin-$(whoami)" --clusterrole=cluster-admin --user="$(gcloud config get-value core/account)"

To install Weave Scope on your Kubernetes cluster, run

    kubectl apply -f https://github.com/weaveworks/scope/releases/download/v1.13.2/k8s-scope.yaml

This downloads a recent Scope image from Dockerhub and launches a probe onto every node as well as a single Scope app. Once launched, Scope doesn't require any other configuration.

Allowable parameters for the launcher URL:

- `v` - Weave Scope version or tag, e.g. `latest` current release is the default
- `k8s-service-type` - Kubernetes service type (for running Scope in Standalone mode), can be either
`LoadBalancer` or `NodePort`, by default this is unspecified (only internal access)

**Open Scope in Your Browser**

    kubectl port-forward -n weave "$(kubectl get -n weave pod --selector=weave-scope-component=app -o jsonpath='{.items..metadata.name}')" 4040

The URL is: http://localhost:4040.

>**Note:** Do not expose the Scope service to the Internet, e.g. by
   changing the type to NodePort or LoadBalancer. Scope allows anyone
   with access to the user interface control over your hosts and
   containers.

### Kubernetes (local clone)

A simple way to get Scope running in a Kubernetes setting is to

1. Spin up a cluster wherever it suits you.
   [Minikube](https://github.com/kubernetes/minikube) is a simple option.

1. Clone the Scope repo:

   ```sh
   git clone https://github.com/weaveworks/scope
   cd scope
   ```

1. Run

   ```sh
   kubectl apply -f examples/k8s
   ```

   to deploy Scope to your cluster.
1. Port-forward to access `weave-scope-app`:

   ```sh
   kubectl port-forward svc/weave-scope-app -n weave 4040:80
   ```

1. Point your browser to <http://127.0.0.1:4040.>

### OpenShift

To install Weave Scope on OpenShift, you first need to login as `system:admin` user with the following command:

    oc login -u system:admin

Next, create a dedicated project for Weave Scope then apply policy changes needed to run Weave Scope:

    oc new-project weave
    # Scope probe pods need full access to Kubernetes API via 'weave-scope' service account
    oc adm policy add-cluster-role-to-user cluster-admin -z weave-scope
    # Scope probe pods also need to run as privileged containers, so grant 'privileged' Security Context Constrains (SCC) for 'weave-scope' service account
    oc adm policy add-scc-to-user privileged -z weave-scope
    # Scope app has an init daemon that has to run as UID 0, so grant 'anyuid' SCC for 'default' service account
    oc adm policy add-scc-to-user anyuid -z default

The installation method for Scope on OpenShift is very similar to the one described [above](#k8s) for Kubernetes, but instead of `kubectl apply ...` you need to use
`oc apply ...` and install it into the namespace of the `weave` project you have just created, and not the `weave` namespace, i.e.:

    oc apply -f 'https://github.com/weaveworks/scope/releases/download/v1.13.2/k8s-scope.yaml'

To access the Scope app from the browser, please refer to Kubernetes instructions [above](#k8s).

### Amazon ECS

There are currently three options for launching Weave Scope in ECS:

* An [Amazon Machine Image (AMI)](/site/ami.md) for each ECS region.
* [A simple way to tailor the AMIs to your needs](https://github.com/weaveworks/integrations/tree/master/aws/ecs#creating-your-own-customized-weave-ecs-ami).

The AWS CloudFormation template is the easiest way to get started with Weave Net and Weave Scope. CloudFormation templates provide developers and systems administrators a simple way to create a collection or a stack of related AWS resources, and it provisions and updates them in an orderly and predictable fashion.

Use this specially created Weaveworks CloudFormation template to create an EC2 instance with all of the resources you need, including Weave Net and Weave Scope.

Before launching the stack:

* [Set up an Amazon Account](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/get-set-up-for-amazon-ec2.html)
* [Create the Key Pairs](http://docs.aws.amazon.com/gettingstarted/latest/wah/getting-started-prereq.html). You will need to reference the name of the key pairs when you create the stack.

The link below will launch a sample app using a Cloudformation template, but you can swap out the IdentiOrca app and use your own app instead.

**Ready to launch a stack?  Click here to launch a stack to AWS:**

[![](images/cloudformation-launch-stack.png)](https://console.aws.amazon.com/cloudformation/home#/stacks/new?templateURL=https:%2F%2Fs3.amazonaws.com%2Fweaveworks-cfn-public%2Fintegrations%2Fecs-identiorca.json)

For step by step instructions on how to configure the stack, see: [Install Weave to AWS with One-Click](https://www.weave.works/docs/cloud/latest/install/ecs-no-kubernetes/)

### minimesos

The [minimesos](https://github.com/ContainerSolutions/minimesos) project enables you to run an Apache Mesos cluster on a single machine, which makes it very easy to develop Mesos frameworks.

By default, Weave Scope is included in the minimesos cluster, and can be accessed at `http://172.17.0.1:4040/`.

If Weave Scope is removed from your minimesos cluster, you can add it back with the following command:

```
minimesos install --marathonFile https://raw.githubusercontent.com/weaveworks/scope/master/examples/mesos/minimesos.json
```

### DC/OS

Scope can be installed as a DC/OS Package through the open Universe.

DC/OS is short for Datacenter Operating System, a distributed operating system using Apache Mesos as its kernel. The easiest way to get start with DC/OS in the public-cloud is to [deploy it on Amazon Web Services (AWS)](https://mesosphere.com/amazon/).

**See Also**

 * [Understanding Weave Scope](/site/how-it-works.md)
 * [Scope's FAQ](/site/faq.md)


text:
/**
 * @description
 * Entry point for all public APIs of the Monad-TS package.
 */
export { AsyncFlow } from "./src/asyncFlow";
export { cast } from "./src/services/cast";
export { clone } from "./src/services/clone";
export { D } from "./src/types/d";
export { debounceTime } from "./src/services/debounceTime";
export { Either } from "./src/either";
export { ErrorM } from "./src/error";
export { equality } from "./src/services/equality";
export { Flow } from "./src/flow";
export { hash } from "./src/services/hash";
export { Identity } from "./src/identity";
export { List } from "./src/list";
export { M } from "./src/interfaces/m";
export { Maybe } from "./src/maybe";
export { MF } from "./src/types/mf";
export { Monad } from "./src/monad";
export { Pr } from "./src/types/pr";
export { State } from "./src/state";
export { wait } from "./src/services/wait";


text:
#include "tensorflow/compiler/jit/increase_dynamism_for_auto_jit_pass.h"
#include <iterator>
#include "absl/algorithm/container.h"
#include "absl/container/inlined_vector.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_replace.h"
#include "absl/types/optional.h"
#include "tensorflow/cc/framework/scope_internal.h"
#include "tensorflow/cc/ops/array_ops.h"
#include "tensorflow/cc/ops/const_op.h"
#include "tensorflow/cc/ops/math_ops.h"
#include "tensorflow/compiler/jit/flags.h"
#include "tensorflow/compiler/jit/xla_cluster_util.h"
#include "tensorflow/compiler/tf2xla/cc/ops/xla_ops.h"
#include "tensorflow/compiler/tf2xla/dump_graph.h"
#include "tensorflow/compiler/xla/status_macros.h"
#include "tensorflow/core/common_runtime/shape_refiner.h"
#include "tensorflow/core/graph/algorithm.h"
#include "tensorflow/core/public/session_options.h"
#include "tensorflow/core/util/device_name_utils.h"

namespace tensorflow {
namespace {

// StatusOrOptional<T> instances hold
//
//  - A non-OK Status to indicate an error that needs to be propagated out of
//    this pass (e.g. the Graph is malformed).
//
//  - A nullopt to indicate the function that created the instance failed to do
//    what it set out to do but this is not actually an error
//    (e.g. TryToGetTensorFromConstOp was passed a non-Const node).
//
//  - A T to indicate a successful operation.
template <class T>
using StatusOrOptional = xla::StatusOr<absl::optional<T>>;

StatusOrOptional<Tensor> TryToGetTensorFromConstOp(Node* n) {
  if (n->type_string() != "Const") {
    return {absl::nullopt};
  }

  const TensorProto* proto = nullptr;
  TF_RETURN_IF_ERROR(GetNodeAttr(n->def(), "value", &proto));
  Tensor tensor(proto->dtype());
  TF_RET_CHECK(tensor.FromProto(*proto));
  return {tensor};
}

struct SliceInputs {
  Output slice_op;
  Output input;
  Output begin;
  Output size;

  // The size of the TF slice operation as a std::vector.  We can always compute
  // this because we only manipulate slices with a Const size.
  std::vector<int64> size_as_vector;
};

std::vector<int64> IntTensorAsVector(const Tensor& t) {
  DCHECK(t.dtype() == DT_INT32 || t.dtype() == DT_INT64);
  std::vector<int64> result;
  result.reserve(t.NumElements());
  for (int i = 0; i < t.NumElements(); i++) {
    int64 element = t.dtype() == DT_INT32
                        ? static_cast<int64>(t.flat<int32>()(i))
                        : t.flat<int64>()(i);
    result.push_back(element);
  }
  return result;
}

// Packages up the inputs to a Slice operation into an instance of
// `SliceInputs`.
StatusOrOptional<SliceInputs> GetSliceInputs(Node* slice) {
  const int kSliceInputIndex = 0;
  const int kSliceBeginIndex = 1;
  const int kSliceSizeIndex = 2;

  const Edge* slice_input_edge;
  TF_RETURN_IF_ERROR(slice->input_edge(kSliceInputIndex, &slice_input_edge));
  const Edge* slice_size_edge;
  TF_RETURN_IF_ERROR(slice->input_edge(kSliceSizeIndex, &slice_size_edge));
  const Edge* slice_begin_edge;
  TF_RETURN_IF_ERROR(slice->input_edge(kSliceBeginIndex, &slice_begin_edge));

  SliceInputs slice_inputs;
  slice_inputs.input =
      Output(slice_input_edge->src(), slice_input_edge->src_output());
  slice_inputs.begin =
      Output(slice_begin_edge->src(), slice_begin_edge->src_output());
  slice_inputs.size =
      Output(slice_size_edge->src(), slice_size_edge->src_output());

  TF_ASSIGN_OR_RETURN(absl::optional<Tensor> tf_slice_size,
                      TryToGetTensorFromConstOp(slice_inputs.size.node()));
  if (!tf_slice_size.has_value()) {
    return {absl::nullopt};
  }

  if (tf_slice_size->dims() != 1) {
    return {absl::nullopt};
  }

  slice_inputs.size_as_vector = IntTensorAsVector(*tf_slice_size);
  return {slice_inputs};
}

// Casts `x` to a DT_INT64 if it isn't one already.
Output MakeInt64(const Scope& host_scope, absl::string_view name,
                 const Output& x) {
  return x.type() == DT_INT64
             ? x
             : ops::Cast(host_scope.WithOpName(name, "_s64"), x, DT_INT64);
}

// Returns `slice_inputs` with the index and size inputs cast to DT_INT64.
SliceInputs MakeSliceIndexAndSizeInt64(const Scope& host_scope,
                                       const SliceInputs& slice_inputs) {
  SliceInputs result;
  result.input = slice_inputs.input;
  result.begin = MakeInt64(host_scope, "begin", slice_inputs.begin);
  result.size = MakeInt64(host_scope, "size", slice_inputs.size);
  result.size_as_vector = slice_inputs.size_as_vector;
  return result;
}

// This class caches emitted constants to avoid creating multiple nodes for the
// same constant value.  This helps make the generated GraphDef more readable.
class ConstantCache {
 public:
  explicit ConstantCache(const Scope& s,
                         const std::vector<const Edge*>& control_deps)
      : scope_(s), control_deps_(control_deps) {}

  Output Get1DHostConstant(int64 constant) {
    auto it = cache_.find(constant);
    if (it == cache_.end()) {
      Output new_const =
          ops::Const(scope_.WithOpName("const_", constant), {constant});
      it = cache_.insert({constant, new_const}).first;
      for (const Edge* e : control_deps_) {
        scope_.graph()->AddControlEdge(e->src(), new_const.node());
      }
    }
    return it->second;
  }

 private:
  Scope scope_;
  std::unordered_map<int, Output> cache_;
  std::vector<const Edge*> control_deps_;
};

// Returns a node computing the size of the Slice op with inputs `slice_inputs`.
Status ComputeSliceSize(const Scope& host_scope,
                        const SliceInputs& slice_inputs,
                        std::vector<const Edge*> control_deps, Output* size) {
  // If slice_size[i] >= 0 then slice_size[i] = slice_size[i].
  //
  // If slice_size[i] == -1 then slice_size[i] = input_size[i] -
  // begin[i].
  //
  // If slice_size[i] < -1 then executing the slice will throw an error, and we
  // don't do anything here.  We've already filtered these cases out in
  // IsRewritableSlice.

  if (absl::c_all_of(slice_inputs.size_as_vector,
                     [](int64 i) { return i >= 0; })) {
    *size = slice_inputs.size;
    return Status::OK();
  }

  Output input_shape =
      ops::Shape(host_scope.WithOpName("input_shape"), slice_inputs.input,
                 ops::Shape::OutType(DT_INT64));

  ConstantCache constant_pool(host_scope, control_deps);

  std::vector<Output> slice_size;
  for (int i = 0; i < slice_inputs.size_as_vector.size(); i++) {
    if (slice_inputs.size_as_vector[i] >= 0) {
      slice_size.push_back(
          constant_pool.Get1DHostConstant(slice_inputs.size_as_vector[i]));
      continue;
    }

    DCHECK_EQ(slice_inputs.size_as_vector[i], -1);

    Output begin_i = ops::Slice(
        host_scope.WithOpName("begin_", i), slice_inputs.begin,
        constant_pool.Get1DHostConstant(i), constant_pool.Get1DHostConstant(1));

    Output input_shape_i = ops::Slice(
        host_scope.WithOpName("input_shape_", i), input_shape,
        constant_pool.Get1DHostConstant(i), constant_pool.Get1DHostConstant(1));

    slice_size.push_back(ops::Sub(host_scope.WithOpName("slice_size_", i),
                                  input_shape_i, begin_i));
    DCHECK_EQ(slice_size.back().type(), DT_INT64);
  }

  // Trivial ConcatV2 nodes (with exactly one input) are disallowed.
  if (slice_size.size() == 1) {
    *size = slice_size[0];
  } else {
    auto concat_axis = ops::Const(host_scope.WithOpName("concat_axis"), 0);
    for (const Edge* e : control_deps) {
      host_scope.graph()->AddControlEdge(e->src(), concat_axis.node());
    }
    *size = ops::Concat(host_scope.WithOpName("slice_size"), slice_size,
                        concat_axis);
  }
  return Status::OK();
}

// Terminology: "static sized" slice is a slice with the
// _XlaCompileTimeConstantInputs attribute set to {2}.  The output shape of
// these slices can be solely determined by their "size" input.
Status ConvertTensorFlowSliceToStaticShapedSlice(
    Graph* g, Node* slice, const SliceInputs& slice_inputs,
    absl::string_view cluster_name, Node** result) {
  string host_name;
  TF_RETURN_IF_ERROR(DeviceNameUtils::DeviceNameToCpuDeviceName(
      slice->assigned_device_name(), &host_name));

  Status status;
  Scope main_scope =
      NewInternalScope(g, &status, /*refiner=*/nullptr)
          .WithXlaCluster(string(cluster_name))
          .NewSubScope(absl::StrCat(slice->name(), "/static_shaped_slice"));
  Scope host_scope = main_scope.WithAssignedDevice(host_name);

  // In the future we may want to be clever here and avoid the extra Cast ops.
  SliceInputs slice_inputs_int64 =
      MakeSliceIndexAndSizeInt64(host_scope, slice_inputs);

  // Create a list of all control dependencies to be copied when possibly
  // replacing nodes related to slice_size.
  Node* old_size;
  std::vector<const Edge*> old_size_ctrl_deps;
  TF_RETURN_IF_ERROR(slice->input_node(2, &old_size));
  absl::c_copy_if(old_size->in_edges(), std::back_inserter(old_size_ctrl_deps),
                  [](const Edge* e) { return e->IsControlEdge(); });

  Output slice_size;
  TF_RETURN_IF_ERROR(ComputeSliceSize(host_scope, slice_inputs_int64,
                                      old_size_ctrl_deps, &slice_size));

  *result =
      ops::Slice(main_scope.WithAssignedDevice(slice->assigned_device_name())
                     .WithOpName("static_shaped_slice"),
                 slice_inputs_int64.input, slice_inputs_int64.begin, slice_size)
          .node();

  TF_RETURN_IF_ERROR(main_scope.status());

  std::vector<string> compile_time_const_inputs;
  compile_time_const_inputs.push_back("size");
  (*result)->AddAttr(kXlaCompileTimeConstantInputsAttr,
                     compile_time_const_inputs);
  return status;
}

void ReplaceTensorFlowSliceWithStaticShapedSlice(Graph* g, Node* slice,
                                                 Node* static_shaped_slice) {
  absl::InlinedVector<const Edge*, 6> edges_to_remove;
  std::vector<const Edge*> slice_out_edges;
  absl::c_copy(slice->out_edges(), std::back_inserter(slice_out_edges));
  for (const Edge* e : slice_out_edges) {
    DCHECK(e->src_output() == 0 || e->src_output() == Graph::kControlSlot);

    int src_output = e->src_output();
    int dst_input = e->dst_input();
    Node* dst = e->dst();
    g->RemoveEdge(e);
    g->AddEdge(static_shaped_slice, src_output, dst, dst_input);
  }

  for (const Edge* e : slice->in_edges()) {
    if (e->IsControlEdge()) {
      g->AddControlEdge(e->src(), static_shaped_slice);
    }
  }

  g->RemoveNode(slice);
}

Status RewriteSlice(Graph* g, Node* slice, const SliceInputs& slice_inputs,
                    absl::string_view cluster_name) {
  VLOG(3) << "Rewriting slice " << slice->name()
          << " to a \"static shaped\" Slice";
  Node* static_shaped_slice;
  TF_RETURN_IF_ERROR(ConvertTensorFlowSliceToStaticShapedSlice(
      g, slice, slice_inputs, cluster_name, &static_shaped_slice));
  ReplaceTensorFlowSliceWithStaticShapedSlice(g, slice, static_shaped_slice);
  return Status::OK();
}

// Return true if `n` is a slice we should rewrite to have a static shape
// (i.e. have the output shape only depend on the "size" input).
xla::StatusOr<bool> ShouldRewriteSlice(Node* n) {
  if (n->type_string() != "Slice") {
    return false;
  }

  if (!GetXlaClusterForNode(*n).has_value()) {
    // There is no need to change slice ops outside XLA clusters.
    return false;
  }

  TF_ASSIGN_OR_RETURN(absl::optional<SliceInputs> slice_inputs,
                      GetSliceInputs(n));
  if (!slice_inputs.has_value()) {
    return false;
  }

  // If slice_size[i] < -1 for any i then executing the slice will throw an
  // error, and we don't do anything here.
  bool slice_size_has_error = absl::c_all_of(
      slice_inputs->size_as_vector, [](int64 size_i) { return size_i >= -1; });
  if (!slice_size_has_error) {
    return false;
  }

  // No point in rewriting slices that have both size and begin as constants.
  return !slice_inputs->begin.node()->IsConstant();
}

Status FindAndRewriteSlices(Graph* g, bool* changed) {
  std::vector<Node*> slices_to_rewrite;
  for (Node* n : g->nodes()) {
    TF_ASSIGN_OR_RETURN(bool is_rewritable, ShouldRewriteSlice(n));
    if (is_rewritable) {
      slices_to_rewrite.push_back(n);
    }
  }

  for (Node* n : slices_to_rewrite) {
    TF_ASSIGN_OR_RETURN(absl::optional<SliceInputs> slice_inputs,
                        GetSliceInputs(n));
    TF_RET_CHECK(slice_inputs.has_value());
    TF_RETURN_IF_ERROR(
        RewriteSlice(g, n, *slice_inputs, *GetXlaClusterForNode(*n)));
  }

  if (!slices_to_rewrite.empty()) {
    // We've added constants to the graph; hook them up to _SOURCE.
    FixupSourceAndSinkEdges(g);
  }

  *changed = !slices_to_rewrite.empty();

  return Status::OK();
}
}  // namespace

Status IncreaseDynamismForAutoJitPass::Run(
    const GraphOptimizationPassOptions& options) {
  MarkForCompilationPassFlags* flags = GetMarkForCompilationPassFlags();
  if (flags->tf_xla_clustering_debug) {
    dump_graph::DumpGraphToFile("before_increase_dynamism_for_auto_jit_pass",
                                **options.graph, options.flib_def);
  }

  bool changed;
  TF_RETURN_IF_ERROR(FindAndRewriteSlices(options.graph->get(), &changed));
  if (changed && flags->tf_xla_clustering_debug) {
    dump_graph::DumpGraphToFile("increase_dynamism_for_auto_jit_pass",
                                **options.graph, options.flib_def);
  }

  return Status::OK();
}

}  // namespace tensorflow


text:
#ifndef TENSORFLOW_COMPILER_XLA_SERVICE_COMPUTATION_TRACKER_H_
#define TENSORFLOW_COMPILER_XLA_SERVICE_COMPUTATION_TRACKER_H_

#include <list>
#include <map>
#include <memory>
#include <set>
#include <string>

#include "tensorflow/compiler/xla/service/hlo_module.h"
#include "tensorflow/compiler/xla/service/session.pb.h"
#include "tensorflow/compiler/xla/service/user_computation.h"
#include "tensorflow/compiler/xla/service/versioned_computation_handle.h"
#include "tensorflow/compiler/xla/statusor.h"
#include "tensorflow/compiler/xla/types.h"
#include "tensorflow/compiler/xla/xla_data.pb.h"
#include "tensorflow/core/platform/macros.h"
#include "tensorflow/core/platform/mutex.h"
#include "tensorflow/core/platform/thread_annotations.h"
#include "tensorflow/core/platform/types.h"

namespace xla {

// Tracks computations for the XLA service; computations can be registered
// with a UserComputation instance and can be resolved from a handle for later
// use.
//
// This class is also capable of serializing/deserializing computations that it
// tracks (and to serialize properly you need to serialize all referred-to
// computations as well).
class ComputationTracker {
 public:
  ComputationTracker();

  // Creates a new UserComputation object and returns the corresponding
  // ComputationHandle for it.
  //
  // Precondition: user_computation is not already present in the map.
  ComputationHandle NewComputation(const string& computation_name);

  // Restores session data for a computation that has been serialized, and
  // allocates a new computation handle for it.
  StatusOr<ComputationHandle> LoadSessionModule(
      const SessionModule& session_module);

  // Snapshots a computation (referenced by the provided handle) at its latest
  // version, returning a module where it is the entry, and any referred-to
  // computations are entrained as "embedded" (non-entry) computations.
  StatusOr<std::unique_ptr<SessionModule>> SnapshotComputation(
      const ComputationHandle& computation);

  // Resolves a ComputationHandle to a UserComputation that is present in the
  // map.
  StatusOr<UserComputation*> Resolve(
      const ComputationHandle& computation) const;

  // Builds an HLO module using the specified computation as the entry. The
  // module will include the entry computation as well as all computations which
  // are called directly or indirectly from the entry computation via operations
  // like "map". If include_unreachable_instructions is true, then instructions
  // which are not reachable from the root are lowered into HloInstructions
  // including unreachable parameters. This ensures the entry HloComputation has
  // the same program shape (ProgramShape) as the entry UserComputation.
  StatusOr<std::unique_ptr<HloModule>> BuildHloModule(
      const VersionedComputationHandle& entry_handle,
      bool include_unreachable_instructions = true) const;

  string ToString() const;

 private:
  // Bumps the next_computation_ number and returns the allocated number wrapped
  // in a ComputationHandle.
  ComputationHandle AllocateHandle()
      EXCLUSIVE_LOCKS_REQUIRED(computation_mutex_);

  // Loads a session computation into a UserComputation, registers it, and
  // returns the computation handle of the registered computation. If old_to_new
  // is provided, it is used for remapping references to computations present in
  // session_computation.
  //
  // old_to_new will be updated with the mapping from session_computation's old
  // handle to the returned handle value, and may not be null.
  StatusOr<ComputationHandle> LoadSessionComputation(
      const SessionComputation& session_computation,
      std::map<int64, ComputationHandle>* old_to_new)
      EXCLUSIVE_LOCKS_REQUIRED(computation_mutex_);

  // Internal implementation of Resolve method which requires, but does not
  // acquire the mutex.
  StatusOr<UserComputation*> ResolveInternal(
      const ComputationHandle& computation) const
      EXCLUSIVE_LOCKS_REQUIRED(computation_mutex_);

  // Builds a post order sort of a computation ("entry") and all of its embedded
  // computations including all transitively embedded computations. An embedded
  // computation (the callee) will always appear in the sort before the
  // computation which calls the embedded computation (the caller). Necessarily,
  // the entry computation is the last element in the sort. visited and
  // post_order should be empty when calling. post_order contains the post order
  // sort when the function return.
  void ComputeComputationPostOrder(
      const VersionedComputationHandle& versioned_handle,
      std::set<VersionedComputationHandle>* visited,
      std::list<VersionedComputationHandle>* post_order) const
      EXCLUSIVE_LOCKS_REQUIRED(computation_mutex_);

  string ToStringInternal() const EXCLUSIVE_LOCKS_REQUIRED(computation_mutex_);

  // Guards the computation mapping. Marked mutable so that the Resolve method
  // can remain const; Resolve does't really modify the tracker in any way, but
  // it has to lock the mutex for safety.
  mutable tensorflow::mutex computation_mutex_;

  // The next sequence number to assign to a computation, guarded by the same
  // mutex as the mapping as they'll be mutated at the same time.
  int64 next_computation_ GUARDED_BY(computation_mutex_);

  // Mapping from ComputationHandle value to the corresponding registered
  // UserComputation object.
  std::map<int64, std::unique_ptr<UserComputation>> opaque_to_computation_
      GUARDED_BY(computation_mutex_);

  TF_DISALLOW_COPY_AND_ASSIGN(ComputationTracker);
};

}  // namespace xla

#endif  // TENSORFLOW_COMPILER_XLA_SERVICE_COMPUTATION_TRACKER_H_


text:
package happycows.attributes;

import java.awt.Point;

import jalse.attributes.AttributeEvent;
import jalse.attributes.AttributeListener;

public class Moo implements AttributeListener<Point> {

    @Override
    public void attributeChanged(final AttributeEvent<Point> event) {
	// Get the new position
	final Point p = event.getValue();
	System.out.println(String.format("Cow mooing [%d:%d]", p.x, p.y));
    }
}


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Document</title>
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link href="css/bootstrap.min.css" rel="stylesheet">

                    <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1"
                        aria-expanded="false">
        Toggle navigation

      </button>
                     Waynepen

                    <form class="navbar-form navbar-left" role="search">

                            <input type="text" class="form-control" placeholder="Search">

                        <button type="submit" class="btn btn-default">Submit</button>
                    </form>

Link

                            Sweets

Chocolate

Snowy Lemon cake

 Macaron

more

Hello, Sweets
                <3

EAT, ART, LOVE

Me

 about life

                 me
                 chocolate
                 lemon cake
                 macaron


text:
class AnswerSet < ActiveRecord::Base
  belongs_to :survey
  belongs_to :primary_affiliation, :class_name => 'Affiliation'
  has_and_belongs_to_many :affiliations
  has_many :multiple_choice_answers, :dependent => :destroy, :validate => true
  accepts_nested_attributes_for :multiple_choice_answers, :reject_if => lambda { |a| a[:multiple_choice_option_id].blank? }, :allow_destroy => true
  validates :survey_id, :primary_affiliation_id, :presence => true
  validate :questions_answered

  private

  def questions_answered
    answer_hash = Hash.new
    self.multiple_choice_answers.each do |mca|
      #logger.debug "answer_hash.build: #{mca.inspect}"
      answer_hash[mca.multiple_choice_question_id] = true
    end
    #logger.debug "answer_hash: #{answer_hash.inspect}"
    self.survey.multiple_choice_questions.each do |mcq|
      #logger.debug "answer_hash.check: #{mcq.id.inspect}"
      if answer_hash.has_key?(mcq.id)
        answer_hash.delete(mcq.id)
      else
        if self.survey.all_answers || mcq.required
          errors.add(:multiple_choice_answer_attributes, 'You must answer the question (' + mcq.title + ')')
        end
      end
    end
    errors.add(:multiple_choice_answer, 'You answered an non-existant question!') unless answer_hash.empty?
  end
end


text:
module HealthSeven::V2_6
class Vnd < ::HealthSeven::Segment
  # Set Id - VND
  attribute :set_id_vnd, Si, position: "VND.1", require: true
  # Vendor Identifier
  attribute :vendor_identifier, Ei, position: "VND.2", require: true
  # Vendor Name
  attribute :vendor_name, St, position: "VND.3"
  # Vendor Catalog Number
  attribute :vendor_catalog_number, Ei, position: "VND.4"
  # Primary Vendor Indicator
  attribute :primary_vendor_indicator, Cne, position: "VND.5"
end
end