text:
"use strict";

var escapeQuoteHelpers = require("./escape-quotes");
var escapeDoubleQuotes = escapeQuoteHelpers.___escapeDoubleQuotes;
var escapeSingleQuotes = escapeQuoteHelpers.___escapeSingleQuotes;

module.exports = maybeEmptyAttr;

maybeEmptyAttr.___notEmptyAttr = notEmptyAttr;
maybeEmptyAttr.___isEmptyAttrValue = isEmpty;

function maybeEmptyAttr(name, value) {
  if (isEmpty(value)) {
    return "";
  }

  return notEmptyAttr(name, value);
}

function notEmptyAttr(name, value) {
  switch (typeof value) {
    case "string":
      return " " + name + guessQuotes(value);
    case "boolean":
      return " " + name;
    case "number":
      return " " + name + "=" + value;
    case "object":
      if (value instanceof RegExp) {
        return " " + name + doubleQuote(value.source);
      }
  }

  return " " + name + guessQuotes(value + "");
}

function isEmpty(value) {
  return value == null || value === false;
}

function doubleQuote(value, startPos) {
  return '="' + escapeDoubleQuotes(value, startPos) + '"';
}

function singleQuote(value, startPos) {
  return "='" + escapeSingleQuotes(value, startPos) + "'";
}

function guessQuotes(value) {
  for (var i = 0, len = value.length; i < len; i++) {
    switch (value[i]) {
      case '"':
        return singleQuote(value, i + 1);
      case "'":
      case ">":
      case " ":
      case "\t":
      case "\n":
      case "\r":
      case "\f":
        return doubleQuote(value, i + 1);
    }
  }

  return value && "=" + (value[len - 1] === "/" ? value + " " : value);
}

redpajama_set_name: RedPajamaGithub


text:
using System;
using EloBuddy;
using EloBuddy.SDK.Menu;
using EloBuddy.SDK.Events;
using EloBuddy.SDK.Menu.Values;
using EloBuddy.SDK.Rendering;
using SharpDX;

namespace Ziggs___Beta
{
    internal class Menus
    {
        private static Menu OriginalMenu, ComboTabela, LaneTabela, JungleTabela, HarassTabela, LastLabela, KillSteal, FleeTabela, DrawTabela;

        internal static void Iniciar()
        {

            OriginalMenu = MainMenu.AddMenu("Ziggs", "Ziggs");
            OriginalMenu.AddGroupLabel("Ziggs em modo Beta");
            OriginalMenu.AddLabel("Ziggs versão 7.1.0.2");
            // Fazer o Menu Do Combo
            ComboTabela = OriginalMenu.AddSubMenu("zCombo");
            ComboTabela.Add("usarQ", new CheckBox("Usar Q"));
            ComboTabela.Add("usarW", new CheckBox("Usar W"));
            ComboTabela.Add("usarE", new CheckBox("Usar E", false));
            ComboTabela.Add("usarR", new CheckBox("Usar R"));
            ComboTabela.AddLabel("Configurações para Spell R");
            ComboTabela.Add("MinimoEnemy", new Slider("Use R min Enemys", 1,0,5));
            ComboTabela.Add("ModoSuicida", new CheckBox("Mode Suicidal", false));
            ComboTabela.AddLabel("Config AA");
            ComboTabela.Add("UsarAA", new CheckBox("User Mode AA"));
            // Fazer o Menu Harass
            HarassTabela = OriginalMenu.AddSubMenu("zHarass");
            // Lane Clear
            LaneTabela = OriginalMenu.AddSubMenu("zLane");
            // Jungle Clear
            JungleTabela = OriginalMenu.AddSubMenu("zJungle");
            // KilSteal
            KillSteal = OriginalMenu.AddSubMenu("zKillSteal");
            // Last
            LastLabela = OriginalMenu.AddSubMenu("zLast");
            // Draws
            DrawTabela = OriginalMenu.AddSubMenu("zDraw");
            DrawTabela.AddLabel("Draws Spells");
            DrawTabela.Add("DQ", new CheckBox("Draw Q Spell"));
            DrawTabela.Add("DW", new CheckBox("Draw W Spell"));
            DrawTabela.Add("DE", new CheckBox("Draw E Spell"));
            DrawTabela.Add("DR", new CheckBox("Draw R Spell"));
            //COmando
            Drawing.OnDraw += zDrawing_OnDraw;

        }

        private static void zDrawing_OnDraw(EventArgs args)
        {
            if (DrawTabela["DQ"].Cast<CheckBox>().CurrentValue && Spells.E.IsLearned)
            {
                Circle.Draw(Color.MediumVioletRed, E.Range, Player.Instance.Position);
            }

        }
    }
}


text:
package thirdparty.net.oelen.polarith;

import java.io.UnsupportedEncodingException;

// A strong very fast 64 byte hash generator.
// This can be used on any datatype which can
// be represented as a byte array. A helper
// function for strings is supplied.

class Hash64 {
    private static final long[] byteTable;
    static {
        byteTable = new long[256];
        long h = 0x544B2FBACAAF1684L;
        for (int i = 0; i < 256; i++) {
            for (int j = 0; j < 31; j++) {
                h = (h >>> 7) ^ h;
                h = (h << 11) ^ h;
                h = (h >>> 10) ^ h;
            }
            byteTable[i] = h;
        }
    }

    private static final long HSTART = 0xBB40E64DA205B064L;
    private static final long HMULT = 7664345821815920749L;

    public static long hash(String msg) {
        long hsh;
        byte[] data = null;
        try {
            data = msg.getBytes("UTF-8");
            hsh = hash(data);
        }
        catch (UnsupportedEncodingException ign) {
            // This never occurs, the UTF-8 encoding is a standard
            // encoding and this exception hence never is thrown.
            hsh = msg.hashCode();
        }
        return hsh;
    }

    public static long hash(byte[] data) {
        long h = HSTART;
        final long hmult = HMULT;
        final long[] ht = byteTable;
        for (int len = data.length, i = 0; i < len; i++) {
            h = (h * hmult) ^ ht[data[i] & 0xff];
        }
        return h;
    }
}


text:
#ifndef MockWebMIDIAccessor_h
#define MockWebMIDIAccessor_h

#include "TestCommon.h"
#include "public/platform/WebMIDIAccessor.h"

namespace WebKit {
class WebMIDIAccessorClient;
}

namespace WebTestRunner {

class MockWebMIDIAccessor : public WebKit::WebMIDIAccessor {
public:
    explicit MockWebMIDIAccessor(WebKit::WebMIDIAccessorClient*);
    virtual ~MockWebMIDIAccessor();

    // WebKit::WebMIDIAccessor implementation.
    virtual void startSession() OVERRIDE;
    virtual void sendMIDIData(
        unsigned portIndex,
        const unsigned char* data,
        size_t length,
        double timestamp) OVERRIDE { }

private:
    WebKit::WebMIDIAccessorClient* m_client;
};

} // namespace WebTestRunner

#endif // MockWebMIDIAccessor_h


text:
package com.microsoft.azure.management.batchai.v2018_05_01;

import java.util.Map;
import com.fasterxml.jackson.annotation.JsonProperty;

/**
 * Workspace creation parameters.
 */
public class WorkspaceCreateParameters {
    /**
     * Location.
     * The region in which to create the Workspace.
     */
    @JsonProperty(value = "location", required = true)
    private String location;

    /**
     * Tags.
     * The user specified tags associated with the Workspace.
     */
    @JsonProperty(value = "tags")
    private Map<String, String> tags;

    /**
     * Get the region in which to create the Workspace.
     *
     * @return the location value
     */
    public String location() {
        return this.location;
    }

    /**
     * Set the region in which to create the Workspace.
     *
     * @param location the location value to set
     * @return the WorkspaceCreateParameters object itself.
     */
    public WorkspaceCreateParameters withLocation(String location) {
        this.location = location;
        return this;
    }

