text:
#ifndef __GST_ELEMENT_FACTORY_H__
#define __GST_ELEMENT_FACTORY_H__

/**
 * GstElementFactory:
 *
 * The opaque #GstElementFactory data structure.
 */
typedef struct _GstElementFactory GstElementFactory;
typedef struct _GstElementFactoryClass GstElementFactoryClass;

#include <gst/gstconfig.h>
#include <gst/gstelement.h>
#include <gst/gstpad.h>
#include <gst/gstplugin.h>
#include <gst/gstpluginfeature.h>
#include <gst/gsturi.h>

G_BEGIN_DECLS

#define GST_TYPE_ELEMENT_FACTORY                (gst_element_factory_get_type())
#define GST_ELEMENT_FACTORY(obj)                (G_TYPE_CHECK_INSTANCE_CAST((obj),GST_TYPE_ELEMENT_FACTORY,\
                                                 GstElementFactory))
#define GST_ELEMENT_FACTORY_CLASS(klass)        (G_TYPE_CHECK_CLASS_CAST((klass),GST_TYPE_ELEMENT_FACTORY,\
                                                 GstElementFactoryClass))
#define GST_IS_ELEMENT_FACTORY(obj)             (G_TYPE_CHECK_INSTANCE_TYPE((obj),GST_TYPE_ELEMENT_FACTORY))
#define GST_IS_ELEMENT_FACTORY_CLASS(klass)     (G_TYPE_CHECK_CLASS_TYPE((klass),GST_TYPE_ELEMENT_FACTORY))
#define GST_ELEMENT_FACTORY_CAST(obj)           ((GstElementFactory *)(obj))

GST_API
GType                   gst_element_factory_get_type            (void);

GST_API
GstElementFactory *     gst_element_factory_find                (const gchar *name);

GST_API
GType                   gst_element_factory_get_element_type    (GstElementFactory *factory);

GST_API
const gchar *           gst_element_factory_get_metadata        (GstElementFactory *factory, const gchar *key);

GST_API
gchar **                gst_element_factory_get_metadata_keys   (GstElementFactory *factory);

GST_API
guint                   gst_element_factory_get_num_pad_templates (GstElementFactory *factory);

GST_API
const GList *           gst_element_factory_get_static_pad_templates (GstElementFactory *factory);

GST_API
GstURIType              gst_element_factory_get_uri_type        (GstElementFactory *factory);

GST_API
const gchar * const *   gst_element_factory_get_uri_protocols   (GstElementFactory *factory);

GST_API
gboolean                gst_element_factory_has_interface       (GstElementFactory *factory,
                                                                 const gchar *interfacename);
GST_API
GstElement*             gst_element_factory_create              (GstElementFactory *factory,
                                                                 const gchar *name) G_GNUC_MALLOC;
GST_API
GstElement*             gst_element_factory_make                (const gchar *factoryname, const gchar *name) G_GNUC_MALLOC;

GST_API
gboolean                gst_element_register                    (GstPlugin *plugin, const gchar *name,
                                                                 guint rank, GType type);

/* Factory list functions */

/**
 * GstFactoryListType:
 * @GST_ELEMENT_FACTORY_TYPE_DECODER: Decoder elements
 * @GST_ELEMENT_FACTORY_TYPE_ENCODER: Encoder elements
 * @GST_ELEMENT_FACTORY_TYPE_SINK: Sink elements
 * @GST_ELEMENT_FACTORY_TYPE_SRC: Source elements
 * @GST_ELEMENT_FACTORY_TYPE_MUXER: Muxer elements
 * @GST_ELEMENT_FACTORY_TYPE_DEMUXER: Demuxer elements
 * @GST_ELEMENT_FACTORY_TYPE_PARSER: Parser elements
 * @GST_ELEMENT_FACTORY_TYPE_PAYLOADER: Payloader elements
 * @GST_ELEMENT_FACTORY_TYPE_DEPAYLOADER: Depayloader elements
 * @GST_ELEMENT_FACTORY_TYPE_DECRYPTOR: Elements handling decryption (Since: 1.6)
 * @GST_ELEMENT_FACTORY_TYPE_ENCRYPTOR: Elements handling encryption (Since: 1.6)
 * @GST_ELEMENT_FACTORY_TYPE_MAX_ELEMENTS: Private, do not use
 * @GST_ELEMENT_FACTORY_TYPE_MEDIA_VIDEO: Elements handling video media types
 * @GST_ELEMENT_FACTORY_TYPE_MEDIA_AUDIO: Elements handling audio media types
 * @GST_ELEMENT_FACTORY_TYPE_MEDIA_IMAGE: Elements handling image media types
 * @GST_ELEMENT_FACTORY_TYPE_MEDIA_SUBTITLE: Elements handling subtitle media types
 * @GST_ELEMENT_FACTORY_TYPE_MEDIA_METADATA: Elements handling metadata media types
 *
 * The type of #GstElementFactory to filter.
 *
 * All @GstFactoryListType up to @GST_ELEMENT_FACTORY_TYPE_MAX_ELEMENTS are exclusive.
 *
 * If one or more of the MEDIA types are specified, then only elements
 * matching the specified media types will be selected.
 */

typedef guint64 GstElementFactoryListType;

#define  GST_ELEMENT_FACTORY_TYPE_DECODER        ((GstElementFactoryListType)(G_GUINT64_CONSTANT (1) << 0))
#define  GST_ELEMENT_FACTORY_TYPE_ENCODER        ((GstElementFactoryListType)(G_GUINT64_CONSTANT (1) << 1))
#define  GST_ELEMENT_FACTORY_TYPE_SINK           ((GstElementFactoryListType)(G_GUINT64_CONSTANT (1) << 2))
#define  GST_ELEMENT_FACTORY_TYPE_SRC            ((GstElementFactoryListType)(G_GUINT64_CONSTANT (1) << 3))
#define  GST_ELEMENT_FACTORY_TYPE_MUXER          ((GstElementFactoryListType)(G_GUINT64_CONSTANT (1) << 4))
#define  GST_ELEMENT_FACTORY_TYPE_DEMUXER        ((GstElementFactoryListType)(G_GUINT64_CONSTANT (1) << 5))
#define  GST_ELEMENT_FACTORY_TYPE_PARSER         ((GstElementFactoryListType)(G_GUINT64_CONSTANT (1) << 6))
#define  GST_ELEMENT_FACTORY_TYPE_PAYLOADER      ((GstElementFactoryListType)(G_GUINT64_CONSTANT (1) << 7))
#define  GST_ELEMENT_FACTORY_TYPE_DEPAYLOADER    ((GstElementFactoryListType)(G_GUINT64_CONSTANT (1) << 8))
#define  GST_ELEMENT_FACTORY_TYPE_FORMATTER      ((GstElementFactoryListType)(G_GUINT64_CONSTANT (1) << 9))
#define  GST_ELEMENT_FACTORY_TYPE_DECRYPTOR      ((GstElementFactoryListType)(G_GUINT64_CONSTANT (1) << 10))
#define  GST_ELEMENT_FACTORY_TYPE_ENCRYPTOR      ((GstElementFactoryListType)(G_GUINT64_CONSTANT (1) << 11))

#define  GST_ELEMENT_FACTORY_TYPE_MAX_ELEMENTS   ((GstElementFactoryListType)(G_GUINT64_CONSTANT (1) << 48))

#define  GST_ELEMENT_FACTORY_TYPE_MEDIA_VIDEO    ((GstElementFactoryListType)(G_GUINT64_CONSTANT (1) << 49))
#define  GST_ELEMENT_FACTORY_TYPE_MEDIA_AUDIO    ((GstElementFactoryListType)(G_GUINT64_CONSTANT (1) << 50))
#define  GST_ELEMENT_FACTORY_TYPE_MEDIA_IMAGE    ((GstElementFactoryListType)(G_GUINT64_CONSTANT (1) << 51))
#define  GST_ELEMENT_FACTORY_TYPE_MEDIA_SUBTITLE ((GstElementFactoryListType)(G_GUINT64_CONSTANT (1) << 52))
#define  GST_ELEMENT_FACTORY_TYPE_MEDIA_METADATA ((GstElementFactoryListType)(G_GUINT64_CONSTANT (1) << 53))

/**
 * GST_ELEMENT_FACTORY_TYPE_ANY: (value 562949953421311) (type GstElementFactoryListType)
 *
 * Elements of any of the defined GST_ELEMENT_FACTORY_LIST types
 */
#define  GST_ELEMENT_FACTORY_TYPE_ANY ((GstElementFactoryListType)((G_GUINT64_CONSTANT (1) << 49) - 1))

/**
 * GST_ELEMENT_FACTORY_TYPE_MEDIA_ANY: (value 18446462598732840960) (type GstElementFactoryListType)
 *
 * Elements matching any of the defined GST_ELEMENT_FACTORY_TYPE_MEDIA types
 *
 * Note: Do not use this if you wish to not filter against any of the defined
 * media types. If you wish to do this, simply don't specify any
 * GST_ELEMENT_FACTORY_TYPE_MEDIA flag.
 */
#define GST_ELEMENT_FACTORY_TYPE_MEDIA_ANY ((GstElementFactoryListType)(~G_GUINT64_CONSTANT (0) << 48))

/**
 * GST_ELEMENT_FACTORY_TYPE_VIDEO_ENCODER: (value 2814749767106562) (type GstElementFactoryListType)
 *
 * All encoders handling video or image media types
 */
#define GST_ELEMENT_FACTORY_TYPE_VIDEO_ENCODER ((GstElementFactoryListType)(GST_ELEMENT_FACTORY_TYPE_ENCODER | GST_ELEMENT_FACTORY_TYPE_MEDIA_VIDEO | GST_ELEMENT_FACTORY_TYPE_MEDIA_IMAGE))

/**
 * GST_ELEMENT_FACTORY_TYPE_AUDIO_ENCODER: (value 1125899906842626) (type GstElementFactoryListType)
 *
 * All encoders handling audio media types
 */
#define GST_ELEMENT_FACTORY_TYPE_AUDIO_ENCODER ((GstElementFactoryListType)(GST_ELEMENT_FACTORY_TYPE_ENCODER | GST_ELEMENT_FACTORY_TYPE_MEDIA_AUDIO))

/**
 * GST_ELEMENT_FACTORY_TYPE_AUDIOVIDEO_SINKS: (value 3940649673949188) (type GstElementFactoryListType)
 *
 * All sinks handling audio, video or image media types
 */
#define GST_ELEMENT_FACTORY_TYPE_AUDIOVIDEO_SINKS ((GstElementFactoryListType)(GST_ELEMENT_FACTORY_TYPE_SINK | GST_ELEMENT_FACTORY_TYPE_MEDIA_AUDIO | GST_ELEMENT_FACTORY_TYPE_MEDIA_VIDEO | GST_ELEMENT_FACTORY_TYPE_MEDIA_IMAGE))

/**
 * GST_ELEMENT_FACTORY_TYPE_DECODABLE: (value 1377) (type GstElementFactoryListType)
 *
 * All elements used to 'decode' streams (decoders, demuxers, parsers, depayloaders)
 */
#define GST_ELEMENT_FACTORY_TYPE_DECODABLE \
  ((GstElementFactoryListType)(GST_ELEMENT_FACTORY_TYPE_DECODER | GST_ELEMENT_FACTORY_TYPE_DEMUXER | GST_ELEMENT_FACTORY_TYPE_DEPAYLOADER | GST_ELEMENT_FACTORY_TYPE_PARSER | GST_ELEMENT_FACTORY_TYPE_DECRYPTOR))

/* Element klass defines */
#define GST_ELEMENT_FACTORY_KLASS_DECODER               "Decoder"
#define GST_ELEMENT_FACTORY_KLASS_ENCODER               "Encoder"
#define GST_ELEMENT_FACTORY_KLASS_SINK                  "Sink"
#define GST_ELEMENT_FACTORY_KLASS_SRC                   "Source"
#define GST_ELEMENT_FACTORY_KLASS_MUXER                 "Muxer"
#define GST_ELEMENT_FACTORY_KLASS_DEMUXER               "Demuxer"
#define GST_ELEMENT_FACTORY_KLASS_PARSER                "Parser"
#define GST_ELEMENT_FACTORY_KLASS_PAYLOADER             "Payloader"
#define GST_ELEMENT_FACTORY_KLASS_DEPAYLOADER           "Depayloader"
#define GST_ELEMENT_FACTORY_KLASS_FORMATTER             "Formatter"
#define GST_ELEMENT_FACTORY_KLASS_DECRYPTOR             "Decryptor"
#define GST_ELEMENT_FACTORY_KLASS_ENCRYPTOR             "Encryptor"

