text:
'use strict'

const _ = require('lodash')
//const Eraro = require('eraro')
const Jsonic = require('jsonic')
// const Optioner = require('optioner')
// const Joi = Optioner.Joi

/*
const optioner = Optioner({
  model: Joi.alternatives().try(Joi.string(), Joi.func()),
  debug: {
    client_updates: false
  }
})
*/
/*
var error = Eraro({
  package: 'seneca',
  msgmap: {
    'no-target': 'No targets have been registered for message <%=msg%>',
    'no-current-target': 'No targets are currently active for message <%=msg%>'
  }
})
*/

module.exports = balance_client
balance_client.defaults = {
  debug: {
    client_updates: false
  }
}
balance_client.errors = {
  'no-target': 'No targets have been registered for message <%=msg%>',
  'no-current-target': 'No targets are currently active for message <%=msg%>'
}

// Not as bad as it looks - seneca.id is used at top level to isolate instances.
// Need this here so that preload can reference it.
const global_target_map = {}

var global_options = { debug: {} }

balance_client.preload = function() {
  var seneca = this

  seneca.options({
    transport: {
      balance: {
        makehandle: function(config) {
          global_target_map[seneca.id] = global_target_map[seneca.id] || {
            id: seneca.id
          }
          var instance_map = global_target_map[seneca.id]

          instance_map[config.pg] = instance_map[config.pg] || {
            pg: config.pg,
            id: Math.random()
          }
          var target_map = instance_map[config.pg]

          target_map.pg = config.pg

          //return function(pat, action) {
          return function(actdef) {
            var pat = actdef.client_pattern || actdef.pattern
            add_target(seneca, target_map, config, pat, actdef.func)
          }
        }
      }
    }
  })
}

function balance_client(options) {
  var seneca = this
  var tu = seneca.export('transport/utils')
  var modelMap = {
    observe: observeModel,
    consume: consumeModel,

    // legacy
    publish: observeModel,
    actor: consumeModel
  }

  // options = optioner.check(options)

  // hack to make add_target debug logging work
  // to be fixed when seneca plugin handling is rewritten to not need preload
  Object.assign(global_options, options)

  seneca.add(
    {
      role: 'transport',
      hook: 'client',
      type: 'balance'
    },
    hook_client
  )

  seneca.add(
    {
      role: 'transport',
      type: 'balance',
      add: 'client'
    },
    add_client
  )

  seneca.add(
    {
      role: 'transport',
      type: 'balance',
      remove: 'client'
    },
    remove_client
  )

  seneca.add(
    {
      role: 'transport',
      type: 'balance',
      get: 'target-map'
    },
    get_client_map
  )

  function remove_target(target_map, pat, config) {
    var action_id = config.id || seneca.util.pattern(config)
    var patkey = make_patkey(seneca, pat)
    var targetstate = target_map[patkey]
    var found = false

    targetstate = targetstate || { index: 0, targets: [] }
    target_map[patkey] = targetstate

    for (var i = 0; i < targetstate.targets.length; i++) {
      if (action_id === targetstate.targets[i].id) {
        break
      }
    }

    if (i < targetstate.targets.length) {
      targetstate.targets.splice(i, 1)
      targetstate.index = 0
      found = true
    }

    if (options.debug.client_updates) {
      seneca.log.info('remove', patkey, action_id, found)
    }
  }

  function add_client(msg, done) {
    msg.config = msg.config || {}

    if (!msg.config.pg) {
      msg.config.pg = this.util.pincanon(msg.config.pin || msg.config.pins)
    }

    this.client(msg.config)
    done()
  }

  function remove_client(msg, done) {
    var seneca = this

    msg.config = msg.config || {}

    if (!msg.config.pg) {
      msg.config.pg = this.util.pincanon(msg.config.pin || msg.config.pins)
    }

    var instance_map = global_target_map[seneca.id] || {}
    var target_map = instance_map[msg.config.pg] || {}

    var pins = msg.config.pin ? [msg.config.pin] : msg.config.pins

    _.each(pins, function(pin) {
      remove_target(target_map, pin, msg.config)
    })

    done()
  }

  function get_client_map(msg, done) {
    var seneca = this
    var instance_map = global_target_map[seneca.id] || {}
    done(null, null == msg.pg ? instance_map : instance_map[msg.pg])
  }

  function hook_client(msg, clientdone) {
    var seneca = this.root.delegate()

    // console.log('BC', msg)

    var type = msg.type
    var client_options = seneca.util.clean(_.extend({}, options[type], msg))

    var pg = this.util.pincanon(client_options.pin || client_options.pins)

    var instance_map = global_target_map[seneca.id] || {}
    var target_map = instance_map[pg] || {}

    var model = client_options.model || consumeModel
    model = _.isFunction(model) ? model : modelMap[model] || consumeModel

    // legacy transport
    if (tu.make_client) {
      var make_send = function(spec, topic, send_done) {
        seneca.log.debug(
          'client',
          'send',
          topic + '_res',
          client_options,
          seneca
        )

        send_done(null, function(msg, done, meta) {
          var patkey = (meta || msg.meta$).pattern
          var targetstate = target_map[patkey]

          if (targetstate) {
            model(this, msg, targetstate, done, meta)
            return
          } else return done(seneca.error('no-target', { msg: msg }))
        })
      }

      tu.make_client(make_send, client_options, clientdone)
    } else {
      // console.log('BC A ', pg)

      var send_msg = function(msg, reply, meta) {
        msg = tu.externalize_msg(seneca, msg)

        var msg_meta = meta || msg.meta$

        // console.log('BCM', this.util.clean(msg), pg, msg_meta.client_pattern, msg_meta.pattern)
        // console.dir(target_map,{depth:null})

        var patkey = msg_meta.client_pattern || msg_meta.pattern
        var targetstate = target_map[patkey]

        if (targetstate) {
          model(this, msg, targetstate, reply, meta)
          return
        } else return reply(seneca.error('no-target', { msg: msg }))
      }

      return clientdone({
        config: msg,
        send: send_msg
      })
    }

    seneca.add('role:seneca,cmd:close', function(close_msg, done) {
      var closer = this
      closer.prior(close_msg, done)
    })
  }

  function observeModel(seneca, msg, targetstate, done, meta) {
    if (0 === targetstate.targets.length) {
      return done(seneca.error('no-current-target', { msg: msg }))
    }

    var first = true
    for (var i = 0; i < targetstate.targets.length; i++) {
      var target = targetstate.targets[i]
      target.action.call(
        seneca,
        msg,
        function() {
          if (first) {
            done.apply(seneca, arguments)
            first = false
          }
        },
        meta
      )
    }
  }

  function consumeModel(seneca, msg, targetstate, done, meta) {
    var targets = targetstate.targets
    var index = targetstate.index

    if (!targets[index]) {
      index = targetstate.index = 0
    }

    if (!targets[index]) {
      return done(seneca.error('no-current-target', { msg: msg }))
    }

    targets[index].action.call(seneca, msg, done, meta)
    targetstate.index = (index + 1) % targets.length
  }
}

function add_target(seneca, target_map, config, pat, action) {
  var patkey = make_patkey(seneca, pat)
  var targetstate = target_map[patkey]
  var add = true

  targetstate = targetstate || { index: 0, targets: [] }
  target_map[patkey] = targetstate

  // don't add duplicates
  for (var i = 0; i < targetstate.targets.length; ++i) {
    if (action.id === targetstate.targets[i].id) {
      add = false
      break
    }
  }

  if (add) {
    targetstate.targets.push({
      action: action,
      id: action.id,
      config: config
    })
  }

  if (global_options.debug.client_updates) {
    seneca.log.info('add', patkey, action.id, add)
  }
}

function make_patkey(seneca, pat) {
  if (_.isString(pat)) {
    pat = Jsonic(pat)
  }

  var keys = _.keys(seneca.util.clean(pat)).sort()
  var cleanpat = {}

  _.each(keys, function(k) {
    cleanpat[k] = pat[k]
  })

  var patkey = seneca.util.pattern(cleanpat)
  return patkey
}


text:
module Stupidedi
  module Versions
    module FunctionalGroups
      module FiftyTen
        module SegmentDefs

          s = Schema
          e = ElementDefs
          r = ElementReqs

          BGN = s::SegmentDef.build(:BGN, "Beginning of Hierarchical Transaction",
            "To define the business hierarchical structure of the transaction set and identify the business application purpose and reference data, i.e., number, date, and time",
            e::E353.simple_use(r::Mandatory,  s::RepeatCount.bounded(1)),
            e::E127.simple_use(r::Mandatory,  s::RepeatCount.bounded(1)),
            e::E353.simple_use(r::Mandatory,  s::RepeatCount.bounded(1)),
            e::E337.simple_use(r::Optional,   s::RepeatCount.bounded(1)),
            e::E127.simple_use(r::Optional,   s::RepeatCount.bounded(1)),
            e::E640.simple_use(r::Optional,   s::RepeatCount.bounded(1)),
            e::E306.simple_use(r::Optional,   s::RepeatCount.bounded(1)))
        end
      end
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
#sidebar {
    display: none;
}
#body {
    margin-left: 0;
}
#body #navigation {
    display: none;
}
html,
body #body{
    font-size: 8.9pt;
}
body {
    background-color: white;
}
pre code {
    font-size: 8.3pt;
}
code.copy-to-clipboard-code {
    border-bottom-right-radius: 2px;
    border-top-right-radius: 2px;
    border-right-width: 1px;
}
pre {
    border: 1px solid #ccc;
}
#body #topbar{
    background-color: #fff; /* avoid background bleeding*/
    border-bottom: 1px solid #ddd;
    border-radius: 0;
    padding-left: 0; /* for print, we want to align with the footer to ease the layout */
    color: #777;
}
.navigation,
#top-github-link {
    /* we don't need this while printing */
    display: none;
}
#body #breadcrumbs {
    width: 100%;
}
#body #breadcrumbs .links {
    overflow-x: hidden;
}
.copy-to-clipboard-button {
    display: none;
}

#body h1, #body h2, #body h3, #body h4, #body h5, #body h6 {
    /* better contrast for colored elements */
    color: black;
}
#body th, #body td,
#body code, #body strong, #body b,
#body li, #body dd, #body dt,
#body p,
#body .anchor,
#body a {
    /* better contrast for colored elements */
    color: black;
}
#body pre,
#body code {
    background-color: white;
    border-color: #ddd;
}