    /**
     * Get the user specified tags associated with the Workspace.
     *
     * @return the tags value
     */
    public Map<String, String> tags() {
        return this.tags;
    }

    /**
     * Set the user specified tags associated with the Workspace.
     *
     * @param tags the tags value to set
     * @return the WorkspaceCreateParameters object itself.
     */
    public WorkspaceCreateParameters withTags(Map<String, String> tags) {
        this.tags = tags;
        return this;
    }

}


text:
package manager

import (
	"github.com/epinion-online-research/ant-worker/entity"
	. "github.com/epinion-online-research/ant-worker/module"
)

type JobManager struct {
	Observer chan string
	Module Module
	JobProcessors [] JobProcessor
}

const STATUS_CREATED  int = 1;
const STATUS_PAUSED   int = 2;
const STATUS_STOPPED  int = 3;
const STATUS_PENDING  int = 4;
const STATUS_PROGRESS int = 5;
const STATUS_FINISHED int = 6;

const PROGRESS_START  int = 1;
const PROGRESS_DONE   int = 2;

func (manager *JobManager) Create(data entity.JobApi) (entity.Job, error) {
	db := manager.Module.Sql.Db
	job := entity.Job {
		Name: data.Name,
		Description: data.Description,
		Type: data.Type,
		Callback: data.Callback,
		Status: STATUS_CREATED,
	}
	db.Create(&job)
	return job, nil
}

func( manager *JobManager ) GetAll() ([]entity.Job, error) {
	db := manager.Module.Sql.Db
	var jobs []entity.Job
	db.Find(&jobs)
	return jobs, nil
}

func (manager *JobManager) Get(jobId int) (entity.Job, error) {
	db := manager.Module.Sql.Db
	var job entity.Job
	db.Select("*").Where("id = ?", jobId).Find(&job)
	return job, nil
}

func( manager *JobManager ) Update(jobId int, data entity.JobApi) (entity.Job, error) {
	var job entity.Job
	db := manager.Module.Sql.Db
	db.Select("*").Where("id = ?", jobId).First(&job)

	job.Name = data.Name
	job.Description = data.Description
	job.Type = data.Type
	job.Callback = data.Callback

	db.Save(&job)
	return job, nil
}

/*
func( manager *JobManager ) ParlyUpdate(data entity.JobApi) (entity.Job, error) {
	return job, nil
}*/

func (manager *JobManager) Delete(jobId int) error {
	var job entity.Job
	db := manager.Module.Sql.Db
	db.Where("id = ?", jobId).Delete(&job)
	return nil
}

func (manager *JobManager) Start(jobId int)  (error) {
	job, err := manager.Get(jobId)
	if err != nil {
		return err
	}
	job.Status = STATUS_PROGRESS
	job.Progress = 0
	db := manager.Module.Sql.Db
	db.Save(&job)
	return nil
}

func (manager *JobManager) Pause(jobId int)  (error) {
	job, err := manager.Get(jobId)
	if err != nil {
		return err
	}
	job.Status = STATUS_PAUSED
	// job.Progress is not changed
	db := manager.Module.Sql.Db
	db.Save(&job)
	return nil
}

func (manager *JobManager) Resume(jobId int) (error) {
	job, err := manager.Get(jobId)
	if err != nil {
		return err
	}
	job.Status = STATUS_PROGRESS
	// job.Progress is not changed
	db := manager.Module.Sql.Db
	db.Save(&job)
	return nil
}

func (manager *JobManager) Stop(jobId int) (error) {
	job, err := manager.Get(jobId)
	if err != nil {
		return err
	}
	job.Status = STATUS_STOPPED
	// job.Progress is not changed
	db := manager.Module.Sql.Db
	db.Save(&job)
	return nil
}

func (manager *JobManager) Finish(jobId int) (error) {
	job, err := manager.Get(jobId)
	if err != nil {
		return err
	}
	job.Status   = STATUS_FINISHED
	job.Progress = PROGRESS_DONE
	db := manager.Module.Sql.Db
	db.Save(&job)
	return nil
}

func (manager *JobManager) Process(job entity.Job) {
	processor := JobProcessor {
		Job: job,
		Config: manager.Module.Config,
	}
	//append( manager.JobProcessors, processor)
	go processor.Process()
}

func (manager *JobManager ) Monitor() {
	go func() {
		for {
			select {
			case msg := <- manager.Observer :
				go func() {
					println( msg )
				}()
			}
		}
	}()
}

/*

func (manager *JobManager) Init(){

}

func( manager *JobManager ) UpdateJob(){

}

func( manager *JobManager ) PauseJob(){

}

func( manager *JobManager ) DeleteJob(){

}
*/


text:
@font-face {
  font-family: 'Roboto';
  font-style: normal;
  font-weight: 400;
  src: local('Roboto'), local('Roboto-Regular'), url(roboto.ttf) format('truetype');
}


text:
namespace GitVersion;

public interface IObjectId : IEquatable<IObjectId?>, IComparable<IObjectId>
{
    string Sha { get; }
    string ToString(int prefixLength);
}


text:
<wicket:panel>

</wicket:panel>


text:
<?php
namespace Procure\Application\Service\QR\Output;

use Procure\Application\Service\Output\Formatter\RowFormatterDecorator;
use Procure\Domain\RowSnapshot;
use Procure\Domain\QuotationRequest\QRRowSnapshot;

/**
 * QR Row Output.
 *
 * @author Nguyen Mau Tri - ngmautri@gmail.com
 *
 */
class QrRowFormatter extends RowFormatterDecorator
{

    /**
     *
     * {@inheritdoc}
     * @see \Procure\Application\Service\Output\Formatter\AbstractRowFormatter::format()
     */
    public function format(RowSnapshot $row)
    {
        if (! $row instanceof RowSnapshot) {
            return null;
        }
        $this->formatter->setLocale($this->getLocale());
        $row = $this->formatter->format($row);

        // then decorate
        if ($row instanceof QRRowSnapshot) {
            // $row->unitPrice = ($row->getUnitPrice() !== null ? number_format($row->getUnitPrice(), $decimalNo) : 0);
        }

        return $row;
    }
}


text:
package com.google.template.soy.jbcsrc.api;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import static java.nio.charset.StandardCharsets.UTF_8;

import com.google.auto.value.AutoValue;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.io.ByteSource;
import com.google.common.io.CharSource;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * Info about a plugin runtime instance class, such as the class name and the source locations where
 * the plugin is used.
 *
 * <p>We store this info in meta-inf files and use it to verify that bindings have been provided for
 * all required plugin runtime instances. The source locations are stored so that we can provide
 * better error messages when a binding is missing, so that users can figure out where the function
 * is used / if they actually need it or should just remove the dep.
 */
@AutoValue
public abstract class PluginRuntimeInstanceInfo {
  private static final char FIELD_DELIMITER = '|';
  private static final Splitter FIELD_SPLITTER = Splitter.on(FIELD_DELIMITER);
  private static final char SOURCE_LOCATION_DELIMITER = ',';
  private static final Joiner SOURCE_LOCATION_JOINER = Joiner.on(SOURCE_LOCATION_DELIMITER);
  private static final Splitter SOURCE_LOCATION_SPLITTER = Splitter.on(SOURCE_LOCATION_DELIMITER);

  /** The name of the Soy plugin. */
  public abstract String pluginName();

  /** The class name of the plugin runtime instance. */
  public abstract String instanceClassName();

  /**
   * Soy source locations where the plugin is used, stored as strings because we read the plugin
   * info from meta-inf files and want to easily the PluginRuntimeInstanceInfo data structure.
   */
  public abstract ImmutableSortedSet<String> sourceLocations();

  public static ByteSource serialize(Iterable<PluginRuntimeInstanceInfo> plugins) {
    StringBuilder builder = new StringBuilder();
    for (PluginRuntimeInstanceInfo plugin : plugins) {
      builder.append(plugin.toMetaInfEntry());
    }
    return CharSource.wrap(builder.toString()).asByteSource(UTF_8);
  }

