text:
package smartthings.dw.cassandra.addresstranslator;

import com.datastax.driver.core.policies.AddressTranslator;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import io.dropwizard.jackson.Discoverable;

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type")
public interface AddressTranslatorFactory extends Discoverable {
    AddressTranslator build();
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace TwigJs\Compiler\Expression\Test;

use TwigJs\JsCompiler;
use TwigJs\TypeCompilerInterface;

class ConstantCompiler implements TypeCompilerInterface
{
    public function getType()
    {
        return 'Twig_Node_Expression_Test_Constant';
    }

    public function compile(JsCompiler $compiler, \Twig_NodeInterface $node)
    {
        if (!$node instanceof \Twig_Node_Expression_Test_Constant) {
            throw new \RuntimeException(sprintf('$node must be an instanceof of \Twig_Node_Expression_Test_Constant, but got "%s".', get_class($node)));
        }

        $compiler->subcompile(new \Twig_Node_Expression_Test($node->getNode('node'), $node->getAttribute('name'), $node->getNode('arguments'), $node->getLine()));
    }
}


text:
<?php
/*
  TDatabase: TFireBirdDB
  Rutinas para manipulación de bases de datos a través de Firebird
  Autor: Andres Melguizo Velez
  Created: 20050826
  Modified: 20050827
*/

// TFireBirdDB
class TDataBase {

  //var $bDebug = false;
  var $id = "FIREBIRD";
  var $conn = null;
  var $rs = null;
  var $rows = array(); // will store an array for each recordset
  var $currow = array(); // will store a current record for each recordset
  var $szquery = "";
  var $szUserName = "";
  var $szPassword = "";
  var $szServerName = "";
  var $iCurrentRecord = -1;

  function __construct($szDbName, $szUserName, $szPassword, $szServerName = 'localhost') {
    $this->szDbName = $szDbName;
    $this->szUserName = $szUserName;
    $this->szPassword = $szPassword;
    $this->szServerName = $szServerName;
  }

  function __destruct() {
    $this->closeDatabase();
  }

  // Open the database
  function openDatabase() {
    $this->conn = null;
    $this->rs = null;
    $this->szquery = "";
    $host = (($this->szServerName != "") ? ($this->szServerName . ":") : "") . $this->szDbName;
    return(($this->conn = ibase_connect($host, $this->szUserName, $this->szPassword, 'ISO8859_1')) !== false);
  }

  // Close the database
  function closeDatabase() {
    if($this->conn == null)
       return(true);
    // close the recordset
    //$this->closeRecordset($this->rs);
    // close the connection
    $iStatus = (ibase_close($this->conn) !== false);
    $this->conn = null;
    return($iStatus);
  }

  // Open a recordset
  function openRecordset($szSqlCmd) {
    //if($this->bDebug)
    //  echo "openRecordset(\"$szSqlCmd\");
";
    return($this->execute($szSqlCmd));
  }

  //  Close a recordset
  function closeRecordset($recordSet) {
    $this->szQuery = "";
    if($recordSet == null)
      return(true);
    $iStatus = (ibase_free_result($recordSet) !== false);
    unset($this->rows[$recordSet]);
    unset($this->currow[$recordSet]);
    $recordSet = null;
    return($iStatus);
  }

  // Execute a Sql Command
  function execute($szSqlCmd) {
    //if($this->bDebug)
    //  echo "execute(\"$szSqlCmd\");
";
    $this->szQuery = $szSqlCmd;
    $this->rs = ibase_query($this->conn, $this->szQuery) or die("execute error: = " . $szSqlCmd . "
Check SQL validity and check if database is opened!");
    // I don't like this, but I have no chioce by now
    $records = array();
    while($data = ibase_fetch_object($this->rs, IBASE_TEXT)) {
      $row = array();
      for($iField = 0; $iField < ibase_num_fields($this->rs); $iField++) {
        $fi = ibase_field_info($this->rs, $iField);
        // take data
        $dp = $data->$fi[0];
        // change literal characters
        $dp = str_replace("\\r", "\r", $dp);
        $dp = str_replace("\\n", "\n", $dp);
        $dp = str_replace('\"', '"', $dp);
        // save data
        $row[$iField] = $dp;
        $row[$fi["name"]] = $dp;
      }
      $records[] = $row;
    }
    $this->rows[$this->rs] = $records;
    $this->currow[$this->rs] = -1;
    return($this->rs);
  }

  // Move to start: get ready for movenext() but it doesn't contain a valid current row.
  function rewind($recordSet) {
    $this->currow[$recordSet] = -1;
    return(true);
  }

  // Move to first row
  function movefirst($recordSet) {
    if(!$this->isEmptyRecordset($recordSet)) {
      $this->currow[$recordSet] = 0;
      return(true);
    }
    return(false);
 }

  // Move to next row
  function movenext($recordSet) {
    if(!$this->isEmptyRecordset($recordSet) && (($this->currow[$recordSet] + 1) < $this->recordCount($recordSet))) {
      $this->currow[$recordSet]++;
      return(true);
    }
    return(false);
  }

  // Move to last row
  function movelast($recordSet) {
    if(!$this->isEmptyRecordset($recordSet)) {
      $this->currow[$recordSet] = $this->recordCount($recordSet) - 1;
      return(true);
    }
    return(false);
  }

  // Get the value of a field in the current row
  function getvalue($recordSet, $szFieldName) {
    $records = $this->rows[$recordSet];
    $row = $records[$this->currow[$recordSet]];
    return($row[strtoupper($szFieldName)]);
  }

  // Get the number of records in a result set
  function recordCount($recordSet) {
    return(count($this->rows[$recordSet]));
  }

  // Return true if the current recordset has no elements
  function isEmptyRecordset($recordSet) {
    return(!($this->recordCount($recordSet) > 0));
  }

  // Return all the recordset content as an array
  function recordsetAsArray($recordSet) {
    return($this->rows[$recordSet]);
  }

}

?>


text:
/*
 * Do not modify this file. This file is generated from the iam-2010-05-08.normal.json service model.
 */
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;

using Amazon.Runtime;
using Amazon.Runtime.Internal;

namespace Amazon.IdentityManagement.Model
{
    ///
    /// Container for the parameters to the ListAccountAliases operation.
    /// Lists the account aliases associated with the account. For information about using
    /// an AWS account alias, see Using
    /// an Alias for Your AWS Account ID in the Using IAM guide.
    ///
    ///
    /// <para>
    ///  You can paginate the results using the MaxItems and Marker
    /// parameters.
    /// </para>
    ///
    public partial class ListAccountAliasesRequest : AmazonIdentityManagementServiceRequest
    {
        private string _marker;
        private int? _maxItems;

        ///
        /// Empty constructor used to set  properties independently even when a simple constructor is available
        ///
        public ListAccountAliasesRequest() { }

        ///
        /// Gets and sets the property Marker.
        /// <para>
        /// Use this parameter only when paginating results and only after you receive a response
        /// indicating that the results are truncated. Set it to the value of the Marker
        /// element in the response you received to inform the next call about where to start.
        /// </para>
        ///
        public string Marker
        {
            get { return this._marker; }
            set { this._marker = value; }
        }

        // Check to see if Marker property is set
        internal bool IsSetMarker()
        {
            return this._marker != null;
        }

        ///
        /// Gets and sets the property MaxItems.
        /// <para>
        /// Use this only when paginating results to indicate the maximum number of items you
        /// want in the response. If there are additional items beyond the maximum you specify,
        /// the IsTruncated response element is true.
        /// </para>
        ///
        /// <para>
        /// This parameter is optional. If you do not include it, it defaults to 100.
        /// </para>
        ///
        public int MaxItems
        {
            get { return this._maxItems.GetValueOrDefault(); }
            set { this._maxItems = value; }
        }

        // Check to see if MaxItems property is set
        internal bool IsSetMaxItems()
        {
            return this._maxItems.HasValue;
        }

    }
}


text:
package cz.afrosoft.whattoeat.cookbook.cookbook.logic.service.impl;

import cz.afrosoft.whattoeat.cookbook.cookbook.logic.model.AuthorRef;
import org.apache.commons.lang3.Validate;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;

/**
 * Immutable implementation of {@link AuthorRef} used to represent related cookbooks in other entities.
 *
 * @author Tomas Rejent
 */
final class AuthorRefImpl implements AuthorRef {

    private final Integer id;
    private final String name;

    AuthorRefImpl(final Integer id, final String name) {
        Validate.notNull(id);
        Validate.notNull(name);

        this.id = id;
        this.name = name;
    }

    @Override
    public Integer getId() {
        return id;
    }