hr{
    border-bottom: 1px solid #ddd;
}
#body-inner.chapter h1 {
    border-bottom: 1px solid #ddd;
}
.footline {
    /* in print mode show footer line to signal reader the end of document */
    border-top: 1px solid #ddd;
    color: #777;
    margin-top: 1.5rem;
    padding-top: .75rem;
}
#body #body-inner a {
    /* in print we want to distinguish links in our content from
    normal text even if printed black/white;
    don't use a.highlight in selector to also get links that are
    put as HTML into markdown */
    text-decoration-line: underline;
}
#toc-menu {
    /* we don't need this while printing */
    display: none;
}
#sidebar-toggle-span {
    /* we don't need this while printing */
    display: none;
}
#breadcrumbs .links {
    display: inline;
}
#topbar{
    /* the header is sticky which is not suitable for print; */
    position: inherit; /* IE11 doesn't know "initial" here */
}
#body .tab-nav-button:not(.active) {
    opacity: .5;
}
#head-tags {
    display: none;
}
mark {
    background: inherit;
    color: inherit;
}
.mermaid > svg:hover {
    border-color: transparent;
}
div.box {
    border: 1px solid #ddd;
}
div.box > .box-content {
    background-color: white;
}
.btn-default,
#body .tab-nav-button {
    color: black !important;
}
#body .tab-nav-button.active {
    background-color: white !important;
    border-bottom-color: white !important;
    color: black;
}
#body .tab-nav-button:not(.active) {
    opacity: 1;
}


text:
import os
import logging

PROJECT_PATH = os.path.abspath(os.path.split(__file__)[0])
LOG_LEVEL = logging.DEBUG

DEBUG = True
TEMPLATE_DEBUG = DEBUG

ADMINS = (
    # ('Your Name', 'your_email@example.com'),
)

MANAGERS = ADMINS

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': 'snh_schema',                 # Or path to database file if using sqlite3.
        'USER': 'snh',                        # Not used with sqlite3.
        'PASSWORD': '123123',                 # Not used with sqlite3.
        'HOST': '127.0.0.1',                  # Set to empty string for localhost. Not used with sqlite3.
        'PORT': '',                           # Set to empty string for default. Not used with sqlite3.
    }
}

FACEBOOK_APPLICATION_ID = 'xxx'
FACEBOOK_APPLICATION_SECRET_KEY = 'xxx'
FACEBOOK_APPLICATION_NAMESPACE = 'xxx'
FACEBOOK_APPLICATION_ID = 'xxxxx'
FACEBOOK_APPLICATION_SECRET_KEY = 'xxxx'
FACEBOOK_APPLICATION_NAMESPACE = 'xxxx'
FACEBOOK_APPLICATION_INITIAL_PERMISSIONS = [
                                            'user_about_me','friends_about_me',
                                            'user_activities','friends_activities',
                                            'user_birthday','friends_birthday',
                                            'user_checkins','friends_checkins',
                                            'user_education_history','friends_education_history',
                                            'user_events','friends_events',
                                            'user_groups','friends_groups',
                                            'user_hometown','friends_hometown',
                                            'user_interests','friends_interests',
                                            'user_likes','friends_likes',
                                            'user_location','friends_location',
                                            'user_notes','friends_notes',
                                            #'user_photo_video_tags','friends_photo_video_tags',
                                            'user_photos','friends_photos',
                                            'user_questions','friends_questions',
                                            'user_relationships','friends_relationships',
                                            'user_relationship_details','friends_relationship_details',
                                            'user_religion_politics','friends_religion_politics',
                                            'user_status','friends_status',
                                            'user_videos','friends_videos',
                                            'user_website','friends_website',
                                            'user_work_history','friends_work_history',
                                            'email',
                                            'read_friendlists',
                                            'read_insights',
                                            'read_mailbox',
                                            'read_requests',
                                            'read_stream',
                                            'xmpp_login',
                                            'ads_management',
                                            'create_event',
                                            'manage_friendlists',
                                            'manage_notifications',
                                            #'offline_access',
                                            'user_online_presence',
                                            'friends_online_presence',
                                            'publish_checkins',
                                            'publish_stream',
                                            'rsvp_event',
                                            #'publish_actions',
                                            ]

#FACEBOOK_APPLICATION_INITIAL_PERMISSIONS = ['read_stream', 'publish_stream','friends_online_presence','friends_status','read_friendlists']

# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# On Unix systems, a value of None will cause Django to use the same
# timezone as the operating system.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'America/Montreal'

# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'fr-ca'

SITE_ID = 1

# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True

# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale
USE_L10N = True

# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/media/"
MEDIA_ROOT = os.path.join(PROJECT_PATH, "upload/")

# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = ''

# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = os.path.join(PROJECT_PATH, "public/")

# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'

# URL prefix for admin static files -- CSS, JavaScript and images.
# Make sure to use a trailing slash.
# Examples: "http://foo.com/static/admin/", "/static/admin/".
ADMIN_MEDIA_PREFIX = STATIC_URL + "grappelli/"

# Additional locations of static files
STATICFILES_DIRS = (
    # Put strings here, like "/home/html/static" or "C:/www/django/static".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
    os.path.join(PROJECT_PATH, "static/"),
)

# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
#    'django.contrib.staticfiles.finders.DefaultStorageFinder',
)

# Make this unique, and don't share it with anybody.
SECRET_KEY = 'b6%$tv8f@y3s8*tm!b0$(a4u^#j_#itv9d7g7%wx-@0cdt9_*l'

# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.Loader',
    'django.template.loaders.app_directories.Loader',
#     'django.template.loaders.eggs.Loader',
)

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'fandjango.middleware.FacebookMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',

)

ROOT_URLCONF = 'urls'

TEMPLATE_DIRS = (
    # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
    os.path.join(PROJECT_PATH, "templates/"),
)

GRAPPELLI_ADMIN_TITLE = "SNH Admin | Consultation | Test Facebook token"

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'fandjango',
    'snh',
    'grappelli.dashboard',
    'grappelli',
    # Uncomment the next line to enable the admin:
    'django.contrib.admin',
    # Uncomment the next line to enable admin documentation:
    # 'django.contrib.admindocs',
)

GRAPPELLI_ADMIN_TITLE = "SNH Admin | Consultation | Test Facebook token"

LOGIN_REDIRECT_URL = "/"

TEMPLATE_CONTEXT_PROCESSORS = (
    "django.contrib.auth.context_processors.auth",
    "django.core.context_processors.request",
    "django.core.context_processors.i18n",
    'django.contrib.messages.context_processors.messages',
)

GRAPPELLI_INDEX_DASHBOARD = {
    'django.contrib.admin.site': 'snh.dashboard.CustomIndexDashboard',
}

# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'mail_admins': {
            'level': 'ERROR',
            'class': 'django.utils.log.AdminEmailHandler'
        }
    },
    'loggers': {
        'django.request': {
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': True,
        },
    }
}


text:
/**
 * @author Brandon Wood
 */
function MentorWindow() {
    // If you don't want margins around the Translucent or Web View you can set the gutter to zero.
    var gutter = 0;
    // If you don't want a navBar with the corresponding back button you can set this to false.
    // If so, this requires you to have a back button in your HTML on iOS. Android uses standard hardware back button.
    var titleBarOn = false;
    var osname = Ti.Platform.osname;

    if (osname == 'iphone' || osname == 'ipad') {
        titleBarOn = true;
    };

    var self = Ti.UI.createWindow({
        title: 'MyInfo',
        // If no image desired, you can remove this line and set the backgroundColor instead.
        backgroundColor : '#FFFFFF',
        fullscreen:false,
        modal : false,
        exitOnClose : false  // Android only
    });

    //Create a WebView, this will host the HTML
    var mentorWebView = Ti.UI.createWebView({
        left : gutter,
        top : gutter,
        right : gutter,
        bottom : gutter,
        // // This allows the translucent view and the background to shine through. You could set this to a standard RGB color and change the opacity if desired.
        // backgroundColor : translucentViewOn ? 'transparent' : backgroundColor,
        // opacity : animationsOn ? 0 : 1,
        disableBounce: true,
        willHandleTouches: false,
        enableZoomControls : false, // Android only
        // Default assumes that all HTML is in the HTML folder and the first file is index.html, you can change the next line to suit your HTML.
        url : '/HTML/myMentor.html'
    });

    function addEventListeners() {
         Ti.App.addEventListener('mentor:getMentorInfo', function() {
            var mentorObject = Ti.App.Properties.getObject('mentorObject');
            var file = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, mentorObject.FACULTY_USERNAME + '.jpg');

            Ti.App.fireEvent('mentor:sendMentorInfo', {
                username: Ti.App.Properties.getString('username'),
                mentorObject: mentorObject,
                mentorPicNativePath: file.nativePath}
            );
        });

        //listens for mentor request
        Ti.App.addEventListener('myMentor:loadMentorInfo', function() {
            loadMentorInfo();
        });

        function loadMentorInfo() {
            var mentorObject;
            mentorObject = Ti.App.Properties.getObject('mentorInfo');
            Ti.App.fireEvent('myMentor:sendMentor', {mentor: mentorObject});
        }

        Ti.App.addEventListener('mentor:closeWindow', function() {
            if( osname == 'iphone' || osname == 'ipad') {
                nav.close(mentorWindow, {animated: true});
                // mentorWebView.setHtml("");
                // mentorWebView.setHtml('hello');
            } else {
                mentorWindow.close();
            }
        });

        Ti.App.addEventListener('login:deleteMentorPic', function() {
            Ti.API.info('login:deleteMentorPic heard');
            Ti.App.fireEvent('mentor:deleteMentorPic');

        });
    }

    addEventListeners();
    self.add(mentorWebView);
    return self;
}

module.exports = MentorWindow;


text:
package sh.isaac.model.semantic.version.brittle;

import sh.isaac.api.Get;
import sh.isaac.api.chronicle.Version;
import sh.isaac.api.component.semantic.SemanticChronology;
import sh.isaac.api.component.semantic.version.brittle.Nid1_Nid2_Version;
import sh.isaac.api.externalizable.ByteArrayDataBuffer;
import sh.isaac.model.semantic.version.AbstractVersionImpl;

/**
 *
 * @author kec
 */