#define GST_ELEMENT_FACTORY_KLASS_MEDIA_VIDEO           "Video"
#define GST_ELEMENT_FACTORY_KLASS_MEDIA_AUDIO           "Audio"
#define GST_ELEMENT_FACTORY_KLASS_MEDIA_IMAGE           "Image"
#define GST_ELEMENT_FACTORY_KLASS_MEDIA_SUBTITLE        "Subtitle"
#define GST_ELEMENT_FACTORY_KLASS_MEDIA_METADATA        "Metadata"

/**
 * GST_ELEMENT_FACTORY_KLASS_HARDWARE:
 *
 * Elements interacting with hardware devices should specify this classifier in
 * their metadata. You may need to put the element in "READY" state to test if
 * the hardware is present in the system.
 *
 * Since: 1.16
 */
#define GST_ELEMENT_FACTORY_KLASS_HARDWARE              "Hardware"

GST_API
gboolean      gst_element_factory_list_is_type      (GstElementFactory *factory,
                                                     GstElementFactoryListType type);

GST_API
GList *       gst_element_factory_list_get_elements (GstElementFactoryListType type,
                                                     GstRank minrank) G_GNUC_MALLOC;

GST_API
GList *       gst_element_factory_list_filter       (GList *list, const GstCaps *caps,
                                                     GstPadDirection direction,
                                                     gboolean subsetonly) G_GNUC_MALLOC;
#ifdef G_DEFINE_AUTOPTR_CLEANUP_FUNC
G_DEFINE_AUTOPTR_CLEANUP_FUNC(GstElementFactory, gst_object_unref)
#endif

G_END_DECLS

#endif /* __GST_ELEMENT_FACTORY_H__ */


text:
export * from './Conference';
export * from './controls';

redpajama_set_name: RedPajamaGithub


text:
<?php

$tables = []; # cached tables

$this->module("datastore")->extend([

    "get_datastore" => function($name) use($app, $tables) {

        if (!isset($tables[$name])) {
            $tables[$name] = $app->db->findOne("common/datastore", ["name"=>$name]);
        }

        return $tables[$name];
    },

    "collectionById" => function($datastoreId) use($app) {

        $entrydb = "datastore{$datastoreId}";

        return $app->db->getCollection("datastore/{$entrydb}");
    },

    "entries" => function($name) use($app) {

        $datastore = $this->get_datastore($name);

        if (!$datastore) return false;

        $entrydb = "datastore".$datastore["_id"];

        return $app->db->getCollection("datastore/{$entrydb}");
    },

    "find" => function($table, $options = []) {

        $datastore = $this->get_datastore($table);

        if (!$datastore) return false;

        $collection = "datastore".$datastore["_id"];

        return $this->app->db->find("datastore/{$collection}", $options);
    },

    "findOne" => function($table, $criteria = [], $projection = null) {

        $datastore = $this->get_datastore($table);

        if (!$datastore) return false;

        $collection = "datastore".$datastore["_id"];

        return $this->app->db->findOne("datastore/{$collection}", $criteria, $projection);
    },

    "save_entry" => function($table, $data) {

        $datastore = $this->get_datastore($table);

        if (!$datastore) return false;

        $collection = "datastore".$datastore["_id"];

        $data["modified"] = time();

        if (!isset($data["_id"])){
            $data["created"] = $data["modified"];
        }

        return $this->app->db->save("datastore/{$collection}", $data);
    },

    "remove" => function($table, $criteria) {

        $datastore = $this->get_datastore($table);

        if (!$datastore) return false;

        $collection = "datastore".$datastore["_id"];

        return $this->app->db->remove("datastore/{$collection}", $criteria);
    },

    'count' => function($table, $criteria = []) {

        $datastore = $this->get_datastore($table);

        if (!$datastore) return false;

        $collection = "datastore".$datastore["_id"];

        return $this->app->db->count("datastore/{$collection}", $criteria);
    }
]);

// ADMIN
if (COCKPIT_ADMIN && !COCKPIT_REST) include_once(__DIR__.'/admin.php');


text:
'use strict';

var assert = require('assert');
var grpc = require('../src/grpc_extension');

/**
 * Helper function to return an absolute deadline given a relative timeout in
 * seconds.
 * @param {number} timeout_secs The number of seconds to wait before timing out
 * @return {Date} A date timeout_secs in the future
 */
function getDeadline(timeout_secs) {
  var deadline = new Date();
  deadline.setSeconds(deadline.getSeconds() + timeout_secs);
  return deadline;
}

var insecureCreds = grpc.ChannelCredentials.createInsecure();

describe('call', function() {
  var channel;
  var server;
  before(function() {
    server = new grpc.Server();
    var port = server.addHttp2Port('localhost:0',
                                   grpc.ServerCredentials.createInsecure());
    server.start();
    channel = new grpc.Channel('localhost:' + port, insecureCreds);
  });
  after(function() {
    server.forceShutdown();
  });
  describe('constructor', function() {
    it('should reject anything less than 3 arguments', function() {
      assert.throws(function() {
        new grpc.Call();
      }, TypeError);
      assert.throws(function() {
        new grpc.Call(channel);
      }, TypeError);
      assert.throws(function() {
        new grpc.Call(channel, 'method');
      }, TypeError);
    });
    it('should succeed with a Channel, a string, and a date or number',
       function() {
         assert.doesNotThrow(function() {
           new grpc.Call(channel, 'method', new Date());
         });
         assert.doesNotThrow(function() {
           new grpc.Call(channel, 'method', 0);
         });
       });
    it('should accept an optional fourth string parameter', function() {
      assert.doesNotThrow(function() {
        new grpc.Call(channel, 'method', new Date(), 'host_override');
      });
    });
    it('should fail with a closed channel', function() {
      var local_channel = new grpc.Channel('hostname', insecureCreds);
      local_channel.close();
      assert.throws(function() {
        new grpc.Call(channel, 'method');
      });
    });
    it('should fail with other types', function() {
      assert.throws(function() {
        new grpc.Call({}, 'method', 0);
      }, TypeError);
      assert.throws(function() {
        new grpc.Call(channel, null, 0);
      }, TypeError);
      assert.throws(function() {
        new grpc.Call(channel, 'method', 'now');
      }, TypeError);
    });
    it('should succeed without the new keyword', function() {
      assert.doesNotThrow(function() {
        var call = grpc.Call(channel, 'method', new Date());
        assert(call instanceof grpc.Call);
      });
    });
  });
  describe('deadline', function() {
    it('should time out immediately with negative deadline', function(done) {
      var call = new grpc.Call(channel, 'method', -Infinity);
      var batch = {};
      batch[grpc.opType.RECV_STATUS_ON_CLIENT] = true;
      call.startBatch(batch, function(err, response) {
        assert.strictEqual(response.status.code, grpc.status.DEADLINE_EXCEEDED);
        done();
      });
    });
  });
  describe('startBatch', function() {
    it('should fail without an object and a function', function() {
      var call = new grpc.Call(channel, 'method', getDeadline(1));
      assert.throws(function() {
        call.startBatch();
      });
      assert.throws(function() {
        call.startBatch({});
      });
      assert.throws(function() {
        call.startBatch(null, function(){});
      });
    });
    it('should succeed with an empty object', function(done) {
      var call = new grpc.Call(channel, 'method', getDeadline(1));
      assert.doesNotThrow(function() {
        call.startBatch({}, function(err) {
          assert.ifError(err);
          done();
        });
      });
    });
  });
  describe('startBatch with metadata', function() {
    it('should succeed with a map of strings to string arrays', function(done) {
      var call = new grpc.Call(channel, 'method', getDeadline(1));
      assert.doesNotThrow(function() {
        var batch = {};
        batch[grpc.opType.SEND_INITIAL_METADATA] = {'key1': ['value1'],
                                                    'key2': ['value2']};
        call.startBatch(batch, function(err, resp) {
          assert.ifError(err);
          assert.deepEqual(resp, {'send_metadata': true});
          done();
        });
      });
    });
    it('should succeed with a map of strings to buffer arrays', function(done) {
      var call = new grpc.Call(channel, 'method', getDeadline(1));
      assert.doesNotThrow(function() {
        var batch = {};
        batch[grpc.opType.SEND_INITIAL_METADATA] = {
          'key1-bin': [new Buffer('value1')],
          'key2-bin': [new Buffer('value2')]
        };
        call.startBatch(batch, function(err, resp) {
          assert.ifError(err);
          assert.deepEqual(resp, {'send_metadata': true});
          done();
        });
      });
    });
    it('should fail with other parameter types', function() {
      var call = new grpc.Call(channel, 'method', getDeadline(1));
      assert.throws(function() {
        var batch = {};
        batch[grpc.opType.SEND_INITIAL_METADATA] = undefined;
        call.startBatch(batch, function(){});
      });
      assert.throws(function() {
        var batch = {};
        batch[grpc.opType.SEND_INITIAL_METADATA] = null;
        call.startBatch(batch, function(){});
      }, TypeError);
      assert.throws(function() {
        var batch = {};
        batch[grpc.opType.SEND_INITIAL_METADATA] = 'value';
        call.startBatch(batch, function(){});
      }, TypeError);
      assert.throws(function() {
        var batch = {};
        batch[grpc.opType.SEND_INITIAL_METADATA] = 5;
        call.startBatch(batch, function(){});
      }, TypeError);
    });
  });
  describe('cancel', function() {
    it('should succeed', function() {
      var call = new grpc.Call(channel, 'method', getDeadline(1));
      assert.doesNotThrow(function() {
        call.cancel();
      });
    });
  });
  describe('cancelWithStatus', function() {
    it('should reject anything other than an integer and a string', function() {
      assert.doesNotThrow(function() {
        var call = new grpc.Call(channel, 'method', getDeadline(1));
        call.cancelWithStatus(1, 'details');
      });
      assert.throws(function() {
        var call = new grpc.Call(channel, 'method', getDeadline(1));
        call.cancelWithStatus();
      });
      assert.throws(function() {
        var call = new grpc.Call(channel, 'method', getDeadline(1));
        call.cancelWithStatus('');
      });
      assert.throws(function() {
        var call = new grpc.Call(channel, 'method', getDeadline(1));
        call.cancelWithStatus(5, {});
      });
    });
    it('should reject the OK status code', function() {
      assert.throws(function() {
        var call = new grpc.Call(channel, 'method', getDeadline(1));
        call.cancelWithStatus(0, 'details');
      });
    });
    it('should result in the call ending with a status', function(done) {
      var call = new grpc.Call(channel, 'method', getDeadline(1));
      var batch = {};
      batch[grpc.opType.RECV_STATUS_ON_CLIENT] = true;
      call.startBatch(batch, function(err, response) {
        assert.strictEqual(response.status.code, 5);
        assert.strictEqual(response.status.details, 'details');
        done();
      });
      call.cancelWithStatus(5, 'details');
    });
  });
  describe('getPeer', function() {
    it('should return a string', function() {
      var call = new grpc.Call(channel, 'method', getDeadline(1));
      assert.strictEqual(typeof call.getPeer(), 'string');
    });
  });
});


text:
import re

def transform_whitespace(compword):
    """Avoid whitespace-separated compound words.
Returns compword with whitespace substituted with underscores."""
    return re.sub('\s+', '_', compword)