    @Override
    public String getName() {
        return name;
    }

    @Override
    public int compareTo(final AuthorRef otherAuthor) {
        return AuthorComparator.INSTANCE.compare(this, otherAuthor);
    }

    @Override
    public boolean equals(final Object o) {
        if (this == o) {
            return true;
        }

        if (o == null || getClass() != o.getClass()) {
            return false;
        }

        AuthorRefImpl authorRef = (AuthorRefImpl) o;

        return new EqualsBuilder()
                .append(id, authorRef.id)
                .isEquals();
    }

    @Override
    public int hashCode() {
        return new HashCodeBuilder(17, 37)
                .append(id)
                .toHashCode();
    }

    @Override
    public String toString() {
        return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE)
                .append("id", id)
                .append("name", name)
                .toString();
    }
}


text:
/**
 *
 * @author Audrey
 *
 */
package fr.lithie.matchup.entities;

import java.util.ArrayList;

public class Company extends User {
	private String siretNumber;
	private String website;

	private ArrayList<Job> jobs;

	/**
	 * @return the siretNumber
	 */
	public String getSiretNumber() {
		return siretNumber;
	}

	/**
	 * @param siretNumber
	 *            the siretNumber to set. 14 numbers must be present to be validate
	 * @return
	 */
	public boolean setSiretNumber(String siretNumber) {
		boolean result;
		if (siretNumber.length() == 14) {
			this.siretNumber = siretNumber;
			result = true;
		} else {
			result = false;
		}
		return result;
	}

	/**
	 * @return the website
	 */
	public String getWebsite() {
		return website;
	}

	/**
	 * @param website
	 *            the website to set
	 */
	public void setWebsite(String website) {
		this.website = website;
	}

	/**
	 * @return the jobs
	 */
	public ArrayList<Job> getJobs() {
		return jobs;
	}

	/**
	 * @param jobs
	 *            the jobs to set
	 */
	public void setJobs(ArrayList<Job> jobs) {
		this.jobs = jobs;
	}

	/**
	 *
	 */
	public Company() {
		super(Role.COMPANY);
		// TODO Auto-generated constructor stub
	}

}


text:
package disk

import (
	"io/ioutil"
	"net/url"
	"os"
	"path"

	"github.com/rs/zerolog/log"
)

// Disk client
type Disk struct {
	Host string
	Path string
}

// NewEngine struct
func NewEngine(host, path string) *Disk {
	return &Disk{
		Host: host,
		Path: path,
	}
}

// UploadFile to s3 server
func (d *Disk) UploadFile(bucketName, fileName string, content []byte) error {
	return ioutil.WriteFile(d.FilePath(bucketName, fileName), content, os.FileMode(0644))
}

// CreateBucket create bucket
func (d *Disk) CreateBucket(bucketName, region string) error {
	storage := path.Join(d.Path, bucketName)
	if err := os.MkdirAll(storage, os.ModePerm); err != nil {
		return nil
	}
	log.Info().Msgf("Successfully created disk path: %s", storage)

	return nil
}

// FilePath for store path + file name
func (d *Disk) FilePath(bucketName, fileName string) string {
	return path.Join(
		d.Path,
		bucketName,
		fileName,
	)
}

// DeleteFile delete file
func (d *Disk) DeleteFile(bucketName, fileName string) error {
	return os.Remove(d.FilePath(bucketName, fileName))
}

// GetFile for storage host + bucket + filename
func (d *Disk) GetFile(bucketName, fileName string) string {
	if d.Host != "" {
		if u, err := url.Parse(d.Host); err == nil {
			u.Path = path.Join(u.Path, d.Path, bucketName, fileName)
			return u.String()
		}
	}
	return path.Join(d.Path, bucketName, fileName)
}


text:
require 'nokogiri'

require 'caracal/core/models/list_style_model'
require 'caracal/core/models/list_model'
require 'caracal/renderers/xml_renderer'

module Caracal
  module Renderers
    class NumberingRenderer < XmlRenderer

      #-------------------------------------------------------------
      # Public Methods
      #-------------------------------------------------------------

      # This method produces the xml required for the `word/numbering.xml`
      # sub-document.
      #
      def to_xml
        builder = ::Nokogiri::XML::Builder.with(declaration_xml) do |xml|
          xml['w'].numbering root_options do

            # add abstract definitions
            document.toplevel_lists.each_with_index do |model, i|
              xml['w'].abstractNum({ 'w:abstractNumId' => i + 1 }) do
                xml['w'].multiLevelType({ 'w:val' => 'hybridMultilevel' })
                model.level_map.each do |(level, type)|
                  if s = document.find_list_style(type, level)
                    xml['w'].lvl({ 'w:ilvl' => s.style_level }) do
                      xml['w'].start({ 'w:val' => s.style_start })
                      xml['w'].numFmt({ 'w:val' => s.style_format })
                      xml['w'].lvlRestart({ 'w:val' => s.style_restart })
                      xml['w'].lvlText({ 'w:val' => s.style_value })
                      xml['w'].lvlJc({ 'w:val' => s.style_align })
                      xml['w'].pPr do
                        xml['w'].ind({ 'w:left' => s.style_left, 'w:firstLine' => s.style_indent })
                      end
                      xml['w'].rPr do
                        xml['w'].u({ 'w:val' => 'none' })
                      end
                    end
                  end
                end
              end
            end

            # bind individual tables to abstract definitions
            document.toplevel_lists.each_with_index do |model, i|
              xml['w'].num({ 'w:numId' => i + 1 }) do
                xml['w'].abstractNumId({ 'w:val' => i + 1 })
              end
            end
          end

        end
        builder.to_xml(save_options)
      end

      #-------------------------------------------------------------
      # Private Methods
      #-------------------------------------------------------------
      private

      def root_options
        {
          'xmlns:mc'  => 'http://schemas.openxmlformats.org/markup-compatibility/2006',
          'xmlns:o'   => 'urn:schemas-microsoft-com:office:office',
          'xmlns:r'   => 'http://schemas.openxmlformats.org/officeDocument/2006/relationships',
          'xmlns:m'   => 'http://schemas.openxmlformats.org/officeDocument/2006/math',
          'xmlns:v'   => 'urn:schemas-microsoft-com:vml',
          'xmlns:wp'  => 'http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing',
          'xmlns:w10' => 'urn:schemas-microsoft-com:office:word',
          'xmlns:w'   => 'http://schemas.openxmlformats.org/wordprocessingml/2006/main',
          'xmlns:wne' => 'http://schemas.microsoft.com/office/word/2006/wordml',
          'xmlns:sl'  => 'http://schemas.openxmlformats.org/schemaLibrary/2006/main',
          'xmlns:a'   => 'http://schemas.openxmlformats.org/drawingml/2006/main',
          'xmlns:pic' => 'http://schemas.openxmlformats.org/drawingml/2006/picture',
          'xmlns:c'   => 'http://schemas.openxmlformats.org/drawingml/2006/chart',
          'xmlns:lc'  => 'http://schemas.openxmlformats.org/drawingml/2006/lockedCanvas',
          'xmlns:dgm' => 'http://schemas.openxmlformats.org/drawingml/2006/diagram'
        }
      end

    end
  end
end


text:
from threading import Lock
from .loader import *
from .args import *
from .userdata import *
from .exceptions import *
from .module import *
from .context import *
from .settings import *
from .running import runningservers
from .parser import *
from .hooks import *

threads = True
run = True
restartfromcrash = True

from lib import utils, parser
[reload(x) for x in [utils, parser]]

def make_server(module, kind, name, shared, options):
    global currentplugin
    if kind not in servers:
        loadnamedmodule(module)
    if kind not in servers:
        raise IndexError("%s is not a valid server type!" % kind)
    return servers[kind](name, shared, options)

def load_server(*args):
    server = make_server(*args)
    runningservers.append(server)

class Server(LoaderBase, ParserBase, HookBase):

    """The Server Plugin."""

    """Override with plugins that are required to run the server."""
    requiredplugins = []

    """Default Options."""
    options = {
        'charlimit': 0,
    }

    """Optionally loaded plugins."""
    autoload = []

    dautoload = [
        "misc",
        "internet",
        "games",
    ]

    Settings = Settings