public class Nid1_Nid2_VersionImpl
        extends AbstractVersionImpl
         implements Nid1_Nid2_Version {
   int nid1 = Integer.MAX_VALUE;
   int nid2 = Integer.MAX_VALUE;

   @Override
   public StringBuilder toString(StringBuilder builder) {
      builder.append(" ")
              .append("{Nid1: ").append(Get.getTextForComponent(nid1))
              .append(", Nid2: ").append(Get.getTextForComponent(nid2))
              .append(Get.stampService()
                      .describeStampSequence(this.getStampSequence())).append("}");
      return builder;
   }

   public Nid1_Nid2_VersionImpl(SemanticChronology container, int stampSequence) {
      super(container, stampSequence);
   }

   public Nid1_Nid2_VersionImpl(SemanticChronology container,
           int stampSequence, ByteArrayDataBuffer data) {
      super(container, stampSequence);
      this.nid1 = data.getNid();
      this.nid2 = data.getNid();
   }

   private Nid1_Nid2_VersionImpl(Nid1_Nid2_VersionImpl old,
                                int stampSequence) {
      super(old.getChronology(), stampSequence);
      this.setNid1(old.nid1);
      this.setNid2(old.nid2);
   }

   /**
    * Write version data.
    *
    * @param data the data
    */
   @Override
   public void writeVersionData(ByteArrayDataBuffer data) {
      super.writeVersionData(data);
      data.putNid(this.nid1);
      data.putNid(this.nid2);
   }

   @Override
   @SuppressWarnings("unchecked")
   public <V extends Version> V makeAnalog(int stampSequence) {
      final Nid1_Nid2_VersionImpl newVersion = new Nid1_Nid2_VersionImpl(this, stampSequence);
      getChronology().addVersion(newVersion);
      return (V) newVersion;
   }

   @Override
   protected boolean deepEquals3(AbstractVersionImpl other) {
      return editDistance3(other, 0) == 0;
   }

   @Override
   protected int editDistance3(AbstractVersionImpl other, int editDistance) {
      Nid1_Nid2_VersionImpl another = (Nid1_Nid2_VersionImpl) other;
      if (this.nid1 != another.nid1) {
         editDistance++;
      }
      if (this.nid2 != another.nid2) {
         editDistance++;
      }

      return editDistance;
   }

   @Override
   public int getNid1() {
      return nid1;
   }

   @Override
   public void setNid1(int nid1) {
      this.nid1 = nid1;
   }

   @Override
   public int getNid2() {
      return nid2;
   }

   @Override
   public void setNid2(int nid2) {
      this.nid2 = nid2;
   }
}


text:
from rama.dispatch import Dispatcher
from rama.keysymdef import keysyms
from rama.keysyms import Keysyms, keysym_to_str, keysym_to_char
from xcb.xproto import ModMask, GrabMode

MASKS = [ModMask.Shift,
         ModMask.Lock,
         ModMask.Control,
         ModMask._1,
         ModMask._2,
         ModMask._3,
         ModMask._4,
         ModMask._5]

MODSTRS = {'C': ModMask.Control,
           'S': ModMask.Shift,
           'M': ModMask._1,
           's': ModMask._5}

class KeyParseError(Exception):
    pass

def parse(keystr):
    """
    Parse a keystring.
    Returns a (modmask, keycode) tuple.
    """
    modmask = 0
    keys = keystr.split('-')
    for mod in keys[:-1]:
        if mod not in MODSTRS:
            raise KeyParseError()
        modmask = modmask | MODSTRS[mod]
    key = keys[-1:][0]
    if key not in keysyms:
        raise KeyParseError()
    return (modmask, keysyms[key])

def get_numlock_mask(conn):
    syms = Keysyms(conn)
    numlock = syms.get_keycode(keysyms['Num_Lock'])
    modmap = conn.core.GetModifierMapping().reply()
    for i in range(8):
        for j in range(modmap.keycodes_per_modifier):
            keycode = modmap.keycodes[i * modmap.keycodes_per_modifier + j]
            if keycode == numlock:
                return MASKS[i]
    return 0

class Keymap(object):
    bindings = {}

    def __init__(self, conn, keys=None):
        if keys is None:
            keys = {}
        self.numlockmask = get_numlock_mask(conn)
        self.syms = Keysyms(conn)
        for keystr in keys:
            self.bind(keystr, keys[keystr])

    def bind(self, keystr, action):
        key = parse(keystr)
        self.bindings[key] = action
        print "bound %s" % keystr

    def grab(self, conn, root):
        modifiers = [0, ModMask.Lock, self.numlockmask,
                     self.numlockmask | ModMask.Lock]
        for key in self.bindings:
            for mod in modifiers:
                keycode = self.syms.get_keycode(key[1])
                conn.core.GrabKey(True, root, key[0] | mod, keycode,
                                  GrabMode.Async, GrabMode.Async)

    def ungrab(self, conn, root):
        modifiers = [0, ModMask.Lock, self.numlockmask,
                     self.numlockmask | ModMask.Lock]
        for key in self.bindings:
            for mod in modifiers:
                conn.core.UngrabKey(key[1], root, key[0] | mod)

    def handle(self, **kw):
        keypress = kw['event']
        keysym = self.syms.get_keysym(keypress.detail, 0)
        mask = self.cleanmask(keypress.state)
        for key in self.bindings:
            if mask == self.cleanmask(key[0]) and keysym == key[1]:
                self.bindings[key]()

    def cleanmask(self, mask):
        return mask & ~(self.numlockmask | ModMask.Lock)


text:
//----------------------------------------------------------------------
//This code is developed as part of the Java CoG Kit project
//The terms of the license can be found at http://www.cogkit.org/license
//This message may not be removed or altered.
//----------------------------------------------------------------------

/*
 * Created on Dec 6, 2012
 */
package k.rt;

import java.util.Collection;
import java.util.List;

public class FixedArgChannel<T> extends Sink<T> {
	private final Frame f;
	private int index;
	private final int bounds;

	public FixedArgChannel(Frame f, int startIndex, int endIndex) {
		this.f = f;
		this.index = startIndex;
		this.bounds = endIndex + (startIndex << 16);
	}

	public void setNames(List<String> names) {
	}

	public boolean isEmpty() {
	    return index > getStartIndex();
	}

	private int getStartIndex() {
		return bounds >> 16;
	}

	protected int getIndex() {
		return index;
	}

	protected int getBounds() {
		return bounds;
	}

	protected Frame getFrame() {
		return f;
	}

	@Override
	public int size() {
		return index - getStartIndex();
	}

	@Override
	public synchronized boolean add(T value) {
		if (index > (bounds & 0x0000ffff)) {
			throw new IllegalExtraArgumentException(value);
		}
		f.set(index++, value);
		return true;
	}

	@Override
	public synchronized boolean addAll(Collection<? extends T> values) {
		if (index + values.size() - 1 > (bounds & 0x0000ffff)) {
			throw new IndexOutOfBoundsException();
		}
		for (Object o : values) {
			f.set(index++, o);
		}
		return true;
	}

	@Override
	public synchronized void addAll(Channel<? extends T> c) {
		if (index + c.size() - 1 > (bounds & 0x0000ffff)) {
			throw new IndexOutOfBoundsException();
		}
		for (Object o : c) {
            f.set(index++, o);
        }
	}

	public String toString() {
		return "<" + index + ", " + (bounds & 0x0000ffff) + ">";
	}
}


text:
<?php

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

namespace Sami\Console\Command;

use Sami\Message;
use Sami\Parser\Transaction;
use Sami\Project;
use Sami\Renderer\Diff;
use Sami\Sami;
use Symfony\Component\Console\Command\Command as BaseCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Filesystem\Filesystem;

abstract class Command extends BaseCommand
{
    const PARSE_ERROR = 64;

    protected $sami;
    protected $version;
    protected $started;
    protected $diffs = array();
    protected $transactions = array();
    protected $errors = array();
    protected $input;
    protected $output;

    /**
     * @see Command
     */
    protected function configure()
    {
        $this->getDefinition()->addArgument(new InputArgument('config', InputArgument::REQUIRED, 'The configuration'));
        $this->getDefinition()->addOption(new InputOption('only-version', '', InputOption::VALUE_REQUIRED, 'The version to build'));
    }

    protected function initialize(InputInterface $input, OutputInterface $output)
    {
        $this->input = $input;
        $this->output = $output;

        $config = $input->getArgument('config');
        $filesystem = new Filesystem();

        if (!$filesystem->isAbsolutePath($config)) {
            $config = getcwd().'/'.$config;
        }

        if (!is_file($config)) {
            throw new \InvalidArgumentException(sprintf('Configuration file "%s" does not exist.', $config));
        }

        $this->sami = $this->loadSami($config);

        if ($input->getOption('only-version')) {
            $this->sami['versions'] = $input->getOption('only-version');
        }

        if (!$this->sami instanceof Sami) {
            throw new \RuntimeException(sprintf('Configuration file "%s" must return a Sami instance.', $config));
        }
    }

    public function update(Project $project)
    {
        $callback = $this->output->isDecorated() ? array($this, 'messageCallback') : null;

        $project->update($callback, $this->input->getOption('force'));

        $this->displayParseSummary();
        $this->displayRenderSummary();

        return count($this->errors) ? self::PARSE_ERROR : 0;
    }

    public function parse(Project $project)
    {
        $project->parse(array($this, 'messageCallback'), $this->input->getOption('force'));

        $this->displayParseSummary();

        return count($this->errors) ? self::PARSE_ERROR : 0;
    }

    public function render(Project $project)
    {
        $project->render(array($this, 'messageCallback'), $this->input->getOption('force'));

        $this->displayRenderSummary();

        return count($this->errors) ? self::PARSE_ERROR : 0;
    }

    public function messageCallback($message, $data)
    {
        switch ($message) {
            case Message::PARSE_CLASS:
                list($progress, $class) = $data;
                $this->displayParseProgress($progress, $class);
                break;
            case Message::PARSE_ERROR:
                $this->errors = array_merge($this->errors, $data);
                break;
            case Message::SWITCH_VERSION:
                $this->version = $data;
                $this->errors = array();
                $this->started = false;
                $this->displaySwitch();
                break;
            case Message::PARSE_VERSION_FINISHED:
                $this->transactions[(string) $this->version] = $data;
                $this->displayParseEnd($data);
                $this->started = false;
                break;
            case Message::RENDER_VERSION_FINISHED:
                $this->diffs[(string) $this->version] = $data;
                $this->displayRenderEnd($data);
                $this->started = false;
                break;
            case Message::RENDER_PROGRESS:
                list($section, $message, $progression) = $data;
                $this->displayRenderProgress($section, $message, $progression);
                break;
        }
    }

    public function renderProgressBar($percent, $length)
    {
        return
            str_repeat('#', floor($percent / 100 * $length))
            .sprintf(' %d%%', $percent)
            .str_repeat(' ', $length - floor($percent / 100 * $length))
        ;
    }

