text:
require_relative "../../abstract_unit"
require "active_support/cache"
require_relative "../behaviors"
require "dalli"

class MemCacheStoreTest < ActiveSupport::TestCase
  # Emulates a latency on Dalli's back-end for the key latency to facilitate
  # connection pool testing.
  class SlowDalliClient < Dalli::Client
    def get(key, options = {})
      if /latency/.match?(key)
        sleep 3
        super
      else
        super
      end
    end
  end

  class UnavailableDalliServer < Dalli::Protocol::Binary
    def alive? # before https://github.com/petergoldstein/dalli/pull/863
      false
    end

    def ensure_connected! # after https://github.com/petergoldstein/dalli/pull/863
      false
    end
  end

  if ENV["CI"]
    MEMCACHE_UP = true
  else
    begin
      servers = ENV["MEMCACHE_SERVERS"] || "localhost:11211"
      ss = Dalli::Client.new(servers).stats
      raise Dalli::DalliError unless ss[servers] || ss[servers + ":11211"]

      MEMCACHE_UP = true
    rescue Dalli::DalliError
      $stderr.puts "Skipping memcached tests. Start memcached and try again."
      MEMCACHE_UP = false
    end
  end

  def lookup_store(options = {})
    cache = ActiveSupport::Cache.lookup_store(*store, { namespace: @namespace }.merge(options))
    (@_stores ||= []) << cache
    cache
  end

  def setup
    skip "memcache server is not up" unless MEMCACHE_UP

    @namespace = "test-#{Random.rand(16**32).to_s(16)}"
    @cache = lookup_store(expires_in: 60)
    @peek = lookup_store
    @cache.logger = ActiveSupport::Logger.new(File::NULL)
  end

  def after_teardown
    return unless defined?(@_stores) # because skipped test

    stores, @_stores = @_stores, []
    stores.each do |store|
      # Eagerly closing Dalli connection avoid file descriptor exhaustion.
      # Otherwise the test suite is flaky when ran repeatedly
      store.instance_variable_get(:@data).close
    end
  end

  include CacheStoreBehavior
  include CacheStoreVersionBehavior
  include CacheStoreCoderBehavior
  include LocalCacheBehavior
  include CacheIncrementDecrementBehavior
  include CacheInstrumentationBehavior
  include EncodedKeyCacheBehavior
  include ConnectionPoolBehavior
  include FailureSafetyBehavior

  # Overrides test from LocalCacheBehavior in order to stub out the cache clear
  # and replace it with a delete.
  def test_clear_also_clears_local_cache
    key = SecureRandom.uuid
    cache = lookup_store(raw: true)
    client.stub(:flush_all, -> { client.delete(key) }) do
      cache.with_local_cache do
        cache.write(key, SecureRandom.alphanumeric)
        cache.clear
        assert_nil cache.read(key)
      end
      assert_nil cache.read(key)
    end
  end

  def test_raw_values
    cache = lookup_store(raw: true)
    cache.write("foo", 2)
    assert_equal "2", cache.read("foo")
  end

  def test_raw_read_entry_compression
    cache = lookup_store(raw: true)
    cache.write("foo", 2)

    assert_not_called_on_instance_of ActiveSupport::Cache::Entry, :compressed do
      cache.read("foo")
    end
  end

  def test_raw_values_with_marshal
    cache = lookup_store(raw: true)
    cache.write("foo", Marshal.dump([]))
    assert_equal Marshal.dump([]), cache.read("foo")
  end

  def test_local_cache_raw_values
    cache = lookup_store(raw: true)
    cache.with_local_cache do
      cache.write("foo", 2)
      assert_equal "2", cache.read("foo")
    end
  end

  def test_increment_expires_in
    cache = lookup_store(raw: true, namespace: nil)
    assert_called_with client(cache), :incr, [ "foo", 1, 60 ] do
      cache.increment("foo", 1, expires_in: 60)
    end
  end

  def test_decrement_expires_in
    cache = lookup_store(raw: true, namespace: nil)
    assert_called_with client(cache), :decr, [ "foo", 1, 60 ] do
      cache.decrement("foo", 1, expires_in: 60)
    end
  end

  def test_dalli_cache_nils
    cache = lookup_store(cache_nils: false)
    cache.fetch("nil_foo") { nil }
    assert_equal "bar", cache.fetch("nil_foo") { "bar" }

    cache1 = lookup_store(cache_nils: true)
    cache1.fetch("not_nil_foo") { nil }
    assert_nil cache.fetch("not_nil_foo") { "bar" }
  end

  def test_local_cache_raw_values_with_marshal
    cache = lookup_store(raw: true)
    cache.with_local_cache do
      cache.write("foo", Marshal.dump([]))
      assert_equal Marshal.dump([]), cache.read("foo")
    end
  end

  def test_read_should_return_a_different_object_id_each_time_it_is_called
    @cache.write("foo", "bar")
    value = @cache.read("foo")
    assert_not_equal value.object_id, @cache.read("foo").object_id
    value << "bingo"
    assert_not_equal value, @cache.read("foo")
  end

  def test_no_compress_when_below_threshold
    cache = lookup_store(compress: true, compress_threshold: 10.kilobytes)
    val = random_string(2.kilobytes)
    compressed = Zlib::Deflate.deflate(val)

    assert_called(
      Zlib::Deflate,
      :deflate,
      "Memcached writes should not compress when below compress threshold.",
      times: 0,
      returns: compressed
    ) do
      cache.write("foo", val)
    end
  end

  def test_no_multiple_compress
    cache = lookup_store(compress: true)
    val = random_string(100.kilobytes)
    compressed = Zlib::Deflate.deflate(val)

    assert_called(
      Zlib::Deflate,
      :deflate,
      "Memcached writes should not perform duplicate compression.",
      times: 1,
      returns: compressed
    ) do
      cache.write("foo", val)
    end
  end

  def test_unless_exist_expires_when_configured
    cache = ActiveSupport::Cache.lookup_store(:mem_cache_store)
    assert_called_with client(cache), :add, [ "foo", Object, 1, Hash ] do
      cache.write("foo", "bar", expires_in: 1, unless_exist: true)
    end
  end

  def test_uses_provided_dalli_client_if_present
    cache = ActiveSupport::Cache.lookup_store(:mem_cache_store, Dalli::Client.new("custom_host"))

    assert_equal ["custom_host"], servers(cache)
  end

  def test_forwards_string_addresses_if_present
    expected_addresses = ["first", "second"]
    cache = ActiveSupport::Cache.lookup_store(:mem_cache_store, expected_addresses)

    assert_equal expected_addresses, servers(cache)
  end

  def test_falls_back_to_localhost_if_no_address_provided_and_memcache_servers_undefined
    with_memcache_servers_environment_variable(nil) do
      cache = ActiveSupport::Cache.lookup_store(:mem_cache_store)

      assert_equal ["127.0.0.1:11211"], servers(cache)
    end
  end

  def test_falls_back_to_localhost_if_address_provided_as_nil
    with_memcache_servers_environment_variable(nil) do
      cache = ActiveSupport::Cache.lookup_store(:mem_cache_store, nil)

      assert_equal ["127.0.0.1:11211"], servers(cache)
    end
  end

  def test_falls_back_to_localhost_if_no_address_provided_and_memcache_servers_defined
    with_memcache_servers_environment_variable("custom_host") do
      cache = ActiveSupport::Cache.lookup_store(:mem_cache_store)

      assert_equal ["custom_host"], servers(cache)
    end
  end

  def test_large_string_with_default_compression_settings
    assert_compressed(LARGE_STRING)
  end

  def test_large_object_with_default_compression_settings
    assert_compressed(LARGE_OBJECT)
  end

  def test_can_load_raw_values_from_dalli_store
    key = "test-with-value-the-way-the-dalli-store-did"

    @cache.instance_variable_get(:@data).with { |c| c.set(@cache.send(:normalize_key, key, nil), "value", 0, compress: false) }
    assert_nil @cache.read(key)
    assert_equal "value", @cache.fetch(key) { "value" }
  end

  def test_can_load_raw_falsey_values_from_dalli_store
    key = "test-with-false-value-the-way-the-dalli-store-did"

    @cache.instance_variable_get(:@data).with { |c| c.set(@cache.send(:normalize_key, key, nil), false, 0, compress: false) }
    assert_nil @cache.read(key)
    assert_equal false, @cache.fetch(key) { false }
  end

  def test_can_load_raw_values_from_dalli_store_with_local_cache
    key = "test-with-value-the-way-the-dalli-store-did-with-local-cache"

    @cache.instance_variable_get(:@data).with { |c| c.set(@cache.send(:normalize_key, key, nil), "value", 0, compress: false) }
    @cache.with_local_cache do
      assert_nil @cache.read(key)
      assert_equal "value", @cache.fetch(key) { "value" }
    end
  end

  def test_can_load_raw_falsey_values_from_dalli_store_with_local_cache
    key = "test-with-false-value-the-way-the-dalli-store-did-with-local-cache"

    @cache.instance_variable_get(:@data).with { |c| c.set(@cache.send(:normalize_key, key, nil), false, 0, compress: false) }
    @cache.with_local_cache do
      assert_nil @cache.read(key)
      assert_equal false, @cache.fetch(key) { false }
    end
  end

  private
    def random_string(length)
      (0...length).map { (65 + rand(26)).chr }.join
    end

    def store
      [:mem_cache_store]
    end

    def emulating_latency
      old_client = Dalli.send(:remove_const, :Client)
      Dalli.const_set(:Client, SlowDalliClient)

      yield
    ensure
      Dalli.send(:remove_const, :Client)
      Dalli.const_set(:Client, old_client)
    end

    def emulating_unavailability
      old_server = Dalli::Protocol.send(:remove_const, :Binary)
      Dalli::Protocol.const_set(:Binary, UnavailableDalliServer)

      yield ActiveSupport::Cache::MemCacheStore.new
    ensure
      Dalli::Protocol.send(:remove_const, :Binary)
      Dalli::Protocol.const_set(:Binary, old_server)
    end

    def servers(cache = @cache)
      client(cache).instance_variable_get(:@servers)
    end

    def client(cache = @cache)
      cache.instance_variable_get(:@data)
    end

    def with_memcache_servers_environment_variable(value)
      original_value = ENV["MEMCACHE_SERVERS"]
      ENV["MEMCACHE_SERVERS"] = value
      yield
    ensure
      if original_value.nil?
        ENV.delete("MEMCACHE_SERVERS")
      else
        ENV["MEMCACHE_SERVERS"] = original_value
      end
    end
end

class OptimizedMemCacheStoreTest < MemCacheStoreTest
  def setup
    @previous_format = ActiveSupport::Cache.format_version
    ActiveSupport::Cache.format_version = 7.0
    super
  end

  def teardown
    super
    ActiveSupport::Cache.format_version = @previous_format
  end

  def test_forward_compatibility
    previous_format = ActiveSupport::Cache.format_version
    ActiveSupport::Cache.format_version = 6.1
    @old_store = lookup_store
    ActiveSupport::Cache.format_version = previous_format

    @old_store.write("foo", "bar")
    assert_equal "bar", @cache.read("foo")
  end

  def test_backward_compatibility
    previous_format = ActiveSupport::Cache.format_version
    ActiveSupport::Cache.format_version = 6.1
    @old_store = lookup_store
    ActiveSupport::Cache.format_version = previous_format

    @cache.write("foo", "bar")
    assert_equal "bar", @old_store.read("foo")
  end
end


text:
require 'sass'
require_relative 'script'