    def __init__(self, name, shared, options):
        self.name = name
        self.shared = shared
        self.hooks = {}
        self.globalaliases = {}
        self.runlock = Lock()
        self.timers = {}
        self.otimers = []
        self.options.update(options)
        self.settings = self.Settings(self)
        self.build_settings()
        self.modules = {}
        self.plugins = {}
        self.protected = []
        self.righttypes = {}
        self.registry = {}
        self.pluginpaths = []
        for k in ["core",
                  self.index] + self.requiredplugins:
                self.loadplugin(k)
                self.protected.append(k)
                for x in newmodules:
                    self.protected.append(k.split('/')[0] + '/%s' % x)
        self.build_lists()
        for k in self.dautoload + self.autoload + self.settings.get(
                "server.autoload"):
                self.loadplugin(k, auto=True)
        self.build_lists()
        self.addhook("server_ready", "sinit", self.ready)
        self.dohook("server_ready")

    def addrights(self, d):
        """Add <d> to the rights hierarchy."""
        self.righttypes.update(d)

    def opt(self, n):
        """Get config.py value <n>."""
        if n not in self.options and n in Server.options:
            return Server.options[n]
        return self.options[n]

    def log(self, category, text):
        """Log <text> under <category>."""
        print(("%s %s: %s" % (self.name, category, text.strip())))
        self.dohook("log", "bot", category, text.strip())

    def build_settings(self):
        """Ready to build settings."""
        pass

    def build_lists(self):
        """Recreate the command and settings lists."""
        self.commands = {}
        self.numcommands = {}
        for m in list(self.modules.values()):
            for k, v in list(m.commands.items()):
                self.commands[(m.plugin, m.index, k)] = (m, v)
                if k not in self.numcommands:
                    self.numcommands[k] = []
                self.numcommands[k].append(m.index)
        self.commands = sorted(list(self.commands.items()),
                               key=lambda x: -len(x[0][2].split()))
        self.settings.user = []
        self.settings.defaults = {}
        self.settings.tree = {}
        self.dohook("core_prepare_settings")
        for m in list(self.modules.values()):
            for k, v in m.serversettings:
                self.settings.add(k, v)

    def checkbuild(self):
        if self.build:
            self.build = False
            self.build_lists()

    def corerun(self):
        self.checkbuild()
        try:
            self.run()
        except Exception as e:
            import traceback
            traceback.print_exc()
            global run
            run = False
            if restartfromcrash:
                raise e

    def parsecommand(self, context, text, v, argtext):
        parsedargs = self.makeargdict(argtext, context, v,
            quote=v[1]['quote'])
        args = Args(parsedargs)
        return v[1]['function'](context, args)

    def getrights(self, *args):
        """Set by modules to get rights."""
        pass

    def modulesetup(self, m):
        """Modify and return <m>, to add attributes to the module class."""
        return m

    def idstring(self, context):
        """Return the rights idstring from <context>.
        Implemented by modules."""
        pass

    def shutdown(self):
        """Called on bot restart."""
        pass

    def commandlist(self):
        """List of commands and names."""
        commands = []
        for k, v in self.commands:
            for splitc in [
                    [v[0].plugin] + [v[0].index] + v[1]['name'].split(),
                    [v[0].index] + v[1]['name'].split(),
                    v[1]['name'].split()]:
                        commands.append((splitc, v))
        return commands

    def runcommand(self, context, text):
        """Run <text> as <context>."""
        commands = self.commandlist()
        split = text.split()
        commands.sort(key=lambda x: -len(x[0]))
        for splitc, v in commands:
            if splitc == split[:len(splitc)]:
                if len(splitc) == 1:
                    if len(self.numcommands[splitc[0]]) > 1:
                        return None, (
                            "Use <module> %s, %s" % (splitc[0], splitc[0]) +
                            " is provided by multiple modules: %s" % (
                                ', '.join(self.numcommands[splitc[0]])
                            ))
                argtext = ' '.join(split[len(splitc):])
                try:
                    context.exceptcancommand(v[0], v[1])
                    return self.parsecommand(context,
                                             text, v, argtext), None
                except ParserBadCommand as e:
                    return None, e
                except NoPerms as e:
                    if not str(e):
                        return None, None
                    return None, e
                except NoArg as e:
                    return None, "%s, Usage: %s %s" % (e,
                                                       ' '.join(splitc),
                                                       self.gethelp(v[1])[0])
                except Exception as e:
                    import traceback
                    traceback.print_exc()
                    return None, "Internal Error: %s" % type(e).__name__
        responses = []
        try:
            self.dohook('command', context, text, responses, False)
        except ParserBadCommand as e:
            return None, e
        except Exception as e:
            import traceback
            traceback.print_exc()
            return None, "Internal Error: %s" % type(e).__name__
        for r in responses:
            if r[0] is not None:
                return r[0], None
            elif r[1] is not None:
                return None, r[1]
            else:
                continue