    public function displayParseProgress($progress, $class)
    {
        if ($this->started) {
            $this->output->isDecorated() and $this->output->write("\033[2A");
        }
        $this->started = true;

        $this->output->isDecorated() and $this->output->write(
            sprintf(
            "  Parsing <comment>%s</comment>%s\033[K\n          %s\033[K\n",
            $this->renderProgressBar($progress, 50),
            count($this->errors) ? ' <fg=red>'.count($this->errors).' error'.(1 == count($this->errors) ? '' : 's').'</>' : '',
            $class->getName()
        )
        );
    }

    public function displayRenderProgress($section, $message, $progression)
    {
        if ($this->started) {
            $this->output->isDecorated() and $this->output->write("\033[2A");
        }
        $this->started = true;

        $this->output->isDecorated() and $this->output->write(sprintf(
            "  Rendering <comment>%s</comment>\033[K\n            <info>%s</info> %s\033[K\n",
            $this->renderProgressBar($progression, 50),
            $section,
            $message
        ));
    }

    public function displayParseEnd(Transaction $transaction)
    {
        if (!$this->started) {
            return;
        }

        $this->output->isDecorated() and $this->output->write(sprintf("\033[2A<info>  Parsing   done</info>\033[K\n\033[K\n\033[1A", count($this->errors) ? ' <fg=red>'.count($this->errors).' errors</>' : ''));

        if ($this->input->getOption('verbose') && count($this->errors)) {
            foreach ($this->errors as $error) {
                $this->output->write(sprintf('<fg=red>ERROR</>: '));
                $this->output->writeln($error, OutputInterface::OUTPUT_RAW);
            }
            $this->output->writeln('');
        }
    }

    public function displayRenderEnd(Diff $diff)
    {
        if (!$this->started) {
            return;
        }

        $this->output->isDecorated() and $this->output->write("\033[2A<info>  Rendering done</info>\033[K\n\033[K\n\033[1A");
    }

    public function displayParseSummary()
    {
        if (count($this->transactions) <= 0) {
            return;
        }

        $this->output->writeln('');
        $this->output->writeln('<bg=cyan;fg=white> Version </>  <bg=cyan;fg=white> Updated C </>  <bg=cyan;fg=white> Removed C </>');

        foreach ($this->transactions as $version => $transaction) {
            $this->output->writeln(sprintf('%9s  %11d  %11d', $version, count($transaction->getModifiedClasses()), count($transaction->getRemovedClasses())));
        }
        $this->output->writeln('');
    }

    public function displayRenderSummary()
    {
        if (count($this->diffs) <= 0) {
            return;
        }

        $this->output->writeln('<bg=cyan;fg=white> Version </>  <bg=cyan;fg=white> Updated C </>  <bg=cyan;fg=white> Updated N </>  <bg=cyan;fg=white> Removed C </>  <bg=cyan;fg=white> Removed N </>');

        foreach ($this->diffs as $version => $diff) {
            $this->output->writeln(sprintf(
                '%9s  %11d  %11d  %11d  %11d',
                $version,
                count($diff->getModifiedClasses()),
                count($diff->getModifiedNamespaces()),
                count($diff->getRemovedClasses()),
                count($diff->getRemovedNamespaces())
            ));
        }
        $this->output->writeln('');
    }

    public function displaySwitch()
    {
        $this->output->writeln(sprintf("\n<fg=cyan>Version %s</>", $this->version));
    }

    private function loadSami(string $config)
    {
        return require $config;
    }
}


text:
<?php

namespace PHPCR\Tests\Util;

use PHPCR\Util\PathHelper;

class PathHelperTest extends \PHPUnit_Framework_TestCase
{
    // assertValidPath tests

    /**
     * @dataProvider dataproviderValidAbsolutePaths
     */
    public function testAssertValidAbsolutePath($path, $destination = false)
    {
        $this->assertTrue(PathHelper::assertValidAbsolutePath($path, $destination));
    }

    public function dataproviderValidAbsolutePaths()
    {
        return array(
            array('/parent/child'),
            array('/'),
            array('/jcr:foo_/b-a/0^.txt'),
            array('/parent[7]/child'),
            array('/parent[7]/child', true), // index is allowed in destination parent path, only not in last element
            array('/parent[7]/child[3]'),
        );
    }

    /**
     * @dataProvider dataproviderInvalidAbsolutePaths
     * @expectedException \PHPCR\RepositoryException
     */
    public function testAssertInvalidAbsolutePath($path, $destination = false)
    {
        PathHelper::assertValidAbsolutePath($path, $destination);
    }

    /**
     * @dataProvider dataproviderValidAbsolutePathsWithNamespaces
     */
    public function testAssertAbsolutePathNamespace($path)
    {
        PathHelper::assertValidAbsolutePath($path, false, true, array('jcr', 'nt'));
    }

    public function dataproviderValidAbsolutePathsWithNamespaces()
    {
        return array(
            array('/parent/child'),
            array('/jcr:localname'),
            array('/jcr:localname/test'),
            array('/jcr:localname/test/nt:node'),
            array('/jcr:localname/test/nt:node/bla'),
            array('/'),
            array('/jcr:foo_/b-a/0^.txt'),
            array('/parent[7]/child'),
            array('/jcr:localname[3]/test'),
        );
    }

    /**
     * @expectedException \PHPCR\NamespaceException
     * @expectedExceptionMessage invalidprefix and other-ns
     */
    public function testAssertInvalidNamespaceAbsolutePath()
    {
        PathHelper::assertValidAbsolutePath('/invalidprefix:localname/other-ns:test/invalidprefix:node/bla', false, true, array('jcr', 'nt'));
    }

    /**
     * @dataProvider dataproviderInvalidAbsolutePaths
     */
    public function testAssertInvalidAbsolutePathNoThrow($path, $destination = false)
    {
        $this->assertFalse(PathHelper::assertValidAbsolutePath($path, $destination, false));
    }

    public function dataproviderInvalidAbsolutePaths()
    {
        return array(
            array('/parent/child[7]', true), // destination last element with index
            array('parent'), // not absolute
            array('/parent//child'),
            array('//'),
            array('/parent/../child'),
            array('/parent/./child'),
            array('/parent/child/'),
        );
    }

    // assertValidLocalName tests

    public function testAssertValidLocalName()
    {
        $this->assertTrue(PathHelper::assertValidLocalName('nodename'));
    }

    public function testAssertValidLocalNameRootnode()
    {
        $this->assertTrue(PathHelper::assertValidLocalName(''));
    }

    /**
     * @dataProvider dataproviderInvalidLocalNames
     * @expectedException \PHPCR\RepositoryException
     */
    public function testAssertInvalidLocalName($name)
    {
        PathHelper::assertValidLocalName($name);
    }

    public function dataproviderInvalidLocalNames()
    {
        return array(
            array('jcr:nodename'),
            array('/path'),
            array('.'),
            array('..')
        );
    }

    // normalizePath tests

    /**
     * @dataProvider dataproviderNormalizePath
     */
    public function testNormalizePath($inputPath, $outputPath)
    {
        $this->assertSame($outputPath, PathHelper::normalizePath($inputPath));
    }

    public static function dataproviderNormalizePath()
    {
        return array(
            array('/',           '/'),
            array('/../foo',     '/foo'),
            array('/../',        '/'),
            array('/foo/../bar', '/bar'),
            array('/foo/./bar',  '/foo/bar'),
        );
    }

    /**
     * @dataProvider dataproviderNormalizePathInvalid
     * @expectedException \PHPCR\RepositoryException
     */
    public function testNormalizePathInvalidThrow($input)
    {
        PathHelper::normalizePath($input);
    }

    /**
     * @dataProvider dataproviderNormalizePathInvalid
     */
    public function testNormalizePathInvalidNoThrow($input)
    {
        $this->assertFalse(PathHelper::normalizePath($input, true, false));
    }

    public static function dataproviderNormalizePathInvalid()
    {
        return array(
            array('foo/bar'),
            array('bar'),
            array('/foo/bar/'),
            array(''),
            array(new \stdClass()),
        );
    }

    // absolutizePath tests

    /**
     * @dataProvider dataproviderAbsolutizePath
     */
    public function testAbsolutizePath($inputPath, $context, $outputPath)
    {
        $this->assertSame($outputPath, PathHelper::absolutizePath($inputPath, $context));
    }

    public static function dataproviderAbsolutizePath()
    {
        return array(
            array('/../foo',    '/',    '/foo'),
            array('../',        '/',    '/'),
            array('../foo/bar', '/baz', '/foo/bar'),
            array('foo/./bar',  '/baz', '/baz/foo/bar'),
        );
    }

    /**
     * @expectedException \PHPCR\RepositoryException
     * @dataProvider dataproviderAbsolutizePathInvalid
     */
    public function testAbsolutizePathInvalidThrow($inputPath, $context, $target)
    {
        PathHelper::absolutizePath($inputPath, $context, $target);
    }

    /**
     * @dataProvider dataproviderAbsolutizePathInvalid
     */
    public function testAbsolutizePathInvalidNoThrow($inputPath, $context, $target)
    {
        $this->assertFalse(PathHelper::absolutizePath($inputPath, $context, $target, false));
    }

    public static function dataproviderAbsolutizePathInvalid()
    {
        return array(
            array('', '/context', false),
            array(null,    '/context',    false),
            array('foo',        null,    false),
            array(new \stdClass(), '/context', false),
            array('foo[2]',  '/bar', true),
        );
    }

    // relativizePath tests

    /**
     * @dataProvider dataproviderRelativizePath
     */
    public function testRelativizePath($inputPath, $context, $outputPath)
    {
        $this->assertSame($outputPath, PathHelper::relativizePath($inputPath, $context));
    }

    public static function dataproviderRelativizePath()
    {
        return array(
            array('/parent/path/child', '/parent', 'path/child'),
            array('/child', '/', 'child'),
        );
    }

    /**
     * @expectedException \PHPCR\RepositoryException
     * @dataProvider dataproviderRelativizePathInvalid
     */
    public function testRelativizePathInvalidThrow($inputPath, $context)
    {
        PathHelper::relativizePath($inputPath, $context);
    }

    /**
     * @dataProvider dataproviderRelativizePathInvalid
     */
    public function testRelativizePathInvalidNoThrow($inputPath, $context)
    {
        $this->assertFalse(PathHelper::relativizePath($inputPath, $context, false));
    }

    public static function dataproviderRelativizePathInvalid()
    {
        return array(
            array('/path', '/context'),
            array('/parent', '/parent/child'),
        );
    }

    // getParentPath tests