  static ImmutableList<PluginRuntimeInstanceInfo> deserialize(ByteSource byteSource)
      throws IOException {
    Map<String, PluginRuntimeInstanceInfo> pluginNameToClassNameMap = new LinkedHashMap<>();
    try (InputStream inputStream = byteSource.openStream()) {
      BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, UTF_8));
      for (String line = reader.readLine(); line != null; line = reader.readLine()) {
        PluginRuntimeInstanceInfo pluginRuntimeInstanceInfo = fromMetaInfEntry(line);
        pluginNameToClassNameMap.merge(
            pluginRuntimeInstanceInfo.pluginName(),
            pluginRuntimeInstanceInfo,
            PluginRuntimeInstanceInfo::merge);
      }
    }
    return ImmutableList.copyOf(pluginNameToClassNameMap.values());
  }

  /**
   * Converts this {@code PluginRuntimeInstanceInfo} into an entry written to the Soy plugins
   * META_INF file.
   */
  private String toMetaInfEntry() {
    return pluginName()
        + FIELD_DELIMITER
        + instanceClassName()
        + FIELD_DELIMITER
        + SOURCE_LOCATION_JOINER.join(sourceLocations())
        + "\n";
  }

  /**
   * Converts a entry in the Soy plugins META_INF file back into a {@code
   * PluginRuntimeInstanceInfo}. This is the inverse of {@link #toMetaInfEntry()}.
   */
  private static PluginRuntimeInstanceInfo fromMetaInfEntry(String metaInfEntry) {
    List<String> fields = FIELD_SPLITTER.splitToList(metaInfEntry.trim());
    checkState(
        fields.size() == 3,
        "Entry [%s] is expected to have exactly three fields but found %s fields (%s).",
        metaInfEntry,
        fields.size(),
        fields.toArray());
    return builder()
        .setPluginName(fields.get(0))
        .setInstanceClassName(fields.get(1))
        .addAllSourceLocations(SOURCE_LOCATION_SPLITTER.splitToList(fields.get(2)))
        .build();
  }

  /**
   * Merges two {@code PluginRuntimeInstanceInfo} objects with the same plugin name and instance
   * class name into a single {@code PluginRuntimeInstanceInfo}.
   */
  public static PluginRuntimeInstanceInfo merge(
      PluginRuntimeInstanceInfo original, PluginRuntimeInstanceInfo other) {
    checkArgument(original.pluginName().equals(other.pluginName()));
    checkArgument(original.instanceClassName().equals(other.instanceClassName()));
    return builder()
        .setPluginName(original.pluginName())
        .setInstanceClassName(original.instanceClassName())
        .addAllSourceLocations(original.sourceLocations())
        .addAllSourceLocations(other.sourceLocations())
        .build();
  }

  public static Builder builder() {
    return new AutoValue_PluginRuntimeInstanceInfo.Builder();
  }

  /** Builder for {@link PluginRuntimeInstanceInfo}, with an accumulator for source locations. */
  @AutoValue.Builder
  public abstract static class Builder {

    public abstract Builder setPluginName(String value);

    public abstract Builder setInstanceClassName(String value);

    /**
     * Builder for source locations the in the Soy template the Soy plugin is used. Note, we are
     * using an {@link ImmutableSortedSet} to ensure the contents of META_INF file is always
     * deterministic.
     */
    abstract ImmutableSortedSet.Builder<String> sourceLocationsBuilder();

    @CanIgnoreReturnValue
    public Builder addAllSourceLocations(Iterable<String> sourceLocations) {
      sourceLocationsBuilder().addAll(sourceLocations);
      return this;
    }

    @CanIgnoreReturnValue
    public Builder addSourceLocation(String sourceLocation) {
      sourceLocationsBuilder().add(sourceLocation);
      return this;
    }

    public abstract PluginRuntimeInstanceInfo build();
  }
}


text:
from allennlp.interpret.saliency_interpreters.saliency_interpreter import SaliencyInterpreter
from allennlp.interpret.saliency_interpreters.simple_gradient import SimpleGradient
from allennlp.interpret.saliency_interpreters.integrated_gradient import IntegratedGradient
from allennlp.interpret.saliency_interpreters.smooth_gradient import SmoothGradient


text:
import nav from '../nav';

export default {
  init() {
    nav.init();
  },
  finalize() {
    // JavaScript to be fired on all pages, after page specific JS is fired
  },
};


text:
/**
 * Created by jiamiu on 14-4-15.
 */
var assert = require('assert'),
  co = require('co'),
  when = require('when')

describe('Caller test',function(){
  it('Caller of generator',function(done){
    co( function *a(){

        //simulate fire function
        function b(){

          console.log( arguments.callee.caller )
          return co(function *b(){
            when.promise(function(resolve){
              setTimeout( function c(){
                resolve()
                done()
              },200)
            })
          })
        }
        yield b()
    })()

  })
})


text:
require 'action_controller'
require 'rqrcode'
require 'rqrcode-rails3/size_calculator.rb'
require 'rqrcode-rails3/renderers/svg.rb'

module RQRCode
	Mime::Type.register "image/svg+xml", :svg  unless Mime::Type.lookup_by_extension(:svg)
	Mime::Type.register "image/png",     :png  unless Mime::Type.lookup_by_extension(:png)
	Mime::Type.register "image/jpeg",    :jpeg unless Mime::Type.lookup_by_extension(:jpeg)
	Mime::Type.register "image/gif",     :gif  unless Mime::Type.lookup_by_extension(:gif)

	extend SizeCalculator

	ActionController::Renderers.add :qrcode do |string, options|
		format         = self.request.format.symbol
		cqrcode        = RQRCode::CQRCode.new
		options[:info] = string
		data           = cqrcode.generateQRcode(options, format)

		self.response_body = render_to_string(:text => data, :template => nil)
	end

	class CQRCode
		@@defaults = {
			:info     => "no data",
			:bg       => false,
			:bsize    => false,
			:gravity  => "north",
			:geometry => "+00+00",
			:fsize    => false,
			:fsave    => false
		}

		def generateQRcode(options={}, format=:svg)
			options  = @@defaults.merge(options)
			string   = options[:info]
			size     = options[:size]  || RQRCode.minimum_qr_size_from_string(string)
			level    = options[:level] || :h

			bg       = options[:bg]
			bsize    = options[:bsize]
			geometry = options[:geometry]
			gravity  = options[:gravity]
			fsize    = options[:fsize]
			fsave    = options[:fsave]

			qrcode = RQRCode::QRCode.new(string, :size => size, :level => level)
			svg    = RQRCode::Renderers::SVG::render(qrcode, options)

			data   = \
			if format && format == :svg
				svg
			else
				image = MiniMagick::Image.read(svg) { |i| i.format "svg" }
				image.format format

				if bg
					bg_image = MiniMagick::Image.open bg
					bg_image.resize bsize if bsize
					image    =  bg_image.composite(image) do |c|
						c.gravity gravity
						c.geometry geometry
					end
				end
				image.resize fsize if fsize
				image.write fsave if fsave

				image.to_blob
			end
			return data
		end
	end
end


text:
<?php

namespace Forum\Support\Traits;

use Crowfeather\Traverser\Traverser;

trait ForumMutatorTrait
{
    /**
     * Gets the user's displayname.
     *
     * @return string
     */
    public function getAuthorAttribute()
    {
        return ! $this->user ?: $this->user->displayname;
    }
}


text:
FROM golang:1.7

MAINTAINER Andrey Samokhvalov <andrew.shvv@gmail.com>

# Expose mainnet ports (server, rpc)
EXPOSE 8333 8334

# Expose testnet ports (server, rpc)
EXPOSE 18333 18334

# Expose simnet ports (server, rpc)
EXPOSE 18555 18556

# Expose segnet ports (server, rpc)
EXPOSE 28901 28902