        return None, self.settings.get('messages.notfound')


text:
var expect = require("chai").expect;
var React = require("react/addons");
var TestUtils = React.addons.TestUtils;

var config = require("../js/config/config");
var AppVersionsActions = require("../js/actions/AppVersionsActions");
var AppVersionsEvents = require("../js/events/AppVersionsEvents");
var AppVersionsStore = require("../js/stores/AppVersionsStore");
var AppVersionComponent = require("../js/components/AppVersionComponent");
var AppVersionListComponent =
  require("../js/components/AppVersionListComponent");

var expectAsync = require("./helpers/expectAsync");
var HttpServer = require("./helpers/HttpServer").HttpServer;

var server = new HttpServer(config.localTestserverURI);
config.apiURL = "http://" + server.address + ":" + server.port + "/";

describe("AppVersions", function () {

  beforeEach(function (done) {
    this.server = server
    .setup({
      "versions": [
        "version-timestamp-1",
        "version-timestamp-2"
      ]
    }, 200)
    .start(function () {
      AppVersionsStore.once(AppVersionsEvents.CHANGE, function () {
        done();
      });
      AppVersionsActions.requestAppVersions("/app-1");
    });
  });

  afterEach(function (done) {
    this.server.stop(done);
  });

  describe("on app versions request", function () {

    it("updates the AppVersionsStore on success", function (done) {
      AppVersionsStore.once(AppVersionsEvents.CHANGE, function () {
        expectAsync(function () {
          expect(AppVersionsStore.availableAppVersions).to.have.length(2);
          expect(AppVersionsStore.availableAppVersions[0])
            .to.equal("version-timestamp-1");
        }, done);
      });

      AppVersionsActions.requestAppVersions("/app-1");
    });

    it("matches the current app id", function (done) {
      AppVersionsStore.once(AppVersionsEvents.CHANGE, function () {
        expectAsync(function () {
          expect(AppVersionsStore.currentAppId).to.equal("/app-1");
        }, done);
      });

      AppVersionsActions.requestAppVersions("/app-1");
    });

    it("handles failure gracefully", function (done) {
      this.server.setup({message: "Guru Meditation"}, 404);

      AppVersionsStore.once(AppVersionsEvents.REQUEST_VERSION_TIMESTAMPS_ERROR,
          function (error) {
        expectAsync(function () {
          expect(error.message).to.equal("Guru Meditation");
        }, done);
      });

      AppVersionsActions.requestAppVersions("/non-existing-app");
    });

    it("emits requesters appId", function (done) {
      AppVersionsStore.once(AppVersionsEvents.CHANGE, function (appId) {
        expectAsync(function () {
          expect(appId).to.equal("/app-1");
        }, done);
      });

      AppVersionsActions.requestAppVersions("/app-1");
    });

    it("emits requesters appId on error", function (done) {
      this.server.setup({message: "Guru Meditation"}, 404);

      AppVersionsStore.once(AppVersionsEvents.REQUEST_VERSION_TIMESTAMPS_ERROR,
          function (error, appId) {
        expectAsync(function () {
          expect(appId).to.equal("/app-1");
        }, done);
      });

      AppVersionsActions.requestAppVersions("/app-1");
    });

  });

  describe("on single app version request", function () {

    it("updates the AppVersionsStore on success", function (done) {
      this.server.setup({
        "id": "/app-1",
        "version": "version-timestamp-1"
      }, 200);

      AppVersionsStore.once(AppVersionsEvents.CHANGE, function () {
        expectAsync(function () {
          expect(AppVersionsStore.appVersions["version-timestamp-1"].id)
            .to.equal("/app-1");
          expect(AppVersionsStore.appVersions["version-timestamp-1"].version)
            .to.equal("version-timestamp-1");
        }, done);
      });

      AppVersionsActions.requestAppVersion("/app-1", "version-timestamp-1");
    });

    it("matches the current app id", function (done) {
      AppVersionsStore.once(AppVersionsEvents.CHANGE, function () {
        expectAsync(function () {
          expect(AppVersionsStore.currentAppId).to.equal("/app-1");
        }, done);
      });

      AppVersionsActions.requestAppVersion("/app-1", "version-timestamp-1");
    });

    it("handles failure gracefully", function (done) {
      this.server.setup({message: "Guru Meditation"}, 404);

      AppVersionsStore.once(AppVersionsEvents.REQUEST_ONE_ERROR,
          function (error) {
        expectAsync(function () {
          expect(error.message).to.equal("Guru Meditation");
        }, done);
      });

      AppVersionsActions.requestAppVersion("/app-1", "non-existing-version");
    });

    it("emits requesters version timestamp", function (done) {
      AppVersionsStore.once(AppVersionsEvents.CHANGE,
          function (versionTimestamp) {
        expectAsync(function () {
          expect(versionTimestamp).to.equal("version-timestamp-1");
        }, done);
      });

      AppVersionsActions.requestAppVersion("/app-1", "version-timestamp-1");
    });

    it("emits requesters version timestamp on error", function (done) {
      this.server.setup({message: "Guru Meditation"}, 404);

      AppVersionsStore.once(AppVersionsEvents.REQUEST_ONE_ERROR,
          function (error, versionTimestamp) {
        expectAsync(function () {
          expect(versionTimestamp).to.equal("version-timestamp-1");
        }, done);
      });

      AppVersionsActions.requestAppVersion("/app-1", "version-timestamp-1");
    });

  });

});

describe("App Version List component", function () {

  beforeEach(function () {
    AppVersionsStore.currentAppId = "/app-test";
    AppVersionsStore.availableAppVersions = [
      "2015-06-29T13:54:01.577Z",
      "2015-06-29T13:02:29.615Z",
      "2015-06-29T13:02:19.363Z"
    ];

    this.renderer = TestUtils.createRenderer();

    this.renderer.render(<AppVersionListComponent
      appId={"/app-test"} />);

    this.component = this.renderer.getRenderOutput();
  });

  afterEach(function () {
    this.renderer.unmount();
  });

  it("has correct AppVersionListItemComponents", function () {
    var items =
      this.component.props.children[2].props.children[1].props.children[2];

    // First version is sliced out as current version,
    // so that are only 2 versions here
    expect(items.length).to.equal(2);
    expect(items[0].key).to.equal("2015-06-29T13:02:29.615Z");
    expect(items[1].key).to.equal("2015-06-29T13:02:19.363Z");
  });

});

describe("App Version component", function () {

  beforeEach(function () {
    this.model = {
      "id": "/sleep10",
      "cmd": "sleep 10",
      "args": null,
      "user": "testuser",
      "env": {},
      "instances": 14,
      "cpus": 0.1,
      "mem": 16.0,
      "disk": 0.0,
      "executor": "",
      "constraints": [],
      "uris": [],
      "storeUrls": [],
      "ports": [10000, 10001],
      "requirePorts": false,
      "backoffSeconds": 1,
      "backoffFactor": 1.15,
      "maxLaunchDelaySeconds": 3600,
      "container": null,
      "healthChecks": [{
        "path": "/",
        "protocol": "HTTP",
        "portIndex": 0,
        "gracePeriodSeconds": 30,
        "intervalSeconds": 30,
        "timeoutSeconds": 30,
        "maxConsecutiveFailures": 3,
        "ignoreHttp1xx": false
      }],
      "dependencies": [],
      "upgradeStrategy": {
        "minimumHealthCapacity": 1.0,
        "maximumOverCapacity": 1.0
      },
      "labels": {},
      "acceptedResourceRoles": [],
      "version": "2015-06-29T12:57:02.269Z"
    };

    this.renderer = TestUtils.createRenderer();
    this.renderer.render(<AppVersionComponent
      appVersion={this.model} />);
    this.component = this.renderer.getRenderOutput();
    this.table = this.component.props.children[2].props.children;
  });

  afterEach(function () {
    this.renderer.unmount();
  });

  it("has correct command", function () {
    expect(this.table[1].props.children[0]).to.equal("sleep 10");
  });

  it("has correct constraints", function () {
    expect(this.table[3].type.displayName).to.equal("UnspecifiedNodeComponent");
  });

  it("has correct dependencies", function () {
    expect(this.table[5].type.displayName).to.equal("UnspecifiedNodeComponent");
  });

  it("has correct labels", function () {
    expect(this.table[7].type.displayName).to.equal("UnspecifiedNodeComponent");
  });

  it("has correct accepted resource roles", function () {
    expect(this.table[9].type.displayName).to.equal("UnspecifiedNodeComponent");
  });

  it("has correct container", function () {
    expect(this.table[11].type.displayName).to.equal("UnspecifiedNodeComponent");
  });

  it("has correct cpus", function () {
    expect(this.table[13].props.children[0]).to.equal(0.1);
  });

  it("has correct environment", function () {
    expect(this.table[15].type.displayName).to.equal("UnspecifiedNodeComponent");
  });

  it("has correct executor", function () {
    expect(this.table[17].type.displayName).to.equal("UnspecifiedNodeComponent");
  });

  it("has correct health checks", function () {
    var healthChecks = this.table[19].props.children.props.children;
    expect(healthChecks).to.equal(
      JSON.stringify(this.model.healthChecks, null, 2)
    );
  });

  it("has correct number of instances", function () {
    expect(this.table[21].props.children[0]).to.equal(14);
  });

  it("has correct amount of memory", function () {
    expect(this.table[23].props.children[0]).to.equal(16.0);
    expect(this.table[23].props.children[2]).to.equal("MB");
  });

  it("has correct amount of disk space", function () {
    expect(this.table[25].props.children[0]).to.equal(0.0);
    expect(this.table[25].props.children[2]).to.equal("MB");
  });

  it("has correct ports", function () {
    expect(this.table[27].props.children).to.equal("10000, 10001");
  });

  it("has correct backoff factor", function () {
    expect(this.table[29].props.children[0]).to.equal(1.15);
  });

  it("has correct backoff", function () {
    expect(this.table[31].props.children[0]).to.equal(1);
    expect(this.table[31].props.children[2]).to.equal("seconds");
  });

  it("has correct max launch delay", function () {
    expect(this.table[33].props.children[0]).to.equal(3600);
    expect(this.table[33].props.children[2]).to.equal("seconds");
  });

  it("has correct URIs", function () {
    expect(this.table[35].type.displayName)
      .to.equal("UnspecifiedNodeComponent");
  });

  it("has correct User", function () {
    expect(this.table[37].props.children[0]).to.equal("testuser");
  });

  it("has correct version", function () {
    expect(this.table[39].props.children[0])
      .to.equal("2015-06-29T12:57:02.269Z");
  });

});


text:
package org.mamute.dao;

import java.math.BigInteger;
import java.util.List;

import javax.inject.Inject;

import org.hibernate.Query;
import org.hibernate.Session;
import org.mamute.dao.WithUserPaginatedDAO.OrderType;
import org.mamute.dao.WithUserPaginatedDAO.UserRole;
import org.mamute.model.Answer;
import org.mamute.model.User;

@SuppressWarnings("unchecked")
public class AnswerDAO implements PaginatableDAO{

	private Session session;
	private WithUserPaginatedDAO<Answer> withAuthor;

	@Deprecated
	public AnswerDAO() {}

	@Inject
	public AnswerDAO(Session session, InvisibleForUsersRule invisible) {
		this.session = session;
		withAuthor = new WithUserPaginatedDAO<Answer>(session, Answer.class, UserRole.AUTHOR, invisible);
	}

	public Answer getById(Long id) {
		return (Answer) session.load(Answer.class, id);
	}

	public void save(Answer answer) {
		this.session.save(answer);
	}

	public List<Answer> ofUserPaginatedBy(User user, OrderType orderByWhat, Integer page) {
		return withAuthor.by(user, orderByWhat, page);
	}

	public Long countWithAuthor(User user) {
		return withAuthor.count(user);
	}

	public Long numberOfPagesTo(User user) {
		return withAuthor.numberOfPagesTo(user);
	}

	public Answer fromCommentId (Long id) {
		String sql = "SELECT Answer_id FROM Answer_Comments " +
				"WHERE comments_id = :id ";
		Query query = session.createSQLQuery(sql);
		List<BigInteger> idList = query.setParameter("id", id).list();
		Long answerId = null;
		if (idList.size() > 0) {
			answerId = idList.get(0).longValue();
			return getById(answerId);
		}
		return null;
	}

}


text:
package org.apache.kafka.common.config.provider;

import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;

public class MockFileConfigProvider extends FileConfigProvider {

    private static final Map<String, MockFileConfigProvider> INSTANCES = Collections.synchronizedMap(new HashMap<>());
    private String id;
    private boolean closed = false;