    /**
     * @dataProvider dataproviderParentPath
     */
    public function testGetParentPath($path, $parent)
    {
        $this->assertEquals($parent, PathHelper::getParentPath($path));
    }

    public function dataproviderParentPath()
    {
        return array(
            array('/parent/child', '/parent'),
            array('/jcr:parent/ns:child', '/jcr:parent'),
            array('/child', '/'),
            array('/', '/'),
        );
    }

    // getNodeName tests

    /**
     * @dataProvider dataproviderGetNodeName
     */
    public function testGetNodeName($path, $expected = null)
    {
        $this->assertEquals($expected, PathHelper::getNodeName($path));
    }

    public function dataproviderGetNodeName()
    {
        return array(
            array('/parent/child', 'child'),
            array('/parent/ns:child', 'ns:child'),
            array('/', ''),
        );
    }

    /**
     * @dataProvider dataproviderGetLocalNodeName
     */
    public function testGetLocalNodeName($path, $expected = null)
    {
        $this->assertEquals($expected, PathHelper::getLocalNodeName($path));
    }

    public function dataproviderGetLocalNodeName()
    {
        return array(
            array('/parent/child', 'child'),
            array('/foo:child', 'child'),
            array('/parent/ns:child', 'child'),
            array('/ns:parent/child:foo', 'foo'),
            array('/', ''),
        );
    }

    /**
     * @expectedException \PHPCR\RepositoryException
     * @expectedExceptionMessage must be an absolute path
     */
    public function testGetNodeNameMustBeAbsolute()
    {
        PathHelper::getNodeName('foobar');
    }

    // getPathDepth tests

    /**
     * @dataProvider dataproviderPathDepth
     */
    public function testGetPathDepth($path, $depth)
    {
        $this->assertEquals($depth, PathHelper::getPathDepth($path));
    }

    public function dataproviderPathDepth()
    {
        return array(
            array('/', 0),
            array('/foo', 1),
            array('/foo/bar', 2),
            array('/foo/bar/', 2),
        );
    }
}


text:
package com.michaelfotiadis.steam.data.dota2.model.hero;

import com.google.gson.annotations.SerializedName;
import com.michaelfotiadis.steam.data.dota2.model.DotaApiModel;

public class AbilityUpgrade implements DotaApiModel {

    @SerializedName("ability")
    private final Integer ability;
    @SerializedName("time")
    private final Integer time;
    @SerializedName("level")
    private final Integer level;

    public AbilityUpgrade(final int ability, final int time, final int level) {
        this.ability = ability;
        this.time = time;
        this.level = level;
    }

    /**
     * @return ID of the ability upgraded.
     */
    public Integer getAbility() {
        return this.ability;
    }

    /**
     *
     * @return Time since match start that the ability was upgraded.
     */
    public Integer getTime() {
        return time;
    }

    /**
     *
     * @return The level of the player at time of upgrading.
     */
    public Integer getLevel() {
        return level;
    }

}