# Grab and install the latest version of roasbeef's fork of ltcd and all
# related dependencies.
WORKDIR $GOPATH/src/github.com/ltcsuite/ltcd
RUN git clone https://github.com/ltcsuite/ltcd ./
RUN go get -u github.com/Masterminds/glide
RUN glide install
RUN go install . ./cmd/ltcctl ./cmd/gencerts

RUN mkdir "/rpc" "/root/.ltcd" "/root/.ltcctl"
RUN touch "/root/.ltcd/ltcd.conf"

# "ltcctl" and "lnd" to "ltcd" over docker links.
RUN "/go/bin/gencerts" --host="*" --directory="/rpc" --force

# Create a volume to house pregenerated RPC credentials. This will be
# shared with any lnd, btcctl containers so they can securely query ltcd's RPC
# server.
# You should NOT do this before certificate generation!
# Otherwise manually generated certificate will be overriden with shared
# mounted volume! For more info read dockerfile "VOLUME" documentation.
VOLUME ["/rpc"]

COPY "start-ltcctl.sh" .
COPY "start-ltcd.sh" .

RUN chmod +x start-ltcctl.sh
RUN chmod +x start-ltcd.sh


text:
package com.amazonaws.services.panorama.model;

import javax.annotation.Generated;

/**
 *
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public enum NodeCategory {

    BUSINESS_LOGIC("BUSINESS_LOGIC"),
    ML_MODEL("ML_MODEL"),
    MEDIA_SOURCE("MEDIA_SOURCE"),
    MEDIA_SINK("MEDIA_SINK");

    private String value;

    private NodeCategory(String value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return this.value;
    }

    /**
     * Use this in place of valueOf.
     *
     * @param value
     *        real value
     * @return NodeCategory corresponding to the value
     *
     * @throws IllegalArgumentException
     *         If the specified value does not map to one of the known values in this enum.
     */
    public static NodeCategory fromValue(String value) {
        if (value == null || "".equals(value)) {
            throw new IllegalArgumentException("Value cannot be null or empty!");
        }

        for (NodeCategory enumEntry : NodeCategory.values()) {
            if (enumEntry.toString().equals(value)) {
                return enumEntry;
            }
        }

        throw new IllegalArgumentException("Cannot create enum from " + value + " value!");
    }
}


text:
from django.conf.urls import patterns, include, url
from django.conf import settings
from referee.views import *

urlpatterns = patterns(
    '',
    # Referee Home View
    url(r'^$', RefereeHomeView.as_view(), name="referee_home"),

    #Micro Sumo
    url(r'^micro_sumo/$',
        MicroSumoRefereeBaseListView.as_view(),
        name="micro_sumo_base_referee"),
    url(r'^micro_sumo/(?P<type>[\w-]+)/$',
        MicroSumoTypeRefereeListView.as_view(),
        name="micro_sumo_type_list"),
    url(r'^micro_sumo/(?P<type>[\w-]+)/(?P<order>\d+)/$',
        MicroSumoOrdersRefereeListView.as_view(),
        name="micro_sumo_orders"),
    url(r'^micro_sumo/groups/(?P<order>\d+)/(?P<pid>\d+)/update/$',
        MicroSumoGroupResultUpdateView.as_view(),
        name="micro_sumo_group_result_update"),
    url(r'^micro_sumo/stages/(?P<order>\d+)/(?P<pid>\d+)/update/$',
        MicroSumoStageResultUpdateView.as_view(),
        name="micro_sumo_stage_result_update"),
    url(r'^micro_sumo/groups/(?P<order>\d+)/(?P<pid>\d+)/$',
        MicroSumoGroupQRCodeCheckView.as_view(),
        name="micro_sumo_group_qrcode_check"),
    url(r'^micro_sumo/stages/(?P<order>\d+)/(?P<pid>\d+)/$',
        MicroSumoStageQRCodeCheckView.as_view(),
        name="micro_sumo_stage_qrcode_check"),

    # Innovative
    url(r'^innovative/$',
        InnovativeResultListView.as_view(),
        name='innovative_referee'),
    url(r'^innovative/(?P<pid>\d+)/create/$',
        InnovativeResultCreateView.as_view(),
        name='innovative_result_create'),
    url(r'^innovative/(?P<pid>\d+)/update/(?P<rid>\d+)/$',
        InnovativeResultUpdateView.as_view(),
        name='innovative_result_update'),
    url(r'^innovative/(?P<pid>\d+)/delete/(?P<rid>\d+)/$',
        InnovativeResultDeleteView.as_view(),
        name='innovative_result_delete'),

    # Line Follower
    url(r'^line_follower/$',
        RefereeLineFollowerStageListView.as_view(),
        name='referee_line_follower_stage_list_view'),
    url(r'^line_follower/(?P<order>\d+)/$',
        LineFollowerRobotListView.as_view(),
        name='line_follower_robot_list'),
    url(r'^line_follower/(?P<order>\d+)/(?P<pid>\d+)/create/$',
        LineFollowerResultCreateView.as_view(),
        name='line_follower_result_create'),
    url(r'^line_follower/(?P<order>\d+)/(?P<pid>\d+)/check/$',
        LineFollowerQRCodeCheckView.as_view(),
        name='line_follower_qrcode_check'),
    url(r'^line_follower/(?P<order>\d+)/(?P<pid>\d+)/update/(?P<rid>\d+)/$',
        LineFollowerResultUpdateView.as_view(),
        name='line_follower_result_update'),
    url(r'^line_follower/(?P<order>\d+)/(?P<pid>\d+)/delete/(?P<rid>\d+)/$',
        LineFollowerResultDeleteView.as_view(),
        name='line_follower_result_delete'),

    # Line Follower Junior
    url(r'^line_follower_junior/$',
        RefereeLineFollowerJuniorStageListView.as_view(),
        name='referee_line_follower_junior_stage_list_view'),
    url(r'^line_follower_junior/(?P<order>\d+)/$',
        LineFollowerJuniorRobotListView.as_view(),
        name='line_follower_junior_robot_list'),
    url(r'^line_follower_junior/(?P<order>\d+)/(?P<pid>\d+)/create/$',
        LineFollowerJuniorResultCreateView.as_view(),
        name='line_follower_junior_result_create'),
    url(r'^line_follower_junior/(?P<order>\d+)/(?P<pid>\d+)/check/$',
        LineFollowerJuniorQRCodeCheckView.as_view(),
        name='line_follower_junior_qrcode_check'),
    url(r'^line_follower_junior/(?P<order>\d+)/(?P<pid>\d+)/update/(?P<rid>\d+)/$',
        LineFollowerJuniorResultUpdateView.as_view(),
        name='line_follower_junior_result_update'),
    url(r'^line_follower_junior/(?P<order>\d+)/(?P<pid>\d+)/delete/(?P<rid>\d+)/$',
        LineFollowerJuniorResultDeleteView.as_view(),
        name='line_follower_junior_result_delete'),

    # Simulation
    url(r'^simulation/$',
        RefereeSimulationStageListView.as_view(),
        name='referee_simulation_stage_list_view'),
    url(r'^simulation/(?P<stage>\d+)/$',
        SimulationRobotListView.as_view(),
        name='simulation_robot_list'),
    url(r'^simulation/(?P<stage>\d+)/create/(?P<order>\d+)/$',
        SimulationResultCreateView.as_view(),
        name='simulation_result_create'),
    url(r'^simulation/(?P<stage>\d+)/update/(?P<order>\d+)/(?P<rid>\d+)/$',
        SimulationResultUpdateView.as_view(),
        name='simulation_result_update'),
    url(r'^simulation/(?P<stage>\d+)/delete/(?P<order>\d+)/(?P<rid>\d+)/$',
        SimulationResultDeleteView.as_view(),
        name='simulation_result_delete'),

    # Generic Robot List View
    url(r'^(?P<category>[-_\w]+)/$',
        CategoryRobotListView.as_view(),
        name='category_robot_list'),
    url(r'^(?P<category>[-_\w]+)/(?P<pid>\d+)/check/$',
        CategoryQRCodeCheckView.as_view(),
        name="category_qrcode_check"),

    # Construction
    url(r'^construction/(?P<pid>\d+)/create/$',
        ConstructionResultCreateView.as_view(),
        name='construction_result_create'),
    url(r'^construction/(?P<pid>\d+)/update/(?P<rid>\d+)/$',
        ConstructionResultUpdateView.as_view(),
        name='construction_result_update'),
    url(r'^consruction/(?P<pid>\d+)/delete/(?P<rid>\d+)/$',
        ConstructionResultDeleteView.as_view(),
        name='construction_result_delete'),

    # Drone
    url(r'^drone/(?P<pid>\d+)/create/$',
        DroneResultCreateView.as_view(),
        name='drone_result_create'),
    url(r'^drone/(?P<pid>\d+)/update/(?P<rid>\d+)/$',
        DroneResultUpdateView.as_view(),
        name='drone_result_update'),
    url(r'^drone/(?P<pid>\d+)/delete/(?P<rid>\d+)/$',
        DroneResultDeleteView.as_view(),
        name='drone_result_delete'),

    # Stair Climbing
    url(r'^stair_climbing/(?P<pid>\d+)/create/$',
        StairClimbingResultCreateView.as_view(),
        name='stair_climbing_result_create'),
    url(r'^stair_climbing/(?P<pid>\d+)/update/(?P<rid>\d+)/$',
        StairClimbingResultUpdateView.as_view(),
        name='stair_climbing_result_update'),
    url(r'^stair_climbing/(?P<pid>\d+)/delete/(?P<rid>\d+)/$',
        StairClimbingResultDeleteView.as_view(),
        name='stair_climbing_result_delete'),

    # Color Selecting
    url(r'^color_selecting/(?P<pid>\d+)/create/$',
        ColorSelectingResultCreateView.as_view(),
        name='color_selecting_result_create'),
    url(r'^color_selecting/(?P<pid>\d+)/update/(?P<rid>\d+)/$',
        ColorSelectingResultUpdateView.as_view(),
        name='color_selecting_result_update'),
    url(r'^color_selecting/(?P<pid>\d+)/delete/(?P<rid>\d+)/$',
        ColorSelectingResultDeleteView.as_view(),
        name='color_selecting_result_delete'),

    # Scenario
    url(r'^scenario/(?P<pid>\d+)/create/$',
        ScenarioResultCreateView.as_view(),
        name='scenario_result_create'),
    url(r'^scenario/(?P<pid>\d+)/update/(?P<rid>\d+)/$',
        ScenarioResultUpdateView.as_view(),
        name='scenario_result_update'),
    url(r'^scenario/(?P<pid>\d+)/delete/(?P<rid>\d+)/$',
        ScenarioResultDeleteView.as_view(),
        name='scenario_result_delete'),

)