    public void configure(Map<String, ?> configs) {
        Object id = configs.get("testId");
        if (id == null) {
            throw new RuntimeException(getClass().getName() + " missing 'testId' config");
        }
        if (this.id != null) {
            throw new RuntimeException(getClass().getName() + " instance was configured twice");
        }
        this.id = id.toString();
        INSTANCES.put(id.toString(), this);
    }

    @Override
    protected Reader reader(String path) throws IOException {
        return new StringReader("key=testKey\npassword=randomPassword");
    }

    @Override
    public synchronized void close() {
        closed = true;
    }

    public static void assertClosed(String id) {
        MockFileConfigProvider instance = INSTANCES.remove(id);
        assertNotNull(instance);
        synchronized (instance) {
            assertTrue(instance.closed);
        }
    }
}


text:
// ========================================================================
// Copyright (c) 2008-2009 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
// You may elect to redistribute this code under either of these licenses.
// ========================================================================

package org.eclipse.jetty.http;

public class HttpCookie
{
    private final String _name;
    private final String _value;
    private final String _comment;
    private final String _domain;
    private final int _maxAge;
    private final String _path;
    private final boolean _secure;
    private final int _version;
    private final boolean _httpOnly;

    /* ------------------------------------------------------------ */
    public HttpCookie(String name, String value)
    {
        super();
        _name = name;
        _value = value;
        _comment = null;
        _domain = null;
        _httpOnly = false;
        _maxAge = -1;
        _path = null;
        _secure = false;
        _version = 0;
    }

    /* ------------------------------------------------------------ */
    public HttpCookie(String name, String value, String domain, String path)
    {
        super();
        _name = name;
        _value = value;
        _comment = null;
        _domain = domain;
        _httpOnly = false;
        _maxAge = -1;
        _path = path;
        _secure = false;
        _version = 0;

    }

    /* ------------------------------------------------------------ */
    public HttpCookie(String name, String value, int maxAge)
    {
        super();
        _name = name;
        _value = value;
        _comment = null;
        _domain = null;
        _httpOnly = false;
        _maxAge = maxAge;
        _path = null;
        _secure = false;
        _version = 0;
    }

    /* ------------------------------------------------------------ */
    public HttpCookie(String name, String value, String domain, String path, int maxAge, boolean httpOnly, boolean secure)
    {
        super();
        _comment = null;
        _domain = domain;
        _httpOnly = httpOnly;
        _maxAge = maxAge;
        _name = name;
        _path = path;
        _secure = secure;
        _value = value;
        _version = 0;
    }

    /* ------------------------------------------------------------ */
    public HttpCookie(String name, String value, String domain, String path, int maxAge, boolean httpOnly, boolean secure, String comment, int version)
    {
        super();
        _comment = comment;
        _domain = domain;
        _httpOnly = httpOnly;
        _maxAge = maxAge;
        _name = name;
        _path = path;
        _secure = secure;
        _value = value;
        _version = version;
    }

    /* ------------------------------------------------------------ */
    /** Get the name.
     * @return the name
     */
    public String getName()
    {
        return _name;
    }

    /* ------------------------------------------------------------ */
    /** Get the value.
     * @return the value
     */
    public String getValue()
    {
        return _value;
    }

    /* ------------------------------------------------------------ */
    /** Get the comment.
     * @return the comment
     */
    public String getComment()
    {
        return _comment;
    }

    /* ------------------------------------------------------------ */
    /** Get the domain.
     * @return the domain
     */
    public String getDomain()
    {
        return _domain;
    }

    /* ------------------------------------------------------------ */
    /** Get the maxAge.
     * @return the maxAge
     */
    public int getMaxAge()
    {
        return _maxAge;
    }

    /* ------------------------------------------------------------ */
    /** Get the path.
     * @return the path
     */
    public String getPath()
    {
        return _path;
    }

    /* ------------------------------------------------------------ */
    /** Get the secure.
     * @return the secure
     */
    public boolean isSecure()
    {
        return _secure;
    }

    /* ------------------------------------------------------------ */
    /** Get the version.
     * @return the version
     */
    public int getVersion()
    {
        return _version;
    }

    /* ------------------------------------------------------------ */
    /** Get the isHttpOnly.
     * @return the isHttpOnly
     */
    public boolean isHttpOnly()
    {
        return _httpOnly;
    }

}


text:
package net.maisica.time.span;

import java.io.Serializable;
import java.time.Duration;
import java.time.LocalTime;
import java.time.format.DateTimeParseException;
import java.util.Objects;
import net.maisica.time.interval.TimeInterval;

public final class TimeSpan extends AbstractSpan<LocalTime, TimeSpan> implements TemporalSpan<LocalTime>, Serializable {

    public static final TimeSpan WHOLE_DAY = new TimeSpan(LocalTime.MIDNIGHT, Duration.ofDays(1L));

    public static TimeSpan parse(final CharSequence text) {
        Objects.requireNonNull(text, "text");
        for (int i = 0; i < text.length(); i++) {
            if (text.charAt(i) == '/') {
                final LocalTime start = LocalTime.parse(text.subSequence(0, i++).toString());
                final Duration duration = Duration.parse(text.subSequence(i, text.length()).toString());
                return of(start, duration);
            }
        }
        throw new DateTimeParseException("Span cannot be parsed, no forward slash found", text, 0);
    }

    public static TimeSpan wholeDay() {
        return WHOLE_DAY;
    }

    public static TimeSpan of(final Span<LocalTime, Duration> span) {
        Objects.requireNonNull(span, "span");
        if (span instanceof TimeSpan) {
            return (TimeSpan) span;
        }
        return of(span.getStart(), span.getDuration());
    }

    public static TimeSpan of(final LocalTime start, final Duration duration) {
        Objects.requireNonNull(start, "start");
        Objects.requireNonNull(duration, "duration");
        if (duration.isNegative()) {
            throw new IllegalArgumentException("duration is negative");
        }
        return new TimeSpan(start, duration);
    }

    private TimeSpan(final LocalTime start, final Duration duration) {
        super(start, duration);
    }

    @Override
    protected SpanFactory<LocalTime, Duration, TimeSpan> getFactory() {
        return TimeSpan::new;
    }

    @Override
    public TimeInterval toInterval() {
        return TimeInterval.of(getStart(), getDuration());
    }

}


text:
app.directive( 'settings', function () {
	return {
		restrict: 'E',
		templateUrl: 'html/settings.html',
		transclude: true
	};
});


text:
package org.jon.ivmark.graphit.recommendation.ws.resource;

import org.codehaus.jackson.annotate.JsonProperty;

public class Location {
    private final String rel;
    private final String href;

    public Location(@JsonProperty("rel") String rel,
                    @JsonProperty("href") String href) {
        this.rel = rel;
        this.href = href;
    }

    public String getRel() {
        return rel;
    }

