text:
import TestModule from './test-module';
import Ember from 'ember';
import { getResolver } from './test-resolver';
import hasEmberVersion from './has-ember-version';

export default TestModule.extend({
  isComponentTestModule: true,

  init: function(componentName, description, callbacks) {
    // Allow `description` to be omitted
    if (!callbacks && typeof description === 'object') {
      callbacks = description;
      description = null;
    } else if (!callbacks) {
      callbacks = {};
    }

    this.componentName = componentName;

    if (callbacks.needs || callbacks.unit || callbacks.integration === false) {
      this.isUnitTest = true;
    } else if (callbacks.integration) {
      this.isUnitTest = false;
    } else {
      Ember.deprecate(
        "the component:" + componentName + " test module is implicitly running in unit test mode, " +
        "which will change to integration test mode by default in an upcoming version of " +
        "ember-test-helpers. Add `unit: true` or a `needs:[]` list to explicitly opt in to unit " +
        "test mode.",
        false,
        { id: 'ember-test-helpers.test-module-for-component.test-type', until: '0.6.0' }
      );
      this.isUnitTest = true;
    }

    if (description) {
      this._super.call(this, 'component:' + componentName, description, callbacks);
    } else {
      this._super.call(this, 'component:' + componentName, callbacks);
    }

    if (!this.isUnitTest && !this.isLegacy) {
      callbacks.integration = true;
    }

    if (this.isUnitTest || this.isLegacy) {
      this.setupSteps.push(this.setupComponentUnitTest);
    } else {
      this.callbacks.subject = function() {
        throw new Error("component integration tests do not support `subject()`. Instead, render the component as if it were HTML: `this.render('<my-component foo=true>');`. For more information, read: http://guides.emberjs.com/v2.2.0/testing/testing-components/");
      };
      this.setupSteps.push(this.setupComponentIntegrationTest);
      this.teardownSteps.unshift(this.teardownComponent);
    }

    if (Ember.View && Ember.View.views) {
      this.setupSteps.push(this._aliasViewRegistry);
      this.teardownSteps.unshift(this._resetViewRegistry);
    }
  },

  _aliasViewRegistry: function() {
    this._originalGlobalViewRegistry = Ember.View.views;
    var viewRegistry = this.container.lookup('-view-registry:main');

    if (viewRegistry) {
      Ember.View.views = viewRegistry;
    }
  },

  _resetViewRegistry: function() {
    Ember.View.views = this._originalGlobalViewRegistry;
  },

  setupComponentUnitTest: function() {
    var _this = this;
    var resolver = getResolver();
    var context = this.context;

    var layoutName = 'template:components/' + this.componentName;

    var layout = resolver.resolve(layoutName);

    var thingToRegisterWith = this.registry || this.container;
    if (layout) {
      thingToRegisterWith.register(layoutName, layout);
      thingToRegisterWith.injection(this.subjectName, 'layout', layoutName);
    }

    context.dispatcher = this.container.lookup('event_dispatcher:main') || Ember.EventDispatcher.create();
    context.dispatcher.setup({}, '#ember-testing');

    this.callbacks.render = function() {
      var subject;

      Ember.run(function(){
        subject = context.subject();
        subject.appendTo('#ember-testing');
      });

      _this.teardownSteps.unshift(function() {
        Ember.run(function() {
          Ember.tryInvoke(subject, 'destroy');
        });
      });
    };

    this.callbacks.append = function() {
      Ember.deprecate(
        'this.append() is deprecated. Please use this.render() or this.$() instead.',
        false,
        { id: 'ember-test-helpers.test-module-for-component.append', until: '0.6.0' }
      );
      return context.$();
    };

    context.$ = function() {
      this.render();
      var subject = this.subject();

      return subject.$.apply(subject, arguments);
    };
  },

  setupComponentIntegrationTest: function() {
    var module = this;
    var context = this.context;

    this.actionHooks = {};

    context.dispatcher = this.container.lookup('event_dispatcher:main') || Ember.EventDispatcher.create();
    context.dispatcher.setup({}, '#ember-testing');
    context.actions = module.actionHooks;

    (this.registry || this.container).register('component:-test-holder', Ember.Component.extend());

    context.render = function(template) {
      if (!template) {
        throw new Error("in a component integration test you must pass a template to `render()`");
      }
      if (Ember.isArray(template)) {
        template = template.join('');
      }
      if (typeof template === 'string') {
        template = Ember.Handlebars.compile(template);
      }
      module.component = module.container.lookupFactory('component:-test-holder').create({
        layout: template
      });

      module.component.set('context' ,context);
      module.component.set('controller', context);

      Ember.run(function() {
        module.component.appendTo('#ember-testing');
      });
    };

    context.$ = function() {
      return module.component.$.apply(module.component, arguments);
    };

    context.set = function(key, value) {
      var ret = Ember.run(function() {
        return Ember.set(context, key, value);
      });

      if (hasEmberVersion(2,0)) {
        return ret;
      }
    };

    context.setProperties = function(hash) {
      var ret = Ember.run(function() {
        return Ember.setProperties(context, hash);
      });

      if (hasEmberVersion(2,0)) {
        return ret;
      }
    };

    context.get = function(key) {
      return Ember.get(context, key);
    };

    context.getProperties = function() {
      var args = Array.prototype.slice.call(arguments);
      return Ember.getProperties(context, args);
    };

    context.on = function(actionName, handler) {
      module.actionHooks[actionName] = handler;
    };

    context.send = function(actionName) {
      var hook = module.actionHooks[actionName];
      if (!hook) {
        throw new Error("integration testing template received unexpected action " + actionName);
      }
      hook.apply(module, Array.prototype.slice.call(arguments, 1));
    };

    context.clearRender = function() {
      module.teardownComponent();
    };
  },

  setupContext: function() {
    this._super.call(this);

    // only setup the injection if we are running against a version
    // of Ember that has `-view-registry:main` (Ember >= 1.12)
    if (this.container.lookupFactory('-view-registry:main')) {
      (this.registry || this.container).injection('component', '_viewRegistry', '-view-registry:main');
    }

    if (!this.isUnitTest && !this.isLegacy) {
      this.context.factory = function() {};
    }
  },

  teardownComponent: function() {
    var component = this.component;
    if (component) {
      Ember.run(function() {
        component.destroy();
      });
    }
  }
});


text:
require 'dotenv'
require 'websocket-eventmachine-client'
require 'json'

require_relative '../adapter'
require_relative '../../message'
require_relative 'slack_http_client'

module Slacker
  module Adapters
    class SlackAdapter < Adapter
      attr_reader :channels, :users, :username

      def initialize(robot)
        super
        @name, @token =
          ENV['NAME'], ENV['SLACK_TOKEN']

        @api = SlackHttpClient.new(@name, @token)
      end

      def run
        @rtm_meta = @api.start_rtm

        @channels = (@rtm_meta["channels"] + @rtm_meta["groups"] + @rtm_meta["ims"])
        @users = (@rtm_meta["users"] + @rtm_meta["bots"])

        queue = Queue.new
        workers = create_worker_pool(queue, 16)

        start_websocket(queue)

        # Attach a bunch of workers to the queue and handle incoming messages
        workers.each(&:join)
      end

      def send(message)
        @socket.send({
          :type => 'message',
          :channel => message.channel["id"],
          :text => message.pretty_response
        }.to_json)
      end

      def channel_by_id(channel_id)
        @channels.select { |channel| channel["id"] == channel_id }.first
      end

      def user_by_name(username)
        @users.select { |user| user["name"] == username }.first
      end

      def user_by_id(user_id)
        @users.select { |user| user["id"] == user_id }.first
      end

      private
      def create_worker_pool(queue, size=16)
        Array.new(16) do
          Thread.new do
            w = QueueWorker.new(queue, self)
            loop { w.work }
          end
        end
      end

      def start_websocket(queue)
        EM.run do
          @socket = WebSocket::EventMachine::Client.connect(:uri => @rtm_meta["url"])

          @socket.onmessage do |msg, type|
            packet = JSON.parse(msg)
            if packet["type"] == "message" && packet["text"]
              # Replace Slack's username @ mention with their actual username
              packet["text"].gsub! /<@U(.{8})>/ do |match|
                matched_user = user_by_id("U#{$1}")
                matched_user["name"] if matched_user
              end

              queue << packet
            end
          end
        end
      end
    end

    class QueueWorker < Struct.new(:queue, :adapter)
      def work
        message = self.queue.pop

        begin
          self.adapter.hear({
            :text => message["text"],
            :channel => self.adapter.channel_by_id(message["channel"]),
            :user => self.adapter.user_by_id(message["user"])
          })
        rescue Exception => e
          puts e
        end
      end
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**bt_type** | **str** |  | [optional]
**error_message** | **str** |  | [optional]
**should_reset_value_when_confirmed** | **bool** |  | [optional]

[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)


text:
phrase = "Ich bin ein Berliner"

# def reverse_words(phrase)
#   array_phrase = phrase.split.each_slice(1).map{|x|x.join ''}
#   rev_array = array_phrase.map!{|x| x.reverse}
#   p rev_array.join(' ')
# end

# reverse_words(phrase)

# Refactored Solution

def reverse_words(phrase)
  array_phrase = phrase.split.each_slice(1).map{|x| p x.join''}.map!{|x| x.reverse}.join(' ')
end

reverse_words(phrase)

# Reflection
# What concepts did you review or learn in this challenge?
# I think it was helpful to think about the solution and psuedocode before tackling an issues.
# After working on JavaScript, I was able to break down an assignment into a lot more smaller task.
# This was helpful to review and appy with ruby.

# What is still confusing to you about Ruby?
# The biggest challenge is to switch back and forth between JavaScript and Ruby.  I also
# choose one of the easier Tuby assignments for this week.  I should take a look at more assignments.

# What are you going to study to get more prepared for Phase 1?
# I think I really need to be more familiar with switching back between Ruby and JavaScript.
# I felt like I Was making some progress with Ruby but once it came time to switch back between
# the two languages I was thrown off and had a difficult time understanding what was going.
# To get more prepared for Phase 1, I will go through some of the reading materials that talks
# about Ruby and JavaScript.  I will also try to work on more examples.