text:
package org.lcmmun.kiosk.broadcast;

import java.io.Serializable;

import org.lcmmun.kiosk.CommitteeState;
import org.lcmmun.kiosk.gui.Kiosk;

/**
 * An outline of a committee. Instances of this class are sent by {@link Kiosk}s
 * to OmniKiosks.
 *
 * @author William Chargin
 *
 */
public class CommitteeOutline implements Serializable {

	/**
	 *
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * The total number of committee outlines.
	 */
	public static int count;

	/**
	 * The name of the committee.
	 */
	public final String name;

	/**
	 * The state of the committee.
	 */
	public final CommitteeState state;

	/**
	 * The current topic.
	 */
	public final String topic;

	/**
	 * Any comments from the chairs of the committee regarding its status.
	 */
	public final String comments;

	/**
	 * The total number of working papers and resolutions for the current topic.
	 */
	public final int wprCount;

	/**
	 * Creates the committee outline with all required values.
	 *
	 * @param name
	 *            the committee name
	 * @param state
	 *            the committee state
	 * @param topic
	 *            the current topic
	 * @param comments
	 *            the chairs' comments
	 * @param wprCount
	 *            the total number of working papers and resolutions for this
	 *            topic
	 */
	public CommitteeOutline(String name, CommitteeState state, String topic,
			String comments, int wprCount) {
		super();
		this.name = name == null ? new String() : name;
		this.state = state;
		this.topic = topic == null ? new String() : topic;
		this.comments = comments == null ? new String() : comments;
		this.wprCount = wprCount;
	}

	/**
	 * Gets the chairs' comments about this committee.
	 *
	 * @return the comments
	 */
	public String getComments() {
		return comments;
	}

}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Aspicilia mastrucata var. mastrucata

### Remarks
null


text:
#include "atmosphere/model/bruneton/bruneton.h"

#include <sstream>
#include <string>

#include "atmosphere/model/bruneton/core.h"

Bruneton::Bruneton(ScatteringType scattering_type,
    int original_number_of_wavelength)
        : original_number_of_wavelength_(original_number_of_wavelength) {
  std::ifstream f;
  std::string name;
  const std::string cache_directory = "output/cache/bruneton/";

  name = cache_directory + "transmittance.dat";
  f.open(name);
  if (f.good()) {
    f.close();
    transmittance_sampler_.Load(name);
  } else {
    ComputeTransmittance(&transmittance_sampler_);
    transmittance_sampler_.Save(name);
  }

  constexpr int kNumScatteringOrders = 4;
  constexpr int kNumSteps = 2 * kNumScatteringOrders - 1;

  if (scattering_type == DOUBLE_SCATTERING_ONLY) {
    inscatter1R_sampler_.Set(
        IrradianceSpectrum(0.0 * watt_per_square_meter_per_nm));
    inscatter1M_sampler_.Set(
        IrradianceSpectrum(0.0 * watt_per_square_meter_per_nm));
  } else {
    name = cache_directory + "inscatter1R.dat";
    f.open(name);
    if (f.good()) {
      f.close();
      inscatter1R_sampler_.Load(name);
      inscatter1M_sampler_.Load(cache_directory + "inscatter1M.dat");
    } else {
      std::cout << "Precomputing, step 1/" << kNumSteps << "..." << std::endl;
      ComputeInscatter1(transmittance_sampler_, &inscatter1R_sampler_,
          &inscatter1M_sampler_);
      inscatter1R_sampler_.Save(name);
      inscatter1M_sampler_.Save(cache_directory + "inscatter1M.dat");
    }
  }

  if (scattering_type == SINGLE_SCATTERING_ONLY) {
    inscatterN_sum_sampler_.Set(
        RadianceSpectrum(0.0 * watt_per_square_meter_per_sr_per_nm));
    name = cache_directory + "irradiance2.dat";
    f.open(name);
    if (f.good()) {
      f.close();
      sky_irradiance_sum_sampler_.Load(name);
    } else {
      std::cerr << name << " must be precomputed. Run with ALL_ORDERS first."
                << std::endl;
      exit(-1);
    }
    return;
  } else if (scattering_type == DOUBLE_SCATTERING_ONLY) {
    name = cache_directory + "inscatter2.dat";
    f.open(name);
    if (f.good()) {
      f.close();
      inscatterN_sum_sampler_.Load(name);
      sky_irradiance_sum_sampler_.Load(cache_directory + "irradiance3.dat");
    } else {
      std::cerr << name << " must be precomputed. Run with ALL_ORDERS first."
                << std::endl;
      exit(-1);
    }
    return;
  } else {
    name = cache_directory + "inscatterNSum.dat";
    f.open(name);
    if (f.good()) {
      f.close();
      inscatterN_sum_sampler_.Load(name);
      sky_irradiance_sum_sampler_.Load(cache_directory + "irradianceNSum.dat");
      return;
    }
  }

  SkyIrradianceTexture sky_irradiance_sampler;
  name = cache_directory + "irradiance1.dat";
  f.open(name);
  if (f.good()) {
    f.close();
    sky_irradiance_sampler.Load(name);
  } else {
    ComputeSkyIrradiance1(transmittance_sampler_, &sky_irradiance_sampler);
    sky_irradiance_sampler.Save(name);
  }

  RadianceDensityTexture inscatterS_sampler;
  RadianceTexture inscatterN_sampler;
  for (int i = 2; i <= kNumScatteringOrders; ++i) {
    const std::string iteration = std::to_string(i);
    bool first_iteration = i == 2;

    name = cache_directory + "inscatterS" + iteration + ".dat";
    f.open(name);
    if (f.good()) {
      f.close();
      inscatterS_sampler.Load(name);
    } else {
      std::cout << "Precomputing, step " << 2 * i - 2 << "/" << kNumSteps
                << "..." << std::endl;
      ComputeInscatterS(transmittance_sampler_, sky_irradiance_sampler,
          inscatter1R_sampler_, inscatter1M_sampler_, inscatterN_sampler,
          first_iteration, &inscatterS_sampler);
      inscatterS_sampler.Save(name);
    }

    name = cache_directory + "irradiance" + iteration + ".dat";
    f.open(name);
    if (f.good()) {
      f.close();
      sky_irradiance_sampler.Load(name);
    } else {
      ComputeSkyIrradianceN(inscatter1R_sampler_, inscatter1M_sampler_,
          inscatterN_sampler, first_iteration, &sky_irradiance_sampler);
      sky_irradiance_sampler.Save(name);
    }

    name = cache_directory + "inscatter" + iteration + ".dat";
    f.open(name);
    if (f.good()) {
      f.close();
      inscatterN_sampler.Load(name);
    } else {
      std::cout << "Precomputing, step " << 2 * i - 1 << "/" << kNumSteps
                << "..." << std::endl;
      ComputeInscatterN(transmittance_sampler_, inscatterS_sampler,
          &inscatterN_sampler);
      inscatterN_sampler.Save(name);
    }

    if (first_iteration) {
      sky_irradiance_sum_sampler_.Set(sky_irradiance_sampler);
      inscatterN_sum_sampler_.Set(inscatterN_sampler);
    } else {
      sky_irradiance_sum_sampler_ += sky_irradiance_sampler;
      inscatterN_sum_sampler_ += inscatterN_sampler;
    }
  }
  inscatterN_sum_sampler_.Save(cache_directory + "inscatterNSum.dat");
  sky_irradiance_sum_sampler_.Save(cache_directory + "irradianceNSum.dat");
}