# FIXME Will probably barf on larg files, make use of generators
# TODO use newline_eos and marker_eos to enable users to choose none,
#      one or both ways to discover sentence-end markers
#      (these arguments are currently not in use)
def read(cg3_file, newline_eos=True, marker_eos=True):
    """Read a file containing CG3-formatted data.

Returns: a list of sentences of the following structure:
- Each sentence is itself a list containing information about each word.
- Each word is again a list of the form:
  [TOKEN, LEMMA, TAG0, TAG1, ...]
    """
    rx_token = re.compile("^\"<(.+?)>\"$")
    rx_attributes = re.compile("^\s+\"(.+?)\"\s+(.+)$")

    # For files that use an empty line to mark sentence-end
    rx_eos = re.compile("^\s*$")

    # For files that use the "<<<" token to mark sentence-end
    marker_eos = "<<<"
    was_eos = False  # Set to true whenever "<<<" is found

    curr_token = None
    curr_word = []
    curr_sentence = []
    result = []

    for line in cg3_file:

        # Empty line or sentence-end marker marks sentence-end, raise
        # eos flag
        if rx_eos.match(line) or marker_eos in line:
            was_eos = True

        if rx_token.match(line):
            curr_token = transform_whitespace(
                rx_token.match(line).group(1)
            )

        if rx_attributes.match(line):
            curr_lemma = transform_whitespace(
                rx_attributes.match(line).group(1)
            )
            curr_attrs = rx_attributes.match(line).group(2).split()
            curr_word = [curr_lemma] + curr_attrs

            if curr_token and curr_word:
                curr_sentence += [[curr_token] + curr_word]
                curr_token = None
                curr_word = []

        # If a sentence-end marker was encountered in the previuos
        # iteration, process the sentence
        if was_eos:
            result += [curr_sentence]
            curr_sentence = []
            curr_token = None
            curr_word = []
            was_eos = False

    # Final cleanup (in case of missing blank line or attributes at the end)
    if curr_token and curr_word:
        curr_sentence += [[curr_token] + curr_word]
        curr_token = None
        curr_word = []

    if curr_sentence:
        result += [curr_sentence]

    return result

###############################################################################
# WORD-LEVEL
###############################################################################

def token(word):
    """Return the token for the word."""
    return word[0]

def attribute_list(word):
    """Return a list of attributes from the word."""
    return word[1:]

def lemma(word):
    """Return the lemma for the word."""
    return attribute_list(word)[0]

def tag_list(word):
    """Return the tag list for the word."""
    return attribute_list(word)[1:]

def coarse_tag(word):
    """Return the coarse-grained tag for the word."""
    return tag_list(word)[0]

def fine_tag_list(word):
    """Return the fine-grained tags for the word."""
    return tag_list(word)[1:]

###############################################################################
# SENTENCE-LEVEL
###############################################################################

def tokens(sentence):
    """Return a list of tokens from the sentence."""
    return [token(w) for w in sentence]

def attribute_lists(sentence):
    """Return a list of attributes (as a list) from the sentence."""
    return [attribute_list(word) for word in sentence]

def lemmas(sentence):
    """Return a list of lemmas from the sentence."""
    return [lemma(word) for word in sentence]

def tag_lists(sentence):
    """Return a list of tags (as a list) from the sentence."""
    return [tag_list(word) for word in sentence]

def coarse_tags(sentence):
    """Return a list of coarse-grained tags from the sentence."""
    return [coarse_tag(word) for word in sentence]

def fine_tag_lists(sentence):
    """Return a list of fine-grained tags from the sentence."""
    return [fine_tag_list(word) for word in sentence]

###############################################################################
# DOCUMENT-LEVEL
###############################################################################

def tokens_all(document):
    """Return a list of lists of tokens from all sentences."""
    return [tokens(sentence) for sentence in document]

def attribute_lists_all(document):
    """Return a list of lists of attributes from all sentences."""
    return [attribute_lists(sentence) for sentence in document]

def lemmas_all(document):
    """Return a list of lists of lemmas from all sentences."""
    return [lemmas(sentence) for sentence in document]

def tag_lists_all(document):
    """Return a list of lists of tags from all sentences."""
    return [tag_lists(sentence) for sentence in document]

def coarse_tags_all(document):
    """Return a list of lists of coarse-grained tags from all sentences."""
    return [coarse_tags(sentence) for sentence in document]

def fine_tag_lists_all(document):
    """Return a list of lists of fine-grained tags from the sentence."""
    return [fine_tag_lists(sentence) for sentence in document]

def print_tsv(sentence):
    """Print parsed cg3 as tab-separated lines.

Each sentence is separated by an empty line."""
    for sent in sentence:
        for w in sent:
            print "\t".join(w)
        print


text:
package mk.ukim.finki.wp.service.impl.db;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import mk.ukim.finki.wp.model.db.PersonRole;
import mk.ukim.finki.wp.repository.db.PersonRoleRepository;
import mk.ukim.finki.wp.service.db.PersonRoleService;
import mk.ukim.finki.wp.service.impl.BaseEntityCrudServiceImpl;

@Service
public class PersonRoleServiceImpl extends
		BaseEntityCrudServiceImpl<PersonRole, PersonRoleRepository> implements PersonRoleService {

	@Autowired
	private PersonRoleRepository repository;

	@Override
	protected PersonRoleRepository getRepository() {
		return repository;
	}

}


text:
'use strict';

// MODULES //

var partial = require( './partial.js' );

// CDF //

/**
* FUNCTION: cdf( out, matrix, p )
*	Evaluates the cumulative distribution function (CDF) for a Geometric distribution with success probability `p` for each matrix element.
*
* @param {Matrix} out - output matrix
* @param {Matrix} arr - input matrix
* @param {Number} p - success probability
* @returns {Matrix} output matrix
*/
function cdf( y, x, p ) {
	var len = x.length,
		fcn,
		i;
	if ( y.length !== len ) {
		throw new Error( 'cdf()::invalid input arguments. Input and output matrices must be the same length.' );
	}
	fcn = partial( p );
	for ( i = 0; i < len; i++ ) {
		y.data[ i ] = fcn( x.data[ i ] );
	}
	return y;
} // end FUNCTION cdf()

// EXPORTS //

module.exports = cdf;


text:
const path = require('path');

const root = process.cwd();

module.exports = {
  logs: {
    logLevel: 'info',
    path: path.join(root, 'logs'),
    logConsoleLevel: 'info',
  },
  database: {
    path: path.join(root, 'data'),
  },
};


text:
Web 2.0 Touch

 Main Menu

				 Animations

				 Lists

				 Form Controls

				 Buttons

				 Swipable Pages

				 Tabs

				 Overlays

				 Themes

				 About

External Links

Web 2.0 Touch Home

Web 2.0 UI Library


text:
#ifndef __MTK_MEMINFO_H__
#define __MTK_MEMINFO_H__

/* physical offset */
extern phys_addr_t get_phys_offset(void);
/* physical DRAM size */
extern phys_addr_t get_max_DRAM_size(void);
/* DRAM size controlled by kernel */
extern phys_addr_t get_memory_size(void);
extern phys_addr_t mtk_get_max_DRAM_size(void);