text:
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.18051
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace ConsoleInteraction.Assets {
    using System;

    ///
    ///   A strongly-typed resource class, for looking up localized strings, etc.
    ///
    // This class was auto-generated by the StronglyTypedResourceBuilder
    // class via a tool like ResGen or Visual Studio.
    // To add or remove a member, edit your .ResX file then rerun ResGen
    // with the /str option, or rebuild your VS project.
    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
    internal class HtmlFiles {

        private static global::System.Resources.ResourceManager resourceMan;

        private static global::System.Globalization.CultureInfo resourceCulture;

        [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
        internal HtmlFiles() {
        }

        ///
        ///   Returns the cached ResourceManager instance used by this class.
        ///
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        internal static global::System.Resources.ResourceManager ResourceManager {
            get {
                if (object.ReferenceEquals(resourceMan, null)) {
                    global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("ConsoleInteraction.Assets.HtmlFiles", typeof(HtmlFiles).Assembly);
                    resourceMan = temp;
                }
                return resourceMan;
            }
        }

        ///
        ///   Overrides the current thread's CurrentUICulture property for all
        ///   resource lookups using this strongly typed resource class.
        ///
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        internal static global::System.Globalization.CultureInfo Culture {
            get {
                return resourceCulture;
            }
            set {
                resourceCulture = value;
            }
        }

        ///
        ///   Looks up a localized string similar to <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
        ///
        ///
        ///
        ///
        ///	<title>Application Auto-update via Online Files in C# - CodeProject</title>
        ///	<link type="text/css" rel="stylesheet" href="http://s.codeproject.com/App_Themes/Std/Css/Main.min.css?dt=2.6.130329.1">
        ///<link type="text/css" rel="stylesheet" href="http://s.codeproject.com/App_Themes/Easter/Css/Main.min.css?dt=2.6.130329.1">
        ///
        ///
        ///<meta http-equiv="Content-Type" content="text/html; charse [rest of string was truncated]";.
        ///
        internal static string CodeProject {
            get {
                return ResourceManager.GetString("CodeProject", resourceCulture);
            }
        }

        ///
        ///   Looks up a localized string similar to <!DOCTYPE HTML><meta http-equiv="X-UA-Compatible" content="IE=8,IE=9" /><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/><meta name="description" content="Ausführliche und aktuelle Beiträge - von Google News aus verschiedenen Nachrichtenquellen aus aller Welt zusammengetragen"/><title>Google News</title><link href="http://www.gstatic.com/news-static/img/favicon.ico" rel="icon" type="image/x-icon"/><link rel="alternate" type="application/rss+xml" href="http://news.google.de/ne [rest of string was truncated]";.
        ///
        internal static string GoogleNews {
            get {
                return ResourceManager.GetString("GoogleNews", resourceCulture);
            }
        }

        ///
        ///   Looks up a localized string similar to <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">
        ///
        ///
        ///<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        ///<title>Simon Mages</title>
        ///
        ///<frameset rows="*,18" border="0">
        ///    <frameset rows="110,*" border="0">
        ///        <frame src="head.html" />
        ///        <frameset cols="25%,*" border="0">
        ///            <frame src="navigation.html" />
        ///            <frame name="start" src=" [rest of string was truncated]";.
        ///
        internal static string Simon {
            get {
                return ResourceManager.GetString("Simon", resourceCulture);
            }
        }

        ///
        ///   Looks up a localized string similar to <!DOCTYPE html>
        ///<meta charset=utf-8>
        ///<title>Ein Beispiel</title>
        ///

        ///Ein Test...
        ///
.
        ///
        internal static string Test {
            get {
                return ResourceManager.GetString("Test", resourceCulture);
            }
        }

        ///
        ///   Looks up a localized string similar to <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
        ///	"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
        ///
        ///
        ///
        ///	<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
        ///
        ///
        ///
        ///
        ///

        ///

        ///
        ///
Selectors

        ///
        ///
W3C Working Draft 15 December 200 [rest of string was truncated]";.
        ///
        internal static string W3C {
            get {
                return ResourceManager.GetString("W3C", resourceCulture);
            }
        }
    }
}


text:
// https://leetcode.com/problems/remove-duplicates-from-sorted-list/#/description

/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} head
 * @return {ListNode}
 */
var deleteDuplicates = function (head) {
  if (!head || !head.next) return head;
  var pre = head;
  var current = head.next;
  while (current) {
    if (pre.val === current.val) {
      pre.next = current.next;
    } else {
      pre = current;
    }
    current = current.next;
  }
  return head;
};

function ListNode(val) {
  this.val = val;
  this.next = null;
}

var num1 = [1, 1, 1];
var num2 = [1, 1, 2, 3, 3];

var link1 = new ListNode(num1[0]);
var current1 = link1;
for (let i = 1; i < num1.length; i++) {
  let temp = new ListNode(num1[i]);
  current1.next = temp;
  current1 = temp;
}
console.log(deleteDuplicates(link1));

var link2 = new ListNode(num2[0]);
var current2 = link2;
for (let i = 1; i < num2.length; i++) {
  let temp = new ListNode(num2[i]);
  current2.next = temp;
  current2 = temp;
}
console.log(deleteDuplicates(link2));


text:
package com.tinkerpop.blueprints.impls.neo4j2;