IrradianceSpectrum Bruneton::GetSunIrradiance(Length altitude,
    Angle sun_zenith) const {
  return GetTransmittance(transmittance_sampler_, EarthRadius + altitude,
      cos(sun_zenith)) * SolarSpectrum();
}

RadianceSpectrum Bruneton::GetSkyRadiance(Length altitude, Angle sun_zenith,
    Angle view_zenith, Angle view_sun_azimuth) const {
  Number mu_s = cos(sun_zenith);
  Number mu = cos(view_zenith);
  Number nu =
      cos(view_sun_azimuth) * sin(view_zenith) * sin(sun_zenith) + mu * mu_s;
  InverseSolidAngle rayleigh_phase = RayleighPhaseFunction(nu);
  InverseSolidAngle mie_phase = MiePhaseFunction(nu);

  IrradianceSpectrum ray =
      texture4d(inscatter1R_sampler_, EarthRadius + altitude, mu, mu_s, nu);
  IrradianceSpectrum mie =
      texture4d(inscatter1M_sampler_, EarthRadius + altitude, mu, mu_s, nu);
  RadianceSpectrum raymieN =
      texture4d(inscatterN_sum_sampler_, EarthRadius + altitude, mu, mu_s, nu);
  return (ray * rayleigh_phase + mie * mie_phase) + raymieN;
}

IrradianceSpectrum Bruneton::GetSkyIrradiance(Length altitude,
    Angle sun_zenith) const {
  return ::GetSkyIrradiance(
      sky_irradiance_sum_sampler_, EarthRadius + altitude, cos(sun_zenith));
}


text:
require 'spec_helper'

describe HomeController do
  describe 'GET #index' do
    def make_request
      get :index
    end

    before { make_request }

    its(:response) { should be_success }
  end
end


text:
package monitoring_test

import (
	"cloud.google.com/go/monitoring/apiv3"
	"golang.org/x/net/context"
	monitoringpb "google.golang.org/genproto/googleapis/monitoring/v3"
)

func ExampleNewGroupClient() {
	ctx := context.Background()
	c, err := monitoring.NewGroupClient(ctx)
	if err != nil {
		// TODO: Handle error.
	}
	// TODO: Use client.
	_ = c
}

func ExampleGroupClient_ListGroups() {
	ctx := context.Background()
	c, err := monitoring.NewGroupClient(ctx)
	if err != nil {
		// TODO: Handle error.
	}

	req := &monitoringpb.ListGroupsRequest{
	// TODO: Fill request struct fields.
	}
	it := c.ListGroups(ctx, req)
	for {
		resp, err := it.Next()
		if err != nil {
			// TODO: Handle error.
			break
		}
		// TODO: Use resp.
		_ = resp
	}
}

func ExampleGroupClient_GetGroup() {
	ctx := context.Background()
	c, err := monitoring.NewGroupClient(ctx)
	if err != nil {
		// TODO: Handle error.
	}

	req := &monitoringpb.GetGroupRequest{
	// TODO: Fill request struct fields.
	}
	resp, err := c.GetGroup(ctx, req)
	if err != nil {
		// TODO: Handle error.
	}
	// TODO: Use resp.
	_ = resp
}

func ExampleGroupClient_CreateGroup() {
	ctx := context.Background()
	c, err := monitoring.NewGroupClient(ctx)
	if err != nil {
		// TODO: Handle error.
	}

	req := &monitoringpb.CreateGroupRequest{
	// TODO: Fill request struct fields.
	}
	resp, err := c.CreateGroup(ctx, req)
	if err != nil {
		// TODO: Handle error.
	}
	// TODO: Use resp.
	_ = resp
}

func ExampleGroupClient_UpdateGroup() {
	ctx := context.Background()
	c, err := monitoring.NewGroupClient(ctx)
	if err != nil {
		// TODO: Handle error.
	}

	req := &monitoringpb.UpdateGroupRequest{
	// TODO: Fill request struct fields.
	}
	resp, err := c.UpdateGroup(ctx, req)
	if err != nil {
		// TODO: Handle error.
	}
	// TODO: Use resp.
	_ = resp
}

func ExampleGroupClient_DeleteGroup() {
	ctx := context.Background()
	c, err := monitoring.NewGroupClient(ctx)
	if err != nil {
		// TODO: Handle error.
	}

	req := &monitoringpb.DeleteGroupRequest{
	// TODO: Fill request struct fields.
	}
	err = c.DeleteGroup(ctx, req)
	if err != nil {
		// TODO: Handle error.
	}
}

func ExampleGroupClient_ListGroupMembers() {
	ctx := context.Background()
	c, err := monitoring.NewGroupClient(ctx)
	if err != nil {
		// TODO: Handle error.
	}

	req := &monitoringpb.ListGroupMembersRequest{
	// TODO: Fill request struct fields.
	}
	it := c.ListGroupMembers(ctx, req)
	for {
		resp, err := it.Next()
		if err != nil {
			// TODO: Handle error.
			break
		}
		// TODO: Use resp.
		_ = resp
	}
}


text:
<?php

namespace tourze\Http\Exception;

use tourze\Http\Http;

class Http200Exception extends RedirectException
{

    /**
     * @var int
     */
    protected $_code = Http::OK;

}


text:
"""
Module for matching inventory action arguments
"""
from mockito.matchers import Matcher