#endif /* end __MTK_MEMINFO_H__ */


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>geomesa-web</artifactId>
        <groupId>org.locationtech.geomesa</groupId>
        <version>1.1.0-rc.5-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>geomesa-web-data</artifactId>
    <name>GeoMesa Web Data</name>
    <description>Provides direct REST access to GeoMesa data</description>

    <dependencies>
        <dependency>
            <groupId>org.scalatra</groupId>
            <artifactId>scalatra_2.10</artifactId>
        </dependency>
        <dependency>
            <groupId>org.locationtech.geomesa</groupId>
            <artifactId>geomesa-web-core</artifactId>
            <version>${project.parent.version}</version>
        </dependency>
        <dependency>
            <groupId>org.locationtech.geomesa</groupId>
            <artifactId>geomesa-accumulo-datastore</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.locationtech.geomesa</groupId>
            <artifactId>geomesa-tools</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.accumulo</groupId>
            <artifactId>accumulo-core</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>com.typesafe</groupId>
            <artifactId>scalalogging-slf4j_2.10</artifactId>
        </dependency>
    </dependencies>

    <profiles>
        <profile>
            <id>assemble</id>
            <build>
                <plugins>
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-shade-plugin</artifactId>
                        <version>2.0</version>
                        <executions>
                            <execution>
                                <phase>package</phase>
                                <goals>
                                    <goal>shade</goal>
                                </goals>
                                <configuration>
                                    <createDependencyReducedPom>false</createDependencyReducedPom>
                                    <shadedArtifactAttached>true</shadedArtifactAttached>
                                    <shadedClassifierName>geoserver-plugin</shadedClassifierName>
                                    <artifactSet>
                                        <includes>
                                            <include>*:*</include>
                                        </includes>
                                        <excludes>
                                            <exclude>org.scala-lang:scala-library</exclude>
                                            <exclude>org.slf4j:*</exclude>
                                            <exclude>joda-time:joda-time</exclude>
                                            <exclude>org.joda:joda-convert</exclude>
                                        </excludes>
                                    </artifactSet>
                                    <filters>
                                        <filter>
                                            <artifact>*:*</artifact>
                                            <excludes>
                                                <exclude>META-INF/*.SF</exclude>
                                                <exclude>META-INF/*.DSA</exclude>
                                                <exclude>META-INF/*.RSA</exclude>
                                            </excludes>
                                        </filter>
                                    </filters>
                                    <transformers>
                                        <transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer" />
                                        <transformer implementation="org.apache.maven.plugins.shade.resource.XmlAppendingTransformer">
                                            <resource>applicationContext.xml</resource>
                                        </transformer>
                                    </transformers>
                                </configuration>
                            </execution>
                        </executions>
                    </plugin>
                </plugins>
            </build>
        </profile>
    </profiles>

</project>


text:
title: Shrine 2.0.0
---

Backwards compatibility
=======================

* Metadata and upload options are now differently passed to storages, so the
  new signature of `#upload` and `#move` methods on the storage class should
  be:

```rb
def upload(io, id, shrine_metadata: {}, **upload_options)
  # ...
end

def move(io, id, shrine_metadata: {}, **upload_options)
  # ...
end
```

* The `Shrine::Confirm` functionality has been removed from storages'
  specification, storages should update `clear!` to remove the confirmation.

* The `:delegate` option in migration_helpers now defaults to false.

* The migration_helpers plugin has been deprecated, `Shrine::Attacher#cached?`
  and `Shrine::Attacher#stored?` have been moved to base functionality.

* The "background_helpers" alias for the backgrounding plugin has been
  deprecated and will be removed in Shrine 3.

* In backgrounding plugin the "attachment" key has been renamed to
  "name", and "uploaded_file" has been renamed to "attachment" in the data
  hash in background job argument.

* `Shrine::Attacher.promote` and `Shrine::Attacher.delete` from backgrounding
  plugin now return a `Shrine::Attacher` instance instead of the model
  instance.

* The moving plugin doesn't delete files that aren't movable anymore. You should
  use delete_raw and/or delete_promoted plugins for this functionality.

* The deprecated "delete_uploaded" alias for delete_raw plugin has been removed.

* The deprecated "restore_cached" alias for restore_cached_data plugin has been
  removed.

* The deprecated keep_location plugin has been removed.

* The deprecated `:subdirectory` option in FileSystem storage has been removed.

* The deprecated `Shrine#default_url` has been removed (specifying a default
  URL by overriding `#default_url` on the uploader), the default_url plugin
  should be used instead.

* The deprecated `Shrine.direct_endpoint` alias for `Shrine::UploadEndpoint`
  in direct_upload plugin has been removed.

* The `:presign` option in direct_upload plugin cannot be used for specifying
  presign options anymore; `:presign_options` should be used instead.

* `Shrine::Attacher#set` and `#assign` methods don't return the assigned
  uploaded file anymore.

* `Shrine::Attacher#delete!` doesn't spawn a background job anymore with
  backgrounding plugin, plugin writers should switch to `#_delete` instead.

* The phases when files are internally deleted have been renamed.

* Shrine doesn't officially support Rubinius anymore.

New plugins
===========

* The [shrine-reform] plugin has been released, which makes Shrine attachments
  work with [Reform] objects.

* The [shrine-mongoid] plugin has been released, which makes Shrine attachments
  work with [Mongoid] models.

New storages
============

* The [shrine-memory] storage has been released, which saves uploaded files
  in memory (useful in tests).

New features
============

* The built-in analyzers can now be used when implementing a custom MIME type
  analyzer in determine_mime_type plugin.

```rb
plugin :determine_mime_type, analyzer: ->(io, analyzers) do
  analyzers[:mimemagic].call(io) || analyzers[:file].call(io)
end
```

* The built-in analyzers can now be used when implementing a custom dimensions
  analyzer in store_dimensions plugin.

```rb
plugin :store_dimensions, analyzer: ->(io, analyzers) do
  dimensions = analyzers[:filemagic].call(io)
  dimensions || MiniMagick::Image.new(io).dimensions
end
```

* `Shrine::Attacher#cache!`, `#store!` and `#delete!` are now public (they are
  wrappers for `Shrine#upload` and `Shrine#delete` with context passed in).

* `Shrine::Attacher#_delete` has been added as a wrapper around `#delete!`,
  which the backgrounding plugin overrides and makes aynchronous. This nicely
  complements the `Shrine::Attacher#_promote` wrapper around `#promote`.

Other improvements
==================

* Shrine now prints a security warning when determine_mime_type plugin isn't
  loaded.

* Don't error in determine_mime_type with `:mimemagic` analyzer when MimeMagic
  cannot determine MIME of the file.

* When `:host` is given to S3 storage, URLs will now include the query
  parameters, unless `:public` is given, just like without `:host`.

* The Down version has been bumped to 2.2.0, which means the remote_url plugin
  now follows redirects (maximum of 2 redirects by default).

* The `Shrine::Attacher#_promote` and `Shrine::Attacher#promote` now have the
  same generalized method signature.

* The restore_cached_data plugin functionality won't get triggered anymore when
  form is submitted with already saved cached attachmnet (e.g. due to
  background processing).

* The restore_cached_data plugin now doesn't check anymore if the cached file
  exists (which saves an HTTP request with remote storages).

* The download_endpoint now makes only one HTTP request when downloading files
  from remote storages.

* The activerecord plugin now allows attachment modules to be included in
  non-ActiveRecord models.

* The sequel plugin now allows attachment modules to be included in
  non-Sequel models.

* Plugin options are now persisted when reapplying plugins.

```rb
Shrine.plugin :download_endpoint, storages: [:store], prefix: "/downloads", disposition: "inline"

class DocumentUploader < Shrine
  # all other options above will be persisted
  plugin :download_endpoint, disposition: "attachment"
end
```

* The `:include_error` has been removed from remote_url plugin, the error will
  now be included in the second argument depending on lambda's arity.

* The dynamic_storage plugin doesn't cache the instantiated storages anymore,
  which enables use cases like storing storage definitions in the database.

* The determine_mime_type plugin with `:file` analyzer now handles filenames
  that start with a dash ("-").

* `Shrine::Attacher` now allocates less strings.

[shrine-reform]: https://github.com/shrinerb/shrine-reform
[Reform]: https://github.com/apotonick/reform
[shrine-mongoid]: https://github.com/shrinerb/shrine-mongoid
[Mongoid]: https://github.com/mongodb/mongoid
[shrine-memory]: https://github.com/shrinerb/shrine-memory


text:
import {Component,OnInit} from '@angular/core';
import {LoginHService} from './loginh.service';
@Component({
  selector: 'loginh',
    templateUrl: './loginh.component.html',

})
export class LoginHComponent implements OnInit {

	localUser = {email:'',password:''} ;

  constructor(private _service : LoginHService) {
  }
  login() {

        this._service.loginfn(this.localUser).then((res) => {
            if(res)
            	console.log('hello connected')
            //this._router.navigate(['Dashboard']);
            else
            console.log(res);
        })
    }

  ngOnInit() {
   }

}


text:
function renderSourceTweet(post, target, logo) {

	var identifier = post.identifier;
	var timestamp = parseInt(post.timestamp)/1000;
	var moment = timeConverter(timestamp);
	var retweets = 	post.metadata['retweet_count'];

	var verified = post.metadata['user.verified'];
	if (verified==="true") verified="";
	else verified="";

	var friends = post.metadata['user.friends_count'];
	var followers = post.metadata['user.friends_count'];
	var statuses = post.metadata['user.statuses_count'];
	var userCreatedAt = post.metadata['user.created_at'];

	var credibility = parseFloat(post.metadata['risf.credibility.1']);
	credibility="Disabled";//credibility.toFixed(2);

	var sentiment = "Disabled";//post.metadata.sentiment;
	if (sentiment==="positive") sentiment="";
	else if (sentiment==="negative") sentiment="";
	else if (sentiment==="neutral") sentiment="";

	var aNewItem = document.createElement('div');
	aNewItem.setAttribute("id", "threadSourcePost")
        aNewItem.innerHTML = "Source Post
"+
	"
"+post.text+"
"+
	"
"+moment+"
"+
	""+
	"
"+
			"
"+
				"
"+
					""+
						"Source"+
						""+
					""+
				"
"+
				"
"+
					""+
						"Verified"+
						""+verified+""+
					""+
				"
"+
				"
"+
					""+
						"Retweets"+
						""+retweets+""+
					""+
				"
"+
				"
"+
					""+
						"Credibility"+
						""+credibility	+""+
					""+
				"
"+
				"
"+
					""+
						"Sentiment"+
						""+sentiment+""+
					""+
				"
"+
				"
"+
					""+
						"User Followers"+
						""+followers+""+
					""+
				"
"+
			"
"+
		"

";

        document.getElementById(target).appendChild(aNewItem);

}

//render a source tweet stored as a SUPER post
function renderSourceFB(post, target, nopreview, logo) {

	var identifier = post.identifier;
	var timestamp = parseInt(post.timestamp)/1000;
	var moment = timeConverter(timestamp);
	var likes = 	post.metadata['likesCount'];

	var fromCategory = post.metadata['from.category'];

	var shares = post.metadata['shares.count'];

	var link = post.metadata['link'];

	var credibility = parseFloat(post.metadata['risf.credibility.1']);
	credibility="Disabled";//credibility.toFixed(2);

	var sentiment = "Disabled";//post.metadata.sentiment;
	if (sentiment==="positive") sentiment="";
	else if (sentiment==="negative") sentiment="";
	else if (sentiment==="neutral") sentiment="";

	var mediaBlock = "";

	var type = post.metadata['type'];
	if (type === "photo") {
		mediaBlock = "

";
	}

	if (type === "video") {
		mediaBlock = "

";
	}

	var aNewItem = document.createElement('div');
	aNewItem.setAttribute("id", "threadSourcePost")
        aNewItem.innerHTML = "Source Post
"+
	"
"+post.text+"
"+
	"
"+moment+"
"+
	""+
	"
"+
			"
"+
			"
"+
				""+
					"Source"+
					""+
				""+
			"
"+
				"
"+
					""+
						"Post Type"+
						""+type+""+
					""+
				"
"+
				"
"+
					""+
						"User Type"+
						""+fromCategory+""+
					""+
				"
"+
				"
"+
				""+
					"Shares"+
					""+shares+""+
				""+
				"
"+
				"
"+
					""+
						"Likes"+
						""+likes+""+
					""+
				"
"+
				"
"+
					""+
						"Credibility"+
						""+credibility	+""+
					""+
				"
"+
				"
"+
					""+
						"Sentiment"+
						""+sentiment+""+
					""+
				"
"+
			"
"+
		"
"+mediaBlock+"
";

        document.getElementById(target).appendChild(aNewItem);

}

function renderThreadStats(thread, target) {

	var interactions = thread.statisicalData['sharedCount'];
	var replies = thread.statisicalData['threadsize'];
	var positivePosts = "Disabled";//thread.statisicalData['positivePosts'];
	var negativePosts = "Disabled";//thread.statisicalData['negativePosts'];

	var aNewItem = document.createElement('div');
        aNewItem.innerHTML = "Thread Statistics
"+
	"
"+
			"
"+
				"
"+
					""+
						"Interations"+
						""+interactions+""+
					""+
				"
"+
				"
"+
					""+
						"Replies"+
						""+replies+""+
					""+
				"
"+
				"
"+
					""+
						"Positive Sentiment"+
						""+positivePosts+" posts"+
					""+
				"
"+
				"
"+
					""+
						"Negative Sentiment"+
						""+negativePosts+" posts"+
					""+
				"
"+
			"
"+
		"
</div<";

        document.getElementById(target).appendChild(aNewItem);

}

function renderThreadGrowth(thread, target) {

	var growth1h = thread.statisicalData['growth1h'];
	var growth30m = thread.statisicalData['growth30m'];
	var growth10m = thread.statisicalData['growth10m'];
	var sharedCount = thread.statisicalData['sharedCount'];

	var shareTrend = "Finished";
	if ((parseFloat(thread.statisicalData.growth10m)<5)) {
		shareTrend = "Low Activity";
	}
	if ((parseFloat(thread.statisicalData.growth10m)>=5)) {
		shareTrend = "Active";
	}
	if ((parseFloat(thread.statisicalData.growth30m)*2)>parseFloat(sharedCount)) {
		shareTrend = "Bursting";
	}

	var aNewItem = document.createElement('div');
        aNewItem.innerHTML = "Activity Statistics
"+
	"
"+
			"
"+
				"
"+
					""+
						"10min Activity"+
						""+growth10m+" posts"+
					""+
				"
"+
				"
"+
					""+
						"30min Activity"+
						""+growth30m+" posts"+
					""+
				"
"+
				"
"+
					""+
						"Spread"+
						""+growth1h+" posts/hour"+
					""+
				"
"+
				"
"+
					""+
						"Status"+
						""+shareTrend+""+
					""+
				"
"+
			"
"+
		"
</div<";

        document.getElementById(target).appendChild(aNewItem);

}

function renderRISFInfo(thread, target) {

	var doubtScore = thread.statisicalData['doubtScore'];
	var threadsize = thread.statisicalData['threadsize'];
	var credibleScore = thread.statisicalData['credibleScore'];

	var credibilityLabel = "Low";
	if (parseFloat(credibleScore)>(parseFloat(threadsize)/4)) credibilityLabel = "Medium";
	if (parseFloat(credibleScore)>(parseFloat(threadsize)/2)) credibilityLabel = "High";

	var doubtLabel = "Low";
	if (parseFloat(doubtScore)>(parseFloat(threadsize)/4)) doubtLabel = "Medium";
	if (parseFloat(doubtScore)>(parseFloat(threadsize)/2)) doubtLabel = "High";

	var aNewItem = document.createElement('div');
        aNewItem.innerHTML = "Rumour / Credibility Analysis
"+
	"
"+
			"
"+
				"
"+
					""+
						"Aggregate Doubt Level"+
						""+parseFloat(doubtScore).toFixed(2)+" ("+doubtLabel+")"+
					""+
				"
"+
				"
"+
					""+
						"Aggregate Credibility"+
						""+parseFloat(credibleScore).toFixed(2)+" ("+credibilityLabel+")"+
					""+
				"
"+
			"
"+
		"
</div<";

        document.getElementById(target).appendChild(aNewItem);

}

function renderReplies(thread, target) {

	var replies = thread.replies;

	var timeline = document.createElement('div');

	addTimelineLine();

	var previousDateUnix = parseFloat(thread.sourcePost.timestamp)/1000;
	var previousDate = time10minConverter(previousDateUnix);
	//addTimelineTimestamp(previousDate);

	addTimelineItemMedia(thread.sourcePost)

	for ( var i = 0; i < replies.length; i++ ) {
		var replyPost = replies[i];

		var currentDateUnix = parseFloat(replyPost.timestamp)/1000;
		var currentDate = time10minConverter(currentDateUnix);
		if (currentDate===previousDate) {
			// do nothing
		} else {
			addTimelineTimestamp(currentDate);//+" (+"+timeDiff(previousDateUnix, currentDateUnix)+")");
			previousDate = currentDate;
		}

		if (thread.sourcePost.type === "FACEBOOKPOSTS") {
			addTimelineItemFB(replyPost);
			addTimelineItemMedia(replyPost)
		} else {
			addTimelineItemTweet(replyPost);
			addTimelineItemMedia(replyPost)
		}

	}

	timeline.innerHTML = "Thread Timeline
"+timelineBuffer+"
";

	document.getElementById(target).appendChild(timeline);

}

var timelineBuffer = "";

function addTimelineItemFB(post) {

	var identifier = post.identifier;
	var timestamp = parseInt(post.timestamp)/1000;
	var moment = timeConverter(timestamp);
	var likes = post.metadata['likeCount'];
	var text  = post.text;

	var comments = post.metadata['commentCount'];

	var doubt = parseFloat(post.metadata['risf.doubt.1']);
	if (doubt>0.6) doubt="";
	else doubt="";
	doubt = "Disabled";//

	var credibility = post.metadata['risf.credibility.label'];
	if (credibility==="unverified") credibility="Low";
	else credibility="Medium";;
	credibility = "Disabled";//

	var sentiment = post.metadata.sentiment;
	if (sentiment==="positive") sentiment="";
	else if (sentiment==="negative") sentiment="";
	else if (sentiment==="neutral") sentiment="";
	sentiment = "Disabled";//

	var html = "
"+
            "
"+
                ""+
            "
"+
            "
"+
                text+
                "
"+
			"
"+
				"
"+
					""+
						"Likes"+
						""+likes+""+
					""+
				"
"+
				"
"+
					""+
						"Comments"+
						""+comments+""+
					""+
				"
"+
				"
"+
					""+
						"Doubt"+
						""+doubt+""+
					""+
				"
"+
				"
"+
					""+
						"Credibility"+
						""+credibility	+""+
					""+
				"
"+
				"
"+
					""+
						"Sentiment"+
						""+sentiment+""+
					""+
				"
"+
			"
"+
		"
"+
	     "
"+
        "
";

	timelineBuffer =timelineBuffer+html;

}

function addTimelineItemTweet(post) {

	var identifier = post.identifier;
	var text  = post.text;
	var retweets = 	post.metadata['retweet_count'];
	var lang = 	post.metadata['lang'];

	var verified = post.metadata['user.verified'];
	if (verified==="true") verified="";
	else verified="";

	var friends = post.metadata['user.friends_count'];
	var followers = post.metadata['user.friends_count'];
	var statuses = post.metadata['user.statuses_count'];
	var userCreatedAt = post.metadata['user.created_at'];

	var doubt = parseFloat(post.metadata['risf.doubt.1']);
	if (doubt>0.6) doubt="";
	else doubt="";
	doubt = "Disabled";//

	var credibility = post.metadata['risf.credibility.label'];
	if (credibility==="unverified") credibility="Low";
	else credibility="Medium";;
	credibility = "Disabled";//

	var sentiment = post.metadata.sentiment;
	if (sentiment==="positive") sentiment="";
	else if (sentiment==="negative") sentiment="";
	else if (sentiment==="neutral") sentiment="";
	sentiment = "Disabled";//

	var html = "
"+
            "
"+
            	""+
                ""+
                ""+
            "
"+
            "
"+
                text+
                "
"+
			"
"+
				"
"+
					""+
						"Verified"+
						""+verified+""+
					""+
				"
"+
				"
"+
					""+
						"Retweets"+
						""+retweets+""+
					""+
				"
"+
				"
"+
					""+
						"Doubt"+
						""+doubt+""+
					""+
				"
"+
				"
"+
					""+
						"Credibility"+
						""+credibility	+""+
					""+
				"
"+
				"
"+
					""+
						"Sentiment"+
						""+sentiment+""+
					""+
				"
"+
				"
"+
					""+
						"User Followers"+
						""+followers+""+
					""+
				"
"+
			"
"+
		"
"+
	     "
"+
        "
";

	timelineBuffer =timelineBuffer+html;

}

function addTimelineItemMedia(post) {

	if (post.metadata.hasOwnProperty('entities.media')) {

		var mediaArray = JSON.parse(post.metadata['entities.media']);

		for ( var i = 0; i < mediaArray.length; i++ ) {

			var mediaItem = mediaArray[i];

			var transformedURL = mediaItem.media_url.replace("http://", "").replace(".", "_").replace(".", "_").replace(".", "_").replace(".", "_").replace(".", "_"); ;

			if (document.getElementById(transformedURL)===null) {

				if (mediaItem.type==="photo") {

				var photo = "
"+
            					"
"+
                					""+
            					"
"+
            					"
"+
							"

"+
						"
"+
        				     "
";

				timelineBuffer =timelineBuffer+photo;

				}

			}

		}
	}

}

function addTimelineLine() {

	var html = "

";

	timelineBuffer =timelineBuffer+html;

}

function addTimelineTimestamp(time) {

	var html = "
<time>"+time+"</time>
";

	timelineBuffer =timelineBuffer+html;

}

function time10minConverter(UNIX_timestamp){
  var a = new Date(UNIX_timestamp * 1000);
  var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
  var year = a.getFullYear();
  var month = months[a.getMonth()];
  var date = a.getDate();
  var hour = a.getHours();
  if (hour < 10) hour = "0"+hour;
  var min = a.getMinutes();
  if (min < 10) min = "0";
  else min = (""+(min/10)).substring(0,1)+"0";
  if (min==="0") min = "00";
  var time = date + ' ' + month + ' ' + year + ' ' + hour + ':' + min;
  return time;
}

function timeDiff( tstart, tend ) {
  var diff = Math.floor((tend - tstart)), units = [
    { d: 60, l: "seconds" },
    { d: 60, l: "minutes" },
    { d: 24, l: "hours" },
    { d: 7, l: "days" }
  ];

  var s = '';
  for (var i = 0; i < units.length; ++i) {
    if ((diff % units[i].d)>0) s = (diff % units[i].d) + " " + units[i].l + " " + s;
    diff = Math.floor(diff / units[i].d);
  }
  return s;
}


text:
from ray.rllib.env.base_env import BaseEnv
from ray.rllib.env.env_context import EnvContext
from ray.rllib.env.external_env import ExternalEnv
from ray.rllib.env.external_multi_agent_env import ExternalMultiAgentEnv
from ray.rllib.env.multi_agent_env import MultiAgentEnv
from ray.rllib.env.policy_client import PolicyClient
from ray.rllib.env.policy_server_input import PolicyServerInput
from ray.rllib.env.remote_vector_env import RemoteVectorEnv
from ray.rllib.env.vector_env import VectorEnv

from ray.rllib.env.wrappers.dm_env_wrapper import DMEnv
from ray.rllib.env.wrappers.dm_control_wrapper import DMCEnv
from ray.rllib.env.wrappers.group_agents_wrapper import GroupAgentsWrapper
from ray.rllib.env.wrappers.pettingzoo_env import PettingZooEnv
from ray.rllib.env.wrappers.pettingzoo_env import ParallelPettingZooEnv
from ray.rllib.env.wrappers.unity3d_env import Unity3DEnv

__all__ = [
    "BaseEnv",
    "DMEnv",
    "DMCEnv",
    "EnvContext",
    "ExternalEnv",
    "ExternalMultiAgentEnv",
    "GroupAgentsWrapper",
    "MultiAgentEnv",
    "PettingZooEnv",
    "ParallelPettingZooEnv",
    "PolicyClient",
    "PolicyServerInput",
    "RemoteVectorEnv",
    "Unity3DEnv",
    "VectorEnv",
]


text:
package com.adaptris.core.transform;

import com.adaptris.core.AdaptrisComponent;
import com.adaptris.core.AdaptrisMessage;
import com.adaptris.core.CoreException;

public interface MessageValidator extends AdaptrisComponent {

  void validate(AdaptrisMessage msg) throws CoreException;

}


text:
/*
 * History and Acknowledgments
 *
 * The original Linux driver for SQ905 based cameras was written by
 * Marcell Lengyel and furter developed by many other contributors
 * and is available from http://sourceforge.net/projects/sqcam/
 *
 * This driver takes advantage of the reverse engineering work done for
 * that driver and for libgphoto2 but shares no code with them.
 *
 * This driver has used as a base the finepix driver and other gspca
 * based drivers and may still contain code fragments taken from those
 * drivers.
 */