module Gluey::Glues
    class Sass < Script

      class << self
        # Options that are passed to Sass::Engine.
        attr_accessor :engine_opts
      end
      self.engine_opts = {line_comments: true}

      # Processes sass source files (by given base_file) into css and notes dependencies.
      # @return [String] Resulted css output.
      def process(base_file, deps)
        opts = self.class.engine_opts.merge syntax: @material.file_extension.to_sym,
            load_paths: [File.expand_path('..', base_file)],
            cache_store: ::Sass::CacheStores::Filesystem.new("#{@context.cache_path}/.sass"),
            filename: base_file

        engine = ::Sass::Engine.new super(base_file, deps), opts
        output = engine.render

        engine.dependencies.each do |dependency|
          deps << ::Gluey::Dependencies::SingleFile.new(dependency.options[:filename]).actualize
        end

        output
      end

    end
  end

redpajama_set_name: RedPajamaGithub


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
Lotos 6: 78 (1856)

#### Original name
Placidium custnani A. Massal.

### Remarks
null


text:
=====
Usage
=====

The application can enable TinyMCE for one form field using the ``widget``
keyword argument of ``Field`` constructors or for all textareas on a page using
a view.

.. _widget:

Using the widget
----------------

If you use the widget (recommended) you need to add some python code and
possibly modify your template.

Python code
^^^^^^^^^^^

The TinyMCE widget can be enabled by setting it as the widget for a formfield.
For example, to use a nice big TinyMCE widget for the content field of a
flatpage form you could use the following code::

  from django import forms
  from django.contrib.flatpages.models import FlatPage
  from tinymce.widgets import TinyMCE

  class FlatPageForm(forms.ModelForm):
      ...
      content = forms.CharField(widget=TinyMCE(attrs={'cols': 80, 'rows': 30}))
      ...

      class Meta:
          model = FlatPage

The widget accepts the following extra keyword argument:

``mce_attrs`` (default: ``{}``)
  Extra TinyMCE configuration options. Options from
  ``settings.TINYMCE_DEFAULT_CONFIG`` (see :ref:`configuration`) are applied
  first and can be overridden.
  Python types are automatically converted to Javascript types, using standard
  JSON encoding. For example, to disable word wrapping you would include
  ``'nowrap': True``.

The tinymce application adds one TinyMCE configuration option that can be set
using ``mce_attrs`` (it is not useful as a default configuration):

``content_language`` (default: ``django.utils.translation.get_language_code()``)
  The language of the widget content. Will be used to set the ``language``,
  ``directionality`` and ``spellchecker_languages`` configuration options of
  the TinyMCE editor. It may be different from the interface language, which
  defaults to the current Django language and can be changed using the
  ``language`` configuration option in ``mce_attrs``)

Templates
^^^^^^^^^

The widget requires a link to the TinyMCE javascript code. The
``django.contrib.admin`` templates do this for you automatically, so if you are
just using tinymce in admin forms then you are done. In your own templates
containing a TinyMCE widget you must add the following to the HTML ``HEAD``
section (assuming you named your form 'form')::

      ...
      {{ form.media }}

See also `the section of form media`_ in the Django documentation.

.. _`the section of form media`: http://www.djangoproject.com/documentation/forms/#media-on-forms

The ``HTMLField`` model field type
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

For lazy developers the tinymce application also contains a model field type
for storing HTML. It uses the TinyMCE widget to render its form field. In this
example, the admin will render the ``my_field`` field using the TinyMCE
widget::

  from django.db import models
  from tinymce import models as tinymce_models

  class MyModel(models.Model):
      my_field = tinymce_models.HTMLField()

In all other regards, ``HTMLField`` behaves just like the standard Django
``TextField`` field type.

Using the view
--------------

If you cannot or will not change the widget on a form you can also use the
``tinymce-js`` named view to convert some or all textfields on a page to
TinyMCE editors. On the template of the page, add the following lines to the
``HEAD`` element::

The use of ``STATIC_URL`` needs the
``django.core.context_processors.static`` context processors.

You may want to use``{% static %}`` instead like::

Be careful that some ``STATICFILES_STORAGE`` will modify your
``tiny_mce.js`` file name and your file will fail to load.

The ``NAME`` argument allows you to create multiple TinyMCE configurations. Now
create a template containing the Javascript initialization code. It should be
placed in the template path as ``NAME/tinymce_textareas.js`` or
``tinymce/NAME_textareas.js``.

Example::

  tinyMCE.init({
      mode: "textareas",
      theme: "advanced",
      plugins: "spellchecker,directionality,paste,searchreplace",
      language: "{{ language }}",
      directionality: "{{ directionality }}",
      spellchecker_languages : "{{ spellchecker_languages }}",
      spellchecker_rpc_url : "{{ spellchecker_rpc_url }}"
  });

This example also shows the variables you can use in the template. The language
variables are based on the current Django language. If the content language is
different from the interface language use the ``tinymce-js-lang`` view which
takes a language (``LANG_CODE``) argument::

External link and image lists
-----------------------------

The TinyMCE link and image dialogs can be enhanced with a predefined list of
links_ and images_. These entries are filled using a variable loaded from an
external Javascript location. The tinymce application can serve these lists for
you.

.. _links: http://www.tinymce.com/wiki.php/Configuration:link_list
.. _images: http://www.tinymce.com/wiki.php/Configuration:image_list

Creating external link and image views
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

To use a predefined link list, add the ``external_link_list_url`` option to the
``mce_attrs`` keyword argument to the widget (or the template if you use the
view). The value is a URL that points to a view that fills a list of 2-tuples
(*name*, *URL*) and calls ``tinymce.views.render_to_link_list``. For example:

Create the widget::

  from django import forms
  from django.core.urlresolvers import reverse
  from tinymce.widgets import TinyMCE

  class SomeForm(forms.Form):
      somefield = forms.CharField(widget=TinyMCE(mce_attrs={'external_link_list_url': reverse('someapp.views.someview')})

Create the view::

  from tinymce.views import render_to_link_list

  def someview(request):
      objects = ...
      link_list = [(unicode(obj), obj.get_absolute_url()) for obj in objects]
      return render_to_link_list(link_list)

Finally, include the view in your URLconf.

Image lists work exactly the same way, just use the TinyMCE
``external_image_list_url`` configuration option and call
``tinymce.views.render_to_image_list`` from your view.

The ``flatpages_link_list`` view
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

As an example, the tinymce application contains a predefined view that lists
all ``django.contrib.flatpages`` objects:
``tinymce.views.flatpages_link_list``. If you want to use a TinyMCE widget for
the flatpages ``content`` field with a predefined list of other flatpages in
the link dialog you could use something like this::

  from django import forms
  from django.core.urlresolvers import reverse
  from django.contrib.flatpages.admin import FlatPageAdmin
  from django.contrib.flatpages.models import FlatPage
  from tinymce.widgets import TinyMCE

  class TinyMCEFlatPageAdmin(FlatPageAdmin):
      def formfield_for_dbfield(self, db_field, **kwargs):
          if db_field.name == 'content':
              return db_field.formfield(widget=TinyMCE(
                  attrs={'cols': 80, 'rows': 30},
                  mce_attrs={'external_link_list_url': reverse('tinymce.views.flatpages_link_list')},
              ))
          return super(TinyMCEFlatPageAdmin, self).formfield_for_dbfield(db_field, **kwargs)

  somesite.register(FlatPage, TinyMCEFlatPageAdmin)

If you want to enable this for the default admin site
(``django.contrib.admin.site``) you will need to unregister the original
ModelAdmin class for flatpages first::

  from django.contrib import admin

  admin.site.unregister(FlatPage)
  admin.site.register(FlatPage, TinyMCEFlatPageAdmin)

The source contains a `test project`_ that includes this flatpages model admin.
You just need to add the TinyMCE javascript code.

#. Checkout the test project:
   ``svn checkout http://django-tinymce.googlecode.com/svn/trunk/testtinymce``
#. Copy the ``tiny_mce`` directory from the TinyMCE distribution into
   ``media/js``
#. Run ``python manage.py syncdb``
#. Run ``python manage.py runserver``
#. Connect to `http://localhost:8000/admin/`_

.. _`test project`: http://code.google.com/p/django-tinymce/source/browse/trunk/testproject/
.. _`http://localhost:8000/admin/`: http://localhost:8000/admin/

The TinyMCE preview button
--------------------------

TinyMCE contains a `preview plugin`_ that can be used to allow the user to view
the contents of the editor in the website context. The tinymce application
provides a view and a template tag to make supporting this plugin easier. To
use it point the ``plugin_preview_pageurl`` configuration to the view named
``tinymce-preview``::

  from django.core.urlresolvers import reverse
  widget = TinyMCE(mce_attrs={'plugin_preview_pageurl': reverse('tinymce-preview', "NAME")})

The view named by ``tinymce-preview`` looks for a template named either
``tinymce/NAME_preview.html`` or ``NAME/tinymce_preview.html``. The template
accesses the content of the TinyMCE editor by using the ``tinymce_preview``
tag::

  {% load tinymce_tags %}

  ...
  {% tinymce_preview "preview-content" %}

  ...

  ...

With this template code the text inside the HTML element with id
``preview-content`` will be replaced by the content of the TinyMCE editor.

.. _`preview plugin`: http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/preview


text:
var fs = require('fs');
if (!fs.existsSync) {
  fs.existsSync = require('path').existsSync;
}

var azure;
if (fs.existsSync('./../../lib/azure.js')) {
  azure = require('./../../lib/azure');
} else {
  azure = require('azure');
}

var express = require('express');
var formidable = require('formidable');
var helpers = require('./helpers.js');

var app = module.exports = express.createServer();
// Global request options, set the retryPolicy
var blobClient = azure.createBlobService(azure.ServiceClient.DEVSTORE_STORAGE_ACCOUNT, azure.ServiceClient.DEVSTORE_STORAGE_ACCESS_KEY, azure.ServiceClient.DEVSTORE_BLOB_HOST).withFilter(new azure.ExponentialRetryPolicyFilter());
var containerName = 'webpi';

//Configuration
app.configure(function () {
  app.set('views', __dirname + '/views');
  app.set('view engine', 'ejs');
  app.use(express.methodOverride());
  // app.use(express.logger());
  app.use(app.router);
  app.use(express.static(__dirname + '/public'));
});

app.configure('development', function () {
  app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});

app.configure('production', function () {
  app.use(express.errorHandler());
});

app.param(':id', function (req, res, next) {
  next();
});

//Routes
app.get('/', function (req, res) {
  res.render('index.ejs', { locals: {
    title: 'Welcome'
  }
  });
});

app.get('/Upload', function (req, res) {
  res.render('upload.ejs', { locals: {
    title: 'Upload File'
  }
  });
});

app.get('/Display', function (req, res) {
  blobClient.listBlobs(containerName, function (error, blobs) {
    res.render('display.ejs', { locals: {
      title: 'List of Blobs',
      serverBlobs: blobs
    }
    });
  });
});

app.get('/Download/:id', function (req, res) {
  blobClient.getBlobProperties(containerName, req.params.id, function (err, blobInfo) {
    if (err === null) {
      res.header('content-type', blobInfo.contentType);
      res.header('content-disposition', 'attachment; filename=' + blobInfo.metadata.filename);
      blobClient.getBlobToStream(containerName, req.params.id, res, function () { });
    } else {
      helpers.renderError(res);
    }
  });
});

app.post('/uploadhandler', function (req, res) {
  var form = new formidable.IncomingForm();

  form.parse(req, function (err, fields, files) {
    var formValid = true;
    if (fields.itemName === '') {
      helpers.renderError(res);
      formValid = false;
    }

    if (formValid) {
      var extension = files.uploadedFile.name.split('.').pop();
      var newName = fields.itemName + '.' + extension;

      var options = {
        contentType: files.uploadedFile.type,
        metadata: { fileName: newName }
      };

      blobClient.createBlockBlobFromFile(containerName, fields.itemName, files.uploadedFile.path, options, function (error) {
        if (error != null) {
          helpers.renderError(res);
        } else {
          res.redirect('/Display');
        }
      });
    } else {
      helpers.renderError(res);
    }
  });
});

app.post('/Delete/:id', function (req, res) {
  blobClient.deleteBlob(containerName, req.params.id, function (error) {
    if (error != null) {
      helpers.renderError(res);
    } else {
      res.redirect('/Display');
    }
  });
});

blobClient.createContainerIfNotExists(containerName, function (error) {
  if (error) {
    console.log(error);
  } else {
    setPermissions();
  }
});

function setPermissions() {
  blobClient.setContainerAcl(containerName, azure.Constants.BlobConstants.BlobContainerPublicAccessType.BLOB, function (error) {
    if (error) {
      console.log(error);
    } else {
      app.listen(process.env.port || 1337);
      console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env);
    }
  });
}