text:
If you intend to contribute to the project, please make sure you've followed
the instructions provided in the [Azure Projects Contribution Guidelines]
(http://azure.github.io/guidelines/).

## Project Setup on Windows
On Windows, the Azure Storage development team uses Visual Studio so
instructions will be tailored to that preference. However, any preferred IDE or
other toolset should be usable.

### Install
* Visual Studio 2015 or Visual Studio 2013 with C++ toolsets.
* Clone the source code from GitHub.

#### Open Solution
Open the project from Visual Studio using **File->Open->Project/Solution...**
and navigate to the `Microsoft.WindowsAzure.Storage.v140.sln` (for Visual
Studio 2015) or `Microsoft.WindowsAzure.Storage.v120.sln` (for Visual Studio
2013) solution file in the repo base folder. The dependent library Casablanca
will be installed by NuGet upon building.

### Tests

#### Add Unit Test Project
Use Visual Studio menu **File->Add->Existing Project...** and navigate to the
folder `Microsoft.WindowsAzure.Storage\tests`. Select
`Microsoft.WindowsAzure.Storage.UnitTests.v140.vcxproj` (for Visual Studio 2015)
or `Microsoft.WindowsAzure.Storage.UnitTests.v120.vcxproj` (for Visual Studio
2013).

#### Install UnitTest++
* Fetch source code of UnitTest++ from its [GitHub repo]
(https://github.com/unittest-cpp/unittest-cpp)
* Checkout version 1.4
```bash
git checkout v1.4
```
* Create a folder `UnitTest++` under `Microsoft.WindowsAzure.Storage\tests` and
copy all contents of `unittest-cpp` to it.
* Add another existing project to the Visual Studio via **File->Add->Existing
Project...**. Navigate to `Microsoft.WindowsAzure.Storage\tests\UnitTest++`, and
select `UnitTest++.vsnet2005.vcproj`.
* A "Review Project And Solution Changes" dialog popups. Choose **OK**, and a
new `UnitTest++.vsnet2005.vcxproj` is generated and added to the solution.

#### Configuration
The only step to configure testing is to change the `test_configuration.json`
file in `Microsoft.WindowsAzure.Storage\tests` folder. You should insert your
storage account information into the file. If you want to run the tests against
Azure Storage Emulator, change `target` to `devstore`. If you want to run the
tests against real Azure Storage, use real connection string in `production`.

#### Running
Set `Microsoft.WindowsAzure.Storage.UnitTests` as startup project. You can specify
a subset of tests to run on the command line before running the project. Go to the
project properties for the unit test project, select **Configuration Properties->
Debugging->Command Arguments**. Enter a space-separated list of `SUITE:TEST` and/or
`SUITE`. For example: `Queue:Queue_Messages`, `Core`, or `Table TableClient`.

### Debug
To use Fiddler, you need to set the system winhttp proxy. Open an administrator
command prompt. Run `netsh.exe`. Set the proxy by executing the command: `winhttp
set proxy localhost:8888`. Clear the proxy by executing the command: `winhttp reset
proxy`.

## Project Setup on Linux
The Azure Storage development team uses Ubuntu 14.04 LTS as the main development
platform, so instructions will be tailored to that. However, you can refer to other
platforms' documentation to install the dependent libraries and preferred IDE or
other toolset.

### Casablanca
Azure Storage Client Library for C++ depends on Casablanca. Follow [these
instructions](https://github.com/Microsoft/cpprestsdk/wiki/How-to-build-for-Linux)
to compile and install it.

### Additional Dependencies
```bash
sudo apt-get install libxml++2.6-dev libxml++2.6-doc uuid-dev
```

### Build
```bash
cd azure-storage-cpp/Microsoft.WIndowsAzure.Storage
mkdir build.release
cd build.release
CASABLANCA_DIR=<path to Casablanca> CXX=g++-5.1 cmake .. -DCMAKE_BUILD_TYPE=Release
make
```
In the above command, replace `<path to Casablanca>` to point to your local
installation of Casablanca. For example, if the file `libcpprest.so` exists at
location `~/Github/Casablanca/cpprestsdk/Release/build.release/Binaries/libcpprest.so`,
then your `cmake` command should be:
```bash
CASABLANCA_DIR=~/Github/Casablanca/cpprestsdk CXX=g++-5.1 cmake .. -DCMAKE_BUILD_TYPE=Release
```
The library is generated under
`azure-storage-cpp/Microsoft.WindowsAzure.Storage/build.release/Binaries/`.

### Tests

#### Install UnitTest++
```bash
sudo apt-get install libunittest++-dev
```

#### Build the Test Code
```bash
CASABLANCA_DIR=<path to Casablanca> CXX=g++-5.1 cmake .. -DCMAKE_BUILD_TYPE=Release -DBUILD_TESTS=ON
make
```
The test binary `azurestoragetest` and `test_configuration.json` are generated under
the same directory as `libazurestorage.so`.

#### Configuration
The only step to configure testing is to change the `test_configuration.json`
file in `Microsoft.WindowsAzure.Storage/tests` folder. You should insert your
storage account information into the file. If you want to run the tests against
Azure Storage Emulator, change `target` to `devstore`. If you want to run the
tests against real Azure Storage, use real connection string in `production`.

#### Running
```bash
cd Binaries
./azurestoragetest [<SUITE>|<SUITE:TEST>]*
```

### Samples
```bash
CASABLANCA_DIR=<path to Casablanca> CXX=g++-5.1 cmake .. -DCMAKE_BUILD_TYPE=Release -DBUILD_SAMPLES=ON
make
```

```bash
cd Binaries
./samplesblobs            # run the blobs sample
./samplestables           # run the tables sample
./samplesjson             # run the tables sample with json_no_metadata to reduce payload size
./samplesqueues           # run the queues sample
```

## Pull Requests

### Guidelines
The following are the minimum requirements for any pull request that must be met
before contributions can be accepted.
* Make sure you've signed the CLA before you start working on any change.
* Discuss any proposed contribution with the team via a GitHub issue **before**
starting development.
* Code must be professional quality.
	* You should strive to mimic the style with which we have written the library.
	* Clean, well-commented, well-designed code.
	* Try to limit the number of commits for a feature to 1-2. If you end up having
	too many we may ask you to squash your changes into fewer commits.
* [Changelog.txt](Changelog.txt) needs to be updated describing the new change.
* [BreakingChanges.txt](BreakingChanges.txt) contains changes that break
backward-compatibility.
* Thoroughly test your feature.

### Testing Features
As you develop a feature, you'll need to write tests to ensure quality. You should
also run existing tests related to your change to address any unexpected breaks.

### Branching Policy
Changes should be based on the `dev` branch. We're following [semver](http://semver.org/).
We generally release any breaking changes in the next major version (e.g. 1.0, 2.0)
and non-breaking changes in the next minor or major version (e.g. 2.1, 2.2).

### Adding Features for All Platforms
We strive to release each new feature for each of our environments at the same time.
Therefore, we ask that all contributions be written for both Window and Linux. This
includes testing work for both platforms as well. Because most of our code is written using
standard C++11 and upon a cross-platform library Casablanca, we expect contributions are
also using standard language and cross-platform libraries, so that it won't cause much effort
for cross-platform support.

### Review Process
We expect all guidelines to be met before accepting a pull request. As such, we will
work with you to address issues we find by leaving comments in your code. Please
understand that it may take a few iterations before the code is accepted as we maintain
high standards on code quality. Once we feel comfortable with a contribution, we will
validate the change and accept the pull request.

# Thank you for any contributions!
Please let the team know if you have any questions or concerns about our contribution policy.


text:
/*******************************************************************************
*
*  Filename    : WeightCounter.cc
*  Description : This stores information per event
*  Author      : Yi-Mu "Enoch" Chen [ ensc@hep1.phys.ntu.edu.tw ]
*
*  Reference:
*       CMSSW EventCountProducer Class
*
*******************************************************************************/
// system include files
#include <algorithm>
#include <iostream>
#include <memory>
#include <string>
#include <vector>
// user include files
#include "FWCore/Framework/interface/Event.h"
#include "FWCore/Framework/interface/Frameworkfwd.h"
#include "FWCore/Framework/interface/LuminosityBlock.h"
#include "FWCore/Framework/interface/MakerMacros.h"
#include "FWCore/Framework/interface/Run.h"
#include "FWCore/Framework/interface/one/EDProducer.h"
#include "FWCore/ParameterSet/interface/ParameterSet.h"
#include "SimDataFormats/GeneratorProducts/interface/LHEEventProduct.h"

#include "ManagerUtils/EDMUtils/interface/Counter.hpp"

// ------------------------------------------------------------------------------
//   Class Definition
// ------------------------------------------------------------------------------
class WeightCounter : public edm::one::EDProducer<edm::one::WatchRuns, edm::EndRunProducer>
{
public:
  explicit
  WeightCounter( const edm::ParameterSet& );
  ~WeightCounter();

private:
  virtual void produce( edm::Event&, const edm::EventSetup& ) override;
  virtual void beginRun( const edm::Run&, const edm::EventSetup& ) override;
  virtual void endRun( const edm::Run&, const edm::EventSetup& ) override;
  virtual void endRunProduce( edm::Run&, const edm::EventSetup& ) override;

  const edm::EDGetToken _lhesrc;
  edm::Handle<LHEEventProduct> _lheHandle;
  double _eventCount;
};
using namespace edm;
using namespace std;

// ------------------------------------------------------------------------------
//   Constructor and destructor
// ------------------------------------------------------------------------------
WeightCounter::WeightCounter( const edm::ParameterSet& iConfig ) :
  _lhesrc( consumes<LHEEventProduct>( iConfig.getParameter<edm::InputTag>( "lhesrc" ) ) )
{
  produces<mgr::Counter, edm::InRun>( "EventsCount" );
}

WeightCounter::~WeightCounter(){}

// ------------------------------------------------------------------------------
//   Main Control flow
// ------------------------------------------------------------------------------
void
WeightCounter::beginRun( const edm::Run&, const edm::EventSetup& )
{
  _eventCount = 0;
}

void
WeightCounter::produce( edm::Event& iEvent, const edm::EventSetup& iSetup )
{
  iEvent.getByToken( _lhesrc, _lheHandle );
  if( _lheHandle.isValid() ){
    _eventCount += _lheHandle->hepeup().XWGTUP;
  } else {
    _eventCount += 1;
  }
}

void
WeightCounter::endRun( const edm::Run&, const edm::EventSetup& )
{}

void
WeightCounter::endRunProduce( edm::Run& iRun, const EventSetup& iSetup )
{
  auto_ptr<mgr::Counter> ptr( new mgr::Counter( _eventCount ) );
  iRun.put( ptr, "" );
}

DEFINE_FWK_MODULE( WeightCounter );


text:
import utils from './utils'

export function getProductList(params) {
  return utils.list('product/', params)
}

export function exportProductList(params) {
  if (params.product_ids) {
    params.product_ids = params.product_ids.join(',')
  }
  return utils.getView('product/export/data/', params)
}

export function updateProductStock(id, params) {
  return utils.put(`product/${id}/productsku/`, params)
}

export function updateProductStatus(id, params) {
  return utils.put(`product/${id}/`, params)
}

export function getProduct(id) {
  return utils.get(`product/${id}/`)
}

export function addProduct(params) {
  return utils.post('product/', params)
}

export function updateProduct(id, params) {
  return utils.put(`product/${id}/`, params)
}

export function addSpec(params) {
  return utils.post('spec/', params)
}

export function updateSpec(id, params) {
  return utils.put(`spec/${id}/`, params)
}

export function updateSpecFields(id, params) {
  return utils.patch(`spec/${id}/`, params)
}

export function updateProductFields(params) {
  return utils.patch('product/', params)
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>
Ghost Bed Ideas | blog.ipedrazas.me
</title>

    <link href="/feeds/all.atom.xml" type="application/atom+xml" rel="alternate" title="Sitewide ATOM Feed">

  <meta name="theme-color" content="#ffffff">
  <link rel="stylesheet" href="/static/css/bootstrap.min.css">
  <link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-glyphicons.css" rel="stylesheet">

          <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
            Toggle navigation

          </button>
          blog.ipedrazas.me

Archives

            Categories

              Android 6

              Architecture 1

              Arduino 2

              Bitcoin 1

              CMS 1

              Cassandra 3

              DevOps 9

              Development 8

              Docker 5

              Idea 3

              London 2

              Maker 1

              Me 2

              Python 2

              Spanish 2

              Uncategorized 1

              analytics 1

              books 1

              children 3

              startups 1

              stats 1

            Tags

              Android 3

              Idea 5

              stats 1

              kubernetes 3

              immutable 1

              architecture 1

              Arduino 1

              Cassandra 3

              Docker 7

              cassandra 2

              docker 8

              tutorial 1

              DevOps 11

              ansible 1

              vagrant 2

              jenkins 1

              neo4j 1

              devops 2

              mesos 3

              Mesos 1

              apachekafka 1

              aws 1

              kinesis 1

              London 2

              coreos 1

              lxd 1

              meetup 1

              ubuntu 1

              microservices 1

              Development 6

              Javascript 1

              Python 3

              deploy 1

              python 2

              clinker 1

              Java 2

              elasticsearch 2

              github 1

              testing 1

              taiga 1

              Spanish 4

              pycones 2

              Me 1

              startups 4

              Maker 1

              RaspberryPi 1

              dev 1

              gunicorn 1

              java 1

              tomcat 1

              sexism 1

              Uncategorized 1

              dotmarks 1

              children 2

              security 1

              raspberrypi 1

              anti-patterns 1

Ghost Bed Ideas

by ipedrazas

2013-04-18

Idea

Idea

Me

Was talking about ideas last week and suddenly I realised that my ideas don’t come from nothing but from a seed idea. Something that makes an impact or attracts my mind somehow triggers the idea generation process.

The process is more or less like this:

I see something I like, for example, the stool that rocks.

That sensation/memory lingers in y head for a while.

Start spawning random thoughts of how I would do if I were or what I would do if I could

A lot of side jumping between ideas.

Have you seen how designers work? designers produce and discard an extraordinary amount of work. My idea generation process is a bit like that. Hammering the concept with as many random thoughts as possible and looking at how the idea shapes up.

For example, using the stool that rocks I could talk about the “Ghost Bed Idea” which is nothing more that a design of a bed I’ve made based on the principles of the stool that rocks: that you can make your own furniture.

But can you? Can you really make your own table? bed? chairs?

I don’t see why not. Unfortunately for me, my cad skills are almost none, but I know how to draw, and yes I know how to do technical drawing too… and I’m not engineer but I know enough of tensions, forces and resistance to think of what it means to build something like a bed.

I don’t want to imagine my wife’s reaction next time she ask me what I’m doing: “Actually, a bed, darling”…

But let’s face it. For now, it’s more a concept, a few sketches and some random queries in google to find out how thick wood has to be to be able to build a bed.


text:
'use strict';

var up = require('../src/index.js');

module.exports = {

    'package.json': function(test) {

        test.expect(1);
        up.search('package.json', function(path) {

            test.equal('package.json', path.split(/\\|\//g).pop());
            test.done();
        });
    },
    'package.json - sync': function(test) {
        var
            path;

        test.expect(1);
        path = up.searchSync('package.json');
        test.equal('package.json', path.split(/\\|\//g).pop());
        test.done();
    }
};


text:
<?php

namespace ApiGen\Configuration\Readers\Exceptions;

use InvalidArgumentException;

class MissingFileException extends InvalidArgumentException
{

}


text:
angular.module( 'celestial.auditAdd', [
  'ui.state',  'ngResource'
])
.config(function config($stateProvider) {
  $stateProvider.state( 'auditAdd', {
    url: '/audit/add/',
    views: {
	"main": {
        controller: 'AuditAddCtrl',
        templateUrl: 'audits/add/add.tpl.html'
       }
    },
    data:{ pageTitle: 'New audit' }
  });
})
.controller( 'AuditAddCtrl', function typeAddController($scope, $http, $resource ,auditsService) {

  $scope.audit= {type:'kibana'};

  $scope.submit = function(){
    auditsService.save($scope.audit);
  };

});


text:
import select
import socket
import sys
import Queue
import os
import time
from thread import *
from collections import defaultdict

uploadInfos = defaultdict(dict) # For seeders
downloadInfos = defaultdict(dict) # For leechers
pieceRequestQueue = defaultdict(dict) # For leechers

PIECE_SIZE = 1024*512
BLOCK_SIZE = 4*1024
DELIMITER = '|/!@#$%^&*\|'
SEPAERATOR = '|/<>?\~|'
lastBuffered = ''

fd = None

badaFlag = False
torrentInfo = {}
pieceBitVector = {}
seeder = True
count = 0
myHost= ""
myPort = 0
inputs = []
#	inputs = []
	# Sockets to which we expect to write
outputs = []
	# Outgoing message queues (socket:Queue)
message_queues = {}

def getKey(item):
	return item[0]

def returnPeerList(torrentInfo,host,port):
	connected = False
	for tracker in torrentInfo['trackers'] :
		print tracker
		tracker = tracker.strip('\n')
		hostTracker,portTracker = tracker.split(':')
		server_address = (hostTracker, int(portTracker))

		msg = "REQUEST_PEERS-"+host+":"+str(port)+",FILE:"+torrentInfo['name']
		s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		print   'connecting to %s port %s' % server_address

		try:
			s.connect(server_address)
			print  '%s: sending "%s"' % (s.getsockname(), msg)
			s.send(msg)
			connected = True
			break
		except:
			print "Unable to Connect"
			pass
	if connected :
		data = s.recv(BLOCK_SIZE)
		print "Received data:" + data
		data = data.split('-')
		peerList = data[1].split(',')
		print peerList
		return peerList
	else:
		return []

def parseTorrentFile(inp):
	global trackers,torrentName

	with open(inp) as f:
		for line in f:
			info = line.strip(' ')
			info = line.strip('\n')
			info = line.split('-')
			if info[0] == 'trackers'	:
				torrentInfo['trackers'] = info[1].split(',')
			elif info[0] == 'name':
				torrentInfo['name'] = info[1]
			elif info[0] == 'length':
				torrentInfo['length'] = int(info[1])
			elif info[0] == 'pieces':
				torrentInfo['pieces'] = int(info[1])
			else :
				print "Torrent File Corrupted\n"
				sys.exit(0)
def processData(data):
	response = ''
	header = data.split(':')[0]
	if header == "REQUEST_FILE":
		pass
	elif header == "HAVE":
		pass
	elif header == "":
		pass

def availablePieces():
	return 10

def processMsg(data):
	global seeder,torrentInfo,uploadInfos,downloadInfos,pieceRequestQueue
	response = ''
	data = data.split(SEPAERATOR)
	Q = Queue.Queue()
	header = data[0]
	if header == "REQUEST_FILE":
		currentPiece = 1
		count = 0
		pieceFlag = True
		f=open (data[1].strip('\n'), "rb")

		fileInfo = os.stat(data[1].strip('\n'))
		fileSize = fileInfo.st_size

		pieces = fileSize/2
		offset = 1	#for 1st seeder and this for 2nd seeder
		#offset = (pieces/PIECE_SIZE)*PIECE_SIZE + 1
		f.seek(offset)
		msg = "OFFSET"+SEPAERATOR+str(offset)
	#	Q.put(msg)
		l = f.read(BLOCK_SIZE)

		while (l and pieceFlag):
			Q.put(l)
			l = f.read(BLOCK_SIZE)
			count = count+1
			if(count/10 == currentPiece):
				print "Piece "+str(currentPiece) +" put in queue for senting to leecher"
				currentPiece = currentPiece +1
			if(currentPiece == pieces/PIECE_SIZE and offset == 0):
				pieceFlag = False

		f.close()
		response = "Queue"
		ret = (response, Q)
	elif header == "HAVE":
		pass
	return ret

def handleRecvIO(s,file,length):

	global seeder,torrentInfo,uploadInfos,downloadInfos,pieceRequestQueue
	count = 1
	percent = 100
	offset = 0
	f = open(file, "wb")
	f.seek(offset)
	print "Ready to Recieve : "+file
	while(count<=length):
		part = s.recv(BLOCK_SIZE)
		f.write(part)
		count=count+1
		if count == length/percent :
			print ""+str(percent)+" Percent Remaining"
			if percent != 1 :
				percent = percent-1
	f.close()
	print file + " Downloaded Successfully"

def pieceRequestOrdering(filename):
	filename = filename.strip("\n")
	global seeder,torrentInfo,uploadInfos,downloadInfos,pieceRequestQueue,inputs
	for x in xrange(1,int(torrentInfo["pieces"])+1):
		pieceRequestQueue[filename][x] = Queue.Queue()
	print inputs
	tempList = inputs[1:]
	for s in tempList:
		print "Hello"
		if s in downloadInfos[filename]:
			bitvector = downloadInfos[filename][s]
			index = 1
			for i in bitvector:
				if i =='1':
					pieceRequestQueue[filename][index].put(s)
					index = index + 1
					print index

	#print pieceRequestQueue[filename]
	#TO DO
	#Message format
	#Create message and put msg in the outut message queue
def retrieveBytesFromFile(s,filename,index):
	global PIECE_SIZE,BLOCK_SIZE
	filename = filename.strip('\n')
	print filename
	offset = 0
	try:
		fo = open(filename, "r+b")
		print "Reading File at index : " + str(index)

		fo.seek((index-1)*PIECE_SIZE, 0)

		print "current file position is : "+  str(fo.tell())
		# print "Name of the file: ", fo.name
		# fo.seek((index-1)*PIECE_SIZE, 0)
		for blockNumber in xrange(0,PIECE_SIZE/BLOCK_SIZE):
			print "In Loop"
			byteData = fo.read(BLOCK_SIZE)

			if(byteData==''):
				print "byteData is NULL"
				break
			print "current file position is : "+ str(fo.tell())
			if(byteData):
				data = "HAVE_PIECE"+SEPAERATOR+filename+SEPAERATOR+str(index)+SEPAERATOR+str(blockNumber)+SEPAERATOR+byteData+DELIMITER

				message_queues[s].put(data)
		fo.close()
	except:
		print "Error Handling File "
		pass

def processRecvdMsg(data,s):

	global seeder,torrentInfo,uploadInfos,downloadInfos,pieceRequestQueue,badaFlag,fd
#	print   'received "%s" from %s' % (data, s.getpeername())
	data = data.strip('\n')
	temp = data.split(SEPAERATOR)
	header = temp[0]
	data = ""

	if header == "RECEIVE_FILE":
		file = temp[1]
		length = int(temp[2])
		handleRecvIO(s,file,length)
		# running = False
		pass
	elif header == "REQUEST_FILE":
		response, Q = processMsg(data)
		if response == "Queue":
			length = Q.qsize()
			msg = "RECEIVE_FILE"+SEPAERATOR+ temp[1] +SEPAERATOR+str(length)+SEPAERATOR
			message_queues[s].put(msg)
			while(not Q.empty()):
				message_queues[s].put(Q.get_nowait())
	elif header == "HANDSHAKE":
		filename = temp[1]
		bitvector = temp[2]
		print bitvector
		print "Hello"
		pieces = len(bitvector)
		# uploadInfos[filename][s.getpeername()] = bitvector
		uploadInfos[filename][s] = bitvector

		bitvector =  returnBitVector(filename,pieces)
		data = "REPLY_HANDSHAKE"+SEPAERATOR+filename+SEPAERATOR+stringify(bitvector)+DELIMITER
		message_queues[s].put(data)

	elif header == "REPLY_HANDSHAKE":
		filename = temp[1]
		bitvector = temp[2]
		pieces = len(bitvector)
		downloadInfos[filename][s] = bitvector
		if(not os.path.exists(filename)):
			fd= open(filename,"w+b",0)
			fd.close()
		fd = open(filename,"rw+b",0)

		#uploadInfos[filename][s] = bitvector
	elif header == "REQUEST_PIECE" :
		print temp
		filename = temp[1]
		index = int(temp[2])
		actualPieceData = retrieveBytesFromFile(s,filename,index)

	elif header == "HAVE_PIECE":
		filename = temp[1]
		index = int(temp[2])
		blockNumber = int(temp[3])
		byteData = temp[4]
		print len(temp)
		print len(byteData)
		try:
			# if(not os.path.exists(filename)):
			# 	fd = open(filename,"wb+")
			# 	fd.close()
			# fd = open(filename,"rwb+")
			position = PIECE_SIZE*(index-1) + blockNumber*BLOCK_SIZE

			fd.seek(position,0)
			writtenAmount = fd.write(byteData)
			#time.sleep(0.001)
			fd.flush()
			print "Downloaded index = " +str(index) + " blockNumber = "+str(blockNumber)+" for filename = "+filename + " at position: " + str(position) + " till: " + str(fd.tell()) + " Written = "+str(writtenAmount)
		except:
			print "Error handling while Flushing data"
		if(index == 13 and blockNumber==25):
			badaFlag = True
			fd.close()
	else:
		print "data count: "  + data

	if s not in outputs:
		outputs.append(s)

def handShaking(peerList):

	global seeder,torrentInfo,uploadInfos,downloadInfos,pieceRequestQueue
	for peers in peerList:
		print peers
		host,port = peers.split(':')
		port = int(port)
		peerServer = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		try:
			peerServer.connect((host,port))
			# peerServer.setblocking(0)
			outputs.append(peerServer)
			print "Connection to "	+ peers + " succeeded"
			print "Creating output queue for "+ peers
			message_queues[peerServer] = Queue.Queue()

			data = "HANDSHAKE"+SEPAERATOR+torrentInfo['name'] +SEPAERATOR+stringify(pieceBitVector[torrentInfo["name"]])+DELIMITER

			peerServer.send(data)
			print peerServer.getpeername()
			print "Hello"
			try:
				data = peerServer.recv(BLOCK_SIZE)
				print   'received "%s" from %s' % (data, peerServer.getpeername())
				print data
				processRecvdMsg(data,peerServer)
			except:
				print "Error while recieveing "
			inputs.append(peerServer)

		except:
			print "Some error"
			pass
		peerServer.setblocking(0)

def rarestPieceFirstAlgo(filename,pieces):
	filename = filename.strip('\n')
	global seeder,torrentInfo,uploadInfos,downloadInfos,pieceRequestQueue

	# Creating list of tuples for rarest first order (pieceCount,pieceIndex)
	countPiece = []
	for i in xrange(1,pieces+1):
		countPiece.append((pieceRequestQueue[filename][i].qsize(),i))

	sorted(countPiece, key=getKey)
	for tuples in countPiece:
		pieceQsize = tuples[0]
		pieceIndex = tuples[1]
		# FORMAT of Sending message

		if pieceQsize != 0 :
			data = "REQUEST_PIECE"+SEPAERATOR+filename+SEPAERATOR+str(pieceIndex)+DELIMITER
			s = pieceRequestQueue[filename][pieceIndex].get_nowait()
			message_queues[s].put(data)

def reactor(server):

	global seeder,torrentInfo,uploadInfos,downloadInfos,pieceRequestQueue,inputs,outputs,message_queues,DELIMITER,lastBuffered,badaFlag
	running = True
	while running:

		# Wait for at least one of the sockets to be ready for processing
		print   '\nwaiting for the next event using select'

		readable, writable, exceptional = select.select(inputs, outputs, inputs)
			# Handle inputs
		for s in readable:
			print "In Readable"
			if s is server:
				# A "readable" server socket is ready to accept a connection
				connection, client_address = s.accept()
				print   'new connection from', client_address
				connection.setblocking(0)
				inputs.append(connection)
				outputs.append(connection)
				# Give the connection  a queue for data we want to send
				message_queues[connection] = Queue.Queue()
			else:
				bufferMsg = s.recv(BLOCK_SIZE)

				if bufferMsg:
					if lastBuffered != "":
						bufferMsg = lastBuffered + bufferMsg
						lastBuffered = ""

					if badaFlag :
						print "Stray data is bufferMsg = "+bufferMsg
					bufferMsg = bufferMsg.split(DELIMITER)
					if badaFlag :
						print " bufferMsgafter splitting DELIMITER= " + ('').join(bufferMsg)
					if(bufferMsg[-1]):
						lastBuffered = bufferMsg[-1]
					for data in bufferMsg[:-1]:
						processRecvdMsg(data,s)
					# A readable client socket has data

				else:
					# Interpret empty result as closed connection
					print   'closing', client_address, 'after reading no data'
					# Stop listening for input on the connection
					if s in outputs:
							outputs.remove(s)
					inputs.remove(s)
					s.close()

					# Remove message queue
					del message_queues[s]
						# Handle outputs
		for s in writable:
			print "In writable"
			try:
				next_msg = message_queues[s].get_nowait()
			except:
				# No messages waiting so stop checking for writability.
				print   'output queue for', s.getpeername(), 'is empty'
				outputs.remove(s)
			else:
				temp = next_msg.split(SEPAERATOR)
				if(temp[0] == "HAVE_PIECE"):
					print "Sending data for file = " + temp[1] +" PieceIndex = "+temp[2]+ " blockNumber = "+temp[3]
					#print   'sending "%s" to %s' % (next_msg, s.getpeername())
				s.send(next_msg)
				#time.sleep(0.075)
					# Handle "exceptional conditions"
		for s in exceptional:
			print "In Exceptional"
			print   'handling exceptional condition for', s.getpeername()
			# Stop listening for input on the connection
			inputs.remove(s)
			if s in outputs:
				outputs.remove(s)
			s.close()

			# Remove message queue
			del message_queues[s]

def recvMessage(host,port,peerList):

	global seeder,torrentInfo,uploadInfos,downloadInfos,pieceRequestQueue
	print "Entering recvMessage"
	global count
	server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
	server.setblocking(0)
	# Bind the socket to the port
	server_address = (host, port)
	print   'starting up on %s port %s' % server_address
	server.bind(server_address)
	count = count+1
	# Listen for incoming connections
	server.listen(5)
	inputs.append(server)
	# Sockets from which we expect to read

	handShaking(peerList)

	if not seeder :
		pieceRequestOrdering(torrentInfo["name"])
		rarestPieceFirstAlgo(torrentInfo["name"],int(torrentInfo['pieces']))

	reactor(server)

def returnBitVector(filename,pieces):
	global seeder
	if seeder:
		return [True]*pieces

	return [False]*(pieces)

def stringify(bitvector):
	str = ""
	for i in bitvector :
		if(i == False):
			str = str +'0'
		else:
			str = str +'1'
	return str

def initialize():
	global myHost,myPort,seeder,peerList,torrentInfo,uploadInfos,downloadInfos,pieceRequestQueue
	if(len(sys.argv) < 3):
		print "To run please follow following Format: python %s hostname port (optional:Torrent File)",sys.argv[0]
		sys.exit("Bye")
	seeder = True
	myHost = sys.argv[1]
	myPort = int(sys.argv[2])
	peerList = []
	if len(sys.argv) == 4:
		filename = sys.argv[3]
		parseTorrentFile(filename)
		torrentInfo["name"] = torrentInfo["name"].strip('\n')
		bitvector = returnBitVector(torrentInfo["name"],int(torrentInfo["pieces"]))
		pieceBitVector[torrentInfo["name"]] = bitvector
		seeder = False

	if(not seeder):
		peerList = returnPeerList(torrentInfo,myHost,myPort)
		print "Peer List Received"

# Create a TCP/IP socket
if __name__ == '__main__':

#Tracker connection
	initialize()
	try:
		start_new_thread(recvMessage,(myHost,myPort,peerList))
	#	start_new_thread(sendMessage,(host,port,peerList))
	except:
		print "Error: unable to start thread"
while 1:
	pass


text:
<?php
namespace SPHERE\Common;

use Doctrine\DBAL\Driver\PDOException;
use Doctrine\DBAL\Exception\TableNotFoundException;
use MOC\V\Component\Router\Component\Bridge\Repository\UniversalRouter;
use SPHERE\Application\Availability\Availability;
use SPHERE\Application\Billing\Billing;
use SPHERE\Application\Contact\Contact;
use SPHERE\Application\Corporation\Corporation;
use SPHERE\Application\Dispatcher;
use SPHERE\Application\Education\Education;
use SPHERE\Application\People\People;
use SPHERE\Application\Platform\Platform;
use SPHERE\Application\Platform\System;
use SPHERE\Application\Transfer\Transfer;
use SPHERE\Common\Window\Display;
use SPHERE\Common\Window\Error;
use SPHERE\Common\Window\Navigation\Link;
use SPHERE\Common\Window\Redirect;
use SPHERE\System\Authenticator\Authenticator;
use SPHERE\System\Authenticator\Type\Get;
use SPHERE\System\Authenticator\Type\Post;
use SPHERE\System\Extension\Extension;

/**
 * Class Main
 *
 * @package SPHERE\Common
 */
class Main extends Extension
{

    /** @var Display $Display */
    private static $Display = null;
    /** @var Dispatcher $Dispatcher */
    private static $Dispatcher = null;

    /**
     *
     */
    public function __construct()
    {

        if (self::getDisplay() === null) {
            self::$Display = new Display();
        }
        if (self::getDispatcher() === null) {
            self::$Dispatcher = new Dispatcher(new UniversalRouter());
        }
    }

    /**
     * @return Display
     */
    public static function getDisplay()
    {

        return self::$Display;
    }

    /**
     * @return Dispatcher
     */
    public static function getDispatcher()
    {

        return self::$Dispatcher;
    }

    public function runPlatform()
    {

        try {
            $this->getDebugger();
            $this->setErrorHandler();
            $this->setShutdownHandler();

            /**
             * Register Cluster
             */
            Platform::registerCluster();
            People::registerCluster();
            Corporation::registerCluster();
            Education::registerCluster();
            Billing::registerCluster();
            Transfer::registerCluster();
            Availability::registerCluster();
            Contact::registerCluster();
            /**
             * Execute Request
             */
            if ($this->runAuthenticator()) {
                self::getDisplay()->setContent(
                    self::getDispatcher()->fetchRoute(
                        $this->getRequest()->getPathInfo()
                    )
                );
            }
        } catch (PDOException $Exception) {
            $this->runSelfHeal($Exception);
        } catch (TableNotFoundException $Exception) {
            $this->runSelfHeal($Exception);
        } catch (\PDOException $Exception) {
            $this->runSelfHeal($Exception);
        } catch (\ErrorException $Exception) {
            self::getDisplay()->setException($Exception, 'Error');
        } catch (\Exception $Exception) {
            self::getDisplay()->setException($Exception, 'Exception');
        }

        try {
            echo self::getDisplay()->getContent();
            exit( 0 );
        } catch (\Exception $Exception) {
            $this->runSelfHeal($Exception);
        }
    }

    /**
     *
     */
    private function setErrorHandler()
    {

        set_error_handler(
            function ($Code, $Message, $File, $Line) {

                if (!preg_match('!apc_store.*?was.*?on.*?gc-list.*?for!is', $Message)) {
                    throw new \ErrorException($Message, 0, $Code, $File, $Line);
                }
            }, E_ALL
        );
    }

    /**
     *
     */
    private function setShutdownHandler()
    {

        register_shutdown_function(
            function () {

                $Error = error_get_last();
                if (!$Error) {
                    return;
                }
                $Display = new Display();
                $Display->addServiceNavigation(
                    new Link(new Link\Route('/'), new Link\Name('Zurück zur Anwendung'))
                );
                $Display->setException(
                    new \ErrorException($Error['message'], 0, $Error['type'], $Error['file'], $Error['line']),
                    'Shutdown'
                );
                echo $Display->getContent(true);
            }
        );
    }

    /**
     * @return bool
     */
    private function runAuthenticator()
    {

        if (!array_key_exists('REST', $this->getRequest()->getParameterArray())) {
            $Get = (new Authenticator(new Get()))->getAuthenticator();
            $Post = (new Authenticator(new Post()))->getAuthenticator();
            if (!( $Get->validateSignature() && $Post->validateSignature() )) {
                self::getDisplay()->setClusterNavigation();
                self::getDisplay()->setApplicationNavigation();
                self::getDisplay()->setModuleNavigation();
                self::getDisplay()->setServiceNavigation(new Link(
                    new Link\Route('/'),
                    new Link\Name('Zurück zur Anwendung')
                ));
                self::getDisplay()->setContent(Dispatcher::fetchRoute('System/Assistance/Error/Authenticator'));
                return false;
            }
        }
        return true;
    }

    /**
     * @param \Exception $Exception
     */
    private function runSelfHeal(\Exception $Exception = null)
    {

        $Display = new Display();
        $Display->setContent(
            ( $Exception
                ? new Error($Exception->getCode(), $Exception->getMessage())
                : ''
            ).
            (new System\Database\Database())->frontendSetup(false)
            .(new Redirect($this->getRequest()->getPathInfo(), 60))
        );
        echo $Display->getContent(true);
        exit( 0 );
    }
}


text:
import uirouter from 'angular-ui-router';

import { HomeComponent } from "./home.component";
import HomeConfig from "./home.config";

export default angular.module('home', [uirouter])
  .config(HomeConfig)
  .component('home', HomeComponent)
  .name;


text:
package org.jetbrains.plugins.scala
package lang
package psi
package api
package expr

/**
* @author Alexander Podkhalyuzin
*/

trait ScTryStmt extends ScExpression {
  def tryBlock = findChildByClassScala(classOf[ScTryBlock])
  def catchBlock = findChild(classOf[ScCatchBlock])
  def finallyBlock = findChild(classOf[ScFinallyBlock])

  override def accept(visitor: ScalaElementVisitor) = visitor.visitTryExpression(this)
}

object ScTryStmt {
  def unapply(tryStmt: ScTryStmt): Option[(ScTryBlock, Option[ScCatchBlock], Option[ScFinallyBlock])] =
    Some((tryStmt.tryBlock, tryStmt.catchBlock, tryStmt.finallyBlock))
}


text:
using System;
using Twilio.TaskRouter;

class Example
{
  static void Main(string[] args)
  {
    // Find your Account Sid and Auth Token at twilio.com/user/account
    string AccountSid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
    string AuthToken = "your_auth_token";
    string WorkspaceSid = "WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
    string TaskSid = "WTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
    var client = new TaskRouterClient(AccountSid, AuthToken);

    ReservationResult reservationResult = client.ListReservations(WorkspaceSid, TaskSid);
    foreach(Reservation reservation in reservationResult.Reservations) {
        Console.WriteLine(reservation.ReservationStatus);
        Console.WriteLine(reservation.WorkerName);
    }
  }
}


text:
/**
 * Internal dependencies
 */
import { default as wellbeingArrowDark } from './arrowDark';
import { default as wellbeingArrowLight } from './arrowLight';
import { default as wellbeingCTA } from './cta';

export { wellbeingArrowDark, wellbeingArrowLight, wellbeingCTA };