#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt

#define MODULE_NAME "sq905"

#include <linux/workqueue.h>
#include <linux/slab.h>
#include "gspca.h"

MODULE_AUTHOR("Adam Baker <linux@baker-net.org.uk>, "
		"Theodore Kilgore <kilgota@auburn.edu>");
MODULE_DESCRIPTION("GSPCA/SQ905 USB Camera Driver");
MODULE_LICENSE("GPL");

/* Default timeouts, in ms */
#define SQ905_CMD_TIMEOUT 500
#define SQ905_DATA_TIMEOUT 1000

/* Maximum transfer size to use. */
#define SQ905_MAX_TRANSFER 0x8000
#define FRAME_HEADER_LEN 64

/* The known modes, or registers. These go in the "value" slot. */

/* 00 is "none" obviously */

#define SQ905_BULK_READ	0x03	/* precedes any bulk read */
#define SQ905_COMMAND	0x06	/* precedes the command codes below */
#define SQ905_PING	0x07	/* when reading an "idling" command */
#define SQ905_READ_DONE 0xc0    /* ack bulk read completed */

/* Any non-zero value in the bottom 2 bits of the 2nd byte of
 * the ID appears to indicate the camera can do 640*480. If the
 * LSB of that byte is set the image is just upside down, otherwise
 * it is rotated 180 degrees. */
#define SQ905_HIRES_MASK	0x00000300
#define SQ905_ORIENTATION_MASK	0x00000100

/* Some command codes. These go in the "index" slot. */

#define SQ905_ID      0xf0	/* asks for model string */
#define SQ905_CONFIG  0x20	/* gets photo alloc. table, not used here */
#define SQ905_DATA    0x30	/* accesses photo data, not used here */
#define SQ905_CLEAR   0xa0	/* clear everything */
#define SQ905_CAPTURE_LOW  0x60	/* Starts capture at 160x120 */
#define SQ905_CAPTURE_MED  0x61	/* Starts capture at 320x240 */
#define SQ905_CAPTURE_HIGH 0x62	/* Starts capture at 640x480 (some cams only) */
/* note that the capture command also controls the output dimensions */

/* Structure to hold all of our device specific stuff */
struct sd {
	struct gspca_dev gspca_dev;	/* !! must be the first item */

	/*
	 * Driver stuff
	 */
	struct work_struct work_struct;
	struct workqueue_struct *work_thread;
};

static struct v4l2_pix_format sq905_mode[] = {
	{ 160, 120, V4L2_PIX_FMT_SBGGR8, V4L2_FIELD_NONE,
		.bytesperline = 160,
		.sizeimage = 160 * 120,
		.colorspace = V4L2_COLORSPACE_SRGB,
		.priv = 0},
	{ 320, 240, V4L2_PIX_FMT_SBGGR8, V4L2_FIELD_NONE,
		.bytesperline = 320,
		.sizeimage = 320 * 240,
		.colorspace = V4L2_COLORSPACE_SRGB,
		.priv = 0},
	{ 640, 480, V4L2_PIX_FMT_SBGGR8, V4L2_FIELD_NONE,
		.bytesperline = 640,
		.sizeimage = 640 * 480,
		.colorspace = V4L2_COLORSPACE_SRGB,
		.priv = 0}
};

/*
 * Send a command to the camera.
 */
static int sq905_command(struct gspca_dev *gspca_dev, u16 index)
{
	int ret;

	gspca_dev->usb_buf[0] = '\0';
	ret = usb_control_msg(gspca_dev->dev,
			      usb_sndctrlpipe(gspca_dev->dev, 0),
			      USB_REQ_SYNCH_FRAME,                /* request */
			      USB_DIR_OUT | USB_TYPE_VENDOR | USB_RECIP_DEVICE,
			      SQ905_COMMAND, index, gspca_dev->usb_buf, 1,
			      SQ905_CMD_TIMEOUT);
	if (ret < 0) {
		pr_err("%s: usb_control_msg failed (%d)\n", __func__, ret);
		return ret;
	}

	ret = usb_control_msg(gspca_dev->dev,
			      usb_sndctrlpipe(gspca_dev->dev, 0),
			      USB_REQ_SYNCH_FRAME,                /* request */
			      USB_DIR_IN | USB_TYPE_VENDOR | USB_RECIP_DEVICE,
			      SQ905_PING, 0, gspca_dev->usb_buf, 1,
			      SQ905_CMD_TIMEOUT);
	if (ret < 0) {
		pr_err("%s: usb_control_msg failed 2 (%d)\n", __func__, ret);
		return ret;
	}

	return 0;
}

/*
 * Acknowledge the end of a frame - see warning on sq905_command.
 */
static int sq905_ack_frame(struct gspca_dev *gspca_dev)
{
	int ret;

	gspca_dev->usb_buf[0] = '\0';
	ret = usb_control_msg(gspca_dev->dev,
			      usb_sndctrlpipe(gspca_dev->dev, 0),
			      USB_REQ_SYNCH_FRAME,                /* request */
			      USB_DIR_OUT | USB_TYPE_VENDOR | USB_RECIP_DEVICE,
			      SQ905_READ_DONE, 0, gspca_dev->usb_buf, 1,
			      SQ905_CMD_TIMEOUT);
	if (ret < 0) {
		pr_err("%s: usb_control_msg failed (%d)\n", __func__, ret);
		return ret;
	}

	return 0;
}