text:
$ErrorActionPreference = "Stop"

# Hide any progress bars, due to downloads and installs of remote components.
$ProgressPreference = "SilentlyContinue"

# Discard any collected errors from a previous execution.
$Error.Clear()

# Allow certian operations, like downloading files, to execute.
Set-ExecutionPolicy Bypass -Scope Process -Force

###################################################################################################
#
# Handle all errors in this script.
#

trap
{
    # NOTE: This trap will handle all errors. There should be no need to use a catch below in this
    #       script, unless you want to ignore a specific error.
    $message = $Error[0].Exception.Message
    if ($message)
    {
        Write-Host -Object "`nERROR: $message" -ForegroundColor Red
    }

    Write-Host "`nThe artifact failed to apply.`n"

    # IMPORTANT NOTE: Throwing a terminating error (using $ErrorActionPreference = "Stop") still
    # returns exit code zero from the PowerShell script when using -File. The workaround is to
    # NOT use -File when calling this script and leverage the try-catch-finally block and return
    # a non-zero exit code from the catch block.
    exit -1
}

###################################################################################################
#
# Main execution block.
#

if ([Environment]::OSVersion.Version.Major -gt 6) {
    Write-Host "`nRemoving Appx Packages for current user`n"

    Get-AppxPackage | Remove-AppxPackage -ErrorAction SilentlyContinue

    Write-Host "`nRemoving All users Appx Packages for current user`n"
    Get-AppxPackage -AllUsers | Remove-AppxPackage -ErrorAction SilentlyContinue

    Write-Host "`nRemoving removable apps from provisioned apps list so they don't reinstall on new users`n"
    Get-AppxProvisionedPackage -Online  | Remove-AppxProvisionedPackage -Online -ErrorAction SilentlyContinue

    Write-Host "`nRemoving all removable apps for all users`n"
    $allPackageNames = Get-AppxPackage -AllUsers | Select-Object -Expand Name
    $allPackageNames = $allPackageNames | ForEach-Object {"*$_*"}
    ForEach($app in $allPackageNames){
        Try{
            Get-AppxPackage -Allusers -Name $app | Remove-AppxPackage -Allusers -ErrorAction SilentlyContinue
        }
        Catch{
        }
    }

    Write-Host "`nDone Removing Appx Packages`n"
}
else {
    Write-Host "`nOS Major version is older than 7. Skipping...`n"
}

Write-Host "`nThe artifact was applied successfully.`n"