class DropActionParameterMatcher(Matcher):
    """
    Matcher to check drop action parameters
    """
    def __init__(self, item):
        """
        Default constructor

        :param item: item to check
        :type item: Item
        """
        super().__init__()
        self.item = item

    def matches(self, arg):
        """
        Check if the passed argument matches

        :param arg: argument to check
        :returns: True if match, otherwise False
        :rtype: boolean
        """
        match_ok = True

        if arg.action_type != 'inventory':
            match_ok = False

        if arg.sub_action != 'drop':
            match_ok = False

        if arg.item != self.item:
            match_ok = False

        return match_ok

    def __repr__(self):
        """
        Get string explanation of this matcher

        :returns: explanation of expected match
        :rtype: string
        """
        return """action_type = 'inventory'
                  sub_action = 'drop'
                  item = {0}""".format(self.item)


text:
package com.ofg.loan;

import com.wordnik.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping(value = "/api/marketing")
@Api(value = "marketingOfferGenerator", description = "Manages Loan marketing offers")
class MarketingOfferGeneratorController {

    private MarketingOfferGenerator marketingOfferGenerator;

    @Autowired
    MarketingOfferGeneratorController(MarketingOfferGenerator marketingOfferGenerator) {
        this.marketingOfferGenerator = marketingOfferGenerator;
    }

    @RequestMapping(method = RequestMethod.PUT, value = "{loanApplicationId}", consumes = "application/json")
    ResponseEntity saveLoan(@PathVariable("loanApplicationId") String loanApplicationId,
                                      @RequestBody LoanApplication loanApplication) {
        marketingOfferGenerator.save(loanApplicationId, loanApplication);
        return new ResponseEntity(HttpStatus.OK);
    }

    @RequestMapping(method = RequestMethod.GET, value = "{loanApplicationId}", produces = "application/json")
    ResponseEntity<LoanApplication> getLoan(@PathVariable("loanApplicationId") String loanApplicationId) {
        LoanApplication loanApplication = marketingOfferGenerator.get(loanApplicationId);
        if (loanApplication == null) {
            return new ResponseEntity<>(loanApplication, HttpStatus.NOT_FOUND);
        }
        return new ResponseEntity<>(loanApplication, HttpStatus.OK);
    }
}


text: Project moved to: https://github.com/4thCircleCorner/wp-vereinsflieger-login


text:
package com.modinfodesigns.ontology.builder;

import com.modinfodesigns.property.DataObject;
import com.modinfodesigns.property.DataList;
import com.modinfodesigns.property.IProperty;
import com.modinfodesigns.property.IPropertyHolder;

import com.modinfodesigns.property.string.StringProperty;

import com.modinfodesigns.pipeline.process.IDataObjectProcessor;
import com.modinfodesigns.pipeline.source.IDataObjectSource;
import com.modinfodesigns.security.IUserCredentials;

public class MockDataObjectSource implements IDataObjectSource
{
  IDataObjectProcessor myProcessor;

  public MockDataObjectSource( ) {  }

  @Override
  public void run()
  {
    DataList theData = new DataList( );

    // Create some DataObjects that simulate a Taxonomy with parentIDs
    DataObject rootObj = new DataObject( "root" );
    rootObj.setID( "0" );
    theData.addDataObject( rootObj );

    DataObject childObj = new DataObject( "child 1" );
    childObj.setID( "1" );
    childObj.setProperty( new StringProperty( "parentID", "0" ) );
    theData.addDataObject( childObj );

    childObj = new DataObject( "child 2" );
    childObj.setID( "2" );
    childObj.setProperty( new StringProperty( "parentID", "0" ) );
    theData.addDataObject( childObj );

    // add some grand kids to child 1
    DataObject grandChildObj = new DataObject( "grandChild 1.1" );
    grandChildObj.setID( "3" );
    grandChildObj.setProperty( new StringProperty( "parentID", "1" ) );
    theData.addDataObject( grandChildObj );

    grandChildObj = new DataObject( "grandChild 1.2" );
    grandChildObj.setID( "4" );
    grandChildObj.setProperty( new StringProperty( "parentID", "1" ) );
    theData.addDataObject( grandChildObj );

    myProcessor.processDataList( theData );
    myProcessor.processComplete( (IPropertyHolder)null, true );
  }

  @Override
  public void run(IUserCredentials withUser)
  {
    run( );
  }

  @Override
  public void addDataObjectProcessor(IDataObjectProcessor dataProcessor)
  {
    myProcessor = dataProcessor;
  }

}


text:
/*
 * <blockinfo type="PacketCounter" invocation="direct" thread_exclusive="False">
 *   <humandesc>
 *     Keeps packet and byte counts of traffic going through it and logs,
 *     every 0.5 seconds, the packet rate.
 *     An xml parameter can be used in order to disable the timer mechanism.
 *   </humandesc>
 *
 *   <shortdesc>Keeps packet and byte counts of traffic going through it.</shortdesc>
 *
 *   <gates>
 *     <gate type="input" name="in_pkt" msg_type="Packet" m_start="0" m_end="0" />
 *   </gates>
 *
 *   <paramsschema>
 *    element params {
 *      element notimer {text}?
 *      }
 *
 *   </paramsschema>
 *
 *    <paramsexample>
 *        <params>
 *              <notimer/>
 *          </params>
 *
 *   </paramsexample>
 *
 *   <variables>
 *     <variable name="pktcnt" human_desc="integer" access="read"/>
 *     <variable name="bytecnt" human_desc="integer" access="read"/>
 *     <variable name="byterate" human_desc="integer" access="read"/>
 *     <variable name="pktrate" human_desc="integer" access="read"/>
 *     <variable name="reset" human_desc="write 1 to reset packet and byte counts" access="write"/>
 *   </variables>
 *
 * </blockinfo>
 */

#include <PassthroughPacketCounter.hpp>
namespace blockmon
{
    void PassthroughPacketCounter::_handle_timer(std::shared_ptr<Timer>&& )
    {
        std::chrono::system_clock::time_point n= std::chrono::system_clock::now();
        auto d = std::chrono::duration_cast<std::chrono::microseconds>(n-m_last_t);

        unsigned long long tmp_pkt_cnt = m_pkt_cnt;
        unsigned long long tmp_byte_cnt = m_byte_cnt;

        m_pkt_rate = (double)(tmp_pkt_cnt - m_pkt_cnt_prev) / ((double)d.count() / 1000000.0);
        m_byte_rate = (double)(tmp_byte_cnt - m_byte_cnt_prev) / ((double)d.count() / 1000000.0);
    m_pkt_cnt_prev = m_pkt_cnt;
    m_byte_cnt_prev = m_byte_cnt;
        m_last_t = n;
    }
} // namespace blockmon


text:
import os
import math

# Third-party modules
import numpy

import matplotlib
from mpl_toolkits.axes_grid1 import make_axes_locatable
import matplotlib.pyplot as plt

try:
    import weblogo
    # Weblogo compatibility
    # With version < 3.5, the color class is 'ColorGroup'. In version >= 3.5,
    # it is 'SymbolColor'. Here, we change to always have 'ColorGroup'.
    try:
        ColorGroup = weblogo.SymbolColor
    except AttributeError:
        ColorGroup = weblogo.ColorGroup
except ImportError:
    IS_WEBLOGO = False
else:
    IS_WEBLOGO = True

# Local modules
from .. import PB
from . import utils

# Python2/Python3 compatibility
# The range function in python 3 behaves as the range function in python 2
# and returns a generator rather than a list. To produce a list in python 3,
# one should use list(range). Here we change range to behave the same in
# python 2 and in python 3. In both cases, range will return a generator.
try:
    range = xrange
except NameError:
    pass

# Create the __all__ keyword according to the conditional imports
__all__ = ['plot_neq', 'plot_map']
if IS_WEBLOGO:
    __all__ += ['generate_weblogo']