/*
 *  request and read a block of data - see warning on sq905_command.
 */
static int
sq905_read_data(struct gspca_dev *gspca_dev, u8 *data, int size, int need_lock)
{
	int ret;
	int act_len;

	gspca_dev->usb_buf[0] = '\0';
	if (need_lock)
		mutex_lock(&gspca_dev->usb_lock);
	ret = usb_control_msg(gspca_dev->dev,
			      usb_sndctrlpipe(gspca_dev->dev, 0),
			      USB_REQ_SYNCH_FRAME,                /* request */
			      USB_DIR_OUT | USB_TYPE_VENDOR | USB_RECIP_DEVICE,
			      SQ905_BULK_READ, size, gspca_dev->usb_buf,
			      1, SQ905_CMD_TIMEOUT);
	if (need_lock)
		mutex_unlock(&gspca_dev->usb_lock);
	if (ret < 0) {
		pr_err("%s: usb_control_msg failed (%d)\n", __func__, ret);
		return ret;
	}
	ret = usb_bulk_msg(gspca_dev->dev,
			   usb_rcvbulkpipe(gspca_dev->dev, 0x81),
			   data, size, &act_len, SQ905_DATA_TIMEOUT);

	/* successful, it returns 0, otherwise  negative */
	if (ret < 0 || act_len != size) {
		pr_err("bulk read fail (%d) len %d/%d\n", ret, act_len, size);
		return -EIO;
	}
	return 0;
}

/*
 * This function is called as a workqueue function and runs whenever the camera
 * is streaming data. Because it is a workqueue function it is allowed to sleep
 * so we can use synchronous USB calls. To avoid possible collisions with other
 * threads attempting to use gspca_dev->usb_buf we take the usb_lock when
 * performing USB operations using it. In practice we don't really need this
 * as the camera doesn't provide any controls.
 */
static void sq905_dostream(struct work_struct *work)
{
	struct sd *dev = container_of(work, struct sd, work_struct);
	struct gspca_dev *gspca_dev = &dev->gspca_dev;
	int bytes_left; /* bytes remaining in current frame. */
	int data_len;   /* size to use for the next read. */
	int header_read; /* true if we have already read the frame header. */
	int packet_type;
	int frame_sz;
	int ret;
	u8 *data;
	u8 *buffer;

	buffer = kmalloc(SQ905_MAX_TRANSFER, GFP_KERNEL | GFP_DMA);
	if (!buffer) {
		pr_err("Couldn't allocate USB buffer\n");
		goto quit_stream;
	}

	frame_sz = gspca_dev->cam.cam_mode[gspca_dev->curr_mode].sizeimage
			+ FRAME_HEADER_LEN;

	while (gspca_dev->present && gspca_dev->streaming) {
#ifdef CONFIG_PM
		if (gspca_dev->frozen)
			break;
#endif
		/* request some data and then read it until we have
		 * a complete frame. */
		bytes_left = frame_sz;
		header_read = 0;

		/* Note we do not check for gspca_dev->streaming here, as
		   we must finish reading an entire frame, otherwise the
		   next time we stream we start reading in the middle of a
		   frame. */
		while (bytes_left > 0 && gspca_dev->present) {
			data_len = bytes_left > SQ905_MAX_TRANSFER ?
				SQ905_MAX_TRANSFER : bytes_left;
			ret = sq905_read_data(gspca_dev, buffer, data_len, 1);
			if (ret < 0)
				goto quit_stream;
			PDEBUG(D_PACK,
				"Got %d bytes out of %d for frame",
				data_len, bytes_left);
			bytes_left -= data_len;
			data = buffer;
			if (!header_read) {
				packet_type = FIRST_PACKET;
				/* The first 64 bytes of each frame are
				 * a header full of FF 00 bytes */
				data += FRAME_HEADER_LEN;
				data_len -= FRAME_HEADER_LEN;
				header_read = 1;
			} else if (bytes_left == 0) {
				packet_type = LAST_PACKET;
			} else {
				packet_type = INTER_PACKET;
			}
			gspca_frame_add(gspca_dev, packet_type,
					data, data_len);
			/* If entire frame fits in one packet we still
			   need to add a LAST_PACKET */
			if (packet_type == FIRST_PACKET &&
			    bytes_left == 0)
				gspca_frame_add(gspca_dev, LAST_PACKET,
						NULL, 0);
		}
		if (gspca_dev->present) {
			/* acknowledge the frame */
			mutex_lock(&gspca_dev->usb_lock);
			ret = sq905_ack_frame(gspca_dev);
			mutex_unlock(&gspca_dev->usb_lock);
			if (ret < 0)
				goto quit_stream;
		}
	}
quit_stream:
	if (gspca_dev->present) {
		mutex_lock(&gspca_dev->usb_lock);
		sq905_command(gspca_dev, SQ905_CLEAR);
		mutex_unlock(&gspca_dev->usb_lock);
	}
	kfree(buffer);
}

/* This function is called at probe time just before sd_init */
static int sd_config(struct gspca_dev *gspca_dev,
		const struct usb_device_id *id)
{
	struct cam *cam = &gspca_dev->cam;
	struct sd *dev = (struct sd *) gspca_dev;

	/* We don't use the buffer gspca allocates so make it small. */
	cam->bulk = 1;
	cam->bulk_size = 64;

	INIT_WORK(&dev->work_struct, sq905_dostream);

	return 0;
}

/* called on streamoff with alt==0 and on disconnect */
/* the usb_lock is held at entry - restore on exit */
static void sd_stop0(struct gspca_dev *gspca_dev)
{
	struct sd *dev = (struct sd *) gspca_dev;

	/* wait for the work queue to terminate */
	mutex_unlock(&gspca_dev->usb_lock);
	/* This waits for sq905_dostream to finish */
	destroy_workqueue(dev->work_thread);
	dev->work_thread = NULL;
	mutex_lock(&gspca_dev->usb_lock);
}

/* this function is called at probe and resume time */
static int sd_init(struct gspca_dev *gspca_dev)
{
	u32 ident;
	int ret;

	/* connect to the camera and read
	 * the model ID and process that and put it away.
	 */
	ret = sq905_command(gspca_dev, SQ905_CLEAR);
	if (ret < 0)
		return ret;
	ret = sq905_command(gspca_dev, SQ905_ID);
	if (ret < 0)
		return ret;
	ret = sq905_read_data(gspca_dev, gspca_dev->usb_buf, 4, 0);
	if (ret < 0)
		return ret;
	/* usb_buf is allocated with kmalloc so is aligned.
	 * Camera model number is the right way round if we assume this
	 * reverse engineered ID is supposed to be big endian. */
	ident = be32_to_cpup((__be32 *)gspca_dev->usb_buf);
	ret = sq905_command(gspca_dev, SQ905_CLEAR);
	if (ret < 0)
		return ret;
	PDEBUG(D_CONF, "SQ905 camera ID %08x detected", ident);
	gspca_dev->cam.cam_mode = sq905_mode;
	gspca_dev->cam.nmodes = ARRAY_SIZE(sq905_mode);
	if (!(ident & SQ905_HIRES_MASK))
		gspca_dev->cam.nmodes--;

	if (ident & SQ905_ORIENTATION_MASK)
		gspca_dev->cam.input_flags = V4L2_IN_ST_VFLIP;
	else
		gspca_dev->cam.input_flags = V4L2_IN_ST_VFLIP |
					     V4L2_IN_ST_HFLIP;
	return 0;
}

/* Set up for getting frames. */
static int sd_start(struct gspca_dev *gspca_dev)
{
	struct sd *dev = (struct sd *) gspca_dev;
	int ret;

	/* "Open the shutter" and set size, to start capture */
	switch (gspca_dev->curr_mode) {
	default:
/*	case 2: */
		PDEBUG(D_STREAM, "Start streaming at high resolution");
		ret = sq905_command(&dev->gspca_dev, SQ905_CAPTURE_HIGH);
		break;
	case 1:
		PDEBUG(D_STREAM, "Start streaming at medium resolution");
		ret = sq905_command(&dev->gspca_dev, SQ905_CAPTURE_MED);
		break;
	case 0:
		PDEBUG(D_STREAM, "Start streaming at low resolution");
		ret = sq905_command(&dev->gspca_dev, SQ905_CAPTURE_LOW);
	}

	if (ret < 0) {
		PERR("Start streaming command failed");
		return ret;
	}
	/* Start the workqueue function to do the streaming */
	dev->work_thread = create_singlethread_workqueue(MODULE_NAME);
	queue_work(dev->work_thread, &dev->work_struct);

	return 0;
}

/* Table of supported USB devices */
static const struct usb_device_id device_table[] = {
	{USB_DEVICE(0x2770, 0x9120)},
	{}
};

MODULE_DEVICE_TABLE(usb, device_table);

/* sub-driver description */
static const struct sd_desc sd_desc = {
	.name   = MODULE_NAME,
	.config = sd_config,
	.init   = sd_init,
	.start  = sd_start,
	.stop0  = sd_stop0,
};

/* -- device connect -- */
static int sd_probe(struct usb_interface *intf,
		const struct usb_device_id *id)
{
	return gspca_dev_probe(intf, id,
			&sd_desc,
			sizeof(struct sd),
			THIS_MODULE);
}

static struct usb_driver sd_driver = {
	.name       = MODULE_NAME,
	.id_table   = device_table,
	.probe      = sd_probe,
	.disconnect = gspca_disconnect,
#ifdef CONFIG_PM
	.suspend = gspca_suspend,
	.resume  = gspca_resume,
	.reset_resume = gspca_resume,
#endif
};

module_usb_driver(sd_driver);


text:
package com.colobu.unittest.zookeeper;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.api.CuratorEvent;
import org.apache.curator.framework.api.CuratorListener;
import org.apache.curator.framework.api.CuratorWatcher;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.curator.utils.ZKPaths;
import org.apache.zookeeper.WatchedEvent;