    public String getHref() {
        return href;
    }
}


text:
int main(int argc, char** argv) {
  // Default environment.
  iree_hal_executable_environment_v0_t environment;
  iree_hal_executable_environment_initialize(iree_allocator_system(),
                                             &environment);

  // Query the library header at the requested version.
  // The query call in this example is going into the handwritten demo code
  // but could be targeted at generated files or runtime-loaded shared objects.
  union {
    const iree_hal_executable_library_header_t** header;
    const iree_hal_executable_library_v0_t* v0;
  } library;
  library.header = demo_executable_library_query(
      IREE_HAL_EXECUTABLE_LIBRARY_VERSION_LATEST, &environment);
  IREE_ASSERT_NE(library.header, NULL, "version may not have matched");
  const iree_hal_executable_library_header_t* header = *library.header;
  IREE_ASSERT_NE(header, NULL, "version may not have matched");
  IREE_ASSERT_LE(
      header->version, IREE_HAL_EXECUTABLE_LIBRARY_VERSION_LATEST,
      "expecting the library to have the same or older version as us");
  IREE_ASSERT(strcmp(header->name, "demo_library") == 0,
              "library name can be used to rendezvous in a registry");
  IREE_ASSERT_GT(library.v0->exports.count, 0,
                 "expected at least one entry point");

  // Push constants are an array of 4-byte values that are much more efficient
  // to specify (no buffer pointer indirection) and more efficient to access
  // (static struct offset address calculation, all fit in a few cache lines,
  // etc). They are limited in capacity, though, so only <=64(ish) are usable.
  dispatch_tile_a_push_constants_t push_constants;
  memset(&push_constants, 0, sizeof(push_constants));
  push_constants.f0 = 5.0f;

  // Setup the two buffer bindings the entry point is expecting.
  // They only need to remain valid for the duration of the invocation and all
  // memory accessed by the invocation will come from here.
  float arg0[4] = {1.0f, 2.0f, 3.0f, 4.0f};
  float ret0[4] = {0.0f, 0.0f, 0.0f, 0.0f};
  const float ret0_expected[4] = {6.0f, 7.0f, 8.0f, 9.0f};
  size_t binding_lengths[2] = {
      sizeof(arg0),
      sizeof(ret0),
  };
  void* binding_ptrs[2] = {
      arg0,
      ret0,
  };

  // Resolve the entry point by ordinal.
  const iree_hal_executable_dispatch_v0_t entry_fn_ptr =
      library.v0->exports.ptrs[0];

  // Dispatch each workgroup with the same state.
  const iree_hal_executable_dispatch_state_v0_t dispatch_state = {
      .workgroup_count_x = 4,
      .workgroup_count_y = 1,
      .workgroup_count_z = 1,
      .workgroup_size_x = 1,
      .workgroup_size_y = 1,
      .workgroup_size_z = 1,
      .max_concurrency = 1,
      .push_constant_count = IREE_ARRAYSIZE(push_constants.values),
      .push_constants = push_constants.values,
      .binding_count = IREE_ARRAYSIZE(binding_ptrs),
      .binding_ptrs = binding_ptrs,
      .binding_lengths = binding_lengths,
  };
  iree_hal_executable_workgroup_state_v0_t workgroup_state = {
      .processor_id = iree_cpu_query_processor_id(),
  };
  for (uint32_t z = 0; z < dispatch_state.workgroup_count_z; ++z) {
    workgroup_state.workgroup_id_z = z;
    for (uint32_t y = 0; y < dispatch_state.workgroup_count_y; ++y) {
      workgroup_state.workgroup_id_y = y;
      for (uint32_t x = 0; x < dispatch_state.workgroup_count_x; ++x) {
        workgroup_state.workgroup_id_x = x;
        // Invoke the workgroup (x, y, z).
        int ret = entry_fn_ptr(&environment, &dispatch_state, &workgroup_state);
        IREE_ASSERT_EQ(
            ret, 0,
            "if we have bounds checking enabled the executable will signal "
            "us of badness");
      }
    }
  }

  // Ensure it worked.
  bool all_match = true;
  for (size_t i = 0; i < IREE_ARRAYSIZE(ret0_expected); ++i) {
    IREE_ASSERT_EQ(ret0[i], ret0_expected[i], "math is hard");
    all_match = all_match && ret0[i] == ret0_expected[i];
  }
  return all_match ? 0 : 1;
}


text:
var Person = function(firstName, lastName, gender) {
	this.firstName = firstName;
	this.lastName = lastName;
	this.gender = gender;
	this.name = function() { // this is how you add a method
		return this.firstName + " " + this.lastName;
	}
}

var p1 = new Person("John", "Smith", "Male");
console.log( p1.firstName );
console.log( p1["lastName"] );
console.log( p1.name );

Person.prototype.print = function() { // this is a method of the prototype
	console.log( this.name() + " " + this.gender );
}

console.log(p1);
console.log(Person.prototype);
var proto1 = Object.getPrototypeOf(p1);
console.log(proto1);
console.log(Object.getPrototypeOf(proto1));
console.log(Object.getPrototypeOf(Person));

var p2 = new Person("Linda", "James", "Female");
console.log(p2);
var proto2 = Object.getPrototypeOf(p2);
console.log(proto2);

p1.print();
p2.print();
console.log( proto1.constructor );

var Employee = function(firstName, lastName, gender, title) {
	Person.call(this, firstName, lastName, gender);
	this.title = title;
};

Employee.prototype = new Person();
Employee.prototype.constructor = Employee;

Employee.prototype.print = function() {
	console.log( this.name() + " " + this.gender + " " + this.title );
}

var e1 = new Employee("XYZ", "ABC", "Male", "Manager");
console.log( Employee.prototype );
console.log( Object.getPrototypeOf(e1) );

// Print all the people and the employees
e1.print();
p1.print();
p2.print();

// COMMENT OUT THIS CODE OR YOU"LL GET UNEXPECTED RESULTS
// EXERCISE: Can you figure out what would happen otherwise ?
// Employee.prototype = Object.prototype;

// Check the instances and the prototypes
console.log(e1 instanceof Employee);
console.log(e1 instanceof Person);
console.log(e1 instanceof Object);

console.log(p1 instanceof Employee);
console.log(p1 instanceof Person);
console.log(p1 instanceof Object);

console.log(p2 instanceof Employee);
console.log(p2 instanceof Person);
console.log(p2 instanceof Object);

console.log( "firstName" in p1 );
console.log( "lastName" in p1 );
console.log( "title" in p1 );

console.log( "firstName" in e1 );
console.log( "lastName" in e1 );
console.log( "title" in e1 );

console.log( p1.hasOwnProperty("firstName") );
console.log( p1.hasOwnProperty("lastName") );
console.log( p1.hasOwnProperty("print") );
console.log( e1.hasOwnProperty("firstName") );
console.log( e1.hasOwnProperty("lastName") );
console.log( e1.hasOwnProperty("print") );


text:
"""The :program:`celery graph` command.

.. program:: celery graph
"""
from __future__ import absolute_import, unicode_literals

from operator import itemgetter

from celery.five import items, python_2_unicode_compatible
from celery.utils.graph import DependencyGraph, GraphFormatter

from .base import Command

__all__ = ('graph',)

class graph(Command):
    """The ``celery graph`` command."""

    args = """<TYPE> [arguments]
            .....  bootsteps [worker] [consumer]
            .....  workers   [enumerate]
    """

    def run(self, what=None, *args, **kwargs):
        map = {'bootsteps': self.bootsteps, 'workers': self.workers}
        if not what:
            raise self.UsageError('missing type')
        elif what not in map:
            raise self.Error('no graph {0} in {1}'.format(what, '|'.join(map)))
        return map[what](*args, **kwargs)

    def bootsteps(self, *args, **kwargs):
        worker = self.app.WorkController()
        include = {arg.lower() for arg in args or ['worker', 'consumer']}
        if 'worker' in include:
            worker_graph = worker.blueprint.graph
            if 'consumer' in include:
                worker.blueprint.connect_with(worker.consumer.blueprint)
        else:
            worker_graph = worker.consumer.blueprint.graph
        worker_graph.to_dot(self.stdout)

    def workers(self, *args, **kwargs):

        def simplearg(arg):
            return maybe_list(itemgetter(0, 2)(arg.partition(':')))

        def maybe_list(l, sep=','):
            return (l[0], l[1].split(sep) if sep in l[1] else l[1])

        args = dict(simplearg(arg) for arg in args)
        generic = 'generic' in args

        def generic_label(node):
            return '{0} ({1}://)'.format(type(node).__name__,
                                         node._label.split('://')[0])

        @python_2_unicode_compatible
        class Node(object):
            force_label = None
            scheme = {}

            def __init__(self, label, pos=None):
                self._label = label
                self.pos = pos

            def label(self):
                return self._label

            def __str__(self):
                return self.label()

        class Thread(Node):
            scheme = {
                'fillcolor': 'lightcyan4',
                'fontcolor': 'yellow',
                'shape': 'oval',
                'fontsize': 10,
                'width': 0.3,
                'color': 'black',
            }

            def __init__(self, label, **kwargs):
                self.real_label = label
                super(Thread, self).__init__(
                    label='thr-{0}'.format(next(tids)),
                    pos=0,
                )

        class Formatter(GraphFormatter):

            def label(self, obj):
                return obj and obj.label()

            def node(self, obj):
                scheme = dict(obj.scheme) if obj.pos else obj.scheme
                if isinstance(obj, Thread):
                    scheme['label'] = obj.real_label
                return self.draw_node(
                    obj, dict(self.node_scheme, **scheme),
                )

            def terminal_node(self, obj):
                return self.draw_node(
                    obj, dict(self.term_scheme, **obj.scheme),
                )

            def edge(self, a, b, **attrs):
                if isinstance(a, Thread):
                    attrs.update(arrowhead='none', arrowtail='tee')
                return self.draw_edge(a, b, self.edge_scheme, attrs)

        def subscript(n):
            S = {'0': '₀', '1': '₁', '2': '₂', '3': '₃', '4': '₄',
                 '5': '₅', '6': '₆', '7': '₇', '8': '₈', '9': '₉'}
            return ''.join([S[i] for i in str(n)])

        class Worker(Node):
            pass

        class Backend(Node):
            scheme = {
                'shape': 'folder',
                'width': 2,
                'height': 1,
                'color': 'black',
                'fillcolor': 'peachpuff3',
            }

            def label(self):
                return generic_label(self) if generic else self._label