def plot_neq(fname, neq_array, idx_first_residue=1, residue_min=1, residue_max=None):
    """
    Generate the Neq plot along the protein sequence

    Parameters
    ----------
    fname : str
        The path to the file to write in
    neq_array : numpy array
        an array containing the neq value associated to the residue number
    idx_first_residue: int
        the index of the first residue in the array
    residue_min: int
        the lower bound of the protein sequence
    residue_max: int
        the upper bound of the protein sequence
    """

    neq = utils._slice_matrix(neq_array, idx_first_residue, residue_min, residue_max)
    nb_residues = neq.shape[0]

    # Residue number with good offset given the slice
    x = numpy.arange(residue_min, residue_min + nb_residues)

    fig = plt.figure(figsize=(2.0 * math.log(nb_residues), 5))
    ax = fig.add_subplot(1, 1, 1)
    ax.set_ylim([0, round(max(neq), 0) + 1])
    ax.plot(x, neq)
    ax.set_xlabel('Residue number', fontsize=18)
    ax.set_ylabel('Neq', fontsize=18, style='italic')
    fig.savefig(fname)

def plot_map(fname, count_mat, idx_first_residue=1, residue_min=1, residue_max=None):
    """
    Generate a map of the distribution of PBs along protein sequence from
    an occurence matrix.

    Parameters
    ----------
    fname : str
        The path to the file to write in
    count_mat : numpy array
        an occurence matrix returned by `count_matrix`.
    idx_first_residue: int
        the index of the first residue in the matrix
    residue_min: int
        the lower bound of the protein sequence
    residue_max: int
        the upper bound of the protein sequence
    """
    # Get the frequency matrix
    freq_mat = utils.compute_freq_matrix(count_mat)
    # take a slice with min/max residues
    freq = utils._slice_matrix(freq_mat, idx_first_residue, residue_min, residue_max)
    nb_residues = freq.shape[0]
    # Residue number with good offset given the slice
    x = numpy.arange(residue_min, residue_min + nb_residues)

    # Define a scaling factor to handle nice rendering for small and large proteins
    # This is empirical!
    scaling_factor = math.log(nb_residues)

    # define ticks for x-axis
    x_step = 1
    # space ticks for large proteins
    if nb_residues > 12:
        x_step = 2
    if nb_residues > 25:
        x_step = 5
    if nb_residues > 100:
        x_step = 10
    if nb_residues > 200:
        x_step = int(scaling_factor) * 5
    xticks = x[::x_step]
    # trying to round ticks: 5, 10, 15 instead of 6, 11, 16...
    if xticks[0] == 1:
        xticks = xticks - 1
        xticks[0] += 1

    # define ticks for y-axis
    yticks = ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
              'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p')

    fig = plt.figure(figsize=(2.0 * scaling_factor, 4))

    gs = matplotlib.gridspec.GridSpec(1, 3, width_ratios=[1, 2.0 * scaling_factor, 1])
    ax1 = fig.add_subplot(gs[0])
    ax2 = fig.add_subplot(gs[1])
    ax3 = fig.add_subplot(gs[2])
    # Color scheme inspired from ColorBrewer
    # http://colorbrewer2.org/?type=diverging&scheme=RdYlBu&n=5
    # This color scheme is colorblind safe
    colors = [(44.0 / 255, 123.0 / 255, 182.0 / 255),
              (171.0 / 255, 217.0 / 255, 233.0 / 255),
              (255.0 / 255, 255.0 / 255, 191.0 / 255),
              (253.0 / 255, 174.0 / 255, 97.0 / 255),
              (215.0 / 255, 25.0 / 255, 28.0 / 255)]
    cmap = matplotlib.colors.LinearSegmentedColormap.from_list('ColBrewerRdYlBu', colors)

    img = ax2.imshow(numpy.transpose(freq[:, :]), interpolation='none', vmin=0, vmax=1,
                     origin='lower', aspect='auto', cmap=cmap)

    # add colorbar
    divider2 = make_axes_locatable(ax2)
    # cax2 = divider2.append_axes("right", size="5%", pad=0.08)
    cax2 = divider2.append_axes("right", size=0.15, pad=0.08)
    plt.colorbar(img, cax=cax2)

    # add ticks and labels
    ax2.set_xticks(xticks - numpy.min(xticks))
    ax2.set_xticklabels(xticks)
    ax2.set_yticks(range(len(yticks)))
    ax2.set_yticklabels(yticks, style='italic', weight='bold')
    ax2.set_xlabel("Residue number", weight="bold")

    # add secondary structures
    ax1.set_axis_off()
    ax1.text(0.2, 0.5, "PBs", rotation=90, weight="bold",
                       size='larger', ha='center', va='center')
    # center alpha-helix: PB m (13th PB out of 16 PBs)
    # center coil: PB h and i (8th and 9th PBs out of 16 PBs)
    # center beta-sheet: PB d (4th PB out of 16 PBs)
    ax1.text(0.5, 4.0 / 16, r"$\beta$-strand", rotation=90,
             ha='center', va='center')
    ax1.text(0.5, 8.5 / 16, r"coil", rotation=90,
             ha='center', va='center')
    ax1.text(0.5, 13.0 / 16, r"$\alpha$-helix", rotation=90,
             ha='center', va='center')

    # add "intensity"
    ax3.set_axis_off()
    ax3.text(0.7, 0.5, "Intensity", rotation=90, weight="bold", ha='center', va='center')

    # adjust margins and save
    fig.subplots_adjust(left=0.01, bottom=0.12, top=0.96, right=0.99, wspace=0)
    fig.savefig(fname, dpi=300)

def generate_weblogo(fname, count_mat, idx_first_residue=1, residue_min=1, residue_max=None, title=""):
    """
    Generates logo representation of PBs frequency along protein sequence through
    the weblogo library.

    The weblogo reference:
    G. E. Crooks, G. Hon, J.-M. Chandonia, and S. E. Brenner.
    'WebLogo: A Sequence Logo Generator.'
    Genome Research 14:1188–90 (2004)
    doi:10.1101/gr.849004.
    http://weblogo.threeplusone.com/

    Parameters
    ----------
    fname : str
        The path to the file to write in
    count_mat : numpy array
        an occurence matrix returned by `count_matrix`.
    idx_first_residue: int
        the index of the first residue in the matrix
    residue_min: int
        the lower bound of residue frame
    residue_max: int
        the upper bound of residue frame
    title: str
        the title of the weblogo. Default is empty.
    """

    # Slice the matrix
    count = utils._slice_matrix(count_mat, idx_first_residue, residue_min, residue_max)

    # Create a custom color scheme for PB
    colors = weblogo.ColorScheme([ColorGroup("d", "#1240AB", "strand main"),
                                     ColorGroup("abcdef", "#1240AB", "strand others"),
                                     ColorGroup("ghij", "#0BD500", "coil"),
                                     ColorGroup("m", "#FD0006", "helix main"),
                                     ColorGroup("klnop", "#FD0006", "helix others")])

    # Load data from an occurence matrix
    data = weblogo.LogoData.from_counts(PB.NAMES, count)

    # Create options
    options = weblogo.LogoOptions(fineprint=False, logo_title=title, color_scheme=colors,
                                     stack_width=weblogo.std_sizes["large"],
                                     first_residue=residue_min)

    # Generate weblogo
    logo = weblogo.LogoFormat(data, options)

    # Retrieve image format
    image_format = os.path.splitext(fname)[1][1:]

    # Retrieve the right function given the image format
    try:
        if image_format == 'jpg':
            image_format = 'jpeg'
        formatter = weblogo.formatters[image_format]
    except KeyError:
        raise ValueError("Invalid format image '{0}'."
                         " Valid ones are : eps, png, pdf, jpg/jpeg, svg".format(image_format))
    # Format the logo
    image = formatter(data, logo)

    # Write it
    with open(fname, "wb") as f:
        f.write(image)


text:
namespace pythonic
{

  namespace numpy
  {
    namespace wrapper
    {
      template <class T>
      double fix(T const &v)
      {
        return nt2::trunc(v);
      }
    }

#define NUMPY_NARY_FUNC_NAME fix
#define NUMPY_NARY_FUNC_SYM wrapper::fix
#include "pythonic/types/numpy_nary_expr.hpp"
  }
}

#endif