import com.tinkerpop.blueprints.CloseableIterable;
import com.tinkerpop.blueprints.Edge;
import com.tinkerpop.blueprints.Index;
import com.tinkerpop.blueprints.Parameter;
import com.tinkerpop.blueprints.Vertex;
import com.tinkerpop.blueprints.util.StringFactory;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.PropertyContainer;
import org.neo4j.graphdb.Relationship;
import org.neo4j.graphdb.index.IndexHits;
import org.neo4j.graphdb.index.IndexManager;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Marko A. Rodriguez (http://markorodriguez.com)
 */
public class Neo4j2Index<T extends Neo4j2Element, S extends PropertyContainer> implements Index<T> {

    private final Class<T> indexClass;
    protected final Neo4j2Graph graph;
    private final String indexName;
    protected org.neo4j.graphdb.index.Index<S> rawIndex;

    protected Neo4j2Index(final String indexName, final Class<T> indexClass, final Neo4j2Graph graph, final Parameter... indexParameters) {
        this.indexClass = indexClass;
        this.graph = graph;
        this.indexName = indexName;
        this.generateIndex(indexParameters);
    }

    public Class<T> getIndexClass() {
        if (Vertex.class.isAssignableFrom(this.indexClass))
            return (Class) Vertex.class;
        else
            return (Class) Edge.class;
    }

    public String getIndexName() {
        return this.indexName;
    }

    public void put(final String key, final Object value, final T element) {
        try {
            this.graph.autoStartTransaction(true);
            this.rawIndex.add((S) element.getRawElement(), key, value);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    /**
     * {@inheritDoc}
     *

     * The underlying Neo4j graph does not natively support this method within a transaction.
     * If the graph is not currently in a transaction, then the operation runs efficiently.
     * If the graph is in a transaction, then, for every element, a try/catch is used to determine if its in the current transaction.
     */
    public CloseableIterable<T> get(final String key, final Object value) {
        this.graph.autoStartTransaction(false);
        final IndexHits<S> itty = this.rawIndex.get(key, value);
        if (this.indexClass.isAssignableFrom(Neo4j2Vertex.class))
            return new Neo4j2VertexIterable((Iterable<Node>) itty, this.graph, this.graph.checkElementsInTransaction());
        return new Neo4j2EdgeIterable((Iterable<Relationship>) itty, this.graph, this.graph.checkElementsInTransaction());
    }

    /**
     * {@inheritDoc}
     *

     * The underlying Neo4j graph does not natively support this method within a transaction.
     * If the graph is not currently in a transaction, then the operation runs efficiently.
     * If the graph is in a transaction, then, for every element, a try/catch is used to determine if its in the current transaction.
     */
    public CloseableIterable<T> query(final String key, final Object query) {
        this.graph.autoStartTransaction(false);
        final IndexHits<S> itty = this.rawIndex.query(key, query);
        if (this.indexClass.isAssignableFrom(Neo4j2Vertex.class))
            return new Neo4j2VertexIterable((Iterable<Node>) itty, this.graph, this.graph.checkElementsInTransaction());
        return new Neo4j2EdgeIterable((Iterable<Relationship>) itty, this.graph, this.graph.checkElementsInTransaction());
    }

    /**
     * {@inheritDoc}
     *

     * The underlying Neo4j graph does not natively support this method within a transaction.
     * If the graph is not currently in a transaction, then the operation runs efficiently.
     * If the graph is in a transaction, then, for every element, a try/catch is used to determine if its in the current transaction.
     */
    public CloseableIterable<T> query(final Object query) {
        this.graph.autoStartTransaction(false);
        final IndexHits<S> itty = this.rawIndex.query(query);
        if (this.indexClass.isAssignableFrom(Neo4j2Vertex.class))
            return new Neo4j2VertexIterable((Iterable<Node>) itty, this.graph, this.graph.checkElementsInTransaction());
        return new Neo4j2EdgeIterable((Iterable<Relationship>) itty, this.graph, this.graph.checkElementsInTransaction());
    }

    /**
     * {@inheritDoc}
     *

     * The underlying Neo4j graph does not natively support this method within a transaction.
     * If the graph is not currently in a transaction, then the operation runs efficiently.
     * If the graph is in a transaction, then, for every element, a try/catch is used to determine if its in the current transaction.
     */
    public long count(final String key, final Object value) {
        this.graph.autoStartTransaction(false);
        if (!this.graph.checkElementsInTransaction()) {
            final IndexHits hits = this.rawIndex.get(key, value);
            final long count = hits.size();
            hits.close();
            return count;
        } else {
            final CloseableIterable<T> hits = this.get(key, value);
            long count = 0;
            for (final T t : hits) {
                count++;
            }
            hits.close();
            return count;
        }
    }

    public void remove(final String key, final Object value, final T element) {
        try {
            this.graph.autoStartTransaction(true);
            this.rawIndex.remove((S) element.getRawElement(), key, value);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    private void generateIndex(final Parameter<Object, Object>... indexParameters) {
        this.graph.autoStartTransaction(true);
        final IndexManager manager = this.graph.getRawGraph().index();
        if (Vertex.class.isAssignableFrom(this.indexClass)) {
            if (indexParameters.length > 0)
                this.rawIndex = (org.neo4j.graphdb.index.Index<S>) manager.forNodes(this.indexName, generateParameterMap(indexParameters));
            else
                this.rawIndex = (org.neo4j.graphdb.index.Index<S>) manager.forNodes(this.indexName);
        } else {
            if (indexParameters.length > 0)
                this.rawIndex = (org.neo4j.graphdb.index.Index<S>) manager.forRelationships(this.indexName, generateParameterMap(indexParameters));
            else
                this.rawIndex = (org.neo4j.graphdb.index.Index<S>) manager.forRelationships(this.indexName);
        }
    }

    public String toString() {
        return StringFactory.indexString(this);
    }

    private static Map<String, String> generateParameterMap(final Parameter<Object, Object>... indexParameters) {
        final Map<String, String> map = new HashMap<String, String>();
        for (final Parameter<Object, Object> parameter : indexParameters) {
            map.put(parameter.getKey().toString(), parameter.getValue().toString());
        }
        return map;
    }

    public org.neo4j.graphdb.index.Index<S> getRawIndex() {
        return this.rawIndex;
    }
}


text:
import feedparser

def startElementNS(self, name, qname, attrs):
    namespace, localname = name
    lowernamespace = str(namespace or '').lower()
    if lowernamespace.find('backend.userland.com/rss') != -1:
        # match any backend.userland.com namespace
        namespace = 'http://backend.userland.com/rss'
        lowernamespace = namespace
    if qname and qname.find(':') > 0:
        givenprefix = qname.split(':')[0]
    else:
        givenprefix = None
    prefix = self._matchnamespaces.get(lowernamespace, givenprefix)
    # I couldn't care one whit about namespaces,
    # so don't let them throw exceptions
    # if givenprefix and (prefix is None or (prefix == '' and lowernamespace == '')) and givenprefix not in self.namespaces_in_use:
    #     raise UndeclaredNamespace("'%s' is not associated with a namespace" % givenprefix)
    # localname = str(localname).lower()

    # qname implementation is horribly broken in Python 2.1 (it
    # doesn't report any), and slightly broken in Python 2.2 (it
    # doesn't report the xml: namespace). So we match up namespaces
    # with a known list first, and then possibly override them with
    # the qnames the SAX parser gives us (if indeed it gives us any
    # at all).  Thanks to MatejC for helping me test this and
    # tirelessly telling me that it didn't work yet.
    attrsD, self.decls = self.decls, {}
    if localname == 'math' and namespace == 'http://www.w3.org/1998/Math/MathML':
        attrsD['xmlns'] = namespace
    if localname == 'svg' and namespace == 'http://www.w3.org/2000/svg':
        attrsD['xmlns'] = namespace

    if prefix:
        localname = prefix.lower() + ':' + localname
    elif namespace and not qname:  # Expat
        for name, value in self.namespaces_in_use.items():
            if name and value == namespace:
                localname = name + ':' + localname
                break

    for (namespace, attrlocalname), attrvalue in attrs.items():
        lowernamespace = (namespace or '').lower()
        prefix = self._matchnamespaces.get(lowernamespace, '')
        if prefix:
            attrlocalname = prefix + ':' + attrlocalname
        attrsD[str(attrlocalname).lower()] = attrvalue
    for qname in attrs.getQNames():
        attrsD[str(qname).lower()] = attrs.getValueByQName(qname)
    localname = str(localname).lower()
    self.unknown_starttag(localname, list(attrsD.items()))

feedparser.parsers.strict._StrictFeedParser.startElementNS = startElementNS


text:
#pragma once

#include <infer_model/portability.h>
#include <infer_no_model/crash_on_exec.h>


text:
package seedu.address.model;

import static org.junit.Assert.assertEquals;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import seedu.address.model.person.Person;
import seedu.address.model.person.ReadOnlyPerson;
import seedu.address.model.tag.Tag;
import seedu.address.testutil.TypicalTestPersons;

public class AddressBookTest {

    @Rule
    public ExpectedException thrown = ExpectedException.none();

    private final AddressBook addressBook = new AddressBook();

    @Test
    public void constructor() {
        assertEquals(Collections.emptyList(), addressBook.getPersonList());
        assertEquals(Collections.emptyList(), addressBook.getTagList());
    }

    @Test
    public void resetData_null_throwsAssertionError() {
        thrown.expect(AssertionError.class);
        addressBook.resetData(null);
    }

    @Test
    public void resetData_withValidReadOnlyAddressBook_replacesData() {
        AddressBook newData = new TypicalTestPersons().getTypicalAddressBook();
        addressBook.resetData(newData);
        assertEquals(newData, addressBook);
    }

    @Test
    public void resetData_withDuplicatePersons_throwsAssertionError() {
        TypicalTestPersons td = new TypicalTestPersons();
        // Repeat td.alice twice
        List<Person> newPersons = Arrays.asList(new Person(td.alice), new Person(td.alice));
        List<Tag> newTags = td.alice.getTags().asObservableList();
        AddressBookStub newData = new AddressBookStub(newPersons, newTags);

        thrown.expect(AssertionError.class);
        addressBook.resetData(newData);
    }

    @Test
    public void resetData_withDuplicateTags_throwsAssertionError() {
        AddressBook typicalAddressBook = new TypicalTestPersons().getTypicalAddressBook();
        List<ReadOnlyPerson> newPersons = typicalAddressBook.getPersonList();
        List<Tag> newTags = new ArrayList<>(typicalAddressBook.getTagList());
        // Repeat the first tag twice
        newTags.add(newTags.get(0));
        AddressBookStub newData = new AddressBookStub(newPersons, newTags);

        thrown.expect(AssertionError.class);
        addressBook.resetData(newData);
    }

    /**
     * A stub ReadOnlyAddressBook whose persons and tags lists can violate interface constraints.
     */
    private static class AddressBookStub implements ReadOnlyAddressBook {
        private final ObservableList<ReadOnlyPerson> persons = FXCollections.observableArrayList();
        private final ObservableList<Tag> tags = FXCollections.observableArrayList();

        AddressBookStub(Collection<? extends ReadOnlyPerson> persons, Collection<? extends Tag> tags) {
            this.persons.setAll(persons);
            this.tags.setAll(tags);
        }

        @Override
        public ObservableList<ReadOnlyPerson> getPersonList() {
            return persons;
        }

        @Override
        public ObservableList<Tag> getTagList() {
            return tags;
        }
    }

}


text:
package ngSpring.demo.domain.dto;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.validation.constraints.NotNull;

@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class UserRoleDTO {

    @NotNull
    private String roleId;

    @NotNull
    private String roleName;
}


text:
class PrefService;

namespace content {
class BrowserContext;
class WebContents;
}  // namespace content

namespace enterprise_connectors {

class AccessTokenFetcher;
class BoxUploader;
class SigninExperienceTestObserver;

using InterruptReason = download::DownloadInterruptReason;
constexpr auto kSuccess = download::DOWNLOAD_INTERRUPT_REASON_NONE;
constexpr auto kServiceProviderUnknownError =
    download::DOWNLOAD_INTERRUPT_REASON_SERVER_FAILED;
constexpr auto kServiceProviderDown =
    download::DOWNLOAD_INTERRUPT_REASON_NETWORK_SERVER_DOWN;
constexpr auto kBrowserFailure = download::DOWNLOAD_INTERRUPT_REASON_CRASH;
constexpr auto kCredentialUpdateFailure = kBrowserFailure;
constexpr auto kSignInCancellation =
    download::DOWNLOAD_INTERRUPT_REASON_USER_CANCELED;

// An implementation of download::DownloadItemRenameHandler that sends a
// download item file to a cloud-based storage provider as specified in the
// SendDownloadToCloudEnterpriseConnector policy.
class FileSystemRenameHandler : public download::DownloadItemRenameHandler {
 public:
  static std::unique_ptr<download::DownloadItemRenameHandler> CreateIfNeeded(
      download::DownloadItem* download_item);

  class TestObserver : public base::CheckedObserver {
   public:
    explicit TestObserver(FileSystemRenameHandler* rename_handler);
    ~TestObserver() override;

    enum Status { kNotStarted, kInProgress, kSucceeded, kFailed };

    virtual void OnStart() {}
    virtual void OnFetchAccessTokenStart() {}
    virtual void OnAccessTokenFetched(const GoogleServiceAuthError& status) {}
    virtual void OnDestruction();

    static BoxUploader* GetBoxUploader(FileSystemRenameHandler* rename_handler);

   private:
    base::WeakPtr<FileSystemRenameHandler> rename_handler_;
  };

  FileSystemRenameHandler(download::DownloadItem* download_item,
                          FileSystemSettings settings);
  explicit FileSystemRenameHandler(download::DownloadItem* download_item);
  ~FileSystemRenameHandler() override;

  base::WeakPtr<FileSystemRenameHandler> RegisterSigninObserverForTesting(
      SigninExperienceTestObserver* observer);
  void UnregisterSigninObserverForTesting(
      SigninExperienceTestObserver* observer);

 protected:
  // download::DownloadItemRenameHandler interface.
  void Start(ProgressUpdateCallback progress_update_cb,
             DownloadCallback upload_complete_cb) override;
  void OpenDownload() override;
  void ShowDownloadInContext() override;

  // These methods are declared protected to be overridden in unit tests so that
  // calls to other components can be isolated.
  virtual void TryUploaderTask(content::BrowserContext* context,
                               const std::string& access_token);
  virtual void PromptUserSignInForAuthorization(content::WebContents* contents);
  virtual void FetchAccessToken(content::BrowserContext* context,
                                const std::string& refresh_token);

  // These methods are declared protected so that they can be used in tests.
  void SetUploaderForTesting(std::unique_ptr<BoxUploader> fake_uploader);
  // Callback for PromptUserSignInForAuthorization().
  void OnAuthorization(const GoogleServiceAuthError& status,
                       const std::string& access_token,
                       const std::string& refresh_token);
  // Callback for FetchAccessToken().
  void OnAccessTokenFetched(const GoogleServiceAuthError& status,
                            const std::string& access_token,
                            const std::string& refresh_token);

 private:
  static absl::optional<FileSystemSettings> IsEnabled(
      download::DownloadItem* download_item);

  void StartInternal(std::string access_token = std::string());
  scoped_refptr<network::SharedURLLoaderFactory> GetURLLoaderFactory(
      content::BrowserContext* context);

  // Helper method used in OpenDownload() and ShowDownloadInContext().
  void AddTabToShowDownload(const GURL& url);

  // Called when failure status is returned via callbacks but is not
  // GoogleServiceAuthError::State::REQUEST_CANCELED.
  void OnAuthenticationError(const GoogleServiceAuthError& error);
  // Called when failure status is returned via callbacks and is
  // GoogleServiceAuthError::State::REQUEST_CANCELED.
  void OnSignInCancellation();
  // Callback for uploader_ upon API requests returning authentication error.
  void OnApiAuthenticationError();

  PrefService* GetPrefs();

  // Copied from policy settings. Constant for the life of the rename handler.
  const FileSystemSettings settings_;

  std::unique_ptr<AccessTokenFetcher> token_fetcher_;
  // Main uploader that manages the entire API call flow of file upload.
  std::unique_ptr<BoxUploader> uploader_;
  base::ObserverList<TestObserver> observers_;
  raw_ptr<SigninExperienceTestObserver> signin_observer_ = nullptr;
  base::WeakPtrFactory<FileSystemRenameHandler> weak_factory_{this};
};

class RenameStartObserver : public FileSystemRenameHandler::TestObserver {
 public:
  explicit RenameStartObserver(FileSystemRenameHandler* rename_handler);
  ~RenameStartObserver() override = default;

  // RenameHandlerObserver methods
  void OnStart() override;

  void WaitForStart();

 private:
  bool started_ = false;
  base::RunLoop run_loop_;
};

class BoxFetchAccessTokenTestObserver
    : public FileSystemRenameHandler::TestObserver {
 public:
  explicit BoxFetchAccessTokenTestObserver(
      FileSystemRenameHandler* rename_handler);
  ~BoxFetchAccessTokenTestObserver() override = default;

  // RenameHandlerObserver methods
  void OnFetchAccessTokenStart() override;
  void OnAccessTokenFetched(const GoogleServiceAuthError& status) override;

  bool WaitForFetch();

 private:
  Status status_ = Status::kNotStarted;
  GoogleServiceAuthError fetch_token_err_;
  base::RunLoop run_loop_;
};

}  // namespace enterprise_connectors

#endif  // CHROME_BROWSER_ENTERPRISE_CONNECTORS_FILE_SYSTEM_RENAME_HANDLER_H_


text:
package org.ml4j.nn.synapses;

import java.util.Arrays;
import java.util.List;

import org.ml4j.nn.components.DirectedComponentsContext;
import org.ml4j.nn.components.activationfunctions.DifferentiableActivationFunctionComponentActivation;
import org.ml4j.nn.components.onetone.DefaultChainableDirectedComponentActivation;
import org.ml4j.nn.components.onetone.DefaultDirectedComponentBipoleGraphActivation;
import org.ml4j.nn.neurons.NeuronsActivation;

/**
 * Default implementation of DirectedSynapsesActivation.
 *
 * @author Michael Lavelle
 */
public abstract class DirectedSynapsesActivationBase implements DirectedSynapsesActivation {

	protected NeuronsActivation inputActivation;
	protected DefaultDirectedComponentBipoleGraphActivation axonsActivationGraph;
	protected DifferentiableActivationFunctionComponentActivation activationFunctionActivation;
	protected NeuronsActivation outputActivation;
	protected DirectedSynapses<?, ?> synapses;
	protected DirectedComponentsContext synapsesContext;

	/**
	 * Construct a new default DirectedSynapsesActivation
	 *
	 * @param synapses             The DirectedSynapses
	 * @param inputActivation      The input NeuronsActivation of the
	 *                             DirectedSynapses following a forward propagation
	 * @param axonsActivationGraph The axons NeuronsActivation graph of the
	 *                             DirectedSynapses following a forward propagation
	 * @param outputActivation     The output NeuronsActivation of the
	 *                             DirectedSynapses following a forward propagation.
	 */
	public DirectedSynapsesActivationBase(DirectedSynapses<?, ?> synapses, NeuronsActivation inputActivation,
			DefaultDirectedComponentBipoleGraphActivation axonsActivationGraph,
			DifferentiableActivationFunctionComponentActivation activationFunctionActivation,
			NeuronsActivation outputActivation, DirectedComponentsContext synapsesContext) {
		this.inputActivation = inputActivation;
		this.outputActivation = outputActivation;
		this.synapses = synapses;
		this.axonsActivationGraph = axonsActivationGraph;
		this.activationFunctionActivation = activationFunctionActivation;
		this.synapsesContext = synapsesContext;
	}

	@Override
	public List<DefaultChainableDirectedComponentActivation> decompose() {
		return Arrays.asList(axonsActivationGraph, activationFunctionActivation);
	}

	@Override
	public NeuronsActivation getOutput() {
		return outputActivation;
	}

	@Override
	public DirectedSynapses<?, ?> getSynapses() {
		return synapses;
	}

}


text:
package org.apache.hedwig.server.handlers;

import java.util.concurrent.ConcurrentHashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFutureListener;

import com.google.protobuf.ByteString;
import org.apache.hedwig.client.data.TopicSubscriber;
import org.apache.hedwig.exceptions.PubSubException;
import org.apache.hedwig.exceptions.PubSubException.ServerNotResponsibleForTopicException;
import org.apache.hedwig.protocol.PubSubProtocol.MessageSeqId;
import org.apache.hedwig.protocol.PubSubProtocol.PubSubRequest;
import org.apache.hedwig.protocol.PubSubProtocol.SubscribeRequest;
import org.apache.hedwig.protoextensions.PubSubResponseUtils;
import org.apache.hedwig.protoextensions.SubscriptionStateUtils;
import org.apache.hedwig.server.common.ServerConfiguration;
import org.apache.hedwig.server.delivery.ChannelEndPoint;
import org.apache.hedwig.server.delivery.DeliveryManager;
import org.apache.hedwig.server.netty.UmbrellaHandler;
import org.apache.hedwig.server.persistence.PersistenceManager;
import org.apache.hedwig.server.subscriptions.SubscriptionManager;
import org.apache.hedwig.server.subscriptions.TrueFilter;
import org.apache.hedwig.server.topics.TopicManager;
import org.apache.hedwig.util.Callback;

public class SubscribeHandler extends BaseHandler implements ChannelDisconnectListener {
    static Logger logger = LoggerFactory.getLogger(SubscribeHandler.class);

    private DeliveryManager deliveryMgr;
    private PersistenceManager persistenceMgr;
    private SubscriptionManager subMgr;
    ConcurrentHashMap<TopicSubscriber, Channel> sub2Channel;
    ConcurrentHashMap<Channel, TopicSubscriber> channel2sub;

    public SubscribeHandler(TopicManager topicMgr, DeliveryManager deliveryManager, PersistenceManager persistenceMgr,
                            SubscriptionManager subMgr, ServerConfiguration cfg) {
        super(topicMgr, cfg);
        this.deliveryMgr = deliveryManager;
        this.persistenceMgr = persistenceMgr;
        this.subMgr = subMgr;
        sub2Channel = new ConcurrentHashMap<TopicSubscriber, Channel>();
        channel2sub = new ConcurrentHashMap<Channel, TopicSubscriber>();
    }

    public void channelDisconnected(Channel channel) {
        // Evils of synchronized programming: there is a race between a channel
        // getting disconnected, and us adding it to the maps when a subscribe
        // succeeds
        synchronized (channel) {
            TopicSubscriber topicSub = channel2sub.remove(channel);
            if (topicSub != null) {
                sub2Channel.remove(topicSub);
            }
        }
    }

    @Override
    public void handleRequestAtOwner(final PubSubRequest request, final Channel channel) {

        if (!request.hasSubscribeRequest()) {
            UmbrellaHandler.sendErrorResponseToMalformedRequest(channel, request.getTxnId(),
                    "Missing subscribe request data");
            return;
        }

        final ByteString topic = request.getTopic();

        MessageSeqId seqId;
        try {
            seqId = persistenceMgr.getCurrentSeqIdForTopic(topic);
        } catch (ServerNotResponsibleForTopicException e) {
            channel.write(PubSubResponseUtils.getResponseForException(e, request.getTxnId())).addListener(
                ChannelFutureListener.CLOSE);
            return;
        }

        final SubscribeRequest subRequest = request.getSubscribeRequest();
        final ByteString subscriberId = subRequest.getSubscriberId();

        MessageSeqId lastSeqIdPublished = MessageSeqId.newBuilder(seqId).setLocalComponent(seqId.getLocalComponent()).build();

        subMgr.serveSubscribeRequest(topic, subRequest, lastSeqIdPublished, new Callback<MessageSeqId>() {

            @Override
            public void operationFailed(Object ctx, PubSubException exception) {
                channel.write(PubSubResponseUtils.getResponseForException(exception, request.getTxnId())).addListener(
                    ChannelFutureListener.CLOSE);
            }

            @Override
            public void operationFinished(Object ctx, MessageSeqId resultOfOperation) {

                TopicSubscriber topicSub = new TopicSubscriber(topic, subscriberId);

                // race with channel getting disconnected while we are adding it
                // to the 2 maps
                synchronized (channel) {
                    if (!channel.isConnected()) {
                        // channel got disconnected while we were processing the
                        // subscribe request,
                        // nothing much we can do in this case
                        return;
                    }

                    if (null != sub2Channel.putIfAbsent(topicSub, channel)) {
                        // there was another channel mapped to this sub
                        PubSubException pse = new PubSubException.TopicBusyException(
                            "subscription for this topic, subscriberId is already being served on a different channel");
                        channel.write(PubSubResponseUtils.getResponseForException(pse, request.getTxnId()))
                        .addListener(ChannelFutureListener.CLOSE);
                        return;
                    } else {
                        // channel2sub is just a cache, so we can add to it
                        // without synchronization
                        channel2sub.put(channel, topicSub);
                    }
                }
                // First write success and then tell the delivery manager,
                // otherwise the first message might go out before the response
                // to the subscribe
                channel.write(PubSubResponseUtils.getSuccessResponse(request.getTxnId()));

                // want to start 1 ahead of the consume ptr
                MessageSeqId seqIdToStartFrom = MessageSeqId.newBuilder(resultOfOperation).setLocalComponent(
                                                    resultOfOperation.getLocalComponent() + 1).build();
                deliveryMgr.startServingSubscription(topic, subscriberId, seqIdToStartFrom,
                                                     new ChannelEndPoint(channel), TrueFilter.instance(), SubscriptionStateUtils
                                                     .isHubSubscriber(subRequest.getSubscriberId()));
            }
        }, null);

    }

}


text:
/**
 * @callback identity
 * @description Grab id from given data. Id is used to make sure data points are unique, no duplication.
 *     This is only interface defination. Default identity function will grab *id* property of given object.
 *     If id of data point isn't *id*. You will need to define your own identity function follow this interface.
 * @param {object} data Data to grab id.
 * @return {string} id
 */

/**
 * @callback mapfunc
 * @description Mapping function
 * @param {T} data Data received
 * @return {?T} If return, then map will create a new data store.
 *     If you don't make any change, return nothing.
 * @template T
 */

/**
 * @callback mapperfunc
 * @description Iterator over native data store object.
 * @param {T} data Native data store object
 * @return {T} Return new object if any change.
 * @template T
 */

/**
 * @class ImmutableObjectType
 * @description Leaf node data type tool for native object. Behaves like immutable map
 * @param {identity} [identity] function to get data id
 * @template T
 * @inner
 */
class ImmutableObjectType {
  cons: any;
  identity: (any) => string;
  constructor (identity?: (any) => string) {
    this.cons = Object;
    this.identity = identity || function (obj) { return obj.id; }
  }
  /**
   * @method add
   * @description Add data to the object
   * @param {Object} obj The data store native object
   * @param {T} data Data to store to the object
   * @return {Object} Return new object if any change, original object if no change
   * @memberof ImmutableObjectType
   */
  add (obj, data: Array<any>) {
    if (!data) { return obj; }
    if (!Array.isArray(data)) { data = [data]; }

    var i, id, flag = false;
    var newobj = (<any>Object).assign({}, obj);

    for (i = 0; i < data.length; i++) {
      id = this.identity(data[i]);
      if (!obj[id]) {
        newobj[id] = data[i];
        flag = true;
      }
    }
    if (flag) { return newobj; }
    //no change
    return obj;
  }
  /**
   * @method remove
   * @description Remove data from the object
   * @param {Object} obj The data store native object
   * @param {T} data Data to remove from the object
   * @return {Object} Return new object if any change, original object if no change
   * @memberof ImmutableObjectType
   */
  remove (obj, data: Array<any>) {
    if (!data) { return obj; }
    if (!Array.isArray(data)) { data = [data]; }

    var i, id, flag = false;
    var newobj = (<any>Object).assign({}, obj);

    for (i = 0; i < data.length; i++) {
      id = this.identity(data[i]);
      if (obj[id]) {
        newobj[id] = null;
        delete newobj[id];
        flag = true;
      }
    }
    if (flag) { return newobj; }
    //no change
    return obj;
  }
  /**
   * @method map
   * @description Map f function on all data, behaves like immutable.
   * @param {mapfunc} f Mapping function
   * @return {mapperfunc} Function iterator over data store object
   * @memberof ImmutableObjectType
   */
  map (f: (any) => any): (Object) => Object {
    return function (obj) {
      var k, newv, newobj;
      for (k in obj) {
        if (obj[k]) {
          newv = f(obj[k]);
          if (newv && newv !== obj[k]) {
            if (!newobj) {
              newobj = (<any>Object).assign({}, obj);
            }
            newobj[k] = newv;
          }
        }
      }
      return newobj || obj;
    }
  }
};


text:
import simplegui
# define global variables
cntr,x,y = 0,0,0
timer_has_been_stopped = None

# define helper function format that converts time
# in tenths of seconds into formatted string A:BC.D
def format(t):
    A = t // 600
    B = (t%600)//100
    C = (t%100)//10
    D = t%10

    return str(A)+":"+str(B)+str(C)+"."+str(D)

# define event handlers for buttons; "Start", "Stop", "Reset"
def start_handler():
    global timer_has_been_stopped
    timer.start()
    timer_has_been_stopped = False

def stop_handler():
    global y,x,timer_has_been_stopped
    timer.stop()
    if(timer_has_been_stopped == False):
        y +=1
        timer_has_been_stopped=True
    	if(cntr % 10 == 0):
        	x+=1

def reset_handler():
    global cntr,x,y
    timer.stop()
    cntr,x,y = 0,0,0

# define event handler for timer with 0.1 sec interval
def timer_handler():
    global cntr
    cntr += 1
    #print cntr

# define draw handler
def draw_handler(canvas):
    global x,y
    canvas.draw_text(format(cntr),[50,100],40,"Red")
    canvas.draw_text(str(x)+"/"+str(y),[130,25],25,"Green")

# create frame
frame = simplegui.create_frame("Stop watch",180,180)

# register event handlers
timer =  simplegui.create_timer(100,timer_handler)
startbutton = frame.add_button("Start",start_handler,150)
stopbutton = frame.add_button("Stop",stop_handler,150)
resetbutton = frame.add_button("Reset",reset_handler,150)
frame.set_draw_handler(draw_handler)

# start frame
#timer.start()
frame.start()

# Please remember to review the grading rubric


text:
class AccessoryController {
 public:
  virtual ~AccessoryController() = default;

  // Triggered when a user selects an item for filling. This handler is
  // responsible for propagating it so that it ultimately ends up in the form
  // in the content area.
  virtual void OnFillingTriggered(
      const autofill::UserInfo::Field& selection) = 0;

  // Triggered when a user selects an option.
  virtual void OnOptionSelected(autofill::AccessoryAction selected_action) = 0;

  // Triggered when a user changes a toggle.
  virtual void OnToggleChanged(autofill::AccessoryAction toggled_action,
                               bool enabled) = 0;
};

#endif  // CHROME_BROWSER_AUTOFILL_ACCESSORY_CONTROLLER_H_


text:
import doctest_simple

if __name__ == '__main__':
    import doctest
    doctest.testmod(doctest_simple)


text:
package mongodb.sample03;

import java.net.UnknownHostException;
import java.util.Arrays;

import com.mongodb.*;

/**
 * Hello world!
 *
 */
public class App
{
    public static void main( String[] args ) throws UnknownHostException, InterruptedException
    {
        MongoClient client = new MongoClient(new ServerAddress("localhost", 30001));
        DBCollection collection = client.getDB("replica_test").getCollection("ids");
        collection.drop();

        for (int i = 0; i < Integer.MAX_VALUE; i++) {
        	try {
        		collection.insert(new BasicDBObject("_id", i));
        		System.out.println("Inserted : " + i);
        	}
        	catch (Exception exception) {
        		System.out.println(exception.getMessage());
        	}
        	Thread.sleep(500);
        }
    }
}


text:
<!doctype html>

<meta charset="utf-8">
<title>Using a remote server to build your Scala projects – Pere Villega</title>
<meta name="description" content="">
<meta name="keywords" content="scala, sbt, vscode, ssh, remote, linode, triplequote">

<meta name="twitter:title" content="Using a remote server to build your Scala projects – Pere Villega">
<meta name="twitter:description" content="VS Code has released tooling for remote development via ssh. In Scala the combo of Metals and VS Code for development...">
<meta name="twitter:creator" content="@pvillega">

<meta name="twitter:card" content="summary">
<meta name="twitter:image:src" content="/images/default-thumb.png">
<meta property="og:type" content="article">
<meta property="og:image" content="/images/default-thumb.png">

<meta property="og:locale" content="en_US">
<meta property="og:title" content="Using a remote server to build your Scala projects – Pere Villega">
<meta property="og:description" content="VS Code has released tooling for remote development via ssh. In Scala the combo of Metals and VS Code for development...">
<meta property="og:url" content="/remote-build-servers-with-vs-code-and-metals">
<meta property="og:site_name" content="Pere Villega">

<meta name="google-site-verification" content="bkCiO-bEhrfzDurtD6X772P1JroB8Q_Hb_I_AVSXqIE">
<meta name="msvalidate.01" content="A144448522476B8417CB74945AA3E085">

<link rel="canonical" href="/remote-build-servers-with-vs-code-and-metals">
<link href="/feed.xml" type="application/atom+xml" rel="alternate" title="Pere Villega Feed">

<meta name="HandheldFriendly" content="True">
<meta name="MobileOptimized" content="320">
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<link href='http://fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700|PT+Serif:400,700,400italic' rel='stylesheet' type='text/css'>

<link rel="stylesheet" href="/assets/css/main.css">

<meta http-equiv="cleartype" content="on">

<link rel="shortcut icon" href="/favicon.ico">

<link rel="shortcut icon" href="/favicon.png">

<link rel="apple-touch-icon-precomposed" href="/images/apple-touch-icon-precomposed.png">

<link rel="apple-touch-icon-precomposed" sizes="72x72" href="/images/apple-touch-icon-72x72-precomposed.png">

<link rel="apple-touch-icon-precomposed" sizes="114x114" href="/images/apple-touch-icon-114x114-precomposed.png">

<link rel="apple-touch-icon-precomposed" sizes="144x144" href="/images/apple-touch-icon-144x144-precomposed.png">

		Pere Villega

About

Articles

Projects

 Feed

Pere Villega

If at first you don't succeed; call it version 1.0

 Email

 Twitter

 LinkedIn

 Github

Using a remote server to build your Scala projects

VS Code has released tooling for remote development via ssh. In Scala the combo of Metals and VS Code for development has become the norm for many people. How easy and convenient may it be to use them while on ssh with a remote server? Let's discover it.

Why would someone do that

First of all we should tackle an obvious question: why would a developer do that? The answer is that there are many valid scenarios for this approach:

someone may work in a big corporation that gives lower-end Windows laptops, but has several servers available for developers to use

someone may not have enough budget to replace their aging laptop, and it is looking at the cloud as a cheaper alternative

an employer has Intellectual Property concerns and would like tight controls on where is the codebase cloned to

a developer uses mainly a desktop and they don't want to buy a powerful laptop, but recently they need to travel more and still code

a developer is fed up with seeing iStats show 90+ C degrees on the cpu sensor of their laptop, sustained while sbt compiles the project

Or, if none of them applies, just because we can. We'll talk about cost-effectiveness of this approach towards the end of the post.

Setting up your environment

To make this work you will need:

a local machine capable of running Visual Studio Code.

a remote server, preferably with Linux (we use Ubuntu 20.04 LTS).

to read and follow the steps in this post, adapting as needed if you use a different OS on your remote host.

The requirements for Visual Studio Code are quite low, remember that the heavy lifting (compiling) won't be done in the local machine, so even old laptops should work fine.

Ideally you have some internet exposed desktop or server that you can use as the remote host. If you don't have any at hand, look at a VPS service like Linode or Hetzner. We'd recommend against AWS or GCP as they seem to be more expensive for worse performance. This post will use Linode, for no other reason that we used it in the past and we were happy with it. No affiliation with the brand.

Important note: if you are creating a new account in a VPS, expect to provide a valid credit card number to cover for the costs of any usage. There may also be a delay while they verify your account details; a new account via a UK-based Ltd company with Linode took 30m to be verified.

Creating your remote developer instance

First of all, provision an instance for the server if you need it. We use Linode Dedicated CPU instances as they are supposed to have better CPU performance. You can follow these steps to create one. We chose the following settings:

OS: Ubuntu 20.04 LTS

Region: London

Plan: Dedicated 8 Gb (4 cores, 8 Gb RAM)

Provide root password and ssh key for your local machine

Provisioning takes around one minute, and then you can ssh into the box with ssh root@<ip>.

Important note: on new accounts with Linode, you need to open a ticket with support to enable Dedicated 16 Gb and Dedicated 32 Gb Linode for your account. Otherwise you won't be allowed to create those instances. Other VPS may have similar rules.

Once the machine is up, ssh into it. The next step is to install a valid JDK. You can use Adopt OpenJDK by running the following:

> wget -qO - https://adoptopenjdk.jfrog.io/adoptopenjdk/api/gpg/key/public | sudo apt-key add
> add-apt-repository --yes https://adoptopenjdk.jfrog.io/adoptopenjdk/deb/
> apt-get update
> apt-get install adoptopenjdk-11-hotspot

Then edit your .profile and add an export for JAVA_HOME to it:

export JAVA_HOME='/usr/lib/jvm/adoptopenjdk-11-hotspot-amd64/'

We also want to increase the number of file descriptors available to avoid issues with VS Code and large projects. To that end, edit /etc/sysctl.conf
and add to the bottom of the file fs.inotify.max_user_watches=524288 and run sysctl -p to reapply the changes.

We also want sbt and npm (for scala.js), which we can install as follows:

> echo "deb https://dl.bintray.com/sbt/debian /" | sudo tee -a /etc/apt/sources.list.d/sbt.list
> apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 2EE0EA64E40A89B84B2DF73499E82A75642AC823
> apt-get update
> apt-get -y install sbt npm

To be able to work with Github, you will need to add the ssh public key of this instance to your profile. To generate a key, run:

> ssh-keygen -t rsa -b 4096 -C "your_email@example.com"  # don't add a password
> cat ~/.ssh/id_rsa.pub

Copy the output of the last command and add it to your SSH key list in Github.

As the last step, clone the repository of cats so that we can run some tests on it later:

git clone git@github.com:typelevel/cats.git

With these, your remote server should be ready to run scala code. As the next step, we need to connect a VS Code instance to it.

Connecting Visual Studio Code

Open your VS Code and install the extension Remote - SSH.
Then follow the official documentation to connect to the remote server:

open the Remote Explorer menu and add your server

once configured, you can connect to the server. This will open a new VS Code window. The bottom panel will show (on the left side) that you are connected to a remote server

extensions are (usually) installed on the server, which means you will need to reinstall Metals. Open the Extensions panel, in there you will see that extensions are split between local and ssh. Scroll the local list and press the green install in ssh button for all those extensions you want to enable on your remote machine.

if you haven't done so, search for Metals and install it. Then reload the window.

Edit VS Code settings for Metals, on the ssh section for your remote machine set the proper path for Java Home in Metals (see previous section of this post for the path). This will require another reload of VS Code.

If you installed the Live Share extension, you may be prompted to install additional components, which requires yet another window refresh.

Loading your project

Once the VS Code window has reloaded and reconnected to the server, you can just go to File > Open and select the cats project you cloned when setting up the server.
Metals will let you know that this is an sbt project and it will request to load it.

That's it. Once Metals completes the set up, you are ready to go and code as you are used to.

Important: Note that any terminal you open while in the ssh window will open directly in the remote server.

Backing up your remote server

At this point you want to create an image of your server. Note that Linode (and most other platforms) will still charge you for the box if you stop it, as it is still provisioned for you.

To reduce costs what you want is to have an image with the latest changes to your server, which you can do following these steps. Building the image took less than 2 minutes for our server. Once you have the image, you can delete your instance and create a new one when needed, using that image as a starting point. The image will keep the same ssh public key, which means you can interact with Github using your account without any additional steps.

Note that in Linode you have some restrictions on images but even so this should be enough for your purposes. Alternatively, you could use Stack Scripts or some other automated system to create images on demand.

Performance

Now that we have everything set up, we need to verify how fast is this setup. How does it compare to running everything locally? To test this we downloaded cats and we run ;clean;test in sbt a few times. The following is a completely non-scientific table of the measurements:

      Machine
      Avg

      Macbook 16" late 2019 (8 cores)
      3:28

      Linode 4 cores
      Error

      Linode 8 cores
      11:48

      Linode 16 cores
      4:46

All Linode instances are 'Dedicated CPU' instances. On the 'Linode 4' instance,sbt was often killed by the OS when running alongside VS Code.

Let's be realistic, the performance is worse. The fastest Linode test, using the 16 cores machine, is over 1 minute slower than a test using a local environment. Unless you have a remote server you own and with a decent cpu, you are going to lose at least some performance. But it's not too terrible.

Enter Hydra

Remember that we are trying to find a way to run compilation in remote servers for cases where a local setup is not an option. Maybe we can improve on it? Triplequote offers Hydra, a parallel compiler for Scala. This would increase costs, but can this turn it into a viable alternative?

We followed the instructions for a trial with Hydra and we run the tests again in Linode. The trial license uses a Developer (Enterprise) license which can take advantage of up to 8 cores.

      Machine (with Hydra)
      Avg

      Linode 8 cores
      6:39

      Linode 16 cores
      1:30

We can see Hydra makes a big difference as it is able to take advantage of the number of cores available. In the lower spec Linode we halve the compile time, while in the Linode with 16 cores we compile cats in a third of the time it originally took. The improvements would be similar in a local setup, but let's remember that we are looking at scenarios where you need (want) to use a remote setup.

Cost of the setup

A MacBook Pro 16" 2019, with the maximum RAM (64 Gb) and CPU (8 core 2.4 Ghz) currently costs $3,799.00, taxes aside. Other non-Apple laptops and desktops will be cheaper, but I use this as a reference as it is the one many companies give to their developers, so it is a fair benchmark for comparison.

A Linode (Dedicated CPU) with 8 cores and 16 Gb RAM costs $0.18/hr. For a standard work schedule of 45h per week and 50 weeks per year (and you should really work less than that), it adds up to $8.1 per week, and $405 for the year. Assuming the same use pattern, a Linode with 16 cores and 32 Gb of RAM ($0.36/hr) costs twice as much: $16.2 per week, $910 per year.

A Developer - Enterprise license for Hydra costs $1,080/year per seat, to take advantage of up to 8 cores.

The slower Linode with 8 cores, with Hydra, would cost $1,485/year but it is twice as slow as the laptop we compare it with, which makes it a less appealing choice. Without Hydra the compilation times become too high to even consider it as an option.

But with the Linode 16 cores the story changes, as the performance is closer to what we get with a local machine. You could pay $910 for the Linode instance and get compile times around 30% slower, but at 25% of the cost of the laptop. Or, if you add Hydra and increase the cost to $1,990, you can be 60% faster than the laptop for around 50% of the price.

Conclusions

Is it cloud computing ready to become your development server? As with most things in development, it depends. If you need to squeeze every bit of performance
from your machines, then a local setup is still preferred. And you should get a Hydra license, period.

But if not, you can get reasonable performance from dedicated machines. A Linode with 16 cores and without Hydra is a quarter of the price of a top of the shelf laptop,
and you still get reasonable performance. If you add Hydra on top, then we are looking at remote setups that outperform a local setup, while costing you less upfront. A hard-to-beat proposition.

There are multiple caveats, of course. For example, the SSH extension for Visual Studio Code is still on preview and there may be glitches. Also, things that are easily achieved with a local workflow may be slightly more complicated with a remote one.

But not many project will be as demanding as cats for compilation, due to its multiple compile targets. And there are other possible benefits, like being to replace docker services running locally by ones in remote servers, reducing pressure on the computer even more. Given that we would expect costs for
cloud computing to decrease as time goes by, this setup can only become better as time goes by. Yes, it is unlikely to beat a local setup on raw performance, but sometimes that is not the only constraint.

That's all for now, I hope this was informative and useful. As always, feedback via Twitter/Email is more than welcome. Cheers!

Pere Villega

If at first you don't succeed; call it version 1.0

 Email

 Twitter

 LinkedIn

 Github

Using a remote server to build your Scala projects was published on <time datetime="2020-05-09T20:00:00+01:00" itemprop="datePublished">May 09, 2020</time> by Pere Villega.

You might also enjoy (View all articles)

© 2020 Pere Villega. Powered by Jekyll using the Minimal Mistakes theme.


text:
package com.google.android.gms.wearable.internal;

import org.microg.safeparcel.AutoSafeParcelable;
import org.microg.safeparcel.SafeParceled;

public class GetChannelInputStreamResponse extends AutoSafeParcelable {
    @SafeParceled(1)
    private int versionCode = 1;
    public static final Creator<GetChannelInputStreamResponse> CREATOR = new AutoCreator<GetChannelInputStreamResponse>(GetChannelInputStreamResponse.class);
}


text:
sPwd=`pwd`

echo $sPwd

# sanity check. CORE | www | html | public
if [[ "$sPwd" != *"libs/PHPCore/cli"* ]] || [[ "$sPwd" != *"www"* ]] || [[ "$sPwd" != *"html"* ]] || [[ "$sPwd" != *"public"* ]]
    then
        echo "Must be run inside CORE."
        exit 0
fi

# get back to vHost root.
cd "${sPwd}"/../../../

# get vhost root
sVHostRoot=`pwd`

# permissions
chmod -f 775 "$sVHostRoot"
chmod -f 775 "$sVHostRoot/classes"
chmod -f 775 "$sVHostRoot/cli"
chmod -fR 750 "$sVHostRoot/configs"
chmod -f 775 "$sVHostRoot/css"
chmod -f 775 "$sVHostRoot/docs"
chmod -fR 750 "$sVHostRoot/files"
chmod -f 775 "$sVHostRoot/img"
chmod -f 775 "$sVHostRoot/includes"
chmod -f 775 "$sVHostRoot/js"
chmod -f 775 "$sVHostRoot/libs"
chmod -fR 750 "$sVHostRoot/logs"
chmod -f 750 "$sVHostRoot/media"
chmod -f 775 "$sVHostRoot/templates"
chmod -f 775 "$sVHostRoot/tests"
chmod -f 775 "$sVHostRoot/configs/app.xml"
chmod -f 775 "$sVHostRoot/configs/contacts.xml"
chmod -f 775 "$sVHostRoot/configs/hosts.xml"
chmod -f 775 "$sVHostRoot/.htaccess"
chmod -f 775 "$sVHostRoot/config.php"
chmod -f 775 "$sVHostRoot/index.php"

# ownership
chown -f apache:webdev "$sVHostRoot"
chown -f apache:webdev "$sVHostRoot/classes"
chown -f apache:webdev "$sVHostRoot/cli"
chown -fR apache:webdev "$sVHostRoot/configs"
chown -f apache:webdev "$sVHostRoot/css"
chown -f apache:webdev "$sVHostRoot/docs"
chown -fR apache:webdev "$sVHostRoot/files"
chown -f apache:webdev "$sVHostRoot/img"
chown -f apache:webdev "$sVHostRoot/includes"
chown -f apache:webdev "$sVHostRoot/js"
chown -f apache:webdev "$sVHostRoot/libs"
chown -fR apache:webdev "$sVHostRoot/logs"
chown -f apache:webdev "$sVHostRoot/media"
chown -f apache:webdev "$sVHostRoot/templates"
chown -f apache:webdev "$sVHostRoot/tests"
chown -f apache:webdev "$sVHostRoot/configs/app.xml"
chown -f apache:webdev "$sVHostRoot/configs/contacts.xml"
chown -f apache:webdev "$sVHostRoot/configs/hosts.xml"
chown -f apache:webdev "$sVHostRoot/.htaccess"
chown -f apache:webdev "$sVHostRoot/config.php"
chown -f apache:webdev "$sVHostRoot/index.php"


text:
The name actually only tells half the story. This plugin lets you:

1. Hide uploads of definable filetypes behind a hash/timestamp/filename combination. Uploads are not stored in the standard path (public/uploads). This ensures, that even when the filename is known, it's pretty hard to guess its location.

2. Set an expiration time(range) for those hash/timestamp/filename urls. Every setting > 0 will have uploads handled by this plugin expire.

**PLEASE NOTE**: Expiration is calculated at request time. If you uploaded a file 7 days ago and now decide to lower the expiration time from 10 to 5 days, this file will be treated as expired.

## Installation
1. `npm install nodebb-plugin-expiring-uploads`

2. Activate the plugin in the ACP.

3. Adjust the settings! Standard expiration time is 0 = uploads never expire.


text:
<?xml version="1.0" encoding="utf-8"?>
<doctrine-mapping xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mapping http://doctrine-project.org/schemas/orm/doctrine-mapping.xsd">
  <entity name="Mangocele\coreBundle\Entity\ProductosImg" table="productos_img">
    <indexes>
      <index name="id_producto_idx" columns="id_producto"/>
    </indexes>
    <unique-constraints>
      <unique-constraint name="id_p_imagen_UNIQUE" columns="id_p_imagen"/>
    </unique-constraints>
    <id name="idPImagen" type="integer" column="id_p_imagen">
      <generator strategy="IDENTITY"/>
    </id>
    <field name="urlImagen" type="string" column="url_imagen" length="45" nullable="true"/>
    <field name="tipoImagen" type="string" column="tipo_imagen" length="45" nullable="true"/>
    <many-to-one field="idProducto" target-entity="Productos">
      <join-columns>
        <join-column name="id_producto" referenced-column-name="id"/>
      </join-columns>
    </many-to-one>
  </entity>
</doctrine-mapping>


text:
package org.lwjgl.vulkan;

import javax.annotation.*;

import java.nio.*;

import org.lwjgl.*;
import org.lwjgl.system.*;

import static org.lwjgl.system.MemoryUtil.*;
import static org.lwjgl.system.MemoryStack.*;

/**
 * Structure describing a Win32 handle semaphore export operation.
 *
 *
Description

 *
 *
The properties of the handle returned depend on the value of {@code handleType}. See {@code VkExternalSemaphoreHandleTypeFlagBits} for a description of the properties of the defined external semaphore handle types.

 *
 *
Valid Usage

 *
 *

 *
{@code handleType} must have been included in {@link VkExportSemaphoreCreateInfo}{@code ::handleTypes} when the {@code semaphore}'s current payload was created

 *
If {@code handleType} is defined as an NT handle, {@link KHRExternalSemaphoreWin32#vkGetSemaphoreWin32HandleKHR GetSemaphoreWin32HandleKHR} must be called no more than once for each valid unique combination of {@code semaphore} and {@code handleType}

 *
{@code semaphore} must not currently have its payload replaced by an imported payload as described below in Importing Semaphore Payloads unless that imported payload's handle type was included in {@link VkExternalSemaphoreProperties}{@code ::exportFromImportedHandleTypes} for {@code handleType}

 *
If {@code handleType} refers to a handle type with copy payload transference semantics, as defined below in Importing Semaphore Payloads, there must be no queue waiting on {@code semaphore}

 *
If {@code handleType} refers to a handle type with copy payload transference semantics, {@code semaphore} must be signaled, or have an associated semaphore signal operation pending execution

 *
{@code handleType} must be defined as an NT handle or a global share handle

 *

 *
 *
Valid Usage (Implicit)

 *
 *

 *
{@code sType} must be {@link KHRExternalSemaphoreWin32#VK_STRUCTURE_TYPE_SEMAPHORE_GET_WIN32_HANDLE_INFO_KHR STRUCTURE_TYPE_SEMAPHORE_GET_WIN32_HANDLE_INFO_KHR}

 *
{@code pNext} must be {@code NULL}

 *
{@code semaphore} must be a valid {@code VkSemaphore} handle

 *
{@code handleType} must be a valid {@code VkExternalSemaphoreHandleTypeFlagBits} value

 *

 *
 *
See Also

 *
 *
{@link KHRExternalSemaphoreWin32#vkGetSemaphoreWin32HandleKHR GetSemaphoreWin32HandleKHR}

 *
 *
Layout

 *
 *

 * struct VkSemaphoreGetWin32HandleInfoKHR {
 *     VkStructureType {@link #sType};
 *     void const * {@link #pNext};
 *     VkSemaphore {@link #semaphore};
 *     VkExternalSemaphoreHandleTypeFlagBits {@link #handleType};
 * }

 */
public class VkSemaphoreGetWin32HandleInfoKHR extends Struct implements NativeResource {

    /** The struct size in bytes. */
    public static final int SIZEOF;

    /** The struct alignment in bytes. */
    public static final int ALIGNOF;

    /** The struct member offsets. */
    public static final int
        STYPE,
        PNEXT,
        SEMAPHORE,
        HANDLETYPE;

    static {
        Layout layout = __struct(
            __member(4),
            __member(POINTER_SIZE),
            __member(8),
            __member(4)
        );

        SIZEOF = layout.getSize();
        ALIGNOF = layout.getAlignment();

        STYPE = layout.offsetof(0);
        PNEXT = layout.offsetof(1);
        SEMAPHORE = layout.offsetof(2);
        HANDLETYPE = layout.offsetof(3);
    }

    /**
     * Creates a {@code VkSemaphoreGetWin32HandleInfoKHR} instance at the current position of the specified {@link ByteBuffer} container. Changes to the buffer's content will be
     * visible to the struct instance and vice versa.
     *
     *
The created instance holds a strong reference to the container object.

     */
    public VkSemaphoreGetWin32HandleInfoKHR(ByteBuffer container) {
        super(memAddress(container), __checkContainer(container, SIZEOF));
    }

    @Override
    public int sizeof() { return SIZEOF; }

    /** the type of this structure. */
    @NativeType("VkStructureType")
    public int sType() { return nsType(address()); }
    /** {@code NULL} or a pointer to a structure extending this structure. */
    @NativeType("void const *")
    public long pNext() { return npNext(address()); }
    /** the semaphore from which state will be exported. */
    @NativeType("VkSemaphore")
    public long semaphore() { return nsemaphore(address()); }
    /** a {@code VkExternalSemaphoreHandleTypeFlagBits} value specifying the type of handle requested. */
    @NativeType("VkExternalSemaphoreHandleTypeFlagBits")
    public int handleType() { return nhandleType(address()); }

    /** Sets the specified value to the {@link #sType} field. */
    public VkSemaphoreGetWin32HandleInfoKHR sType(@NativeType("VkStructureType") int value) { nsType(address(), value); return this; }
    /** Sets the {@link KHRExternalSemaphoreWin32#VK_STRUCTURE_TYPE_SEMAPHORE_GET_WIN32_HANDLE_INFO_KHR STRUCTURE_TYPE_SEMAPHORE_GET_WIN32_HANDLE_INFO_KHR} value to the {@link #sType} field. */
    public VkSemaphoreGetWin32HandleInfoKHR sType$Default() { return sType(KHRExternalSemaphoreWin32.VK_STRUCTURE_TYPE_SEMAPHORE_GET_WIN32_HANDLE_INFO_KHR); }
    /** Sets the specified value to the {@link #pNext} field. */
    public VkSemaphoreGetWin32HandleInfoKHR pNext(@NativeType("void const *") long value) { npNext(address(), value); return this; }
    /** Sets the specified value to the {@link #semaphore} field. */
    public VkSemaphoreGetWin32HandleInfoKHR semaphore(@NativeType("VkSemaphore") long value) { nsemaphore(address(), value); return this; }
    /** Sets the specified value to the {@link #handleType} field. */
    public VkSemaphoreGetWin32HandleInfoKHR handleType(@NativeType("VkExternalSemaphoreHandleTypeFlagBits") int value) { nhandleType(address(), value); return this; }

    /** Initializes this struct with the specified values. */
    public VkSemaphoreGetWin32HandleInfoKHR set(
        int sType,
        long pNext,
        long semaphore,
        int handleType
    ) {
        sType(sType);
        pNext(pNext);
        semaphore(semaphore);
        handleType(handleType);

        return this;
    }

    /**
     * Copies the specified struct data to this struct.
     *
     * @param src the source struct
     *
     * @return this struct
     */
    public VkSemaphoreGetWin32HandleInfoKHR set(VkSemaphoreGetWin32HandleInfoKHR src) {
        memCopy(src.address(), address(), SIZEOF);
        return this;
    }

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

    /** Returns a new {@code VkSemaphoreGetWin32HandleInfoKHR} instance allocated with {@link MemoryUtil#memAlloc memAlloc}. The instance must be explicitly freed. */
    public static VkSemaphoreGetWin32HandleInfoKHR malloc() {
        return wrap(VkSemaphoreGetWin32HandleInfoKHR.class, nmemAllocChecked(SIZEOF));
    }

    /** Returns a new {@code VkSemaphoreGetWin32HandleInfoKHR} instance allocated with {@link MemoryUtil#memCalloc memCalloc}. The instance must be explicitly freed. */
    public static VkSemaphoreGetWin32HandleInfoKHR calloc() {
        return wrap(VkSemaphoreGetWin32HandleInfoKHR.class, nmemCallocChecked(1, SIZEOF));
    }

    /** Returns a new {@code VkSemaphoreGetWin32HandleInfoKHR} instance allocated with {@link BufferUtils}. */
    public static VkSemaphoreGetWin32HandleInfoKHR create() {
        ByteBuffer container = BufferUtils.createByteBuffer(SIZEOF);
        return wrap(VkSemaphoreGetWin32HandleInfoKHR.class, memAddress(container), container);
    }

    /** Returns a new {@code VkSemaphoreGetWin32HandleInfoKHR} instance for the specified memory address. */
    public static VkSemaphoreGetWin32HandleInfoKHR create(long address) {
        return wrap(VkSemaphoreGetWin32HandleInfoKHR.class, address);
    }

    /** Like {@link #create(long) create}, but returns {@code null} if {@code address} is {@code NULL}. */
    @Nullable
    public static VkSemaphoreGetWin32HandleInfoKHR createSafe(long address) {
        return address == NULL ? null : wrap(VkSemaphoreGetWin32HandleInfoKHR.class, address);
    }

    /**
     * Returns a new {@link VkSemaphoreGetWin32HandleInfoKHR.Buffer} instance allocated with {@link MemoryUtil#memAlloc memAlloc}. The instance must be explicitly freed.
     *
     * @param capacity the buffer capacity
     */
    public static VkSemaphoreGetWin32HandleInfoKHR.Buffer malloc(int capacity) {
        return wrap(Buffer.class, nmemAllocChecked(__checkMalloc(capacity, SIZEOF)), capacity);
    }

    /**
     * Returns a new {@link VkSemaphoreGetWin32HandleInfoKHR.Buffer} instance allocated with {@link MemoryUtil#memCalloc memCalloc}. The instance must be explicitly freed.
     *
     * @param capacity the buffer capacity
     */
    public static VkSemaphoreGetWin32HandleInfoKHR.Buffer calloc(int capacity) {
        return wrap(Buffer.class, nmemCallocChecked(capacity, SIZEOF), capacity);
    }

    /**
     * Returns a new {@link VkSemaphoreGetWin32HandleInfoKHR.Buffer} instance allocated with {@link BufferUtils}.
     *
     * @param capacity the buffer capacity
     */
    public static VkSemaphoreGetWin32HandleInfoKHR.Buffer create(int capacity) {
        ByteBuffer container = __create(capacity, SIZEOF);
        return wrap(Buffer.class, memAddress(container), capacity, container);
    }

    /**
     * Create a {@link VkSemaphoreGetWin32HandleInfoKHR.Buffer} instance at the specified memory.
     *
     * @param address  the memory address
     * @param capacity the buffer capacity
     */
    public static VkSemaphoreGetWin32HandleInfoKHR.Buffer create(long address, int capacity) {
        return wrap(Buffer.class, address, capacity);
    }

    /** Like {@link #create(long, int) create}, but returns {@code null} if {@code address} is {@code NULL}. */
    @Nullable
    public static VkSemaphoreGetWin32HandleInfoKHR.Buffer createSafe(long address, int capacity) {
        return address == NULL ? null : wrap(Buffer.class, address, capacity);
    }

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

    /** Deprecated for removal in 3.4.0. Use {@link #malloc(MemoryStack)} instead. */
    @Deprecated public static VkSemaphoreGetWin32HandleInfoKHR mallocStack() { return malloc(stackGet()); }
    /** Deprecated for removal in 3.4.0. Use {@link #calloc(MemoryStack)} instead. */
    @Deprecated public static VkSemaphoreGetWin32HandleInfoKHR callocStack() { return calloc(stackGet()); }
    /** Deprecated for removal in 3.4.0. Use {@link #malloc(MemoryStack)} instead. */
    @Deprecated public static VkSemaphoreGetWin32HandleInfoKHR mallocStack(MemoryStack stack) { return malloc(stack); }
    /** Deprecated for removal in 3.4.0. Use {@link #calloc(MemoryStack)} instead. */
    @Deprecated public static VkSemaphoreGetWin32HandleInfoKHR callocStack(MemoryStack stack) { return calloc(stack); }
    /** Deprecated for removal in 3.4.0. Use {@link #malloc(int, MemoryStack)} instead. */
    @Deprecated public static VkSemaphoreGetWin32HandleInfoKHR.Buffer mallocStack(int capacity) { return malloc(capacity, stackGet()); }
    /** Deprecated for removal in 3.4.0. Use {@link #calloc(int, MemoryStack)} instead. */
    @Deprecated public static VkSemaphoreGetWin32HandleInfoKHR.Buffer callocStack(int capacity) { return calloc(capacity, stackGet()); }
    /** Deprecated for removal in 3.4.0. Use {@link #malloc(int, MemoryStack)} instead. */
    @Deprecated public static VkSemaphoreGetWin32HandleInfoKHR.Buffer mallocStack(int capacity, MemoryStack stack) { return malloc(capacity, stack); }
    /** Deprecated for removal in 3.4.0. Use {@link #calloc(int, MemoryStack)} instead. */
    @Deprecated public static VkSemaphoreGetWin32HandleInfoKHR.Buffer callocStack(int capacity, MemoryStack stack) { return calloc(capacity, stack); }

    /**
     * Returns a new {@code VkSemaphoreGetWin32HandleInfoKHR} instance allocated on the specified {@link MemoryStack}.
     *
     * @param stack the stack from which to allocate
     */
    public static VkSemaphoreGetWin32HandleInfoKHR malloc(MemoryStack stack) {
        return wrap(VkSemaphoreGetWin32HandleInfoKHR.class, stack.nmalloc(ALIGNOF, SIZEOF));
    }

    /**
     * Returns a new {@code VkSemaphoreGetWin32HandleInfoKHR} instance allocated on the specified {@link MemoryStack} and initializes all its bits to zero.
     *
     * @param stack the stack from which to allocate
     */
    public static VkSemaphoreGetWin32HandleInfoKHR calloc(MemoryStack stack) {
        return wrap(VkSemaphoreGetWin32HandleInfoKHR.class, stack.ncalloc(ALIGNOF, 1, SIZEOF));
    }

    /**
     * Returns a new {@link VkSemaphoreGetWin32HandleInfoKHR.Buffer} instance allocated on the specified {@link MemoryStack}.
     *
     * @param stack    the stack from which to allocate
     * @param capacity the buffer capacity
     */
    public static VkSemaphoreGetWin32HandleInfoKHR.Buffer malloc(int capacity, MemoryStack stack) {
        return wrap(Buffer.class, stack.nmalloc(ALIGNOF, capacity * SIZEOF), capacity);
    }

    /**
     * Returns a new {@link VkSemaphoreGetWin32HandleInfoKHR.Buffer} instance allocated on the specified {@link MemoryStack} and initializes all its bits to zero.
     *
     * @param stack    the stack from which to allocate
     * @param capacity the buffer capacity
     */
    public static VkSemaphoreGetWin32HandleInfoKHR.Buffer calloc(int capacity, MemoryStack stack) {
        return wrap(Buffer.class, stack.ncalloc(ALIGNOF, capacity, SIZEOF), capacity);
    }

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

    /** Unsafe version of {@link #sType}. */
    public static int nsType(long struct) { return UNSAFE.getInt(null, struct + VkSemaphoreGetWin32HandleInfoKHR.STYPE); }
    /** Unsafe version of {@link #pNext}. */
    public static long npNext(long struct) { return memGetAddress(struct + VkSemaphoreGetWin32HandleInfoKHR.PNEXT); }
    /** Unsafe version of {@link #semaphore}. */
    public static long nsemaphore(long struct) { return UNSAFE.getLong(null, struct + VkSemaphoreGetWin32HandleInfoKHR.SEMAPHORE); }
    /** Unsafe version of {@link #handleType}. */
    public static int nhandleType(long struct) { return UNSAFE.getInt(null, struct + VkSemaphoreGetWin32HandleInfoKHR.HANDLETYPE); }

    /** Unsafe version of {@link #sType(int) sType}. */
    public static void nsType(long struct, int value) { UNSAFE.putInt(null, struct + VkSemaphoreGetWin32HandleInfoKHR.STYPE, value); }
    /** Unsafe version of {@link #pNext(long) pNext}. */
    public static void npNext(long struct, long value) { memPutAddress(struct + VkSemaphoreGetWin32HandleInfoKHR.PNEXT, value); }
    /** Unsafe version of {@link #semaphore(long) semaphore}. */
    public static void nsemaphore(long struct, long value) { UNSAFE.putLong(null, struct + VkSemaphoreGetWin32HandleInfoKHR.SEMAPHORE, value); }
    /** Unsafe version of {@link #handleType(int) handleType}. */
    public static void nhandleType(long struct, int value) { UNSAFE.putInt(null, struct + VkSemaphoreGetWin32HandleInfoKHR.HANDLETYPE, value); }

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

    /** An array of {@link VkSemaphoreGetWin32HandleInfoKHR} structs. */
    public static class Buffer extends StructBuffer<VkSemaphoreGetWin32HandleInfoKHR, Buffer> implements NativeResource {

        private static final VkSemaphoreGetWin32HandleInfoKHR ELEMENT_FACTORY = VkSemaphoreGetWin32HandleInfoKHR.create(-1L);

        /**
         * Creates a new {@code VkSemaphoreGetWin32HandleInfoKHR.Buffer} instance backed by the specified container.
         *
         * Changes to the container's content will be visible to the struct buffer instance and vice versa. The two buffers' position, limit, and mark values
         * will be independent. The new buffer's position will be zero, its capacity and its limit will be the number of bytes remaining in this buffer divided
         * by {@link VkSemaphoreGetWin32HandleInfoKHR#SIZEOF}, and its mark will be undefined.
         *
         *
The created buffer instance holds a strong reference to the container object.

         */
        public Buffer(ByteBuffer container) {
            super(container, container.remaining() / SIZEOF);
        }

        public Buffer(long address, int cap) {
            super(address, null, -1, 0, cap, cap);
        }

        Buffer(long address, @Nullable ByteBuffer container, int mark, int pos, int lim, int cap) {
            super(address, container, mark, pos, lim, cap);
        }

        @Override
        protected Buffer self() {
            return this;
        }

        @Override
        protected VkSemaphoreGetWin32HandleInfoKHR getElementFactory() {
            return ELEMENT_FACTORY;
        }

        /** @return the value of the {@link VkSemaphoreGetWin32HandleInfoKHR#sType} field. */
        @NativeType("VkStructureType")
        public int sType() { return VkSemaphoreGetWin32HandleInfoKHR.nsType(address()); }
        /** @return the value of the {@link VkSemaphoreGetWin32HandleInfoKHR#pNext} field. */
        @NativeType("void const *")
        public long pNext() { return VkSemaphoreGetWin32HandleInfoKHR.npNext(address()); }
        /** @return the value of the {@link VkSemaphoreGetWin32HandleInfoKHR#semaphore} field. */
        @NativeType("VkSemaphore")
        public long semaphore() { return VkSemaphoreGetWin32HandleInfoKHR.nsemaphore(address()); }
        /** @return the value of the {@link VkSemaphoreGetWin32HandleInfoKHR#handleType} field. */
        @NativeType("VkExternalSemaphoreHandleTypeFlagBits")
        public int handleType() { return VkSemaphoreGetWin32HandleInfoKHR.nhandleType(address()); }

        /** Sets the specified value to the {@link VkSemaphoreGetWin32HandleInfoKHR#sType} field. */
        public VkSemaphoreGetWin32HandleInfoKHR.Buffer sType(@NativeType("VkStructureType") int value) { VkSemaphoreGetWin32HandleInfoKHR.nsType(address(), value); return this; }
        /** Sets the {@link KHRExternalSemaphoreWin32#VK_STRUCTURE_TYPE_SEMAPHORE_GET_WIN32_HANDLE_INFO_KHR STRUCTURE_TYPE_SEMAPHORE_GET_WIN32_HANDLE_INFO_KHR} value to the {@link VkSemaphoreGetWin32HandleInfoKHR#sType} field. */
        public VkSemaphoreGetWin32HandleInfoKHR.Buffer sType$Default() { return sType(KHRExternalSemaphoreWin32.VK_STRUCTURE_TYPE_SEMAPHORE_GET_WIN32_HANDLE_INFO_KHR); }
        /** Sets the specified value to the {@link VkSemaphoreGetWin32HandleInfoKHR#pNext} field. */
        public VkSemaphoreGetWin32HandleInfoKHR.Buffer pNext(@NativeType("void const *") long value) { VkSemaphoreGetWin32HandleInfoKHR.npNext(address(), value); return this; }
        /** Sets the specified value to the {@link VkSemaphoreGetWin32HandleInfoKHR#semaphore} field. */
        public VkSemaphoreGetWin32HandleInfoKHR.Buffer semaphore(@NativeType("VkSemaphore") long value) { VkSemaphoreGetWin32HandleInfoKHR.nsemaphore(address(), value); return this; }
        /** Sets the specified value to the {@link VkSemaphoreGetWin32HandleInfoKHR#handleType} field. */
        public VkSemaphoreGetWin32HandleInfoKHR.Buffer handleType(@NativeType("VkExternalSemaphoreHandleTypeFlagBits") int value) { VkSemaphoreGetWin32HandleInfoKHR.nhandleType(address(), value); return this; }

    }

}


text:
package org.elasticsearch.xpack.sql.jdbc;

class JdbcException extends RuntimeException {

    JdbcException(String message) {
        super(message);
    }

    JdbcException(Throwable cause, String message) {
        super(message, cause);
    }
}


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.1-833
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2015.02.12 at 07:19:45 em CET
//

package se.sparavisering;

import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlEnumValue;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for SlutAnvandarBehorighetTYPE.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *

 *

 * <simpleType name="SlutAnvandarBehorighetTYPE">
 *   <restriction base="{http://www.w3.org/2001/XMLSchema}string">
 *     <enumeration value="KAT1"/>
 *     <enumeration value="KAT2"/>
 *     <enumeration value="KAT3"/>
 *     <enumeration value="KAT4"/>
 *   </restriction>
 * </simpleType>
 *

 *
 */
@XmlType(name = "SlutAnvandarBehorighetTYPE")
@XmlEnum
public enum SlutAnvandarBehorighetTYPE {

    /**
     * Behörighetskategori 1
     *
     */
    @XmlEnumValue("KAT1")
    KAT_1("KAT1"),

    /**
     * Behörighetskategori 2
     *
     */
    @XmlEnumValue("KAT2")
    KAT_2("KAT2"),

    /**
     * Behörighetskategori 3
     *
     */
    @XmlEnumValue("KAT3")
    KAT_3("KAT3"),

    /**
     * Behörighetskategori 4
     *
     */
    @XmlEnumValue("KAT4")
    KAT_4("KAT4");
    private final String value;

    SlutAnvandarBehorighetTYPE(String v) {
        value = v;
    }

    public String value() {
        return value;
    }

    public static SlutAnvandarBehorighetTYPE fromValue(String v) {
        for (SlutAnvandarBehorighetTYPE c: SlutAnvandarBehorighetTYPE.values()) {
            if (c.value.equals(v)) {
                return c;
            }
        }
        throw new IllegalArgumentException(v);
    }

}


text:
package gov.nih.nci.cagrid.authentication.common;

import gov.nih.nci.cagrid.authentication.bean.Credential;
import gov.nih.nci.cagrid.opensaml.SAMLAssertion;

import java.rmi.RemoteException;

public interface AuthenticationProvider {

    void setSAMLProvider(SAMLProvider samlProvider);

    void setSubjectProvider(SubjectProvider subjectProvider);

    SAMLAssertion authenticate(Credential credential)
	throws RemoteException, InvalidCredentialException,
	InsufficientAttributeException, AuthenticationProviderException;

}


text:
package com.twitter.elephantbird.mapreduce.output;

import java.io.IOException;

import org.apache.hadoop.mapreduce.RecordWriter;
import org.apache.hadoop.mapreduce.TaskAttemptContext;
import org.apache.hadoop.util.ReflectionUtils;

import com.twitter.elephantbird.mapreduce.input.BinaryConverterProvider;
import com.twitter.elephantbird.mapreduce.io.BinaryBlockWriter;
import com.twitter.elephantbird.mapreduce.io.BinaryConverter;
import com.twitter.elephantbird.mapreduce.io.GenericWritable;
import com.twitter.elephantbird.util.HadoopCompat;
import com.twitter.elephantbird.util.HadoopUtils;

import org.apache.hadoop.conf.Configuration;

/**
 * Generic OutputFormat for records to be stored as lzo-compressed protobuf blocks.
 */
public class LzoGenericBlockOutputFormat<M> extends LzoOutputFormat<M, GenericWritable<M>> {

  private static String CLASS_CONF_KEY = "elephantbird.class.for.LzoGenericBlockOutputFormat";
  private static String GENERIC_ENCODER_KEY = "elephantbird.encoder.class.for.LzoGenericBlockOutputFormat";

  public static void setGenericConverterClassConf(Class<?> clazz, Configuration conf) {
    HadoopUtils.setClassConf(conf, GENERIC_ENCODER_KEY, clazz);
  }

  public static void setClassConf(Class<?> clazz, Configuration conf) {
    HadoopUtils.setClassConf(conf, CLASS_CONF_KEY, clazz);
  }

  @Override
  public RecordWriter<M, GenericWritable<M>> getRecordWriter(TaskAttemptContext job)
      throws IOException, InterruptedException {
    Configuration conf = HadoopCompat.getConfiguration(job);
    String encoderClassName = conf.get(GENERIC_ENCODER_KEY);
    Class<?> valueClass = null;
    BinaryConverterProvider<?> converterProvider = null;
    // get the converter provider from job conf
    // which then gives us the BinaryConverter for the type M in question
    try {
      String valueClassName = conf.get(CLASS_CONF_KEY);
      valueClass = conf.getClassByName(valueClassName);
      converterProvider = (BinaryConverterProvider<?>) ReflectionUtils.newInstance(
        conf.getClassByName(encoderClassName), conf);
    } catch (ClassNotFoundException e) {
      throw new RuntimeException("failed to instantiate class '" + encoderClassName + "'", e);
    }

    BinaryConverter<?> converter = converterProvider.getConverter(conf);

    return new LzoBinaryBlockRecordWriter<M, GenericWritable<M>>(new BinaryBlockWriter(
        getOutputStream(job), valueClass, converter));
  }
}