public class CuratorApp {
	private String path = "/com/colobu/test";
	public String setAndGetData(String zookeeperConnectionString, String payload) {
		RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
		CuratorFramework client = CuratorFrameworkFactory.newClient(zookeeperConnectionString, retryPolicy);
		client.start();

		try {
			ZKPaths.mkdirs(client.getZookeeperClient().getZooKeeper(), path);
			client.setData().forPath(path, payload.getBytes());

			return new String(client.getData().forPath(path));
		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}

	public void watch(String zookeeperConnectionString) throws Exception {
		RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
		final CuratorFramework client = CuratorFrameworkFactory.newClient(zookeeperConnectionString, retryPolicy);
		client.start();
		client.getCuratorListenable().addListener(new CuratorListener() {

			public void eventReceived(CuratorFramework client, CuratorEvent event) throws Exception {
				System.err.println("CuratorListenable:" + event.getType() + ":" + new String(event.getData()));
			}
		});
		ZKPaths.mkdirs(client.getZookeeperClient().getZooKeeper(), path);

		new Thread() {
			@Override
			public void run() {
				try {
					client.getData().usingWatcher(new CuratorWatcher() {
						public void process(WatchedEvent event) throws Exception {
							System.out.println("Watcher:" + event.getType() + ":" + new String(event.getPath()));
						}
					}).forPath(path);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}}.start();

		for(int i =0; i < 10; i++) {
			client.setData().forPath(path, (System.currentTimeMillis()+"").getBytes());
			Thread.sleep(1000);
		}
	}

}


text:
<!doctype html>

	<meta charset="UTF-8">
	<title>{% block title %}{% endblock %}</title>
	<link rel="stylesheet" href="{{ url_for('static', filename='css/normalize.min.css')}}">
	<link rel="stylesheet" href="{{ url_for('static', filename='css/base.css')}}">
	<link rel="stylesheet" href="{{ url_for('static', filename='css/messages.css')}}">
	<link rel="stylesheet" href="{{ url_for('static', filename='icons-font.css')}}">

	{% block head %}
	{% endblock %}

	{% for category, message in get_flashed_messages(with_categories=true) %}

		X
		{{ message }}

	{% endfor %}

Home

	{% block content %}
	{% endblock %}


text:
var i = 0;
var m = 11                         // Perfectly valid even without a semicolon
console.log("m:", m);

// Multiple Statements
// 1. Multiple statements can be written on a single line using semicolons.
var j = 0;
var k = 1;                          // Same as var j = 0; var k = 1;
console.log("i, j, k: ", i, j, k);

// Statement Blocks
// 1. Statements can be grouped together using curly braces.
// 2. Unlike many other languages, blocks in JavaScript do not create a new scope, so variables should be
//    defined at the top of the function, and not in blocks.
var l = 0;
{
    var l = 2;
    l = l + 1;
    console.log("l:", l);
}
// Surprise, Surprise! Variable in JavaScript are in global namespace
console.log("l:", l);               // Prints 3 instead of 0

// Multi-line Statements
// 1. A statement in JavaScript can be split into multiple lines using \. Extra white spaces are ignored.
var sentence = "A quick brown fox jumps \
right over the lazy dog.";
console.log(sentence);


text:
In this exercise you have to implement a tool for the mathematical exercise [*Turmrechnen*](http://www.floriangeier.at/schule/kopf/kopf.php) with Angular.

## Requirements

* The exercise has to be implement with *Angular*
* Create two input fields for the parameter of the *Turm*
* Create a button with which the calculation can be started.
* Display all steps of the *Turm* as shown in the following screenshot:

* If the parameter *height* is < 2, display an error message in red as shown in the following screenshot:

## Extra point

You can earn an **extra point** for your grade by creating the solution using [StackBlitz](https://stackblitz.com) and sending me a link to it using a GitHub issue.

## Solution

You can find a sample solution (deliberately without comments) in [*app.component.ts*](app.component.ts), [*app.component.html*](app.component.html) and [*app.component.css*](app.component.css). You can try it live on [StackBlitz](https://stackblitz.com/edit/angular-efz4je). However, before you take a look at it, try to find your own solution!


text:
set -e
set -x

if [ x"$TRAVIS" = xtrue ]; then
	CPU_COUNT=2
fi

unset CFLAGS
unset CXXFLAGS
unset CPPFLAGS
unset DEBUG_CXXFLAGS
unset DEBUG_CPPFLAGS
unset LDFLAGS

INCLUDES="$(PKG_CONFIG_PATH=/usr/lib/x86_64-linux-gnu/pkgconfig pkg-config --dont-define-prefix --cflags libftdi1 libusb libudev)"
INCLUDES='-I/usr/include/libftdi1 -I/usr/include/libusb-1.0'
STATIC_LIBS="$(PKG_CONFIG_PATH=/usr/lib/x86_64-linux-gnu/pkgconfig pkg-config --dont-define-prefix --libs libftdi1 libusb)"
STATIC_LIBS="-L/usr/lib/x86_64-linux-gnu -lftdi1 -lusb-1.0 -lusb"
DYNAMIC_LIBS="$(PKG_CONFIG_PATH=/usr/lib/x86_64-linux-gnu/pkgconfig pkg-config --dont-define-prefix --libs libudev)"
DYNAMIC_LIBS="-L/lib/x86_64-linux-gnu -ludev"

export CFLAGS="$CFLAGS $INCLUDES"
export LDFLAGS="$LDFLAGS -lm -lstdc++ -lpthread -Wl,--whole-archive -Wl,-Bstatic $STATIC_LIBS -Wl,-Bdynamic -Wl,--no-whole-archive $DYNAMIC_LIBS"

make -j$CPU_COUNT

make install

iceprog -h


text:
package io.spacedog.services.push;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;

import com.amazonaws.services.sns.model.CreatePlatformApplicationRequest;
import com.amazonaws.services.sns.model.DeletePlatformApplicationRequest;
import com.amazonaws.services.sns.model.EndpointDisabledException;
import com.amazonaws.services.sns.model.PlatformApplication;
import com.amazonaws.services.sns.model.PlatformApplicationDisabledException;
import com.amazonaws.services.sns.model.PublishRequest;
import com.amazonaws.services.sns.model.SetPlatformApplicationAttributesRequest;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.common.base.Strings;

import io.spacedog.client.credentials.Credentials;
import io.spacedog.client.data.DataWrap;
import io.spacedog.client.http.SpaceFields;
import io.spacedog.client.push.BadgeStrategy;
import io.spacedog.client.push.Installation;
import io.spacedog.client.push.PushApplication;
import io.spacedog.client.push.PushProtocol;
import io.spacedog.client.push.PushRequest;
import io.spacedog.client.push.PushResponse;
import io.spacedog.client.push.PushResponse.Notification;
import io.spacedog.client.push.PushSettings;
import io.spacedog.client.schema.Schema;
import io.spacedog.services.JsonPayload;
import io.spacedog.services.Server;
import io.spacedog.services.Services;
import io.spacedog.services.SpaceService;
import io.spacedog.services.data.DataResults;
import io.spacedog.services.db.elastic.ElasticIndex;
import io.spacedog.utils.Check;
import io.spacedog.utils.Exceptions;
import io.spacedog.utils.Json;
import io.spacedog.utils.Utils;

public class PushService extends SpaceService implements SpaceFields {

	public static final String DATA_TYPE = "installation";

	// installation field names
	public static final String APP_ID = "appId";
	public static final String PROTOCOL = "protocol";
	public static final String TOKEN = "token";
	public static final String ENDPOINT = "endpoint";
	public static final String BADGE = "badge";
	public static final String TAGS = "tags";

	// push response field names
	public static final String PUSHED_TO = "pushedTo";
	public static final String FAILURES = "failures";

	//
	// Schema
	//

	public Schema getDefaultInstallationSchema() {
		return Schema.builder(DATA_TYPE)//
				.keyword(APP_ID)//
				.keyword(PROTOCOL)//
				.keyword(TOKEN)//
				.keyword(ENDPOINT)//
				.integer(BADGE)//
				.keyword(TAGS)//
				.build();
	}

	//
	// Applications
	//

	public List<PushApplication> listApps() {
		String backendId = Server.backend().id();

		List<PlatformApplication> applications = AwsSnsPusher.sns()//
				.listPlatformApplications()//
				.getPlatformApplications();

		return applications.stream()//
				.map(application -> toPushApplication(application))//
				.filter(application -> backendId.equals(application.backendId))//
				.collect(Collectors.toList());
	}

	public void saveApp(String name, PushProtocol protocol, //
			PushApplication.Credentials credentials) {

		PushApplication app = new PushApplication();
		app.name = name;
		app.backendId = Server.backend().id();
		app.protocol = protocol;
		app.credentials = credentials;
		deleteApp(app);

	}

	public void saveApp(PushApplication app) {
		Optional<PlatformApplication> application = getPlatformApplication(app);

		if (application.isPresent()) {
			SetPlatformApplicationAttributesRequest request = new SetPlatformApplicationAttributesRequest()//
					.withPlatformApplicationArn(application.get().getPlatformApplicationArn());

			if (!Strings.isNullOrEmpty(app.credentials.credentials))
				request.addAttributesEntry("PlatformCredential", app.credentials.credentials);

			if (!Strings.isNullOrEmpty(app.credentials.principal))
				request.addAttributesEntry("PlatformPrincipal", app.credentials.principal);

			AwsSnsPusher.sns().setPlatformApplicationAttributes(request);

		} else {

			CreatePlatformApplicationRequest request = new CreatePlatformApplicationRequest()//
					.withName(app.id())//
					.withPlatform(app.protocol.toString());

			if (!Strings.isNullOrEmpty(app.credentials.credentials))
				request.addAttributesEntry("PlatformCredential", app.credentials.credentials);

			if (!Strings.isNullOrEmpty(app.credentials.principal))
				request.addAttributesEntry("PlatformPrincipal", app.credentials.principal);

			AwsSnsPusher.sns().createPlatformApplication(request);
		}
	}

	public void deleteApp(String name, PushProtocol protocol) {
		PushApplication app = new PushApplication();
		app.name = name;
		app.backendId = Server.backend().id();
		app.protocol = protocol;
		deleteApp(app);
	}

	public void deleteApp(PushApplication app) {
		Optional<PlatformApplication> application = getPlatformApplication(app);

		if (application.isPresent()) {
			String applicationArn = application.get().getPlatformApplicationArn();

			AwsSnsPusher.sns().deletePlatformApplication(//
					new DeletePlatformApplicationRequest()//
							.withPlatformApplicationArn(applicationArn));
		}
	}

	private Optional<PlatformApplication> getPlatformApplication(PushApplication pushApp) {
		return AwsSnsPusher.getApplication(pushApp.id(), pushApp.protocol);
	}

	private PushApplication fromApplicationArn(String arn) {
		PushApplication pushApp = new PushApplication();
		String[] splitedArn = Utils.splitBySlash(arn);
		if (splitedArn.length != 3)
			throw Exceptions.runtime("invalid amazon platform application arn [%s]", arn);
		pushApp.protocol = PushProtocol.valueOf(splitedArn[1]);
		String[] splitedAppId = Utils.splitByDash(splitedArn[2]);
		if (splitedAppId.length == 2) {
			pushApp.backendId = splitedAppId[0];
			pushApp.name = splitedAppId[1];
		} else
			pushApp.name = splitedAppId[0];
		return pushApp;
	}

	private PushApplication toPushApplication(PlatformApplication application) {
		PushApplication pushApp = fromApplicationArn(application.getPlatformApplicationArn());
		pushApp.attributes = application.getAttributes();
		return pushApp;
	}

	//
	// Push
	//

	public PushResponse push(PushRequest request) {
		BoolQueryBuilder query = QueryBuilders.boolQuery();

		if (!Strings.isNullOrEmpty(request.appId))
			query.must(QueryBuilders.termQuery(APP_ID, request.appId));

		if (!Utils.isNullOrEmpty(request.credentialsIds))
			query.must(QueryBuilders.termsQuery(OWNER_FIELD, request.credentialsIds));

		if (!Utils.isNullOrEmpty(request.installationIds))
			query.must(QueryBuilders.idsQuery().addIds(request.installationIds));

		if (request.protocol != null)
			query.must(QueryBuilders.termQuery(PROTOCOL, request.protocol));

		if (request.usersOnly)
			query.must(QueryBuilders.existsQuery(OWNER_FIELD))//
					.mustNot(QueryBuilders.termQuery(OWNER_FIELD, //
							Credentials.GUEST.id()));

		if (!Utils.isNullOrEmpty(request.tags))
			for (String tag : request.tags)
				query.must(QueryBuilders.termQuery(TAGS, tag));

		Services.data().refresh(request.refresh, DATA_TYPE);

		SearchSourceBuilder source = SearchSourceBuilder.searchSource()//
				.fetchSource(new String[] { OWNER_FIELD, ENDPOINT, PROTOCOL, BADGE }, null)//
				.query(query)//
				.from(0)//
				.size(1000)//
				.version(false);

		// TODO use a scroll to push to all installations found
		SearchHits hits = elastic().search(source, index())//
				.getHits();

		if (hits.getTotalHits().value > 1000)
			throw Exceptions.forbidden(Server.context().credentials(), //
					"push to [%s] installations is a premium feature", //
					hits.getTotalHits());

		PushResponse response = new PushResponse();

		for (SearchHit hit : hits.getHits()) {
			Installation installation = Json.toPojo(//
					BytesReference.toBytes(hit.getSourceRef()), //
					Installation.class);

			DataWrap<Installation> wrap = DataWrap.wrap(installation).id(hit.getId());

			pushToInstallation(response, wrap, //
					toJsonMessage(request), request.badgeStrategy);

			if (response.applicationDisabled)
				break;
		}
		return response;
	}

	//
	// Installations
	//

	public DataWrap<Installation> getInstallation(String id) {
		return Services.data().getWrapped(DATA_TYPE, id, Installation.class);
	}

	public DataWrap<Installation> fetchInstallation(DataWrap<Installation> wrap) {
		return Services.data().fetch(wrap);
	}

	public DataWrap<Installation> saveInstallationIfAuthorized(Installation source) {
		return saveInstallationIfAuthorized(DataWrap.wrap(source));
	}

	public DataWrap<Installation> saveInstallationIfAuthorized(DataWrap<Installation> wrap) {

		wrap.type(DATA_TYPE);
		Installation installation = wrap.source();

		Check.notNullOrEmpty(installation.token(), TOKEN);
		Check.notNullOrEmpty(installation.appId(), APP_ID);
		Check.notNull(installation.protocol(), PROTOCOL);

		installation.endpoint(//
				Server.context().isTest() ? "FAKE_ENDPOINT_FOR_TESTING" //
						: AwsSnsPusher.createApplicationEndpoint(installation.appId(), //
								installation.protocol(), installation.token()));

		return Services.data().saveIfAuthorized(wrap, false);
	}

	public String patchInstallation(String id, Object source) {
		return Services.data().patch(DATA_TYPE, id, source);
	}

	public String saveInstallationField(String id, String field, Object object) {
		return Services.data().saveField(DATA_TYPE, id, field, object);
	}

	public DataResults<Installation> searchInstallations(SearchSourceBuilder source) {
		return Services.data().search(Installation.class, source, DATA_TYPE);
	}

	public void deleteInstallation(String id) {
		deleteInstallation(id, true);
	}

	public void deleteInstallation(String id, boolean throwNotFound) {
		Services.data().delete(DATA_TYPE, id, throwNotFound);
	}

	//
	// Installation tags
	//

	public String[] getTags(String installationId) {
		return Services.data().getField(DATA_TYPE, installationId, "tags", String[].class);
	}

	public String setTags(String installationId, String... tags) {
		return Services.data().saveField(DATA_TYPE, installationId, "tags", tags);
	}

	public String deleteTags(String installationId) {
		return Services.data().deleteField(DATA_TYPE, installationId, TAGS);
	}

	//
	// Index help methods
	//

	public ElasticIndex index() {
		return Services.data().index(DATA_TYPE);
	}

	//
	// Implementation
	//

	void pushToInstallation(PushResponse response, //
			DataWrap<Installation> installation, //
			ObjectNode jsonMessage, BadgeStrategy badgeStrategy) {

		Notification notification = new Notification();
		notification.installationId = installation.id();
		response.notifications.add(notification);

		try {

			if (!Strings.isNullOrEmpty(installation.owner()))
				notification.owner = installation.owner();

			jsonMessage = badgeObjectMessage(//
					installation, jsonMessage, badgeStrategy);

			ObjectNode snsMessage = toSnsMessage(installation.source().protocol(), jsonMessage);

			if (!Server.context().isTest()) {
				PublishRequest pushRequest = new PublishRequest()//
						.withTargetArn(installation.source().endpoint())//
						.withMessageStructure("json")//
						.withMessage(snsMessage.toString());

				AwsSnsPusher.sns().publish(pushRequest);
			} else
				notification.message = snsMessage;

		} catch (Exception e) {
			response.failures = response.failures + 1;
			notification.error = JsonPayload.toJson(e, //
					Server.context().debug().isTrue());

			if (e instanceof EndpointDisabledException //
					|| e.getMessage().contains(//
							"No endpoint found for the target arn specified")) {

				notification.installationDisabled = true;
				removeEndpointQuietly(installation.id());
			}

			if (e instanceof PlatformApplicationDisabledException)
				response.applicationDisabled = true;
		}
	}

	static ObjectNode toJsonMessage(PushRequest request) {

		return request.data == null //
				? Json.object("default", request.text, //
						"APNS", Json.object("aps", Json.object("alert", request.text)), //
						"APNS_SANDBOX", Json.object("aps", Json.object("alert", request.text)), //
						"GCM", Json.object("notification", Json.object("body", request.text)))//
				: request.data;
	}

	static ObjectNode toSnsMessage(PushProtocol protocol, ObjectNode message) {

		JsonNode node = message.get(protocol.toString());
		if (!Json.isNull(node))
			return Json.object(protocol.toString(), toSnsMessageStringValue(protocol, node));

		node = message.get("default");
		if (!Json.isNull(node))
			return Json.object("default", toSnsMessageStringValue(protocol, node));

		throw Exceptions.illegalArgument(//
				"no push message for default nor [%s] service", protocol);
	}

	static String toSnsMessageStringValue(PushProtocol protocol, JsonNode message) {
		if (message.isObject())
			return message.toString();

		// be careful not to 'toString' simple text values
		// because it would double quote stringified objects
		if (message.isValueNode())
			return message.asText();

		throw Exceptions.illegalArgument("push message [%s][%s] is invalid", protocol, message);
	}

	private ObjectNode badgeObjectMessage(DataWrap<Installation> installation, //
			ObjectNode message, BadgeStrategy badgeStrategy) {

		if (badgeStrategy == null || //
				BadgeStrategy.manual.equals(badgeStrategy))
			return message;

		if (PushProtocol.APNS.equals(installation.source().protocol())//
				|| PushProtocol.APNS_SANDBOX.equals(installation.source().protocol())) {

			if (BadgeStrategy.auto.equals(badgeStrategy)) {
				installation.source().badge(installation.source().badge() + 1);

				// update installation badge in data store
				Services.data().patch(installation.type(), //
						installation.id(), installation.version(), //
						Json.object(BADGE, installation.source().badge()));
			}

			message.with(installation.source().protocol().toString())//
					.with("aps").put(BADGE, installation.source().badge());
		}
		return message;
	}

	private void removeEndpointQuietly(String id) {
		try {
			deleteInstallation(id);
		} catch (Throwable t) {
			System.err.println(String.format(//
					"[Warning] failed to delete disabled installation [%s]", id));
			t.printStackTrace();
		}
	}

	public PushSettings settings() {
		return Services.settings().getOrThrow(PushSettings.class);
	}

}


text:
"""Calculate heterogeneity and sub-clonal populations for complex input samples.

Use allele frequencies, copy number calls and structural variants to infer
sub-clonal populations within a potentially mixed population. This attempts
to infer these sub-clones to help improve variant calls and interpretation
especially in complex cancer samples.
"""
from __future__ import print_function
import collections
import os

from bcbio import utils
from bcbio.heterogeneity import bubbletree, phylowgs, theta
from bcbio.pipeline import datadict as dd
from bcbio.variation import vcfutils

def _get_calls(data, cnv_only=False):
    """Retrieve calls, organized by name, to use for heterogeneity analysis.
    """
    cnvs_supported = set(["cnvkit", "battenberg"])
    out = {}
    for sv in data.get("sv", []):
        if not cnv_only or sv["variantcaller"] in cnvs_supported:
            out[sv["variantcaller"]] = sv
    return out

def get_variants(data, include_germline=False):
    """Retrieve set of variant calls to use for heterogeneity analysis.
    """
    data = utils.deepish_copy(data)
    supported = ["precalled", "vardict", "vardict-java", "vardict-perl",
                 "freebayes", "octopus", "strelka2"]
    # Right now mutect2 and mutect do not provide heterozygous germline calls
    # to be useful https://github.com/bcbio/bcbio-nextgen/issues/2464
    # supported += ["mutect2", "mutect"]
    if include_germline:
        supported.insert(1, "gatk-haplotype")
    out = []
    # CWL based input
    if isinstance(data.get("variants"), dict) and "samples" in data["variants"]:
        cur_vs = []
        # Unpack single sample list of files
        if (isinstance(data["variants"]["samples"], (list, tuple)) and
              len(data["variants"]["samples"]) == 1 and isinstance(data["variants"]["samples"][0], (list, tuple))):
            data["variants"]["samples"] = data["variants"]["samples"][0]
        for fname in data["variants"]["samples"]:
            variantcaller = utils.splitext_plus(os.path.basename(fname))[0]
            variantcaller = variantcaller.replace(dd.get_sample_name(data) + "-", "")
            for batch in dd.get_batches(data):
                variantcaller = variantcaller.replace(batch + "-", "")
            cur_vs.append({"vrn_file": fname, "variantcaller": variantcaller})
        data["variants"] = cur_vs
    for v in data.get("variants", []):
        if v["variantcaller"] in supported and v.get("vrn_file"):
            out.append((supported.index(v["variantcaller"]), v))
    out.sort()
    return [xs[1] for xs in out]

def _ready_for_het_analysis(items):
    """Check if a sample has input information for heterogeneity analysis.

    We currently require a tumor/normal sample containing both CNV and variant calls.
    """
    paired = vcfutils.get_paired_bams([dd.get_align_bam(d) for d in items], items)
    has_het = any(dd.get_hetcaller(d) for d in items)
    if has_het and paired:
        return get_variants(paired.tumor_data) and _get_calls(paired.tumor_data, cnv_only=True)

def _get_batches(data):
    batches = dd.get_batch(data) or dd.get_sample_name(data)
    if not isinstance(batches, (list, tuple)):
        batches = [batches]
    return batches

def _group_by_batches(items):
    out = collections.OrderedDict()
    for data in (utils.to_single_data(xs) for xs in items):
        for b in _get_batches(data):
            try:
                out[b].append(data)
            except KeyError:
                out[b] = [data]
    return out

def _get_hetcallers(items):
    out = set([])
    for d in items:
        hetcaller = dd.get_hetcaller(d)
        if hetcaller:
            out = out.union(set(hetcaller))
    return sorted(list(out))

def estimate(items, batch, config):
    """Estimate heterogeneity for a pair of tumor/normal samples. Run in parallel.
    """
    hetcallers = {"theta": theta.run,
                  "phylowgs": phylowgs.run,
                  "bubbletree": bubbletree.run}
    paired = vcfutils.get_paired_bams([dd.get_align_bam(d) for d in items], items)
    calls = _get_calls(paired.tumor_data)
    variants = get_variants(paired.tumor_data)
    het_info = []
    for hetcaller in _get_hetcallers(items):
        try:
            hetfn = hetcallers[hetcaller]
        except KeyError:
            hetfn = None
            print("%s not yet implemented" % hetcaller)
        if hetfn:
            hetout = hetfn(variants[0], calls, paired)
            if hetout:
                het_info.append(hetout)
    out = []
    for data in items:
        if batch == _get_batches(data)[0]:
            if dd.get_sample_name(data) == paired.tumor_name:
                if het_info:
                    data["heterogeneity"] = het_info
            out.append([data])
    return out

def run(items, run_parallel):
    """Top level entry point for calculating heterogeneity, handles organization and job distribution.
    """
    to_process = []
    extras = []
    for batch, cur_items in _group_by_batches(items).items():
        if _ready_for_het_analysis(cur_items):
            to_process.append((batch, cur_items))
        else:
            for data in cur_items:
                extras.append([data])
    processed = run_parallel("heterogeneity_estimate", ([xs, b, xs[0]["config"]] for b, xs in to_process))
    return _group_by_sample_and_batch(extras + processed)

def _group_by_sample_and_batch(samples):
    """Group samples split by heterogeneity method back one per sample-batch.

    Groups potentially multiple shared samples (multi batch normals) into
    single items per group.
    """
    out = collections.defaultdict(list)
    for data in [utils.to_single_data(x) for x in samples]:
        out[(dd.get_sample_name(data), dd.get_align_bam(data), tuple(_get_batches(data)))].append(data)
    return [[xs[0]] for xs in out.values()]


text:
include_recipe 'imagemagick-source::ohai_plugin'
include_recipe 'build-essential'

execute 'apt-get update'
execute 'apt-get -y build-dep imagemagick' do
  not_if do
    `apt-get -s build-dep imagemagick`[/(\d+)\snewly\sinstalled/m, 1].to_i == 0
  end
end

package 'checkinstall'

im_url = node['imagemagick-source']['url']
im_src_basename = ::File.basename(im_url).split('?').first
im_src_dirname = Chef::Config['file_cache_path'] || '/tmp'
im_src_path = "#{im_src_dirname}/#{im_src_basename}"
configure_flags = node['imagemagick-source']['configure_flags'] || []

im_installed = -> do
  ::File.exists?('/usr/local/bin/convert') &&
    ( node.automatic_attrs['imagemagick'] &&
      node.automatic_attrs['imagemagick']['version'] == node['imagemagick-source']['version'] &&
      node.automatic_attrs['imagemagick']['configure_arguments'].sort == configure_flags.sort
    )
end

remote_file im_url do
  source im_url
  path im_src_path
  backup false
  not_if { im_installed.call }
end

bash "compile_imagemagick_source" do
  cwd im_src_dirname
  code <<-EOH
    tar zxf #{im_src_basename} -C #{im_src_dirname} &&
    ls -al; true
    cd #{::File.basename(im_src_basename, '.tar.gz')} &&
    ./configure #{configure_flags.join(' ')} &&
    make && checkinstall
  EOH

  not_if { im_installed.call }
end

execute 'ldconfig /usr/local/lib' do
  not_if { system('ldconfig -p | grep libMagickCore') }
end