        class Broker(Node):
            scheme = {
                'shape': 'circle',
                'fillcolor': 'cadetblue3',
                'color': 'cadetblue4',
                'height': 1,
            }

            def label(self):
                return generic_label(self) if generic else self._label

        from itertools import count
        tids = count(1)
        Wmax = int(args.get('wmax', 4) or 0)
        Tmax = int(args.get('tmax', 3) or 0)

        def maybe_abbr(l, name, max=Wmax):
            size = len(l)
            abbr = max and size > max
            if 'enumerate' in args:
                l = ['{0}{1}'.format(name, subscript(i + 1))
                     for i, obj in enumerate(l)]
            if abbr:
                l = l[0:max - 1] + [l[size - 1]]
                l[max - 2] = '{0}⎨…{1}⎬'.format(
                    name[0], subscript(size - (max - 1)))
            return l

        try:
            workers = args['nodes']
            threads = args.get('threads') or []
        except KeyError:
            replies = self.app.control.inspect().stats() or {}
            workers, threads = [], []
            for worker, reply in items(replies):
                workers.append(worker)
                threads.append(reply['pool']['max-concurrency'])

        wlen = len(workers)
        backend = args.get('backend', self.app.conf.result_backend)
        threads_for = {}
        workers = maybe_abbr(workers, 'Worker')
        if Wmax and wlen > Wmax:
            threads = threads[0:3] + [threads[-1]]
        for i, threads in enumerate(threads):
            threads_for[workers[i]] = maybe_abbr(
                list(range(int(threads))), 'P', Tmax,
            )

        broker = Broker(args.get(
            'broker', self.app.connection_for_read().as_uri()))
        backend = Backend(backend) if backend else None
        deps = DependencyGraph(formatter=Formatter())
        deps.add_arc(broker)
        if backend:
            deps.add_arc(backend)
        curworker = [0]
        for i, worker in enumerate(workers):
            worker = Worker(worker, pos=i)
            deps.add_arc(worker)
            deps.add_edge(worker, broker)
            if backend:
                deps.add_edge(worker, backend)
            threads = threads_for.get(worker._label)
            if threads:
                for thread in threads:
                    thread = Thread(thread)
                    deps.add_arc(thread)
                    deps.add_edge(thread, worker)

            curworker[0] += 1

        deps.to_dot(self.stdout)


text:
'use strict';

/**
 * selectObjectFromJson() --  get an object in a node internally.
 * The node is the javascript object tree to get an object out of.
 * selectorField is a " > " separated list of properties in node.
 *
 */
function selectObjectFromJson(node, selectorField) {
	var skipDescendants = 0; // number of descendents to skip
	var selectedValue = node;
	var higherValue = selectedValue;
	var selector  = selectorField.split(/ > /);
	var depth = (selector.length - skipDescendants);
	for (var index = 0; index < depth; index++) {
		higherValue = selectedValue;
		selectedValue = selectedValue[selector[index]];
		if (typeof selectedValue === 'undefined') {
			// not sure how we got here, but let's bail
			console.error("Error: I think we went down too far: "+selectorField+" is unavailable.");
			return true;
		}
	}
	return selectedValue;
}

module.exports = selectObjectFromJson;


text:
package com.netflix.conductor.sdk.example.shipment;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

import com.netflix.conductor.common.metadata.workflow.WorkflowDef;
import com.netflix.conductor.common.run.Workflow;
import com.netflix.conductor.sdk.workflow.def.ConductorWorkflow;
import com.netflix.conductor.sdk.workflow.def.WorkflowBuilder;
import com.netflix.conductor.sdk.workflow.def.tasks.*;
import com.netflix.conductor.sdk.workflow.executor.WorkflowExecutor;

public class ShipmentWorkflow {

    private final WorkflowExecutor executor;

    public ShipmentWorkflow(WorkflowExecutor executor) {
        this.executor = executor;
        this.executor.initWorkers(ShipmentWorkflow.class.getPackageName());
    }

    public ConductorWorkflow<Order> createOrderFlow() {
        WorkflowBuilder<Order> builder = new WorkflowBuilder<>(executor);
        builder.name("order_flow")
                .version(1)
                .ownerEmail("user@example.com")
                .timeoutPolicy(WorkflowDef.TimeoutPolicy.TIME_OUT_WF, 60) // 1 day max
                .description("Workflow to track shipment")
                .add(
                        new SimpleTask("calculate_tax_and_total", "calculate_tax_and_total")
                                .input("orderDetail", ConductorWorkflow.input.get("orderDetail")))
                .add(
                        new SimpleTask("charge_payment", "charge_payment")
                                .input(
                                        "billingId",
                                                ConductorWorkflow.input
                                                        .map("userDetails")
                                                        .get("billingId"),
                                        "billingType",
                                                ConductorWorkflow.input
                                                        .map("userDetails")
                                                        .get("billingType"),
                                        "amount", "${calculate_tax_and_total.output.total_amount}"))
                .add(
                        new Switch("shipping_label", "${workflow.input.orderDetail.shippingMethod}")
                                .switchCase(
                                        Order.ShippingMethod.GROUND.toString(),
                                        new SimpleTask(
                                                        "ground_shipping_label",
                                                        "ground_shipping_label")
                                                .input(
                                                        "name",
                                                                ConductorWorkflow.input
                                                                        .map("userDetails")
                                                                        .get("name"),
                                                        "address",
                                                                ConductorWorkflow.input
                                                                        .map("userDetails")
                                                                        .get("addressLine"),
                                                        "orderNo",
                                                                ConductorWorkflow.input
                                                                        .map("orderDetail")
                                                                        .get("orderNumber")))
                                .switchCase(
                                        Order.ShippingMethod.NEXT_DAY_AIR.toString(),
                                        new SimpleTask("air_shipping_label", "air_shipping_label")
                                                .input(
                                                        "name",
                                                                ConductorWorkflow.input
                                                                        .map("userDetails")
                                                                        .get("name"),
                                                        "address",
                                                                ConductorWorkflow.input
                                                                        .map("userDetails")
                                                                        .get("addressLine"),
                                                        "orderNo",
                                                                ConductorWorkflow.input
                                                                        .map("orderDetail")
                                                                        .get("orderNumber")))
                                .switchCase(
                                        Order.ShippingMethod.SAME_DAY.toString(),
                                        new SimpleTask(
                                                        "same_day_shipping_label",
                                                        "same_day_shipping_label")
                                                .input(
                                                        "name",
                                                                ConductorWorkflow.input
                                                                        .map("userDetails")
                                                                        .get("name"),
                                                        "address",
                                                                ConductorWorkflow.input
                                                                        .map("userDetails")
                                                                        .get("addressLine"),
                                                        "orderNo",
                                                                ConductorWorkflow.input
                                                                        .map("orderDetail")
                                                                        .get("orderNumber")))
                                .defaultCase(
                                        new Terminate(
                                                "unsupported_shipping_type",
                                                Workflow.WorkflowStatus.FAILED,
                                                "Unsupported Shipping Method")))
                .add(
                        new SimpleTask("send_email", "send_email")
                                .input(
                                        "name",
                                                ConductorWorkflow.input
                                                        .map("userDetails")
                                                        .get("name"),
                                        "email",
                                                ConductorWorkflow.input
                                                        .map("userDetails")
                                                        .get("email"),
                                        "orderNo",
                                                ConductorWorkflow.input
                                                        .map("orderDetail")
                                                        .get("orderNumber")));
        ConductorWorkflow<Order> conductorWorkflow = builder.build();
        conductorWorkflow.registerWorkflow(true, true);
        return conductorWorkflow;
    }

    public ConductorWorkflow<Shipment> createShipmentWorkflow() {

        WorkflowBuilder<Shipment> builder = new WorkflowBuilder<>(executor);

        SimpleTask getOrderDetails =
                new SimpleTask("get_order_details", "get_order_details")
                        .input("orderNo", ConductorWorkflow.input.get("orderNo"));

        SimpleTask getUserDetails =
                new SimpleTask("get_user_details", "get_user_details")
                        .input("userId", ConductorWorkflow.input.get("userId"));

        ConductorWorkflow<Shipment> conductorWorkflow =
                builder.name("shipment_workflow")
                        .version(1)
                        .ownerEmail("user@example.com")
                        .variables(new ShipmentState())
                        .timeoutPolicy(WorkflowDef.TimeoutPolicy.TIME_OUT_WF, 60) // 30 days
                        .description("Workflow to track shipment")
                        .add(
                                new ForkJoin(
                                        "get_in_parallel",
                                        new Task[] {getOrderDetails},
                                        new Task[] {getUserDetails}))

                        // For all the line items in the order, run in parallel:
                        // (calculate tax, charge payment, set state, prepare shipment, send
                        // shipment, set state)
                        .add(
                                new DynamicFork(
                                        "process_order",
                                        new SimpleTask("generateDynamicFork", "generateDynamicFork")
                                                .input(
                                                        "orderDetails",
                                                        getOrderDetails.taskOutput.get("result"))
                                                .input("userDetails", getUserDetails.taskOutput)))

                        // Update the workflow state with shipped = true
                        .add(new SetVariable("update_state").input("shipped", true))
                        .build();

        conductorWorkflow.registerWorkflow(true, true);

        return conductorWorkflow;
    }