text:
;(function ( $, window, document, undefined ) {
    var methods = {
        init : function( options ) {
            var settings = {
                animType: 'loop', //'backForth' , 'once', or 'loop'
                frameCount: null, //default determined later programmatically
                frameWidth: null, //default determined later programmatically
                speed: 100, //ms per frame
                onInit: function(){}, //callback for initialization on element
                onFrameChange: function(){}, //callback for each frame change
                onOnceEnd: function(){} //callback fired at the end of the 'once' animation - will not be used with other animTypes
            };
            var $this = $(this);
            if ( options ) {
                $.extend( settings, options );
            }
            $this.each(function(){
                var $eachAni = $(this);
                $(this).addClass('ani');
                //find the width of each animated frame
                if (settings.frameWidth === null) {
                    var frameWidth =  $eachAni.outerWidth();
                } else {
                    var frameWidth = settings.frameWidth;
                }
                //find the width of the whole sprite
                var cleanImg = $eachAni.css('background-image').replace(/"/g,""); //strip out quotes, if user agent returns quotes in css property path
                var bgImg = cleanImg.slice(4, -1); //strips out everything but the image path
                var image = new Image();
                image.src = bgImg;
                $(image).on('load', function(){
                    var spriteWidth = image.width;
                    //find the number of frames
                    if (settings.frameCount === null) {
                        var frameCount = spriteWidth/frameWidth;
                    } else {
                        var frameCount = settings.frameCount;
                    }
                    var endPos = (frameCount-1)*frameWidth*-1,
                        keyframing;
                    if (settings.animType === 'backForth'){
                        var direction = 'forward';
                        keyframing = setInterval(function(){
                            var xPos = parseInt($eachAni.css('backgroundPosition'));
                            if(xPos === 0){
                                direction = 'forward';
                            } else if(xPos===endPos){
                                direction = 'backward';
                            }
                            if (direction === 'forward'){
                                $eachAni.css({'background-position': (xPos-frameWidth)+'px 0'});
                            } else if (direction=== 'backward'){
                                $eachAni.css({'background-position': (xPos+frameWidth)+'px 0'});
                            }
                            settings.onFrameChange();
                        }, settings.speed);
                         $eachAni.data('keyframing', keyframing);
                         console.log($eachAni.data('keyframing'));
                    } else if(settings.animType === 'loop'){
                        //looping function
                        keyframing = setInterval(function(){
                            var xPos = parseInt($eachAni.css('backgroundPosition'));
                            if (xPos>endPos){
                                $eachAni.css({'background-position': (xPos-frameWidth)+'px 0'});
                            } else {
                                $eachAni.css({'background-position': '0 0'});
                            }
                        }, settings.speed);
                        $eachAni.data('keyframing', keyframing);
                    } else if(settings.animType === 'once'){
                        keyframing = setInterval(function(){
                            var xPos = parseInt($eachAni.css('backgroundPosition'));
                            if (xPos>endPos){
                                $eachAni.css({'background-position': (xPos-frameWidth)+'px 0'});
                            } else {
                                clearInterval(keyframing);
                                settings.onOnceEnd();
                            }
                        }, settings.speed);
                        $eachAni.data('keyframing', keyframing);
                    }
                });
            });
            settings.onInit();
           return this;
        },
        pause: function() {
            var $this = $(this);
            $this.each(function(){
                if ($(this).data('keyframing')) {
                    clearInterval($(this).data('keyframing'));
                }

            });
            return this;
        },
        destroy : function() {
            var $this = $(this);
            $this.each(function(){
                $(this).removeClass('ani').css({'background-position':'0 0'});
                clearInterval($(this).data('keyframing'));
            });
            return this;
        }
    };

    $.fn.aniSprite = function( method ) {
        if ( methods[method] ) {
            return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
        } else if ( typeof method === 'object' || ! method ) {
            return methods.init.apply( this, arguments );
        } else {
            $.error( 'Method "' +  method + '" does not exist on jQuery.aniSprite' );
        }
    };
})( jQuery, window, document );


text:
package org.datavec.api.transform.sequence;

import lombok.Data;
import lombok.EqualsAndHashCode;
import org.datavec.api.transform.schema.Schema;
import org.datavec.api.transform.schema.SequenceSchema;
import org.nd4j.shade.jackson.annotation.JsonIgnoreProperties;
import org.nd4j.shade.jackson.annotation.JsonProperty;

import java.util.Arrays;
import java.util.Collection;

/**
 * Convert a set of values to a sequence. Two approaches are supported:

 * (a) if "singleStepsequenceMode" is true - convert each record independently, to a "sequence" of length 1

 * (b) otherwise - performa  "group and sort" operations. For example, group by one or more columns, and then
 *     sort each value within the group by some mechanism. For example, group by customer, sort by time.
 *
 * @author Alex Black
 */
@Data
@EqualsAndHashCode(exclude = {"inputSchema"})
@JsonIgnoreProperties({"inputSchema"})
public class ConvertToSequence {

    private boolean singleStepSequencesMode;
    private final String[] keyColumns;
    private final SequenceComparator comparator; //For sorting values within collected (unsorted) sequence
    private Schema inputSchema;

    /**
     *
     * @param keyColumn The value to use as the key for inferring which examples belong to what sequence
     * @param comparator The comparator to use when deciding the order of each possible time step in the sequence
     */
    public ConvertToSequence(String keyColumn, SequenceComparator comparator){
        this(false, new String[]{keyColumn}, comparator);
    }

    /**
     *
     * @param keyColumns The value or values to use as the key (multiple values: compound key)  for inferring which
     *                   examples belong to what sequence
     * @param comparator The comparator to use when deciding the order of each possible time step in the sequence
     */
    public ConvertToSequence(Collection<String> keyColumns, SequenceComparator comparator) {
        this(false, keyColumns.toArray(new String[keyColumns.size()]), comparator);
    }

    /**
     *
     * @param keyColumns The value or values to use as the key (multiple values: compound key)  for inferring which
     *                   examples belong to what sequence
     * @param comparator The comparator to use when deciding the order of each possible time step in the sequence
     */
    public ConvertToSequence(@JsonProperty("singleStepSequencesMode") boolean singleStepSequencesMode,
                             @JsonProperty("keyColumn") String[] keyColumns,
                             @JsonProperty("comparator") SequenceComparator comparator) {
        this.singleStepSequencesMode = singleStepSequencesMode;
        this.keyColumns = keyColumns;
        this.comparator = comparator;
    }

    public SequenceSchema transform(Schema schema) {
        return new SequenceSchema(schema.getColumnMetaData());
    }

    public void setInputSchema(Schema schema) {
        this.inputSchema = schema;
        if(!singleStepSequencesMode){
            comparator.setSchema(transform(schema));
        }
    }

    @Override
    public String toString() {
        if(singleStepSequencesMode) {
            return "ConvertToSequence()";
        } else if(keyColumns.length == 1){
            return "ConvertToSequence(keyColumn=\"" + keyColumns[0] + "\",comparator=" + comparator + ")";
        } else {
            return "ConvertToSequence(keyColumns=\"" + Arrays.toString(keyColumns) + "\",comparator=" + comparator + ")";
        }
    }

}


text:
module Tradewind
  require "tradewind/engine"
end


text:
BLE Stress Tests

******************************************************************************
    QUICK TIPS:
    You need 2 controllers supported by MyNewt. One will become TX device,
    the other will become RX device.

    1. Set role (TX=0, RX=1) for current device in syscfg.yml
        BLE_STRESS_TEST_ROLE: 1

       The RX has LED2 turned on.

    2. Set (in syscfg.yml) number of times to repeat each tested action
       in use case, e.g. do 1000 times connect/disconnect to complete use case.
        RX_STRESS_REPEAT: 1000

    3. To perform only specific test, go to rx_stress.c,
       find definition of rx_stress_main_task_fn(void *arg) and in place of
       for-loop just paste function rx_stress_start(i), where i is id of test.

******************************************************************************

No | Use case
-----------------------------------------------------------------------------
 1 | Stress Connect -> Connect Cancel - repeat 1000
   | RX: Nothing
   | TX: Connect/Connect cancel
   |
 2 | Stress Connect/Disconnect legacy - repeat 1000
   | RX: Advertise legacy
   | TX: Connect/Disconnect
   |
 3 | Stress Connect/Disconnect ext adv - repeat 1000
   | RX: Advertise Ext
   | TX: Connect/Disconnect
   |
 4 | Stress connection params update (TX) - (1000)
   | RX: Advertise
   | TX: Connect/Connect param update
   |
 5 | Stress connection params update (RX) - (1000)
   | RX: Advertise/Connect param update
   | TX: Connect
   |
 6 | Stress Scan
   | RX: Advertise a known data pattern
   | TX: Scan and check received data with pattern
   |
 7 | Stress PHY Update (TX) - (1000)
   | RX: Advertise
   | TX: Connect/Phy update
   |
 8 | Stress PHY update (RX) - (1000)
   | RX: Advertise/Phy update
   | TX: Connect
   |
 9 | Stress multi connection
   | RX: Advertise Ext
   | TX: Establish and maintain as many instances as possible
   |
10 | Stress L2CAP send
   | RX: Send 64kB of data with L2CAP
   | TX: Measure bit rate and max received data MTU
   |
11 | Stress Advertise/Connect/Continue Adv/Disconnect
   | RX: Advertise Ext/Continue same advertise after connect
   | TX: Connect
   |
12 | Stress GATT indicating
   | RX: Indicate
   | TX: Receive indication. Measure average time of indicating.
   |
13 | Stress GATT notification
   | RX: Notify. Measure average time of notifying.
   | TX: Count the number of received notification.
   |
14 | Stress GATT Subscribe/Notify/Unsubscribe
   | RX: Notify on subscribe
   | TX: Measure the average time from sending a subscription request
   |     to receiving a notification.
   |
15 | Stress Connect/Send/Disconnect
   | RX: Advertise/Send via ATT/Disconnect
   | TX: Receive notification. Measure time of notifying.

******************************************************************************
   Concept:
   The RX device advertises data containing a UUID128 of test use case that
   should be performed. The TX device scan for known UUIDs, when it finds,
   adapts to the advertised use case and runs a test.

   Stress Task vs Semaphore:
   The rx_stress_start_auto function starts main stress test task that runs
   all stress tests one by one. The tests are based on event handling, so to
   synchronize main task with events, a semaphore is used. On use case start
   there is 0 tokens for semaphore. After main task starts one of use cases,
   it comes across a semaphore and has to wait. When use case is completed,
   1 token is released, so main task can use it to pass through semaphore.
   The tx_stress_start_auto function works analogically.

   Newt target set example:
    rymek@rymek:~/projects/bletiny_proj$ newt target show bletest_tx
    targets/bletest_tx
        app=@apache-mynewt-nimble/apps/blestress
        bsp=@apache-mynewt-core/hw/bsp/nordic_pca10056
        build_profile=debug
        syscfg=BLE_STRESS_TEST_ROLE=0
    rymek@rymek:~/projects/bletiny_proj$ newt target show bletest_rx
     targets/bletest_rx
        app=@apache-mynewt-nimble/apps/blestress
        bsp=@apache-mynewt-core/hw/bsp/nordic_pca10056
        build_profile=debug
        syscfg=BLE_STRESS_TEST_ROLE=1

   Example of expected logs on TX side(LOG_LEVEL > 1):
     Start test num 1
     >>>>>>>>>>>>>>>>>>>> Stress test 1 completed
     Start scan for test
     Start test num 2
     >>>>>>>>>>>>>>>>>>>> Stress test 2 completed
     Start scan for test
     Start test num 3
     >>>>>>>>>>>>>>>>>>>> Stress test 3 completed
     Start scan for test
     Start test num 4
     >>>>>>>>>>>>>>>>>>>> Stress test 4 completed
     Start scan for test
     Start test num 5
     >>>>>>>>>>>>>>>>>>>> Stress test 5 completed
     Start scan for test
     Start test num 6
     >>>>>>>>>>>>>>>>>>>> Stress test 6 completed
     Start scan for test
     Start test num 7
     >>>>>>>>>>>>>>>>>>>> Stress test 7 completed
     Start scan for test
     Start test num 8
     >>>>>>>>>>>>>>>>>>>> Stress test 8 completed
     All tests completed
     Tests results:
     Use case 1 - Stress Connect -> Connect Cancel:
     Con attempts = 20
     Con success = 0
     Use case 2 - Stress Connect/Disconnect legacy:
     Con attempts = 20
     Con success = 20
     Use case 3 - Stress Connect/Disconnect ext adv:
     Con attempts = 20
     Con success = 20
     Use case 4 - Stress connection params update (TX):
     Params updates = 20
     Use case 5 - Stress connection params update (RX):
     Params updates = 20
     Use case 6 - Stress Scan:
     Received first packets = 20
     Received all packets = 20
     Use case 7 - Stress PHY Update (TX):
     PHY updates = 20
     Use case 8 - Stress Connect -> Connect Cancel:
     PHY updates = 20

   Example of expected logs on RX side(LOG_LEVEL > 1):
     Start test num 2
     >>>>>>>>>>>>>>>>>>>> Stress test 2 completed
     Start test num 3
     >>>>>>>>>>>>>>>>>>>> Stress test 3 completed
     Start test num 4
     >>>>>>>>>>>>>>>>>>>> Stress test 4 completed
     Start test num 5
     >>>>>>>>>>>>>>>>>>>> Stress test 5 completed
     Start test num 6
     Received signal to switch test
     Start test num 7
     >>>>>>>>>>>>>>>>>>>> Stress test 7 completed
     Start test num 8
     >>>>>>>>>>>>>>>>>>>> Stress test 8 completed
     All tests completed
     Tests results:
     Use case 1 - Stress Connect -> Connect Cancel:
     Con attempts = 0
     Con success = 0
     Use case 2 - Stress Connect/Disconnect legacy:
     Con attempts = 20
     Con success = 20
     Use case 3 - Stress Connect/Disconnect ext adv:
     Con attempts = 20
     Con success = 20
     Use case 4 - Stress connection params update (TX):
     Params updates = 20
     Use case 5 - Stress connection params update (RX):
     Params updates = 20
     Use case 6 - Stress Scan:
     Received first packets = 0
     Received all packets = 0
     Use case 7 - Stress PHY Update (TX):
     PHY updates = 20
     Use case 8 - Stress Connect -> Connect Cancel:
     PHY updates = 20


text:
{% load staticfiles %}
<!DOCTYPE html>

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

  <title>BDR</title>

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">

  <link rel="stylesheet" href="{% static  "css/base.css" %}">

      Notre super jeu !

    {% if user.is_authenticated %}
    <form method="get" action="{% url 'profil' %}">
      {% csrf_token %}
      <button type="submit" class="btn btn-bar btn-md" > {{ user.username }} (Mon compte)</button>
    </form>
    <form method="get" action="{% url 'deconnexion' %}">
      {% csrf_token %}
      <button type="submit" class="btn btn-bar btn-md" >Déconnexion</button>
    </form>

    {% else %}
	    <button type="button" class="btn btn-bar btn-md" data-toggle="modal" data-target="#ModalInscription">Inscription</button>
      <button type="button" class="btn btn-bar btn-md" data-toggle="modal" data-target="#ModalConnexion">Connexion</button>
    {%endif%}

	{% block inscription %}
	{% include "core/inscription.html" %}
        {% endblock %}

	{% block connexion %}
	{% include "core/connexion.html" %}
        {% endblock %}

      {% block content %}
      {% endblock %}

2017 BDR Tous droits réservés.

    {% block jquery %}
    {% endblock %}


text:
package com.macro.mall.mapper;

import com.macro.mall.model.OmsOrderOperateHistory;
import com.macro.mall.model.OmsOrderOperateHistoryExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;

public interface OmsOrderOperateHistoryMapper {
    long countByExample(OmsOrderOperateHistoryExample example);

    int deleteByExample(OmsOrderOperateHistoryExample example);

    int deleteByPrimaryKey(Long id);

    int insert(OmsOrderOperateHistory record);

    int insertSelective(OmsOrderOperateHistory record);

    List<OmsOrderOperateHistory> selectByExample(OmsOrderOperateHistoryExample example);

    OmsOrderOperateHistory selectByPrimaryKey(Long id);

    int updateByExampleSelective(@Param("record") OmsOrderOperateHistory record, @Param("example") OmsOrderOperateHistoryExample example);

    int updateByExample(@Param("record") OmsOrderOperateHistory record, @Param("example") OmsOrderOperateHistoryExample example);

    int updateByPrimaryKeySelective(OmsOrderOperateHistory record);

    int updateByPrimaryKey(OmsOrderOperateHistory record);
}


text:
<!DOCTYPE html>
<html>
  <head>
    <title>Gravity</title>
    <link rel="stylesheet" href="css/main.css">
    <script data-main="js/main" src="//cdnjs.cloudflare.com/ajax/libs/require.js/2.1.15/require.min.js"></script>
  </head>
  <body>
    <canvas></canvas>
  </body>
</html>


text:
using System;

namespace Rothko.Interfaces.Components
{
	public interface ITileable : IPlottable, ILayerable
	{
		int IDTileType { get; set; }

		bool Active { get; set; }
	}
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.subscription.models;

import com.azure.resourcemanager.subscription.fluent.models.OperationListResultInner;
import java.util.List;

/** An immutable client-side representation of OperationListResult. */
public interface OperationListResult {
    /**
     * Gets the value property: List of operations.
     *
     * @return the value value.
     */
    List<Operation> value();

    /**
     * Gets the nextLink property: URL to get the next set of operation list results if there are any.
     *
     * @return the nextLink value.
     */
    String nextLink();

    /**
     * Gets the inner com.azure.resourcemanager.subscription.fluent.models.OperationListResultInner object.
     *
     * @return the inner object.
     */
    OperationListResultInner innerModel();
}


text:
serial_test(async (t, fake) => {
  // Don't listen for 'disconnect' events on navigator.serial so we can listen
  // for them on each SerialPort instance instead.
  const eventWatcher = new EventWatcher(t, navigator.serial, ['connect']);

  // Wait for getPorts() to resolve in order to ensure that the Mojo client
  // interface has been configured.
  let ports = await navigator.serial.getPorts();
  assert_equals(ports.length, 0);

  // Add ports one at a time so that we can map tokens to ports.
  const token1 = fake.addPort();
  const port1 = (await eventWatcher.wait_for(['connect'])).target;
  const port1Watcher = new EventWatcher(t, port1, ['disconnect']);

  const token2 = fake.addPort();
  const port2 = (await eventWatcher.wait_for(['connect'])).target;
  const port2Watcher = new EventWatcher(t, port2, ['disconnect']);

  fake.removePort(token2);
  const event1 = await port2Watcher.wait_for(['disconnect']);
  assert_true(event1 instanceof Event);
  assert_equals(event1.target, port2);

  ports = await navigator.serial.getPorts();
  assert_equals(ports.length, 1);
  assert_equals(ports[0], port1);

  fake.removePort(token1);
  const event2 = await port1Watcher.wait_for(['disconnect']);
  assert_true(event2 instanceof Event);
  assert_equals(event2.target, port1);

  ports = await navigator.serial.getPorts();
  assert_equals(ports.length, 0);
}, 'A "disconnect" event is fired on ports when they are removed.');


text:
namespace Firestorm.Engine.Identifiers
{
    /// <summary>
    /// Provides data about URL paths used to identify items within a collection.
    /// </summary>
    public interface IIdentifierProvider<TItem>
    {
        IIdentifierInfo<TItem> GetInfo(string identifierName);
    }
}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace IdentityAdmin.Host.InMemoryService
{
    public class InMemoryScope
    {
        public InMemoryScope()
        {
            ScopeClaims = new List<InMemoryScopeClaim>();
            ScopeSecrets = new List<InMemoryScopeSecret>();
        }
        public int Id { get; set; }
        public string Name { get; set; }
        public string ClaimsRule { get; set; }
        public string Description { get; set; }
        public string DisplayName { get; set; }
        public bool Emphasize { get; set; }
        public bool Enabled { get; set; }
        public bool IncludeAllClaimsForUser { get; set; }
        public bool Required { get; set; }
        public ICollection<InMemoryScopeClaim> ScopeClaims { get; set; }
        public ICollection<InMemoryScopeSecret> ScopeSecrets { get; set; }
        public bool ShowInDiscoveryDocument { get; set; }
        public int Type { get; set; }

        public bool AllowUnrestrictedIntrospection { get; set; }
    }

    public class InMemoryScopeClaim
    {
        public bool AlwaysIncludeInIdToken { get; set; }
        public string Description { get; set; }
        public int Id { get; set; }
        public string Name { get; set; }
    }

    public class InMemoryScopeSecret
    {
        public int Id { get; set; }
        public string Description { get; set; }
        public DateTime? Expiration { get; set; }
        public string Type { get; set; }
        public virtual string Value { get; set; }
    }
}


text:
/**
 *
 */
package org.activejpa.enhancer;

import static org.testng.Assert.assertNotNull;

import org.testng.annotations.Test;

/**
 * @author ganesh.s
 *
 */
public class ActiveJpaAgentLoaderTest {

	@Test
	public void shouldGetLoaderInstance() {
		assertNotNull(ActiveJpaAgentLoader.instance());
	}
}


text:
package com.recursivity.commons.bean

/**
 * Created by IntelliJ IDEA.
 * User: wfaler
 * Date: 20/12/2010
 * Time: 00:51
 * To change this template use File | Settings | File Templates.
 */

class BeanTransformationException(target: Class[_]) extends Exception("Cannot transform from class " + target.getName)


text:
#ifndef __OUTPUT_H__
#define __OUTPUT_H__

#include <iostream>
#include <fstream>
#include <sstream>
#include <exception>
#include "model.h"
#include "data.h"
class Output {
    public:
        typedef std::vector<std::vector<double>> datatype;
        Output();
        Output(const Data& data);

        void save_data(double t,const Model& model);

        void save_at_end(double t,const Model& model);

        int find_timepoint(double t) const;

        /** Output state matrix at specific timepoint. */
        void output_at_timpoint(double t,std::ostream & os);

        /** Output state matrix at specific timepoint. */
        void save_all_timepoints(std::string basepath);

        /** Print time evolution of macroscopic values to os.*/
        void print_time_evol(std::ostream & os);

    private:

        std::vector<datatype> _data;
        std::vector<double> _totalcells_data;
        std::vector<double> _primary_data;
        std::vector<double> _anti_data;
        std::vector<double> _pro_data;
        std::vector<double> _timepoints;

        double _output_interval;
        double _no_runs;

        int _cancer_survived;

};

#endif /* ifndef __OUTPUT_H__ */


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Porosty (Lichenes). 1 (Lublin), Rodzina Lecanoraceae. Hymenelia, Aspicilia, Lecanorella, Protoplacodium, Manzonia 255 (1995)

#### Original name
Aspicilia pseudosquamata Motyka

### Remarks
null


text:
using System.Runtime.InteropServices;

using size_t = System.IntPtr;
using socklen_t = System.UInt32;

internal static partial class Interop
{
    internal static partial class libc
    {
        [DllImport(Libraries.Libc, SetLastError = true)]
        public static extern unsafe size_t recvfrom(int sockfd, void* buf, size_t len, int flags, sockaddr* dest_addr, socklen_t* addrlen);
    }
}


text:
| Travis CI | AppVeyor |
|----------|----------|
|[![Travis CI Status](https://travis-ci.org/mnadel/metrics.net.influxdb.svg?branch=master)](https://travis-ci.org/mnadel/metrics.net.influxdb)|[![AppVeyor Status](https://ci.appveyor.com/api/projects/status/gkd1n41vkigtm4q4?svg=true)](https://ci.appveyor.com/project/mnadel/metrics-net-influxdb)|

# Download

Available on [NuGet.org](https://www.nuget.org/packages/Metrics.NET.InfluxDB/) as [Metrics.NET.InfluxDB](https://www.nuget.org/packages/Metrics.NET.InfluxDB/).

# Changelog

This version has significant *(i.e. breaking)* changes from the previous version. Most derived metrics (min, max, mean, percentiles, etc.) are no longer being exported. InfluxDB recommended using, instead, [continuous queries](https://influxdb.com/docs/v0.9/query_language/continuous_queries.html) on the backend to calculate these values.

# Usage

Nearly identical to the usage shown in the [Metrics.NET Wiki](https://github.com/etishor/Metrics.NET/wiki/InfluxDb), but using `WithInflux` instead of `WithInfluxDb`:

    Metric.Config.WithReporting(report =>
        report.WithInflux("192.168.1.8", 8086, "admin", "admin", "metrics", TimeSpan.FromSeconds(5))

# Additional Configs

Additional configurations are available via `Metrics.NET.InfluxDB.ConfigOptions`. Most are passed-through to InfluxDB.

One noteworthy configuration affects the behavior of this Reporter: `BreakerRate`.

## BreakerRate

This configures a [circuit breaker](https://github.com/michael-wolfenden/Polly) that protects your InfluxDB endpoint. This configuration specifies the number of allowed errors, and a "cool-down" period where no additional requests will be made to the InfluxDB endpoint.

The rate is expressed as: `# of events / timeframe` where `# of events` is an integer, and `timeframe` is a string that can be parsed by `TimeSpan.Parse()`.

So, for example, `2 / 00:00:15` would trip the circuit if two errors occur, and then will wait fifteen seconds before allowing additional requests to InfluxDB.

## MetricNameConverter

This is a transformer that accepts a metric name as reported by Metrics.NET and returns the name that will be reported to InfluxDB.

The default is `ConfigOptions.IdentityConverter` which returns the name as-is.

Also included is `ConfigOptions.CompactConverter` which replaces runs of non-alpha characters with a period.

Example:

    [mono-sgen - Metrics.NET] influxdb.success.meter -> mono.sgen.metrics.net.influxdb.success.meter

## License

This library will always keep the same license as [Metrics.NET](https://github.com/etishor/Metrics.NET) (as long as its an open source, permisive license). This port is inspired by and contains some code from [Metrics.NET](https://github.com/etishor/Metrics.NET).

This library (Metrics.NET.InfluxDB) is release under Apache 2.0 License (see LICENSE).

Copyright (c) 2016 Michael Nadel


text:
module ActiveLogger
  class MyHistoryValue < ActiveRecord::Base

    attr_accessible :my_history_id, :key, :value

    belongs_to :my_history

  end
end


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
in Reumaux, Docums Mycol. 27(no. 106): 53 (1997)

#### Original name
Russula nigropurpurea Bidaud & Moënne-Locc.

### Remarks
null


text:
use super::{
    attr, attr_itemtype_str, elem, json, primitives::array_to_html, EncodeContext, ToHtml,
};
use node_dispatch::dispatch_node;
use stencila_schema::Node;

/// Encode a `Node` to HTML
///
/// Not all node types have `impl ToHtml` in which case this function
/// returns HTML indicating that that is the case.
impl ToHtml for Node {
    fn to_html(&self, context: &EncodeContext) -> String {
        // Call `array_to_html` to avoid `Vec<Primitive>.to_html()` for arrays
        if let Node::Array(array) = self {
            return array_to_html(array, context);
        }

        // In `CodeChunk` outputs we need to use <pre> so that newlines are preserved and in
        // `CodeExpression` output we must use a <span>.
        // See note under `ToHtml` for `InlineContent` for how strings are handled in that context.
        if let Node::String(string) = self {
            return elem(
                if context.inline { "span" } else { "pre" },
                &[attr_itemtype_str("String")],
                &string.to_html(context),
            );
        }

        // Fallback to default `to_html` for other `Node` variants
        dispatch_node!(
            self,
            elem("div", &[attr("class", "unsupported")], &json(self)),
            to_html,
            context
        )
    }
}


text:
<?php

namespace Baratine;

require_once('HttpTransport.php');
require_once('HttpPushPullTransport.php');

abstract class Transport
{
  protected $url;

  protected function __construct(/* string */ $url)
  {
    $this->url = $url;
  }

  public abstract /* void */ function send(Message $msg);
  public abstract /* void */ function query(QueryMessage $msg);
  public abstract /* value */ function querySync(QueryMessage $msg);

  public abstract /* array */ function poll();

  public function /* string */ __toString()
  {
    return __CLASS__ . '[' . $this->url . ']';
  }
}


text:
**version 0.1.1**
- Replaced autocomplete in flow conditions/actions with dropdown.

**version 0.1.0**
- Enabled mute function for mobile interface. Verified app on Homey V2.

**Version 0.0.16**
- Fixed the polling of the volume.

**Version 0.0.15**
- Changed split character to /r.

**Version 0.0.14**
- Added utf8 decoding for polled data.

**Version 0.0.13**
- Polling added to update the state of the amplifier in the mobile interface.

**Version 0.0.8**
- Alpha version with support for C338. NB: 'fire and forget' at this point, so control, but no status updates.

**Version 0.0.7**
- Sorted out internationalization issues

**Version 0.0.6**
- First SDKv2 version
- added 'stay connected' option
- flow trigger cards are now available for on/off and volume changed


text:
<?php
 //Load config file
 require_once('../configs/config.php');

 //Load common function file
 require_once('../require/commonFunc.php');

 $User = new User($sPOST);
 $register = $User->register($sPOST['password']);
 echo json_encode($register);

?>


text:
<?php

namespace Drupal\Tests\key\Unit;

use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Tests\UnitTestCase;

/**
 * Provides a base class for key tests.
 */
abstract class KeyTestBase extends UnitTestCase {

  /**
   * @var \Drupal\Core\Config\ImmutableConfig
   */
  protected $config;

  /**
   * @var \Drupal\Core\Config\Entity\ConfigEntityStorage
   */
  protected $configStorage;

  /**
   * @var \Drupal\Core\Entity\EntityTypeManager
   */
  protected $entityTypeManager;

  /**
   * @var \Drupal\Core\DependencyInjection\ContainerBuilder
   *
   * This should be used sparingly by test cases to add to the container as
   * necessary for tests.
   */
  protected $container;

  /**
   * {@inheritdoc}
   */
  protected function setUp() {
    parent::setUp();

    // Mock the Config object, but methods will be mocked in the test class.
    $this->config = $this->getMockBuilder('\Drupal\Core\Config\ImmutableConfig')
      ->disableOriginalConstructor()
      ->getMock();

    // Mock ConfigEntityStorage object, but methods will be mocked in the test
    // class.
    $this->configStorage = $this->getMockBuilder('\Drupal\Core\Config\Entity\ConfigEntityStorage')
      ->disableOriginalConstructor()
      ->getMock();

    // Mock EntityTypeManager service.
    $this->entityTypeManager = $this->getMockBuilder('\Drupal\Core\Entity\EntityTypeManager')
      ->disableOriginalConstructor()
      ->getMock();
    $this->entityTypeManager->expects($this->any())
      ->method('getStorage')
      ->with('key')
      ->willReturn($this->configStorage);

    // Create a dummy container.
    $this->container = new ContainerBuilder();
    $this->container->set('entity_type.manager', $this->entityTypeManager);

    // Each test class should call \Drupal::setContainer() in its own setUp
    // method so that test classes can add mocked services to the container
    // without affecting other test classes.
  }

  /**
   * Return a token that could be a key.
   *
   * @return string
   *   A hashed string that could be confused as some secret token.
   */
  protected function createToken() {
    return strtoupper(hash('ripemd128', md5($this->getRandomGenerator()->string(30))));
  }

}


text:
import ReliableInfoPacket from './ReliableInfoPacket';
import { decode, encode } from '../encodingUtil';

it('parse', () => {
  const packet = ReliableInfoPacket.parse(
    encode('\x1e\x3f\xbe\xef\x00\x14Data goes here'),
  );
  expect(packet.ackNumber).toEqual(31);
  expect(packet.sequenceNumber).toEqual(15);
  expect(packet.poll).toEqual(true);
  expect(packet.port).toEqual(0xbeef);
  expect(packet.information).toEqual(encode('Data goes here'));
});

it('build', () => {
  expect(
    decode(
      ReliableInfoPacket.build(15, 31, true, 0xbeef, encode('Data goes here')),
    ),
  ).toEqual('\x1e\x3f\xbe\xef\x00\x14Data goes here');
});

it('build with no info', () => {
  expect(decode(ReliableInfoPacket.build(15, 31, true, 0xbeef))).toEqual(
    '\x1e\x3f\xbe\xef\x00\x06',
  );
});

it('build with poll=false', () => {
  expect(decode(ReliableInfoPacket.build(15, 31, false, 0xbeef))).toEqual(
    '\x1e\x3e\xbe\xef\x00\x06',
  );
});

it('throws when parsing truncated packet (below min size)', () => {
  expect(() => ReliableInfoPacket.parse(Buffer.alloc(1))).toThrowError(
    'Packet truncated or corrupt',
  );
});

it('throws when parsing truncated packet (info extends beyond packet end)', () => {
  expect(() =>
    ReliableInfoPacket.parse(encode('\x1e\x3f\xbe\xef\xff\xff')),
  ).toThrowError('Packet truncated or corrupt');
});

it('throws when parsing supervisory packet', () => {
  expect(() =>
    ReliableInfoPacket.parse(encode('\x01\x18\x00\x00\x00\x06')),
  ).toThrowError(
    'isSupervisory must be false for a ReliableInfoPacket, but was true',
  );
});


text:
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */

/*
 Copyright (C) 2009 Mark Joshi

 This file is part of QuantLib, a free-software/open-source library
 for financial quantitative analysts and developers - http://quantlib.org/

 QuantLib is free software: you can redistribute it and/or modify it
 under the terms of the QuantLib license.  You should have received a
 copy of the license along with this program; if not, please email
 <quantlib-dev@lists.sf.net>. The license is also available online at
 <http://quantlib.org/license.shtml>.

 This program is distributed in the hope that it will be useful, but WITHOUT
 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 FOR A PARTICULAR PURPOSE.  See the license for more details.
*/

#ifndef quantlib_swap_forward_basis_system_hpp
#define quantlib_swap_forward_basis_system_hpp

#include <ql/models/marketmodels/callability/marketmodelbasissystem.hpp>
#include <ql/models/marketmodels/evolutiondescription.hpp>

namespace QuantLib {

    class SwapForwardBasisSystem : public MarketModelBasisSystem
    {
      public:
        SwapForwardBasisSystem(const std::vector<Time>& rateTimes,
                                                                    const std::vector<Time>& exerciseTimes);

        Size numberOfExercises() const;
        std::vector<Size> numberOfFunctions() const;
        const EvolutionDescription& evolution() const;
        void nextStep(const CurveState&);
        void reset();
        std::valarray<bool> isExerciseTime() const;

        void values(const CurveState&,
                                  std::vector<Real>& results) const;

        std::auto_ptr<MarketModelBasisSystem> clone() const;
      private:
        std::vector<Time> rateTimes_, exerciseTimes_;
        Size currentIndex_;
        std::vector<Size> rateIndex_;
        EvolutionDescription evolution_;
    };

}

#endif


text:
package com.networknt.eventuate.account.common.event.customer;

import com.networknt.eventuate.common.Event;
import com.networknt.eventuate.common.EventEntity;

@EventEntity(entity = "com.networknt.eventuate.account.command.customer.Customer")
public interface CustomerEvent extends Event {
}


text:
package com.github.ignaciotcrespo.mrpolite.classesfortest;

import static com.github.ignaciotcrespo.mrpolite.utils.TextUtils.has;
import static com.github.ignaciotcrespo.mrpolite.utils.TextUtils.hasNot;
import static org.assertj.core.api.Assertions.assertThat;

/**
 * Created by crespo on 2/20/17.
 */
public class SuperClass_Public extends SuperSuperClass_Public {

    public String parent_textPublic;
    String parent_textDefault;
    protected String parent_textProtected;
    private String parent_textPrivate;

    public final String parent_textPublicFinal = "public_final";
    final String parent_textDefaultFinal = "default_final";
    protected final String parent_textProtectedFinal = "protected_final";
    private final String parent_textPrivateFinal = "private_final";

    public static String parent_textPublicStatic;
    static String parent_textDefaultStatic;
    protected static String parent_textProtectedStatic;
    private static String parent_textPrivateStatic;

    public static final String parent_textPublicStaticFinal = "public_static_final";
    static final String parent_textDefaultStaticFinal = "default_static_final";
    protected static final String parent_textProtectedStaticFinal = "protected_static_final";
    private static final String parent_textPrivateStaticFinal = "private_static_final";

    ParentInnerClass parent_mParentInnerClass;
    ParentInnerClassStatic parent_mParentInnerClassStatic;

    public void assertValidData(int levelsTree) {
        has(parent_textDefault);
        has(parent_textProtected);
        has(parent_textPublic);
        has(parent_textPrivate);

        has(parent_textDefaultStatic);
        has(parent_textProtectedStatic);
        has(parent_textPublicStatic);
        has(parent_textPrivateStatic);

        // final fields should not be set
        assertThat(parent_textPublicFinal).isSameAs("public_final");
        assertThat(parent_textDefaultFinal).isSameAs("default_final");
        assertThat(parent_textProtectedFinal).isSameAs("protected_final");
        assertThat(parent_textPrivateFinal).isSameAs("private_final");

        assertThat(parent_textPublicStaticFinal).isSameAs("public_static_final");
        assertThat(parent_textDefaultStaticFinal).isSameAs("default_static_final");
        assertThat(parent_textProtectedStaticFinal).isSameAs("protected_static_final");
        assertThat(parent_textPrivateStaticFinal).isSameAs("private_static_final");

        assertThat(parent_mParentInnerClass).isNotNull();
        assertThat(parent_mParentInnerClassStatic).isNotNull();
        if (levelsTree > 2) {
            parent_mParentInnerClass.assertValidData();
            parent_mParentInnerClassStatic.assertValidData();
            super.assertValidData(levelsTree);
        } else {
            parent_mParentInnerClass.assertEmptyData();
            parent_mParentInnerClassStatic.assertEmptyData();
            super.assertEmptyData();
        }

    }

    public void assertEmptyData() {
        hasNot(parent_textDefault);
        hasNot(parent_textProtected);
        hasNot(parent_textPublic);
        hasNot(parent_textPrivate);

        hasNot(parent_textDefaultStatic);
        hasNot(parent_textProtectedStatic);
        hasNot(parent_textPublicStatic);
        hasNot(parent_textPrivateStatic);

        // final fields should not be set
        assertThat(parent_textPublicFinal).isSameAs("public_final");
        assertThat(parent_textDefaultFinal).isSameAs("default_final");
        assertThat(parent_textProtectedFinal).isSameAs("protected_final");
        assertThat(parent_textPrivateFinal).isSameAs("private_final");

        assertThat(parent_textPublicStaticFinal).isSameAs("public_static_final");
        assertThat(parent_textDefaultStaticFinal).isSameAs("default_static_final");
        assertThat(parent_textProtectedStaticFinal).isSameAs("protected_static_final");
        assertThat(parent_textPrivateStaticFinal).isSameAs("private_static_final");

        assertThat(parent_mParentInnerClass).isNull();
        assertThat(parent_mParentInnerClassStatic).isNull();
    }

    public static void resetStaticFields() {
        parent_textDefaultStatic = null;
        parent_textPrivateStatic = null;
        parent_textProtectedStatic = null;
        parent_textPublicStatic = null;
        ParentInnerClassStatic.resetStaticFields();
    }

    // ----- BEGIN: INNER CLASS ------ //

    public class ParentInnerClass {
        public String parentInner_textPublic;
        String parentInner_textDefault;
        protected String parentInner_textProtected;
        private String parentInner_textPrivate;

        public final String parentInner_textPublicFinal = "public_final";
        final String parentInner_textDefaultFinal = "default_final";
        protected final String parentInner_textProtectedFinal = "protected_final";
        private final String parentInner_textPrivateFinal = "private_final";

        public static final String parentInner_textPublicStaticFinal = "public_static_final";
        static final String parentInner_textDefaultStaticFinal = "default_static_final";
        protected static final String parentInner_textProtectedStaticFinal = "protected_static_final";
        private static final String parentInner_textPrivateStaticFinal = "private_static_final";

        public void assertValidData() {
            has(parentInner_textDefault);
            has(parentInner_textProtected);
            has(parentInner_textPublic);
            has(parentInner_textPrivate);

            // final fields should not be set
            assertThat(parentInner_textPublicFinal).isSameAs("public_final");
            assertThat(parentInner_textDefaultFinal).isSameAs("default_final");
            assertThat(parentInner_textProtectedFinal).isSameAs("protected_final");
            assertThat(parentInner_textPrivateFinal).isSameAs("private_final");

            assertThat(parentInner_textPublicStaticFinal).isSameAs("public_static_final");
            assertThat(parentInner_textDefaultStaticFinal).isSameAs("default_static_final");
            assertThat(parentInner_textProtectedStaticFinal).isSameAs("protected_static_final");
            assertThat(parentInner_textPrivateStaticFinal).isSameAs("private_static_final");

        }

        public void assertEmptyData() {
            hasNot(parentInner_textDefault);
            hasNot(parentInner_textProtected);
            hasNot(parentInner_textPublic);
            hasNot(parentInner_textPrivate);

            // final fields should not be set
            assertThat(parentInner_textPublicFinal).isSameAs("public_final");
            assertThat(parentInner_textDefaultFinal).isSameAs("default_final");
            assertThat(parentInner_textProtectedFinal).isSameAs("protected_final");
            assertThat(parentInner_textPrivateFinal).isSameAs("private_final");

            assertThat(parentInner_textPublicStaticFinal).isSameAs("public_static_final");
            assertThat(parentInner_textDefaultStaticFinal).isSameAs("default_static_final");
            assertThat(parentInner_textProtectedStaticFinal).isSameAs("protected_static_final");
            assertThat(parentInner_textPrivateStaticFinal).isSameAs("private_static_final");
        }
    }

    // ----- END: INNER CLASS ------ //

    // ----- BEGIN: STATIC INNER CLASS ------ //
    public static class ParentInnerClassStatic {
        public String parentInnerStatic_textPublic;
        String parentInnerStatic_textDefault;
        protected String parentInnerStatic_textProtected;
        private String parentInnerStatic_textPrivate;

        public final String parentInnerStatic_textPublicFinal = "public_final";
        final String parentInnerStatic_textDefaultFinal = "default_final";
        protected final String parentInnerStatic_textProtectedFinal = "protected_final";
        private final String parentInnerStatic_textPrivateFinal = "private_final";

        public static String parentInnerStatic_textPublicStatic;
        static String parentInnerStatic_textDefaultStatic;
        protected static String parentInnerStatic_textProtectedStatic;
        private static String parentInnerStatic_textPrivateStatic;

        public static final String parentInnerStatic_textPublicStaticFinal = "public_static_final";
        static final String parentInnerStatic_textDefaultStaticFinal = "default_static_final";
        protected static final String parentInnerStatic_textProtectedStaticFinal = "protected_static_final";
        private static final String parentInnerStatic_textPrivateStaticFinal = "private_static_final";

        public void assertValidData() {
            has(parentInnerStatic_textDefault);
            has(parentInnerStatic_textProtected);
            has(parentInnerStatic_textPublic);
            has(parentInnerStatic_textPrivate);

            has(parentInnerStatic_textDefaultStatic);
            has(parentInnerStatic_textProtectedStatic);
            has(parentInnerStatic_textPublicStatic);
            has(parentInnerStatic_textPrivateStatic);

            // final fields should not be set
            assertThat(parentInnerStatic_textPublicFinal).isSameAs("public_final");
            assertThat(parentInnerStatic_textDefaultFinal).isSameAs("default_final");
            assertThat(parentInnerStatic_textProtectedFinal).isSameAs("protected_final");
            assertThat(parentInnerStatic_textPrivateFinal).isSameAs("private_final");

            assertThat(parentInnerStatic_textPublicStaticFinal).isSameAs("public_static_final");
            assertThat(parentInnerStatic_textDefaultStaticFinal).isSameAs("default_static_final");
            assertThat(parentInnerStatic_textProtectedStaticFinal).isSameAs("protected_static_final");
            assertThat(parentInnerStatic_textPrivateStaticFinal).isSameAs("private_static_final");

        }

        public void assertEmptyData() {
            hasNot(parentInnerStatic_textDefault);
            hasNot(parentInnerStatic_textProtected);
            hasNot(parentInnerStatic_textPublic);
            hasNot(parentInnerStatic_textPrivate);

            hasNot(parentInnerStatic_textDefaultStatic);
            hasNot(parentInnerStatic_textProtectedStatic);
            hasNot(parentInnerStatic_textPublicStatic);
            hasNot(parentInnerStatic_textPrivateStatic);

            // final fields should not be set
            assertThat(parentInnerStatic_textPublicFinal).isSameAs("public_final");
            assertThat(parentInnerStatic_textDefaultFinal).isSameAs("default_final");
            assertThat(parentInnerStatic_textProtectedFinal).isSameAs("protected_final");
            assertThat(parentInnerStatic_textPrivateFinal).isSameAs("private_final");

            assertThat(parentInnerStatic_textPublicStaticFinal).isSameAs("public_static_final");
            assertThat(parentInnerStatic_textDefaultStaticFinal).isSameAs("default_static_final");
            assertThat(parentInnerStatic_textProtectedStaticFinal).isSameAs("protected_static_final");
            assertThat(parentInnerStatic_textPrivateStaticFinal).isSameAs("private_static_final");
        }

        public static void resetStaticFields() {
            parentInnerStatic_textDefaultStatic = null;
            parentInnerStatic_textPrivateStatic = null;
            parentInnerStatic_textProtectedStatic = null;
            parentInnerStatic_textPublicStatic = null;
        }
    }
    // ----- END: STATIC INNER CLASS ------ //
}


text:
'use strict';

angular.module('ethExplorer', ['ngRoute','ui.bootstrap'])

.config(['$routeProvider',
    function($routeProvider) {
        $routeProvider.
            when('/', {
                templateUrl: 'views/main.html',
                controller: 'mainCtrl'
            }).
            when('/block/:blockId', {
                templateUrl: 'views/blockInfos.html',
                controller: 'blockInfosCtrl'
            }).
            when('/transaction/:transactionId', {
                templateUrl: 'views/transactionInfos.html',
                controller: 'transactionInfosCtrl'
            }).
            when('/address/:addressId', {
                templateUrl: 'views/addressInfos.html',
                controller: 'addressInfosCtrl'
            }).
            otherwise({
                redirectTo: '/'
            });
    }])
    .run(function($rootScope) {
        var web3 = require('web3');
        web3.setProvider(new web3.providers.HttpProvider("http://localhost:8545"));
        $rootScope.web3=web3;

    });


text:
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.Tests.Common;

using Xunit;

public static class ByteTests
{
    [Fact]
    public static void TestCtorEmpty()
    {
        byte i = new byte();
        Assert.Equal(0, i);
    }

    [Fact]
    public static void TestCtorValue()
    {
        byte i = 41;
        Assert.Equal(41, i);
    }

    [Fact]
    public static void TestMaxValue()
    {
        Assert.Equal(0xFF, byte.MaxValue);
    }

    [Fact]
    public static void TestMinValue()
    {
        Assert.Equal(0, byte.MinValue);
    }

    [Theory]
    [InlineData((byte)234, 0)]
    [InlineData(byte.MinValue, 1)]
    [InlineData((byte)0, 1)]
    [InlineData((byte)45, 1)]
    [InlineData((byte)123, 1)]
    [InlineData((byte)235, -1)]
    [InlineData(byte.MaxValue, -1)]
    public static void TestCompareTo(byte value, int expected)
    {
        byte i = 234;
        int result = CompareHelper.NormalizeCompare(i.CompareTo(value));
        Assert.Equal(expected, result);
    }

    [Theory]
    [InlineData(null, 1)]
    [InlineData((byte)234, 0)]
    [InlineData(byte.MinValue, 1)]
    [InlineData((byte)0, 1)]
    [InlineData((byte)45, 1)]
    [InlineData((byte)123, 1)]
    [InlineData((byte)235, -1)]
    [InlineData(byte.MaxValue, -1)]
    public static void TestCompareToObject(object obj, int expected)
    {
        IComparable comparable = (byte)234;
        int i = CompareHelper.NormalizeCompare(comparable.CompareTo(obj));
        Assert.Equal(expected, i);
    }

    [Fact]
    public static void TestCompareToObjectInvalid()
    {
        IComparable comparable = (byte)234;
        Assert.Throws<ArgumentException>(null, () => comparable.CompareTo("a")); //Obj is not a byte
    }

    [Theory]
    [InlineData((byte)78, true)]
    [InlineData((byte)0, false)]
    public static void TestEqualsObject(object obj, bool expected)
    {
        byte i = 78;
        Assert.Equal(expected, i.Equals(obj));
    }

    [Theory]
    [InlineData((byte)78, true)]
    [InlineData((byte)0, false)]
    public static void TestEquals(byte i2, bool expected)
    {
        byte i = 78;
        Assert.Equal(expected, i.Equals(i2));
    }

    [Fact]
    public static void TestGetHashCode()
    {
        byte i1 = 123;
        byte i2 = 65;

        Assert.NotEqual(0, i1.GetHashCode());
        Assert.NotEqual(i1.GetHashCode(), i2.GetHashCode());
    }

    [Fact]
    public static void TestToString()
    {
        byte i1 = 63;
        Assert.Equal("63", i1.ToString());
    }

    [Fact]
    public static void TestToStringFormatProvider()
    {
        var numberFormat = new NumberFormatInfo();

        byte i1 = 63;
        Assert.Equal("63", i1.ToString(numberFormat));
    }

    [Fact]
    public static void TestToStringFormat()
    {
        byte i1 = 63;
        Assert.Equal("63", i1.ToString("G"));

        byte i2 = 82;
        Assert.Equal("82", i2.ToString("g"));

        byte i3 = 246;
        Assert.Equal(string.Format("{0:N}", 246.00), i3.ToString("N"));

        byte i4 = 0x24;
        Assert.Equal("24", i4.ToString("x"));
    }

    [Fact]
    public static void TestToStringFormatFormatProvider()
    {
        var numberFormat = new NumberFormatInfo();

        byte i1 = 63;
        Assert.Equal("63", i1.ToString("G", numberFormat));

        byte i2 = 82;
        Assert.Equal("82", i2.ToString("g", numberFormat));

        numberFormat.NegativeSign = "xx"; // setting it to trash to make sure it doesn't show up
        numberFormat.NumberGroupSeparator = "*";
        numberFormat.NumberNegativePattern = 0;
        numberFormat.NumberDecimalSeparator = ".";
        byte i3 = 24;
        Assert.Equal("24.00", i3.ToString("N", numberFormat));
    }

    public static IEnumerable<object[]> ParseValidData()
    {
        NumberFormatInfo defaultFormat = null;
        NumberStyles defaultStyle = NumberStyles.Integer;
        var emptyNfi = new NumberFormatInfo();

        var testNfi = new NumberFormatInfo();
        testNfi.CurrencySymbol = "$";

        yield return new object[] { "0", defaultStyle, defaultFormat, (byte)0 };
        yield return new object[] { "123", defaultStyle, defaultFormat, (byte)123 };
        yield return new object[] { "  123  ", defaultStyle, defaultFormat, (byte)123 };
        yield return new object[] { "255", defaultStyle, defaultFormat, (byte)255 };

        yield return new object[] { "12", NumberStyles.HexNumber, defaultFormat, (byte)0x12 };
        yield return new object[] { "10", NumberStyles.AllowThousands, defaultFormat, (byte)10 };

        yield return new object[] { "123", defaultStyle, emptyNfi, (byte)123 };

        yield return new object[] { "123", NumberStyles.Any, emptyNfi, (byte)123 };
        yield return new object[] { "12", NumberStyles.HexNumber, emptyNfi, (byte)0x12 };
        yield return new object[] { "ab", NumberStyles.HexNumber, emptyNfi, (byte)0xab };
        yield return new object[] { "$100", NumberStyles.Currency, testNfi, (byte)100 };
    }

    public static IEnumerable<object[]> ParseInvalidData()
    {
        NumberFormatInfo defaultFormat = null;
        NumberStyles defaultStyle = NumberStyles.Integer;
        var emptyNfi = new NumberFormatInfo();

        var testNfi = new NumberFormatInfo();
        testNfi.CurrencySymbol = "$";
        testNfi.NumberDecimalSeparator = ".";

        yield return new object[] { null, defaultStyle, defaultFormat, typeof(ArgumentNullException) };
        yield return new object[] { "", defaultStyle, defaultFormat, typeof(FormatException) };
        yield return new object[] { " ", defaultStyle, defaultFormat, typeof(FormatException) };
        yield return new object[] { "Garbage", defaultStyle, defaultFormat, typeof(FormatException) };

        yield return new object[] { "ab", defaultStyle, defaultFormat, typeof(FormatException) }; // Hex value
        yield return new object[] { "1E23", defaultStyle, defaultFormat, typeof(FormatException) }; // Exponent
        yield return new object[] { "(123)", defaultStyle, defaultFormat, typeof(FormatException) }; // Parentheses
        yield return new object[] { 100.ToString("C0"), defaultStyle, defaultFormat, typeof(FormatException) }; //Currency
        yield return new object[] { 1000.ToString("N0"), defaultStyle, defaultFormat, typeof(FormatException) }; //Thousands
        yield return new object[] { 67.90.ToString("F2"), defaultStyle, defaultFormat, typeof(FormatException) }; //Decimal

        yield return new object[] { "ab", NumberStyles.None, defaultFormat, typeof(FormatException) }; // Negative hex value
        yield return new object[] { "  123  ", NumberStyles.None, defaultFormat, typeof(FormatException) }; // Trailing and leading whitespace

        yield return new object[] { "67.90", defaultStyle, testNfi, typeof(FormatException) }; // Decimal

        yield return new object[] { "-1", defaultStyle, defaultFormat, typeof(OverflowException) }; // < min value
        yield return new object[] { "256", defaultStyle, defaultFormat, typeof(OverflowException) }; // > max value
        yield return new object[] { "(123)", NumberStyles.AllowParentheses, defaultFormat, typeof(OverflowException) }; // Parentheses = negative
    }

    [Theory, MemberData(nameof(ParseValidData))]
    public static void TestParse(string value, NumberStyles style, NumberFormatInfo nfi, byte expected)
    {
        byte i;
        //If no style is specified, use the (String) or (String, IFormatProvider) overload
        if (style == NumberStyles.Integer)
        {
            Assert.Equal(true, byte.TryParse(value, out i));
            Assert.Equal(expected, i);

            Assert.Equal(expected, byte.Parse(value));

            //If a format provider is specified, but the style is the default, use the (String, IFormatProvider) overload
            if (nfi != null)
            {
                Assert.Equal(expected, byte.Parse(value, nfi));
            }
        }

        // If a format provider isn't specified, test the default one, using a new instance of NumberFormatInfo
        Assert.Equal(true, byte.TryParse(value, style, nfi ?? new NumberFormatInfo(), out i));
        Assert.Equal(expected, i);

        //If a format provider isn't specified, test the default one, using the (String, NumberStyles) overload
        if (nfi == null)
        {
            Assert.Equal(expected, byte.Parse(value, style));
        }
        Assert.Equal(expected, byte.Parse(value, style, nfi ?? new NumberFormatInfo()));
    }

    [Theory, MemberData(nameof(ParseInvalidData))]
    public static void TestParseInvalid(string value, NumberStyles style, NumberFormatInfo nfi, Type exceptionType)
    {
        byte i;
        //If no style is specified, use the (String) or (String, IFormatProvider) overload
        if (style == NumberStyles.Integer)
        {
            Assert.Equal(false, byte.TryParse(value, out i));
            Assert.Equal(default(byte), i);

            Assert.Throws(exceptionType, () => byte.Parse(value));

            //If a format provider is specified, but the style is the default, use the (String, IFormatProvider) overload
            if (nfi != null)
            {
                Assert.Throws(exceptionType, () => byte.Parse(value, nfi));
            }
        }

        // If a format provider isn't specified, test the default one, using a new instance of NumberFormatInfo
        Assert.Equal(false, byte.TryParse(value, style, nfi ?? new NumberFormatInfo(), out i));
        Assert.Equal(default(byte), i);

        //If a format provider isn't specified, test the default one, using the (String, NumberStyles) overload
        if (nfi == null)
        {
            Assert.Throws(exceptionType, () => byte.Parse(value, style));
        }
        Assert.Throws(exceptionType, () => byte.Parse(value, style, nfi ?? new NumberFormatInfo()));
    }
}


text:
'''
@author: Gabriele Girelli
@contact: gigi.ga90@gmail.com
@description: methods for FISH image manipulation.
'''

# DEPENDENCIES =================================================================

import numpy as np
import os
import pandas as pd
import tifffile

from skimage.measure import label
from skimage.morphology import dilation

from pygpseq.tools import Binarize
from pygpseq.tools import image as imt
from pygpseq.tools import io as iot
from pygpseq.tools import plot

from pygpseq.fish.dot import dots2cells, calc_dot_distances
from pygpseq.fish.nucleus import build_nuclei, annotate_compartments

# FUNCTIONS ====================================================================

def analyze_field_of_view(ii, imfov, imdir, an_type, seg_type,
	maskdir, dilate_factor, aspect, t, main_mask_dir, main_mask_prefix,
	plotCompartments, pole_fraction, outdir, noplot,
	labeled, compressed, istruct):

	# Logger for logpath
	logger = iot.IOinterface()

	idx = ii
	impath = imfov[ii]
	msg = "> Job '%s'...\n" % (impath,)
	subt_idx = np.where(t['File'] == idx)[0]

	# Read image
	msg += "   - Reading ...\n"
	im = tifffile.imread(os.path.join(imdir, impath))
	if 1 == im.shape[0]:
		im = im[0]

	# Re-slice
	msg += "    > Re-slicing ...\n"
	im = imt.autoselect_time_frame(im)
	im = imt.slice_k_d_img(im, 3)

	# Get DNA scaling factor and rescale
	sf = imt.get_rescaling_factor([impath], basedir = imdir)
	im = (im / sf).astype('float')
	msg += "    > Re-scaling with factor %f...\n" % (sf,)

	# Pick first timeframe
	if 3 == len(im.shape) and 1 == im.shape[0]:
		im = im[0]

	# Binarize image -----------------------------------------------------------
	binarization = Binarize(
		an_type = an_type, seg_type = seg_type, verbose = False)

	# Check if already segmented
	already_segmented = False
	if not type(None) == type(main_mask_dir):
		mpath = os.path.join(main_mask_dir, main_mask_prefix + impath)
		if os.path.isfile(mpath):
			already_segmented = True

	# Skip or binarize
	if already_segmented:
		msg += "   - Skipped binarization, using provided mask.\n"
		imbin = imt.read_tiff(mpath) != 0
		thr = 0
	else:
		msg += "   - Binarizing...\n"
		(imbin, thr, log) = binarization.run(im)
		msg += log

	# Find nuclei --------------------------------------------------------------
	msg += "   - Retrieving nuclei...\n"

	# Estimate background
	dna_bg = imt.estimate_background(im, imbin, seg_type)
	msg += "    > Estimated background: %.2f a.u.\n" % (dna_bg,)

	# Filter object size
	imbin, tmp = binarization.filter_obj_XY_size(imbin)
	imbin, tmp = binarization.filter_obj_Z_size(imbin)

	# Save default mask
	msg += "   - Saving default binary mask...\n"
	outname = "%smask.%s.default.png" % (maskdir, os.path.splitext(impath)[0])
	if not noplot:
		plot.export_mask_png(outname, imbin, impath, "Default mask.")

	# Export dilated mask
	if not noplot and 0 != dilate_factor:
		msg += "   - Saving dilated mask...\n"
		imbin_dil = dilation(imbin, istruct)
		title = "Dilated mask, %d factor." % (dilate_factor,)
		outname = "%smask.%s.dilated%d.png" % (maskdir,
			os.path.splitext(impath)[0], dilate_factor)
		plot.export_mask_png(outname, imbin_dil, impath, title)

	# Identify nuclei
	L = label(imbin)
	seq = range(1, L.max() + 1)

	# Export binary mask
	if not type(None) == type(main_mask_dir) and not already_segmented:
		if not os.path.isdir(main_mask_dir):
			os.mkdir(main_mask_dir)
		msg += "   >>> Exporting mask as tif...\n"
		if labeled:
			plot.save_tif(mpath, L, 'uint8', compressed)
		else:
			L[np.nonzero(L)] = 255
			plot.save_tif(mpath, L, 'uint8', compressed)
			L = label(imbin)

	# Save mask ----------------------------------------------------------------
	msg += "   - Saving nuclear ID mask...\n"
	title = 'Nuclei in "%s" [%d objects]' % (impath, L.max())
	outpath = "%smask.%s.nuclei.png" % (maskdir, os.path.splitext(impath)[0])
	if not noplot:
		plot.export_mask_png(outpath, L, impath, title)

	# Store nuclei -------------------------------------------------------------
	msg, curnuclei = build_nuclei(msg, L, dilate_factor,
		series_id = ii, thr = thr,
		dna_bg = dna_bg, sig_bg = 0,
		aspect = aspect, offset = (1, 1, 1),
		logpath = logger.logpath, i = im, istruct = istruct)

	# Assign dots to cells -----------------------------------------------------
	msg += "   - Analysis...\n"
	msg += "    > Assigning dots to cells...\n"
	subt = dots2cells(t.loc[subt_idx, :], curnuclei, dilate_factor)

	# Distances ----------------------------------------------------------------
	msg += "    > Calculating lamina distance...\n"
	subt, msg = calc_dot_distances(msg, subt, curnuclei, aspect)

	# Compartments -------------------------------------------------------------

	msg += "    > Annotating compartments...\n"
	compdir = None

	if plotCompartments:
		# Create compartments output directory
		compdir = os.path.join(outdir, 'compartments/')
		if not os.path.isdir(compdir):
			os.mkdir(compdir)

	# Perform annotation
	subt, tvcomp, msg = annotate_compartments(
		msg, subt, curnuclei, compdir, pole_fraction, aspect)

	# Clean and output ---------------------------------------------------------

	# Remove masks from curnuclei
	for k in curnuclei.keys():
		del curnuclei[k].mask

	# Output
	msg += "< Finished job.\n"
	#print(msg)
	return((curnuclei, subt, subt_idx, tvcomp, msg))

# END ==========================================================================

################################################################################


text:
layout: global
title: Running Presto with Alluxio
nickname: Presto
group: Frameworks
priority: 2
---

This guide describes how to run [Presto](https://prestodb.io/) with Alluxio, so
that you can easily use presto to query Hive tables in Alluxio's tiered storage.

# Prerequisites

The prerequisite for this part is that you have [Java](Java-Setup.html). And the Java version must use Java 8 Update 60 or higher (8u60+), 64-bit.
Alluxio cluster should also be set up in accordance to these guides for either
[Local Mode](Running-Alluxio-Locally.html) or [Cluster Mode](Running-Alluxio-on-a-Cluster.html).

Alluxio client will need to be compiled with the Presto specific profile. Build the entire project
from the top level `alluxio` directory with the following command:

```bash
mvn clean package -Ppresto -DskipTests
```

Please [Download Presto](https://repo1.maven.org/maven2/com/facebook/presto/presto-server/)(This doc uses presto-0.170). And have finished
[Hive On Alluxio](http://www.alluxio.org/docs/master/en/Running-Hive-with-Alluxio.html)

# Configuration

Presto gets the database and table information by connecting Hive Metastore. At the same time,
The file system location of table is obtained by the table's metadata. So you need to configure
[Presto on Hdfs](https://prestodb.io/docs/current/installation/deployment.html). In order to access hdfs,
you need to add the hadoop conf files (core-site.xml,hdfs-site.xml), and use `hive.config.resources` in
file `/<PATH_TO_PRESTO>/etc/catalog/hive.properties` to point to the file's location for every Presto worker.

#### Configure `core-site.xml`

You need to add the following configuration items to the `core-site.xml` configured in `hive.properties`:

```xml
<property>
  <name>fs.alluxio.impl</name>
  <value>alluxio.hadoop.FileSystem</value>
</property>
<property>
  <name>fs.AbstractFileSystem.alluxio.impl</name>
  <value>alluxio.hadoop.AlluxioFileSystem</value>
  <description>The Alluxio AbstractFileSystem (Hadoop 2.x)</description>
</property>
```
If your Alluxio is HA, another configuration need to added:
```xml
<property>
  <name>fs.alluxio-ft.impl</name>
  <value>alluxio.hadoop.FaultTolerantFileSystem</value>
  <description>The Alluxio FileSystem (Hadoop 1.x and 2.x) with fault tolerant support</description>
</property>
```
#### Configure additional Alluxio properties

Similar to above, add additional Alluxio properties to `core-site.xml` of Hadoop configuration in Hadoop directory on each node.
 For example, change `alluxio.user.file.writetype.default` from default `MUST_CACHE` to `CACHE_THROUGH`:

```xml
<property>
<name>alluxio.user.file.writetype.default</name>
<value>CACHE_THROUGH</value>
</property>
```

Alternatively, you can also append the path to [`alluxio-site.properties`](Configuration-Settings.html) to Presto's JVM config at `etc/jvm.config` under Presto folder. The advantage of this approach is to have all the Alluxio properties set within the same file of `alluxio-site.properties`.

```bash
...
-Xbootclasspath/p:<path-to-alluxio-site-properties>
```

Also, it's recommended to increase `alluxio.user.network.netty.timeout.ms` to a bigger value (e.g. 10 mins) to avoid the timeout
 failure when reading large files from remote.

#### Increase `hive.max-split-size`

Presto's hive integration uses the config [`hive.max-split-size`](https://teradata.github.io/presto/docs/141t/connector/hive.html) to control the parallelism of the query. It's recommended to set this size no less than Alluxio's block size to avoid the read contention within the same block.

# Distribute the Alluxio Client Jar

Distribute the Alluxio client jar to all worker nodes in Presto:
- You must put Alluxio client jar `{{site.ALLUXIO_CLIENT_JAR_PATH}}` into Presto cluster's worker directory
`$PRESTO_HOME/plugin/hive-hadoop2/`
(For different versions of Hadoop, put the appropriate folder), And restart the process of coordinator and worker.

# Presto cli examples

Create a table in Hive and load a file in local path into Hive:

You can download the data file from  [http://grouplens.org/datasets/movielens/](http://grouplens.org/datasets/movielens/)

```
hive> CREATE TABLE u_user (
userid INT,
age INT,
gender CHAR(1),
occupation STRING,
zipcode STRING)
ROW FORMAT DELIMITED
FIELDS TERMINATED BY '|'
STORED AS TEXTFILE;

hive> LOAD DATA LOCAL INPATH '<path_to_ml-100k>/u.user'
OVERWRITE INTO TABLE u_user;
```

View Alluxio WebUI at `http://master_hostname:19999` and you can see the directory and file Hive creates:

![HiveTableInAlluxio]({{site.data.img.screenshot_presto_table_in_alluxio}})

Using a single query:
```
/home/path/presto/presto-cli-0.170-executable.jar --server masterIp:prestoPort --execute "use default;select * from u_user limit 10;" --user username --debug
```

And you can see the query results from console:

![PrestoQueryResult]({{site.data.img.screenshot_presto_query_result}})

Presto Server log:

![PrestoQueryLog]({{site.data.img.screenshot_presto_query_log}})