    public static void main(String[] args) {

        String conductorServerURL =
                "http://localhost:8080/api/"; // Change this to your Conductor server
        WorkflowExecutor executor = new WorkflowExecutor(conductorServerURL);

        // Create the new shipment workflow
        ShipmentWorkflow shipmentWorkflow = new ShipmentWorkflow(executor);

        // Create two workflows

        // 1. Order flow that ships an individual order
        // 2. Shipment Workflow that tracks multiple orders in a shipment
        shipmentWorkflow.createOrderFlow();
        ConductorWorkflow<Shipment> workflow = shipmentWorkflow.createShipmentWorkflow();

        // Execute the workflow and wait for it to complete
        try {
            Shipment workflowInput = new Shipment("userA", "order123");

            // Execute returns a completable future.
            CompletableFuture<Workflow> executionFuture = workflow.execute(workflowInput);

            // Wait for a maximum of a minute for the workflow to complete.
            Workflow run = executionFuture.get(1, TimeUnit.MINUTES);

            System.out.println("Workflow Id: " + run);
            System.out.println("Workflow Status: " + run.getStatus());
            System.out.println("Workflow Output: " + run.getOutput());

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.exit(0);
        }

        System.out.println("Done");
    }
}


text:
require "rails_helper"

# TODO : test FR + EN

RSpec.describe "i18n" do
  Rails.application.eager_load!

  ::Dorsale::ApplicationRecord.descendants.each do |model|
    next unless model.to_s.start_with?("Dorsale")

    it "should i18n #{model} model name" do
      i18n = model.model_name.human(default: "")
      expect(i18n).to be_present
    end

    model.column_names.each do |column_name|
      next if column_name.end_with?("_type")
      next if column_name.end_with?("_bak")
      next if column_name.start_with?("old_")

      # user_id => user
      column_name = column_name[0..-4] if column_name.end_with?("_id")

      it "should i18n #{model}##{column_name}" do
        i18n = model.human_attribute_name(column_name, default: "")
        expect(i18n).to be_present
      end
    end
  end
end


text:
package httpstub

import (
	"bytes"
	"net/http"
	"net/http/httptest"
	"testing"
)

func TestIfWritesStubbedResponseProperly(t *testing.T) {
	expectedBody := []byte("test")
	response := StatusCode(http.StatusOK).
		Body(expectedBody).
		Header("X-Test", "Test")
	recorder := httptest.NewRecorder()
	response.write(recorder)

	if recorder.Code != http.StatusOK {
		t.Errorf("unexpected status code; got %d, want %d", recorder.Code, http.StatusOK)
	}
	if bytes.Compare(expectedBody, recorder.Body.Bytes()) != 0 {
		t.Errorf("unexpected body; got %s, want %s", recorder.Body.String(), expectedBody)
	}
	if recorder.HeaderMap.Get("X-Test") != "Test" {
		t.Error("expected header not found")
	}
}


text:
import argparse

from soilgenerate import data, core

def main():
	"""The main routine."""
	parser = argparse.ArgumentParser()

	parser.add_argument("--area", required=True, type=int, help="Area of land for planting (square feet)")

	parser.add_argument("--soil_texture", required=True, type=str, help="Soil texture of area as combinations of: Course, Medium, or Fine")
	soil_options = set(['course','med-course','med','med-fine','fine'])

	parser.add_argument("--hardiness", required=True, type=int, help="Minimum temperature hardiness of area (fahrenheit)")

	parser.add_argument("--percip_min", required=True, type=int, help="Minimum precipitation of area (inches)")

	parser.add_argument("--percip_max", required=True, type=int, help="Maximum precipitation of area (inches)")

	parser.add_argument("--cn_ratio", default='low-med-high', type=str, help="Filter for C:N Ratio in plants. Value 'low-med' excludes high ratio \
	plants; value 'low-med-high' includes all ratio plants. Low = 23:1, Med = 41:1, High = 91:1")
	ratio_options = set(['low-med','low-med-high'])

	parser.add_argument("--cn_target", default=30, type=int, help="Filter for target carbon amount in C:N Ratio")

	parser.add_argument("--animal_browse", default='low-med-high', type=str, help="Filter for animal browse palatability in plants. \
		value 'low' includes only low browse plants.; value 'low-med' excludes high browse plants; value 'low-med-high' includes all plants.")
	browse_options = set(['low','low-med','low-med-high'])

	parser.add_argument("--growth_rate", required=False, type=str, help="Filter for growth rate in plants. \
		value 'rapid' includes only low rapid plants.; value 'rapid-moderate' excludes slow plants. Growth rate is otherwise weighted in optimization")
	growth_options = set(['rapid','rapid-moderate'])

	parser.add_argument("--invasive", required=False, default=False, type=bool, help="Filter invasive plants")

	parser.add_argument("--full_shade", required=False, default=False, type=bool, help="Filter for only full shade plants")

	parser.add_argument("--full_sun", required=False, default=False, type=bool, help="Filter for only full sun, low height plants; eg: an open field. ")

	parser.add_argument("--max_height", required=False, type=float, help="Filter plants by maximum height")

	parser.add_argument("--known_supplier", required=False, default=False, type=bool, help="Filter plants for those with known supplier (Sheffield's Seeds)")

	parser.add_argument("--budget", required=False, default=False, type=int, help="Budget contraint in USD")

	args = vars(parser.parse_args())

	if args['soil_texture'] not in soil_options:
		raise ValueError('Soil type must be of either ' + str(soil_options))

	if args['cn_ratio'] not in ratio_options:
		raise ValueError('Ratio type must be of either ' + str(ratio_options))

	if args['animal_browse'] not in browse_options:
		raise ValueError('Animal browse type must be of either ' + str(animal_browse))

	filtered_data, filter_count = data.filter(args)

	try:
		objective, growth, seeds = core.optimize(filtered_data, filter_count, args)
		if seeds:
			core.print_result(growth, seeds)
		else:
			objective, variables = core.setup(filtered_data, filter_count, args)
			print('SoilGenerate Error: Problem infeasible with only {} plant species available for optimization. Try removing some data filters or changing CN Target.'.format(len(variables)))
	except Exception as e:
		if type(e).__name__ == "PulpSolverError":
			objective, variables = core.setup(filtered_data, filter_count, args)
			print('SoilGenerate Error: Problem infeasible with only {} plant species available for optimization. Try removing some data filters or changing CN Target.'.format(len(variables)))
		else:
			print(e)

if __name__ == "__main__":
	main()


text:
package com.leon.cool.lang.tree.compile.impl;

import com.leon.cool.lang.ast.AttrDef;
import com.leon.cool.lang.ast.ClassDef;
import com.leon.cool.lang.support.TreeSupport;
import com.leon.cool.lang.support.declaration.AttrDeclaration;
import com.leon.cool.lang.tree.compile.TreeScanner;

import static com.leon.cool.lang.support.ErrorSupport.error;
import static com.leon.cool.lang.support.ErrorSupport.errorPos;
import static com.leon.cool.lang.support.TypeSupport.isSelf;

public class AttrDefTreeScanner extends TreeScanner {
    private String className = null;

    public AttrDefTreeScanner(TreeSupport treeSupport) {
        super(treeSupport);
    }

    @Override
    public void applyClassDef(ClassDef classDef) {
        className = classDef.type.name;
        treeSupport.createAttrGraph(className);
        super.applyClassDef(classDef);
    }

    @Override
    public void applyAttrDef(AttrDef attrDef) {
        if (isSelf(attrDef.id)) {
            error("type.error.assign.self", errorPos(attrDef.id));
        }
        var attrDeclaration = new AttrDeclaration();
        attrDeclaration.id = attrDef.id.name;
        attrDeclaration.type = attrDef.type.name;
        attrDeclaration.expr = attrDef.expr;
        treeSupport.putToAttrGraph(className, attrDef.id.name, attrDeclaration);
        super.applyAttrDef(attrDef);
    }
}