text:
package main

import (
	"bufio"
	"errors"
	"flag"
	"fmt"
	"io/ioutil"
	"os"
	"path/filepath"
	"runtime"
	"strings"
	"syscall"

	"github.com/appc/spec/schema"
	"github.com/appc/spec/schema/types"
	"github.com/hashicorp/errwrap"

	"github.com/coreos/rkt/common"
	rktlog "github.com/coreos/rkt/pkg/log"
	"github.com/coreos/rkt/pkg/sys"
	"github.com/coreos/rkt/pkg/user"
	stage1common "github.com/coreos/rkt/stage1/common"
	stage1commontypes "github.com/coreos/rkt/stage1/common/types"
)

const (
	flavor = "fly"
)

type flyMount struct {
	HostPath         string
	TargetPrefixPath string
	RelTargetPath    string
	Fs               string
	Flags            uintptr
}

type volumeMountTuple struct {
	V types.Volume
	M schema.Mount
}

var (
	debug bool

	discardNetlist common.NetList
	discardBool    bool
	discardString  string

	log  *rktlog.Logger
	diag *rktlog.Logger
)

func getHostMounts() (map[string]struct{}, error) {
	hostMounts := map[string]struct{}{}

	mi, err := os.Open("/proc/self/mountinfo")
	if err != nil {
		return nil, err
	}
	defer mi.Close()

	sc := bufio.NewScanner(mi)
	for sc.Scan() {
		var (
			discard    string
			mountPoint string
		)

		_, err := fmt.Sscanf(sc.Text(),
			"%s %s %s %s %s",
			&discard, &discard, &discard, &discard, &mountPoint,
		)
		if err != nil {
			return nil, err
		}

		hostMounts[mountPoint] = struct{}{}
	}
	if sc.Err() != nil {
		return nil, errwrap.Wrap(errors.New("problem parsing mountinfo"), sc.Err())
	}
	return hostMounts, nil
}

func init() {
	flag.BoolVar(&debug, "debug", false, "Run in debug mode")

	// The following flags need to be supported by stage1 according to
	// https://github.com/coreos/rkt/blob/master/Documentation/devel/stage1-implementors-guide.md
	// TODO: either implement functionality or give not implemented warnings
	flag.Var(&discardNetlist, "net", "Setup networking")
	flag.BoolVar(&discardBool, "interactive", true, "The pod is interactive")
	flag.StringVar(&discardString, "mds-token", "", "MDS auth token")
	flag.StringVar(&discardString, "local-config", common.DefaultLocalConfigDir, "Local config path")
}

func evaluateMounts(rfs string, app string, p *stage1commontypes.Pod) ([]flyMount, error) {
	imApp := p.Images[app].App
	namedVolumeMounts := map[types.ACName]volumeMountTuple{}

	var manifestMPs []types.MountPoint
	if imApp != nil {
		manifestMPs = imApp.MountPoints
	}

	for _, m := range p.Manifest.Apps[0].Mounts {
		_, exists := namedVolumeMounts[m.Volume]
		if exists {
			return nil, fmt.Errorf("duplicate mount given: %q", m.Volume)
		}
		namedVolumeMounts[m.Volume] = volumeMountTuple{M: m}
		diag.Printf("adding %+v", namedVolumeMounts[m.Volume])
	}

	// Merge command-line Mounts with ImageManifest's MountPoints
	for _, mp := range manifestMPs {
		tuple, exists := namedVolumeMounts[mp.Name]
		switch {
		case exists && tuple.M.Path != mp.Path:
			return nil, fmt.Errorf("conflicting path information from mount and mountpoint %q", mp.Name)
		case !exists:
			namedVolumeMounts[mp.Name] = volumeMountTuple{M: schema.Mount{Volume: mp.Name, Path: mp.Path}}
			diag.Printf("adding %+v", namedVolumeMounts[mp.Name])
		}
	}

	// Insert the command-line Volumes
	for _, v := range p.Manifest.Volumes {
		// Check if we have a mount for this volume
		tuple, exists := namedVolumeMounts[v.Name]
		if !exists {
			return nil, fmt.Errorf("missing mount for volume %q", v.Name)
		} else if tuple.M.Volume != v.Name {
			// assertion regarding the implementation, should never happen
			return nil, fmt.Errorf("mismatched volume:mount pair: %q != %q", v.Name, tuple.M.Volume)
		}
		namedVolumeMounts[v.Name] = volumeMountTuple{V: v, M: tuple.M}
		diag.Printf("adding %+v", namedVolumeMounts[v.Name])
	}

	// Merge command-line Volumes with ImageManifest's MountPoints
	for _, mp := range manifestMPs {
		// Check if we have a volume for this mountpoint
		tuple, exists := namedVolumeMounts[mp.Name]
		if !exists || tuple.V.Name == "" {
			return nil, fmt.Errorf("missing volume for mountpoint %q", mp.Name)
		}

		// If empty, fill in ReadOnly bit
		if tuple.V.ReadOnly == nil {
			v := tuple.V
			v.ReadOnly = &mp.ReadOnly
			namedVolumeMounts[mp.Name] = volumeMountTuple{M: tuple.M, V: v}
			diag.Printf("adding %+v", namedVolumeMounts[mp.Name])
		}
	}

	// Gather host mounts which we make MS_SHARED if passed as a volume source
	hostMounts, err := getHostMounts()
	if err != nil {
		return nil, errwrap.Wrap(errors.New("can't gather host mounts"), err)
	}

	argFlyMounts := []flyMount{}
	var flags uintptr = syscall.MS_BIND // TODO: allow optional | syscall.MS_REC
	for _, tuple := range namedVolumeMounts {
		if _, isHostMount := hostMounts[tuple.V.Source]; isHostMount {
			// Mark the host mount as SHARED so the container's changes to the mount are propagated to the host
			argFlyMounts = append(argFlyMounts,
				flyMount{"", "", tuple.V.Source, "none", syscall.MS_REC | syscall.MS_SHARED},
			)
		}
		argFlyMounts = append(argFlyMounts,
			flyMount{tuple.V.Source, rfs, tuple.M.Path, "none", flags},
		)

		if tuple.V.ReadOnly != nil && *tuple.V.ReadOnly {
			argFlyMounts = append(argFlyMounts,
				flyMount{"", rfs, tuple.M.Path, "none", flags | syscall.MS_REMOUNT | syscall.MS_RDONLY},
			)
		}
	}
	return argFlyMounts, nil
}

func stage1() int {
	uuid, err := types.NewUUID(flag.Arg(0))
	if err != nil {
		log.Print("UUID is missing or malformed\n")
		return 1
	}

	root := "."
	p, err := stage1commontypes.LoadPod(root, uuid)
	if err != nil {
		log.PrintE("can't load pod", err)
		return 1
	}

	// Sanity checks
	if len(p.Manifest.Apps) != 1 {
		log.Printf("flavor %q only supports 1 application per Pod for now", flavor)
		return 1
	}

	ra := p.Manifest.Apps[0]

	imgName := p.AppNameToImageName(ra.Name)
	args := ra.App.Exec
	if len(args) == 0 {
		log.Printf(`image %q has an empty "exec" (try --exec=BINARY)`, imgName)
		return 1
	}

	lfd, err := common.GetRktLockFD()
	if err != nil {
		log.PrintE("can't get rkt lock fd", err)
		return 1
	}

	// set close-on-exec flag on RKT_LOCK_FD so it gets correctly closed after execution is finished
	if err := sys.CloseOnExec(lfd, true); err != nil {
		log.PrintE("can't set FD_CLOEXEC on rkt lock", err)
		return 1
	}

	workDir := "/"
	if ra.App.WorkingDirectory != "" {
		workDir = ra.App.WorkingDirectory
	}

	env := []string{"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"}
	for _, e := range ra.App.Environment {
		env = append(env, e.Name+"="+e.Value)
	}

	rfs := filepath.Join(common.AppPath(p.Root, ra.Name), "rootfs")

	argFlyMounts, err := evaluateMounts(rfs, string(ra.Name), p)
	if err != nil {
		log.PrintE("can't evaluate mounts", err)
		return 1
	}

	effectiveMounts := append(
		[]flyMount{
			{"", "", "/dev", "none", syscall.MS_REC | syscall.MS_SHARED},
			{"/dev", rfs, "/dev", "none", syscall.MS_BIND | syscall.MS_REC},

			{"", "", "/proc", "none", syscall.MS_REC | syscall.MS_SHARED},
			{"/proc", rfs, "/proc", "none", syscall.MS_BIND | syscall.MS_REC},

			{"", "", "/sys", "none", syscall.MS_REC | syscall.MS_SHARED},
			{"/sys", rfs, "/sys", "none", syscall.MS_BIND | syscall.MS_REC},

			{"tmpfs", rfs, "/tmp", "tmpfs", 0},
		},
		argFlyMounts...,
	)

	for _, mount := range effectiveMounts {
		var (
			err            error
			hostPathInfo   os.FileInfo
			targetPathInfo os.FileInfo
		)

		if strings.HasPrefix(mount.HostPath, "/") {
			if hostPathInfo, err = os.Stat(mount.HostPath); err != nil {
				log.PrintE(fmt.Sprintf("stat of host path %s", mount.HostPath), err)
				return 1
			}
		} else {
			hostPathInfo = nil
		}

		absTargetPath := filepath.Join(mount.TargetPrefixPath, mount.RelTargetPath)
		if targetPathInfo, err = os.Stat(absTargetPath); err != nil && !os.IsNotExist(err) {
			log.PrintE(fmt.Sprintf("stat of target path %s", absTargetPath), err)
			return 1
		}

		switch {
		case targetPathInfo == nil:
			absTargetPathParent, _ := filepath.Split(absTargetPath)
			if err := os.MkdirAll(absTargetPathParent, 0700); err != nil {
				log.PrintE(fmt.Sprintf("can't create directory %q", absTargetPath), err)
				return 1
			}
			switch {
			case hostPathInfo == nil || hostPathInfo.IsDir():
				if err := os.Mkdir(absTargetPath, 0700); err != nil {
					log.PrintE(fmt.Sprintf("can't create directory %q", absTargetPath), err)
					return 1
				}
			case !hostPathInfo.IsDir():
				file, err := os.OpenFile(absTargetPath, os.O_CREATE, 0700)
				if err != nil {
					log.PrintE(fmt.Sprintf("can't create file %q", absTargetPath), err)
					return 1
				}
				file.Close()
			}
		case hostPathInfo != nil:
			switch {
			case hostPathInfo.IsDir() && !targetPathInfo.IsDir():
				log.Printf("can't mount because %q is a directory while %q is not", mount.HostPath, absTargetPath)
				return 1
			case !hostPathInfo.IsDir() && targetPathInfo.IsDir():
				log.Printf("can't mount because %q is not a directory while %q is", mount.HostPath, absTargetPath)
				return 1
			}
		}

		if err := syscall.Mount(mount.HostPath, absTargetPath, mount.Fs, mount.Flags, ""); err != nil {
			log.PrintE(fmt.Sprintf("can't mount %q on %q with flags %v", mount.HostPath, absTargetPath, mount.Flags), err)
			return 1
		}
	}

	if err = stage1common.WritePid(os.Getpid(), "ppid"); err != nil {
		log.Error(err)
		return 1
	}

	var uidResolver, gidResolver user.Resolver
	var uid, gid int

	uidResolver, err = user.NumericIDs(ra.App.User)
	if err != nil {
		uidResolver, err = user.IDsFromStat(rfs, ra.App.User, nil)
	}

	if err != nil { // give up
		log.PrintE(fmt.Sprintf("invalid user %q", ra.App.User), err)
		return 1
	}

	if uid, _, err = uidResolver.IDs(); err != nil {
		log.PrintE(fmt.Sprintf("failed to configure user %q", ra.App.User), err)
		return 1
	}

	gidResolver, err = user.NumericIDs(ra.App.Group)
	if err != nil {
		gidResolver, err = user.IDsFromStat(rfs, ra.App.Group, nil)
	}

	if err != nil { // give up
		log.PrintE(fmt.Sprintf("invalid group %q", ra.App.Group), err)
		return 1
	}

	if _, gid, err = gidResolver.IDs(); err != nil {
		log.PrintE(fmt.Sprintf("failed to configure group %q", ra.App.Group), err)
		return 1
	}

	diag.Printf("chroot to %q", rfs)
	if err := syscall.Chroot(rfs); err != nil {
		log.PrintE("can't chroot", err)
		return 1
	}

	if err := os.Chdir(workDir); err != nil {
		log.PrintE(fmt.Sprintf("can't change to working directory %q", workDir), err)
		return 1
	}

	// lock the current goroutine to its current OS thread.
	// This will force the subsequent syscalls to be executed in the same OS thread as Setresuid, and Setresgid,
	// see https://github.com/golang/go/issues/1435#issuecomment-66054163.
	runtime.LockOSThread()

	diag.Printf("setting uid %d gid %d", uid, gid)

	if err := syscall.Setresgid(gid, gid, gid); err != nil {
		log.PrintE(fmt.Sprintf("can't set gid %d", gid), err)
		return 1
	}

	if err := syscall.Setresuid(uid, uid, uid); err != nil {
		log.PrintE(fmt.Sprintf("can't set uid %d", uid), err)
		return 1
	}

	diag.Printf("execing %q in %q", args, rfs)
	err = stage1common.WithClearedCloExec(lfd, func() error {
		return syscall.Exec(args[0], args, env)
	})
	if err != nil {
		log.PrintE(fmt.Sprintf("can't execute %q", args[0]), err)
		return 1
	}

	return 0
}

func main() {
	flag.Parse()

	log, diag, _ = rktlog.NewLogSet("run", debug)
	if !debug {
		diag.SetOutput(ioutil.Discard)
	}

	// move code into stage1() helper so defered fns get run
	os.Exit(stage1())
}


text:
<component name="libraryTable">
  <library name="Gradle: org.springframework.boot:spring-boot-starter-logging:1.2.3.RELEASE">
    <CLASSES>
      <root url="jar://$USER_HOME$/.gradle/caches/modules-2/files-2.1/org.springframework.boot/spring-boot-starter-logging/1.2.3.RELEASE/43093c137ea9c6d26ca6341e17295c0a6c506dfb/spring-boot-starter-logging-1.2.3.RELEASE.jar!/" />
    </CLASSES>
    <JAVADOC />
    <SOURCES />
  </library>
</component>

redpajama_set_name: RedPajamaGithub


text:
FROM fedora
MAINTAINER Sundeep Anand <web@sundeep.co.in>

RUN dnf -y update && dnf -y install make python3-pip git sqlite && dnf clean all

ENV PYTHONUNBUFFERED 1
RUN mkdir /workspace
WORKDIR /workspace
RUN git clone -b master https://github.com/sundeep-co-in/makegoalsdaily.git .
RUN make env && make migrate

EXPOSE 8080

CMD ["/workspace/launch.sh"]


text:
<?php

namespace ASURFIWordPress\Services;

use PhpXmlRpc\Value;
use PhpXmlRpc\Request;
use PhpXmlRpc\Client;
use ASURFIWordPress\Helpers\ConditionalHelper;
use ASURFIWordPress\Services\ASUCampusService;

// Avoid direct calls to this file
if ( ! defined( 'ASU_RFI_WORDPRESS_PLUGIN_VERSION' ) ) {
  header( 'Status: 403 Forbidden' );
  header( 'HTTP/1.1 403 Forbidden' );
  exit();
}

/** ASUDegreeService
 * Providing data from ASU Degrees
 * XML RPC API Docs: http://www.public.asu.edu/~lcabre/javadocs/dsws/
 */
class ASUDegreeService {
  private static $RPC_TIMEOUT = 10; // seconds

  public function __construct( $client = null ) {
    if ( null === $client ) {
      $client = new Client( ASU_DIRECTORY_XML_RPC_SERVER );
    }
    $this->client = $client;
  }

  /** Get all the programs across all campuses for a specific degree level in one array.
   * 'graduate' or 'undergraduate' are accepted values for degree levels.
   * returns an array.
   */
  public function get_programs_on_all_campuses( $degree_level = 'graduate' ) {
    $results = array();
    $campuses = ASUCampusService::get_campus_codes();
    foreach ( $campuses as $campus_code ) {
      $results_for_this_campus = $this->get_programs_per_campus( $degree_level, $campus_code );
      $results = array_merge( $results, $results_for_this_campus );
    }
    return $results;
  }

  /** Get Programs offered on a specific Campus
   * the response object is rather obscure to work with, it looks like this:
   *
   * @throws \Exception if unable to make RPC request
   PhpXmlRpc\Response Object (
    [val] => PhpXmlRpc\Value Object
        ( [me] => Array (
            [array] => Array (
                [0] => PhpXmlRpc\Value Object (
                    [me] => Array (
                        [struct] => Array (
                            [AcadCareer] => PhpXmlRpc\Value Object (
                                [me] => Array (
                                    [string] => "blah blah"
                                )
                              )
                              ....
   */
  public function get_programs_per_campus( $degree_level = 'graduate', $campus = 'TEMPE' ) {
    // the RPC endpoint expects specific spelling for grad and undergrad
    if ( ConditionalHelper::graduate( $degree_level ) ) {
      $program_to_search = 'graduate';
    } else {
      $program_to_search = 'undergrad';
    }

    if ( ConditionalHelper::online( $campus ) ) {
      // They want Online to be spelled this way.
      $campus = 'ONLNE';
    }

    $request = new Request( 'eAdvisorDSFind.findDegreeByCampusMapArray',
        array(
        new Value( $campus, 'string' ),
        new Value( $program_to_search, 'string' ),
        new Value( false, 'boolean' ), // get both certificates and majors
        )
    );

    $response = $this->client->send( $request, ASUDegreeService::$RPC_TIMEOUT );
    if ( ! empty( $response->errstr ) ) {
      throw new \Exception( 'ASU Degree Service Error: ' . $response->errno . ': ' . $response->errstr . ' : ' . ASU_DIRECTORY_XML_RPC_SERVER );
    }
    $value = $response->value()->me;
    $value = array_pop( $value );

    return array_map( function( $item ) {
        $program = $item->me['struct'];
        return array(
          'majorcode'   => $program['AcadPlan']->me['string'],
          'majorname'   => $program['Descr100']->me['string'],
          'degreedesc'  => $program['DegreeDescrformal']->me['string'],
          'programname' => $program['DiplomaDescr']->me['string'],
          'programcode' => $program['AcadProg']->me['string'],
         );
    }, $value );

  }

  /** Get major programs for a college at a degree level and optionally for a campus.
   * if no campus is defined than all campuses are returned.
   */
  public function get_majors_per_college( $college_code, $degree_level = 'graduate', $campus = null ) {
    if ( empty( $campus ) ) {
      $programs = $this->get_programs_on_all_campuses( $degree_level );
    } else {
      $programs = $this->get_programs_per_campus( $degree_level , $campus );
    }

    return $this->filter_programs_for_a_college( $college_code, $programs );
  }

  /** Filter all programs and return just the programs that belong to a speicific college
   */
  private function filter_programs_for_a_college( $college_code, $all_programs ) {
    $subset = array();

    foreach ( $all_programs as $program ) {
      if ( 0 === strcasecmp( $college_code, $program['programcode'] ) ) {
        $formatted_program = array(
          'label' => $this->get_program_display_name( $program ),
          'type'  => $this->get_program_type_name( $program ),
          'value' => $program['majorcode'],
         );
        // there could be duplicate programs offered on multiple campuses
        if ( ! in_array( $formatted_program, $subset ) ) {
          $subset [] = $formatted_program;
        }
      }
    }
    asort( $subset );
    return $subset;
  }

  /** Get a programs Display Name( $program ) - if needed, append in () the last two digets
   * of the majorcode unless there is a () in the major name already.
   */
  private function get_program_display_name( $program ) {
    if ( strpos( $program['majorname'], '(' ) === false ) {
      $last_two_letters_of_major_code = substr( $program['majorcode'], -2 );
      return $program['majorname'] . ' (' . $last_two_letters_of_major_code . ')';
    } else {
      return $program['majorname'];
    }

  }

  /** Get a program's degree type name ('Bachelor', Master', 'Doctor', 'Certificate', etc.)
   */
  private function get_program_type_name( $program ) {
    if ( false !== strpos( $program['degreedesc'], 'Bachelor' ) ) {
      $program_type_name = 'Bachelors';

    } elseif ( false !== strpos( $program['degreedesc'], 'Master' ) ) {
      $program_type_name = 'Masters';

    } elseif ( false !== strpos( $program['degreedesc'], 'Doctor' ) ) {
      $program_type_name = 'Doctoral';

    } elseif ( false !== strpos( $program['degreedesc'], 'Certificate' ) ) {
      // to match the studentType code
      $program_type_name = 'cert';

    } else {
      // other non-degree types, like "Pre-prof/Exploratory", aren't passed through
      // because the rfi form will not be able to auto-select the appropriate studentType dropdown.
      // the end-user will have to select the appropriate value themselves.
      $program_type_name = '';
    }

    return $program_type_name;
  }
}


text:
package edacc.model;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

/**
 *
 * @author simon
 */
public class ParameterInstanceDAO {

    private static final String table = "SolverConfig_has_Parameters";
    private static final String deleteQuery = "DELETE FROM " + table + " WHERE SolverConfig_IdSolverConfig=? AND Parameters_IdParameter=?";
    private static final String insertQuery = "INSERT INTO " + table + " (SolverConfig_IdSolverConfig, Parameters_IdParameter, value) VALUES (?,?,?)";
    private static final String updateQuery = "UPDATE " + table + " SET value=? WHERE SolverConfig_IdSolverConfig=? AND Parameters_IdParameter=?";
    private static final HashMap<SolverConfiguration, ArrayList<ParameterInstance>> cache = new HashMap<SolverConfiguration, ArrayList<ParameterInstance>>();

    /**
     * ParameterInstance factory method. Saves the new object in the database.
     * @param parameterId
     * @param solverConfigId
     * @return
     * @throws SQLException
     */
    public static ParameterInstance createParameterInstance(int parameterId, SolverConfiguration sc, String value) throws SQLException {
        ParameterInstance i = new ParameterInstance();
        i.setParameter_id(parameterId);
        i.setSolverConfiguration(sc);
        i.setValue(value);
        save(i);
        return i;
    }

    public static void saveBatch(List<ParameterInstance> parameters) throws SQLException {
        PreparedStatement st = DatabaseConnector.getInstance().getConn().prepareStatement(insertQuery);
        for (ParameterInstance pi : parameters) {
            st.setInt(1, pi.getSolverConfiguration().getId());
            st.setInt(2, pi.getParameter_id());
            st.setString(3, pi.getValue());
            pi.setSaved();
            st.addBatch();
        }
        st.executeBatch();
        st.close();
    }

    public static void saveBulk(List<ParameterInstance> parameters) throws SQLException {
        if (parameters.isEmpty()) {
            return;
        }
        List<ParameterInstance> modified = new LinkedList<ParameterInstance>();
        List<ParameterInstance> deleted = new LinkedList<ParameterInstance>();
        List<ParameterInstance> newOnes = new LinkedList<ParameterInstance>();

        for (ParameterInstance pi : parameters) {
            if (pi.isNew()) {
                newOnes.add(pi);
            } else if (pi.isModified()) {
                modified.add(pi);
            } else if (pi.isDeleted()) {
                deleted.add(pi);
            }
        }

        if (!newOnes.isEmpty()) {
            StringBuilder insertQuery = new StringBuilder();
            insertQuery.append("INSERT INTO " + table + " (SolverConfig_IdSolverConfig, Parameters_IdParameter, value) VALUES ");
            ParameterInstance last = newOnes.get(newOnes.size() - 1);
            for (ParameterInstance pi : newOnes) {
                insertQuery.append("(");
                insertQuery.append(pi.getSolverConfiguration().getId());
                insertQuery.append(",");
                insertQuery.append(pi.getParameter_id());
                insertQuery.append(",?)");
                if (pi != last) {
                    insertQuery.append(",");
                }
            }
            PreparedStatement st = DatabaseConnector.getInstance().getConn().prepareStatement(insertQuery.toString());
            int count = 1;
            for (ParameterInstance pi : newOnes) {
                // update cache
                ArrayList<ParameterInstance> cachedPis = getCached(pi.getSolverConfiguration());
                if (cachedPis != null) {
                    cachedPis.add(pi);
                }

                st.setString(count++, pi.getValue());
                pi.setSaved();
            }
            st.executeUpdate();
            st.close();
        }
        if (!modified.isEmpty()) {
            PreparedStatement st = DatabaseConnector.getInstance().getConn().prepareStatement(updateQuery);
            for (ParameterInstance pi : modified) {
                st.setString(1, pi.getValue());
                st.setInt(2, pi.getSolverConfiguration().getId());
                st.setInt(3, pi.getParameter_id());
                st.addBatch();
            }
            st.executeBatch();
            st.close();
        }
        if (!deleted.isEmpty()) {
            StringBuilder tmp = new StringBuilder();

            int count = deleted.size();
            tmp.append("(?");
            count--;
            for (int i = 0; i < count; i++) {
                tmp.append(",?");
            }
            tmp.append(")");
            StringBuilder deleteQuery = new StringBuilder("DELETE FROM " + table + " WHERE ");
            ParameterInstance last = deleted.get(deleted.size()-1);
            for (int i = 0; i < deleted.size(); i++) {
                deleteQuery.append("SolverConfig_IdSolverConfig=").append(deleted.get(i).getSolverConfiguration().getId()).append(" AND Parameters_IdParameter=").append(deleted.get(i).getParameter_id());
                if (deleted.get(i) != last) {
                    deleteQuery.append(" OR ");
                }
            }
            Statement st = DatabaseConnector.getInstance().getConn().createStatement();
            st.executeUpdate(deleteQuery.toString());
            st.close();
        }
    }

    public static void save(ParameterInstance i) throws SQLException {
        ArrayList<ParameterInstance> pi = getCached(i.getSolverConfiguration());
        if (i.isDeleted()) {
            PreparedStatement st = DatabaseConnector.getInstance().getConn().prepareStatement(deleteQuery);
            st.setInt(1, i.getSolverConfiguration().getId());
            st.setInt(2, i.getParameter_id());
            st.executeUpdate();

            // update cache
            if (pi != null) {
                for (int k = 0; k < pi.size(); k++) {
                    if (pi.get(k).equals(i)) {
                        pi.remove(k);
                        break;
                    }
                }
            }
            st.close();
        } else if (i.isModified()) {
            PreparedStatement st = DatabaseConnector.getInstance().getConn().prepareStatement(updateQuery);
            st.setString(1, i.getValue());
            st.setInt(2, i.getSolverConfiguration().getId());
            st.setInt(3, i.getParameter_id());
            st.executeUpdate();
            i.setSaved();
            st.close();
        } else if (i.isNew()) {
            PreparedStatement st = DatabaseConnector.getInstance().getConn().prepareStatement(insertQuery);
            st.setInt(1, i.getSolverConfiguration().getId());
            st.setInt(2, i.getParameter_id());
            st.setString(3, i.getValue());
            st.executeUpdate();
            i.setSaved();

            // update cache
            if (pi != null) {
                pi.add(i);
            }
            st.close();
        }

    }

    public static void setModified(ParameterInstance i) {
        if (i.isSaved()) {
            i.setModified();
        }
    }

    public static void setDeleted(ParameterInstance i) {
        i.setDeleted();
    }

    private static ParameterInstance getParameterInstanceFromResultset(ResultSet rs, SolverConfiguration sc) throws SQLException {
        ParameterInstance i = new ParameterInstance();
        i.setSolverConfiguration(sc);
        i.setParameter_id(rs.getInt("Parameters_idParameter"));
        i.setValue(rs.getString("value"));
        return i;
    }

    private static ArrayList<ParameterInstance> getCached(SolverConfiguration i) {
        if (cache.containsKey(i)) {
            return cache.get(i);
        } else {
            return null;
        }
    }

    private static void cacheParameterInstances(SolverConfiguration sc, ArrayList<ParameterInstance> i) {
        if (cache.containsKey(sc)) {
            return;
        } else {
            cache.put(sc, i);
        }
    }

    /**
     * Gets all parameter instances from a solver configuration.
     * @param sc
     * @return
     * @throws SQLException
     */
    public static ArrayList<ParameterInstance> getBySolverConfig(SolverConfiguration sc) throws SQLException {
        ArrayList<ParameterInstance> res = getCached(sc);
        if (res != null) {
            return res;
        }
        res = new ArrayList<ParameterInstance>();
        PreparedStatement st = DatabaseConnector.getInstance().getConn().prepareStatement("SELECT * FROM " + table + " WHERE SolverConfig_idSolverConfig=?");
        st.setInt(1, sc.getId());
        ResultSet rs = st.executeQuery();
        while (rs.next()) {
            ParameterInstance i = getParameterInstanceFromResultset(rs, sc);
            i.setSaved();
            res.add(i);
        }
        cacheParameterInstances(sc, res);
        rs.close();
        st.close();
        return res;
    }

    public static void cacheParameterInstances(List<SolverConfiguration> p_scs) throws SQLException {
        if (p_scs == null) {
            return;
        }
        ArrayList<SolverConfiguration> scs = new ArrayList<SolverConfiguration>();
        for (SolverConfiguration sc : p_scs) {
            if (getCached(sc) == null) {
                scs.add(sc);
            }
        }
        if (scs.isEmpty()) {
            return;
        }
        Collections.sort(scs, new Comparator<SolverConfiguration>() {

            @Override
            public int compare(SolverConfiguration o1, SolverConfiguration o2) {
                return o1.getId() - o2.getId();
            }
        });
        StringBuilder sb = new StringBuilder("(");
        for (int i = 0; i < scs.size() - 1; i++) {
            sb.append(scs.get(i).getId()).append(',');
        }
        sb.append(scs.get(scs.size() - 1).getId()).append(')');
        String idString = sb.toString();
        PreparedStatement st = DatabaseConnector.getInstance().getConn().prepareStatement("SELECT * FROM " + table + " WHERE SolverConfig_idSolverConfig IN " + idString + " ORDER BY SolverConfig_idSolverConfig ASC");
        int cur_idx = 0;
        ArrayList<ParameterInstance> cur = new ArrayList<ParameterInstance>();
        SolverConfiguration cur_sc = scs.get(cur_idx);
        ResultSet rs = st.executeQuery();
        while (rs.next()) {
            if (rs.getInt("SolverConfig_idSolverConfig") != cur_sc.getId()) {
                cacheParameterInstances(cur_sc, cur);
                while (cur_sc.getId() != rs.getInt("SolverConfig_idSolverConfig")) {
                    cur_sc = scs.get(++cur_idx);
                }
                cur = new ArrayList<ParameterInstance>();
            }
            ParameterInstance i = getParameterInstanceFromResultset(rs, cur_sc);
            i.setSaved();
            cur.add(i);
        }
        rs.close();
        st.close();
        cacheParameterInstances(cur_sc, cur);
    }

    public static void clearCache() {
        cache.clear();
    }
}


text:
<?php

namespace PHP\Expando\Reflection;

use \PHP\Expando\Reflection\Util\MethodTokenizer;

/**
 * ReflectionMethod
 *
 * Light weight replacement for \ReflectionMethod with added methods
 *
 * @package Metaclass
 * @author  Marcello Duarte <marcello.duarte@gmail.com>
 */
class ReflectionMethod
{
    /**
     * Name of the method
     *
     * @var unknown_type
     */
    protected $_name;

    /**
     * Path to the class of which the method is a part
     *
     * @var string
     */
    protected $_path;

    /**
     * ReflectionMethod is constructed with name and path
     *
     * @param string $name
     * @param string $path
     */
    public function __construct($name, $path)
    {
        $this->_name = $name;
        $this->_path = $path;
        $this->extractBody();
    }

    /**
     * Gets the method body
     *
     * @return string
     */
    public function getBody()
    {
        return $this->body;
    }

    /**
     * Extracts the method body from source
     */
    private function extractBody()
    {
        $string = $this->asString();
        $body = \substr($string, \strpos($string, '{'));
        $this->body = \trim(\rtrim(\rtrim($body), ';'), '{}');
    }

    /**
     * Extracts the full method definition
     *
     * @return string
     */
    public function asString()
    {
        $tokenizer = new MethodTokenizer($this->getSource(), $this->_name);
        return $tokenizer->extract();
    }

    /**
     * Retrieves the source of the class from the file
     *
     * @return string
     */
    public function getSource()
    {
        return rtrim(trim(\file_get_contents($this->_path)), '}');
    }
}


text:
<?php
/* All code covered by the BSD license located at http://silverstripe.org/bsd-license/ */

/**
 * @author Marcus Nyeholt <marcus@symbiote.com.au>
 */
class SymbioteSampleTest extends SapphireTest {
    public function testSomething() {
		$this->assertTrue(true);
	}
}


text:
package org.jbpm.bpmn2.concurrency.persistence;

import static org.jbpm.persistence.util.PersistenceUtil.cleanUp;
import static org.jbpm.persistence.util.PersistenceUtil.createEnvironment;
import static org.jbpm.persistence.util.PersistenceUtil.setupWithPoolingDataSource;

import java.util.HashMap;

import org.jbpm.bpmn2.concurrency.MultipleProcessesPerThreadTest;
import org.jbpm.persistence.util.PersistenceUtil;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.kie.internal.KnowledgeBase;
import org.kie.internal.persistence.jpa.JPAKnowledgeService;
import org.kie.internal.runtime.StatefulKnowledgeSession;
import org.kie.api.runtime.Environment;

/**
 * Class to reproduce bug with multiple threads using persistence and each
 * configures its own entity manager.
 *
 * This test costs time and resources, please only run locally for the time being.
 */
@Ignore
public class MultipleProcessesPerThreadPersistenceTest extends MultipleProcessesPerThreadTest {

    private static HashMap<String, Object> context;

    @Before
    public void setup() {
        context = setupWithPoolingDataSource(PersistenceUtil.JBPM_PERSISTENCE_UNIT_NAME);
    }

    @After
    public void tearDown() {
        cleanUp(context);
    }

    protected static StatefulKnowledgeSession createStatefulKnowledgeSession(KnowledgeBase kbase) {
        Environment env = createEnvironment(context);
        return JPAKnowledgeService.newStatefulKnowledgeSession(kbase, null, env);
    }

}


text:
package container

import (
	"fmt"
	"strings"

	"github.com/docker/docker/cli"
	"github.com/docker/docker/cli/command"
	"github.com/pkg/errors"
	"github.com/spf13/cobra"
	"golang.org/x/net/context"
)

type waitOptions struct {
	containers []string
}

// NewWaitCommand creates a new cobra.Command for `docker wait`
func NewWaitCommand(dockerCli *command.DockerCli) *cobra.Command {
	var opts waitOptions

	cmd := &cobra.Command{
		Use:   "wait CONTAINER [CONTAINER...]",
		Short: "Block until one or more containers stop, then print their exit codes",
		Args:  cli.RequiresMinArgs(1),
		RunE: func(cmd *cobra.Command, args []string) error {
			opts.containers = args
			return runWait(dockerCli, &opts)
		},
	}
	return cmd
}

func runWait(dockerCli *command.DockerCli, opts *waitOptions) error {
	ctx := context.Background()

	var errs []string
	for _, container := range opts.containers {
		status, err := dockerCli.Client().ContainerWait(ctx, container)
		if err != nil {
			errs = append(errs, err.Error())
			continue
		}
		fmt.Fprintf(dockerCli.Out(), "%d\n", status)
	}
	if len(errs) > 0 {
		return errors.New(strings.Join(errs, "\n"))
	}
	return nil
}


text:
package com.hazelcast.client.spi.impl;

import com.hazelcast.client.test.TestHazelcastFactory;
import com.hazelcast.config.Config;
import com.hazelcast.core.ExecutionCallback;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.IMap;
import com.hazelcast.core.LifecycleEvent;
import com.hazelcast.core.LifecycleListener;
import com.hazelcast.instance.TestUtil;
import com.hazelcast.map.EntryBackupProcessor;
import com.hazelcast.map.EntryProcessor;
import com.hazelcast.test.HazelcastParallelClassRunner;
import com.hazelcast.test.HazelcastTestSupport;
import com.hazelcast.test.annotation.ParallelTest;
import com.hazelcast.test.annotation.QuickTest;
import org.junit.After;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;

import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.LockSupport;

import static org.junit.Assert.assertTrue;

@RunWith(HazelcastParallelClassRunner.class)
@Category({QuickTest.class, ParallelTest.class})
public class ClientInvocationTest extends HazelcastTestSupport {

    private final TestHazelcastFactory hazelcastFactory = new TestHazelcastFactory();

    @After
    public void cleanup() {
        hazelcastFactory.terminateAll();
    }

    /**
     * When a async operation fails because of a node termination,
     * failure stack trace is copied incrementally for each async invocation/future
     * <p/>
     * see https://github.com/hazelcast/hazelcast/issues/4192
     */
    @Test
    public void executionCallback_TooLongThrowableStackTrace() throws InterruptedException {
        Config config = new Config();
        config.getNetworkConfig().getJoin().getMulticastConfig().setEnabled(false);
        config.getNetworkConfig().getJoin().getTcpIpConfig().setEnabled(true);
        HazelcastInstance server = hazelcastFactory.newHazelcastInstance(config);

        HazelcastInstance client = hazelcastFactory.newHazelcastClient();
        IMap<Object, Object> map = client.getMap(randomMapName());

        DummyEntryProcessor ep = new DummyEntryProcessor();

        int count = 100;
        FailureExecutionCallback[] callbacks = new FailureExecutionCallback[count];
        String key = randomString();
        for (int i = 0; i < count; i++) {
            callbacks[i] = new FailureExecutionCallback();
            map.submitToKey(key, ep, callbacks[i]);
        }

        // crash the server
        TestUtil.getNode(server).getConnectionManager().shutdown();
        server.getLifecycleService().terminate();

        int callBackCount = 0;
        for (FailureExecutionCallback callback : callbacks) {
            callBackCount++;
            assertOpenEventually("Callback should be notified on time! callbackCount:" + callBackCount, callback.latch);

            Throwable failure = callback.failure;
            if (failure == null) {
                continue;
            }
            int stackTraceLength = failure.getStackTrace().length;
            assertTrue("Failure stack trace should not be too long! Current: "
                    + stackTraceLength, stackTraceLength < 50);

            Throwable cause = failure.getCause();
            if (cause == null) {
                continue;
            }
            stackTraceLength = cause.getStackTrace().length;
            assertTrue("Cause stack trace should not be too long! Current: "
                    + stackTraceLength, stackTraceLength < 50);
        }
    }

    @Test
    public void executionCallback_FailOnShutdown() {
        HazelcastInstance server = hazelcastFactory.newHazelcastInstance();
        HazelcastInstance client = hazelcastFactory.newHazelcastClient();

        final CountDownLatch disconnectedLatch = new CountDownLatch(1);

        IMap<Object, Object> map = client.getMap(randomName());
        client.getLifecycleService().addLifecycleListener(new LifecycleListener() {
            @Override
            public void stateChanged(LifecycleEvent event) {
                if (event.getState() == LifecycleEvent.LifecycleState.CLIENT_DISCONNECTED) {
                    disconnectedLatch.countDown();
                }
            }
        });
        server.shutdown();
        assertOpenEventually(disconnectedLatch);
        int n = 100;
        final CountDownLatch errorLatch = new CountDownLatch(n);
        for (int i = 0; i < n; i++) {
            try {
                map.submitToKey(randomString(), new DummyEntryProcessor(), new ExecutionCallback() {
                    @Override
                    public void onResponse(Object response) {
                    }

                    @Override
                    public void onFailure(Throwable t) {
                        errorLatch.countDown();
                    }
                });
            } catch (Exception e) {
                errorLatch.countDown();
            }
        }
        assertOpenEventually("Not all of the requests failed", errorLatch);
    }

    private static class DummyEntryProcessor implements EntryProcessor {
        @Override
        public Object process(Map.Entry entry) {
            LockSupport.parkNanos(10000);
            return null;
        }

        @Override
        public EntryBackupProcessor getBackupProcessor() {
            return null;
        }
    }

    private static class FailureExecutionCallback implements ExecutionCallback {
        final CountDownLatch latch = new CountDownLatch(1);
        volatile Throwable failure;

        @Override
        public void onResponse(Object response) {
            latch.countDown();
        }

        @Override
        public void onFailure(Throwable t) {
            failure = t;
            latch.countDown();
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <dimen name="margin_humongous">96dp</dimen>
    <dimen name="margin_huge">64dp</dimen>
    <dimen name="margin_big">48dp</dimen>
    <dimen name="margin_large">32dp</dimen>
    <dimen name="margin_post_medium">24dp</dimen>
    <dimen name="margin_medium">16dp</dimen>
    <dimen name="margin_pre_medium">12dp</dimen>
    <dimen name="margin_small">8dp</dimen>
    <dimen name="margin_pre_small">6dp</dimen>
    <dimen name="margin_tiny">4dp</dimen>
    <dimen name="margin_mini">2dp</dimen>
    <dimen name="margin_zero">0dp</dimen>

    <dimen name="text_size_xsmall">12sp</dimen>
    <dimen name="text_size_small">14sp</dimen>
    <dimen name="text_size_medium">16sp</dimen>
    <dimen name="text_size_big">18sp</dimen>
    <dimen name="text_size_large">20sp</dimen>
    <dimen name="text_size_xlarge">22sp</dimen>
    <dimen name="text_size_xxlarge">32sp</dimen>
    <dimen name="text_size_xxxlarge">36sp</dimen>

</resources>


text:
var expect = require("chai").expect;
var Bet = require('../../lib/bet');
var uniqid = require('uniqid');

describe("Running tests for bet", function() {
    it("should get created and saved in file system", function(done) {
       Bet.create("Bet:W:2:10",uniqid(), function(err, response){
            expect(response).to.be.ok;
            done();
        })
    });

    it("should create Exacta bet with array of size 2", function(done) {
       Bet.create("Bet:E:2,3:10",uniqid(), function(err, response){
            expect(response).to.be.ok;
            expect(response.selections).to.be.ok;
            expect(response.selections).to.be.an('array');
            expect(response.selections).to.have.lengthOf(2);
            done();
        })
    });

});


text:
import { NgModule }     from '@angular/core';
import {
	RouterModule,
	Routes
}                       from '@angular/router';

import { SessionGuard } from './session/session.guard';

const routes = [
	{ path: '', redirectTo: 'dashboard', pathMatch: 'full' }
];

@NgModule( {
	imports: [
		RouterModule.forRoot( routes, { useHash: true } )
	],
	exports: [
		RouterModule
	]
} )

export class RoutingModule {
}


text:
#include "trikEnginesGenerator.h"

#include <generatorBase/generatorCustomizer.h>
#include <generatorBase/parts/engines.h>

using namespace trik::simple;
using namespace generatorBase::simple;

TrikEnginesGenerator::TrikEnginesGenerator(const qrRepo::RepoApi &repo
		, generatorBase::GeneratorCustomizer &customizer
		, const qReal::Id &id
		, const QString &engineType
		, QObject *parent)
	: BindingGenerator(repo, customizer, id
			, engineType.contains("EnginesBackward") ? "engines/backward.t" : "engines/forward.t"
			, { Binding::createMultiTarget("@@PORT@@", "Ports", customizer.factory()->enginesConverter())
					, Binding::createConverting("@@POWER@@", "Power"
							, customizer.factory()->intPropertyConverter(id, "Power"))
			}, parent)
{
	// AngularServo is just another block for EnginesForward, since it is controlled the same way as radial servo
	// or power motor.
	mCustomizer.factory()->engines()->registerUsageOnPorts(repo.property(id, "Ports").toString());
}


text:
package main

import (
	"fmt"
	"log"
	"net/http"

	"github.com/ma314smith/go-wsfed"
)

var config wsfed.Config
var sso *wsfed.WSFed

func main() {
	config = wsfed.Config{}
	config.MetadataURL = "https://signin.blackbaud.com/wsfederation/metadata"
	config.MetadataCertsAreTrusted = true
	config.MetadataRefreshIntervalSeconds = 10
	config.Realm = "http://account.blackbaud.com"
	sso = wsfed.New(&config)

	http.Handle("/", http.HandlerFunc(myFunc))
	fmt.Println("Listening on http://127.0.0.1:80")
	err := http.ListenAndServe(":80", nil)
	if err != nil {
		log.Fatal("ListenAndServe:", err)
	}
}

func myFunc(w http.ResponseWriter, r *http.Request) {
	wresult := r.PostFormValue("wresult")

	if wresult == "" {
		rp := sso.GetDefaultRequestParameters()
		rp.Wreply = "http://" + r.Host + r.URL.String()
		url, err := sso.GetRequestURL(rp)
		if err != nil {
			panic(err)
		}
		http.Redirect(w, r, url, 302)
		return
	}

	claims, err := sso.ParseResponse(wresult)
	if err != nil {
		w.Write([]byte(fmt.Sprintf("Error parsing response: %s", err)))
		//w.Write([]byte(wresult))
	} else {
		w.Write([]byte(fmt.Sprintf("Claims: %v", claims)))
		//w.Write([]byte(wresult))
	}
}


text:
package handlers

import (
	"fmt"
	"net/http"
	"regexp"
	"strings"

	"github.com/kevinburke/rest"
)

type route struct {
	pattern *regexp.Regexp
	methods []string
	handler http.Handler
}

// A RegexpHandler is a simple http.Handler that can match regular expressions
// for routes.
type Regexp struct {
	routes []*route
}

// Handle calls the provided handler for requests whose URL matches the given
// pattern and HTTP method. The first matching route will get called. If methods
// is nil, all HTTP methods will be allowed. If GET is in the list of methods,
// HEAD requests will also be allowed.
func (h *Regexp) Handle(pattern *regexp.Regexp, methods []string, handler http.Handler) {
	h.routes = append(h.routes, &route{
		pattern: pattern,
		methods: methods,
		handler: handler,
	})
}

// HandleString is like Handle, but will compile s to a regexp first.
// If s is not a valid regexp HandleString will panic.
func (h *Regexp) HandleString(s string, methods []string, handler http.Handler) {
	rx, err := regexp.Compile(s)
	if err != nil {
		panic(fmt.Sprintf("handlers: could not compile pattern %q to a regex: got error %v", s, err))
	}
	h.Handle(rx, methods, handler)
}

// HandleFunc calls the provided HandlerFunc for requests whose URL matches the
// given pattern and HTTP method. The first matching route will get called.
// If methods is nil, all HTTP methods are allowed. If GET is in the list of
// methods, HEAD requests will also be allowed.
func (h *Regexp) HandleFunc(pattern *regexp.Regexp, methods []string, handler func(http.ResponseWriter, *http.Request)) {
	h.routes = append(h.routes, &route{
		pattern: pattern,
		methods: methods,
		handler: http.HandlerFunc(handler),
	})
}

// HandleStringFunc is like HandleFunc, but will compile s to a regexp first.
// If s is not a valid regexp HandleStringFunc will panic.
func (h *Regexp) HandleStringFunc(s string, methods []string, handler func(http.ResponseWriter, *http.Request)) {
	rx, err := regexp.Compile(s)
	if err != nil {
		panic(fmt.Sprintf("handlers: could not compile pattern %q to a regex: got error %v", s, err))
	}
	h.HandleFunc(rx, methods, handler)
}

var allMethods = []string{
	"GET",
	"POST",
	"PUT",
	"PATCH",
	"DELETE",
	"CONNECT",
	"TRACE",
}

// ServeHTTP checks all registered routes in turn for a match, and calls
// handler.ServeHTTP on the first matching handler. If no routes match,
// StatusMethodNotAllowed will be rendered.
func (h *Regexp) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	upperMethod := strings.ToUpper(r.Method)
	allowed := make([]string, 0)
	oneMatch := false
	for _, route := range h.routes {
		if route.pattern.MatchString(r.URL.Path) {
			oneMatch = true
			if route.methods == nil && upperMethod != "OPTIONS" {
				route.handler.ServeHTTP(w, r)
				return
			}
			for _, method := range route.methods {
				upper := strings.ToUpper(method)
				if upper == upperMethod || upperMethod == "HEAD" && upper == "GET" {
					route.handler.ServeHTTP(w, r)
					return
				}
			}
			if upperMethod == "OPTIONS" {
				allowed = append(allowed, route.methods...)
			}
		}
	}
	if upperMethod == "OPTIONS" {
		var methods string
		if len(allowed) > 0 {
			methods = strings.Join(append(allowed, "OPTIONS"), ", ")
		} else {
			methods = strings.Join(append(allMethods, "OPTIONS"), ", ")
		}
		w.Header().Set("Allow", methods)
		return
	}
	if oneMatch {
		rest.NotAllowed(w, r)
	} else {
		rest.NotFound(w, r)
	}
}


text:
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using DumpMiner.Common;
using DumpMiner.Debugger;

namespace DumpMiner.Operations
{
    [Export(OperationNames.DumpFinalizerQueue, typeof(IDebuggerOperation))]
    class DumpFinalizerQueueOperation : IDebuggerOperation
    {
        public string Name => OperationNames.DumpFinalizerQueue;

        public async Task<IEnumerable<object>> Execute(Models.OperationModel model, CancellationToken token, object customeParameter)
        {
            return await DebuggerSession.Instance.ExecuteOperation(() =>
            {
                var heap = DebuggerSession.Instance.Heap;
                var enumerable = from finalizer in DebuggerSession.Instance.Runtime.EnumerateFinalizerQueueObjectAddresses()
                                 let type = heap.GetObjectType(finalizer)
                                 select new ClrObject(finalizer, type).Fields.Value;
                return enumerable.ToList();
            });
        }
    }
}


text:
<?php
//
// Copyright (c) 2008-2016 Decibel Technology Limited.
//
// @requires	translation
namespace app\decibel\application;

use app\decibel\application\debug\DMissingAppManifestDataException;
use app\decibel\application\debug\DMissingAppManifestException;
use app\decibel\file\DFile;
use app\decibel\file\DFileNotFoundException;
use app\decibel\health\DHealthCheckResult;
use app\decibel\packaging\DAppDependency;
use app\decibel\packaging\DDependency;
use app\decibel\xml\DDOMDocument;
use app\decibel\xml\DXPath;
use DOMElement;

/**
 * Provides a wrapper for accessing an App's manifest file.
 *
 * @author    Timothy de Paris
 */
class DAppManifest extends DXPath
{
    /**
     * 'Version' XML element name.
     *
     * @var        string
     */
    const ELEMENT_VERSION = 'version';
    /**
     * 'Name' XML element name.
     *
     * @var        string
     */
    const ELEMENT_NAME = 'name';

    /**
     * The filename for this manifest.
     *
     * @var        string
     */
    protected $filename;

    /**
     * Loads an App manifest from the provided filename.
     *
     * @param    string $qualifiedName    Qualified name of the App to load
     *                                    the manifest for.
     * @param    string $filename         Optional location of the manifest file.
     *                                    If not provided it will be looked for
     *                                    in the expected location for the
     *                                    provided App.
     *
     * @throws DMissingAppManifestException If the specified manifest file
     *                                            does not exist.
     */
    public function __construct($qualifiedName, $filename = null)
    {
        // Determine the expected location for the App
        // if no filename provided.
        if ($filename === null) {
            $this->filename = static::getManifestFilename($qualifiedName);
        } else {
            $this->filename = $filename;
        }

        try {
            $file = new DFile($this->filename);
            // Handle exception if manifest file doesn't exist.
        } catch (DFileNotFoundException $exception) {
            throw new DMissingAppManifestException($this->filename, $qualifiedName);
        }

        $stream = $file->getStream();

        $document = DDOMDocument::create($stream);
        parent::__construct($document);
    }

    /**
     * Checks the dependencies of the App manifest against the current
     * installation.
     *
     * @param    array $versions      Optional array of current state overrides
     *                                for DAppDependency object that can be provided
     *                                to test dependencies in    particular situations.
     *
     * @return    array    List of {@link DHealthCheckResult} objects.
     */
    public function checkDependencies(array $versions = array())
    {
        // Find dependencies within the manifest.
        $results = array();
        foreach ($this->getDependencies() as $dependency) {
            /* @var $dependency DDependency */
            $result = $this->checkDependency($dependency, $versions);
            if ($result !== null) {
                $results[] = $result;
            }
        }

        return $results;
    }

    /**
     * Checks a dependency against the current installation.
     *
     * @param    DDependency $dependency  The dependency to check.
     * @param    array       $versions    Optional array of current state overrides
     *                                    for DAppDependency object that can be provided
     *                                    to test dependencies in    particular situations.
     *
     * @return    DHealthCheckResult    A warning or error, or null
     *                                if the dependency is satisfied.
     */
    protected function checkDependency(DDependency $dependency, array $versions)
    {
        // Override the current state if required.
        if ($dependency instanceof DAppDependency
            && isset($versions[ $dependency->getName() ])
        ) {
            $dependency->setCurrentState($versions[ $dependency->getName() ]);
        }
        // Test the dependencies.
        $test = $dependency->test();
        if ($test->hasMessages()) {
            $messages = $test->getMessages();
            $currentState = $dependency->getCurrentState();
            if ($currentState) {
                $message = "{$messages[0]} Current environment: {$currentState}";
            } else {
                $message = $messages[0];
            }
        }
        if (!$test->isSuccessful()) {
            $result = new DHealthCheckResult(
                DHealthCheckResult::HEALTH_CHECK_ERROR,
                $message
            );
        } else {
            if ($test->hasMessages()) {
                $result = new DHealthCheckResult(
                    DHealthCheckResult::HEALTH_CHECK_WARNING,
                    $message
                );
            } else {
                $result = null;
            }
        }

        return $result;
    }

    /**
     * Returns the name of the author of the App represented by this manifest.
     *
     * This function will return the name of the first author listed
     * in the manifest.
     *
     * @return    string    The author's name, or null if there is no author
     *                    information in the manifest.
     */
    public function getAuthorName()
    {
        $query = $this->query('//manifest/authors/author/name');
        if ($query->length) {
            $authorName = $query->item(0)->textContent;
        } else {
            $authorName = null;
        }

        return $authorName;
    }

    /**
     * Returns copyright information for the App represented by this manifest.
     *
     * @return    string    The copyright information, or null if there is no
     *                    copyright information in the manifest.
     */
    public function getCopyright()
    {
        $query = $this->query('//manifest/copyright');
        if ($query->length) {
            $copyright = $query->item(0)->textContent;
        } else {
            $copyright = null;
        }

        return $copyright;
    }

    /**
     * Returns the dependencies defined by this manifest.
     *
     * @param    string $type     If specified, only dependencies matching this qualified
     *                            name will be returned.
     *
     * @return    array    List of {@link app::decibel::packaging::DDependency DDependency}
     *                    objects.
     */
    public function getDependencies($type = null)
    {
        $queryPath = '//manifest/dependencies/dependency';
        if ($type !== null) {
            $queryPath .= "[@type='{$type}']";
        }
        // Find dependencies within the manifest.
        $dependencies = array();
        foreach ($this->query($queryPath) as $dependency) {
            /* @var $dependency DOMElement */
            $dependencies[] = DDependency::createFromXml($dependency);
        }

        return $dependencies;
    }

    /**
     * Returns the name of the file from which this manifest was loaded.
     *
     * @return    string
     */
    public function getFilename()
    {
        return $this->filename;
    }

    /**
     * Determines the location of the manifest file for a specified App.
     *
     * @note
     * This method does not validate the provided qualified name.
     *
     * @param    string $qualifiedName    Qualified name of the App to locate
     *                                    the manifest file for.
     *
     * @return    string
     */
    protected static function getManifestFilename($qualifiedName)
    {
        $path = str_replace(array('\\', '/'), DIRECTORY_SEPARATOR, $qualifiedName);
        return (DECIBEL_PATH . $path . '.manifest.xml');
    }

    /**
     * Returns the name of the App represented by this manifest.
     *
     * @return    string
     * @throws    DMissingAppManifestDataException    If the name is missing
     *                                                from the manifest.
     */
    public function getName()
    {
        $query = $this->query('//manifest/name');
        if ($query->length) {
            return $query->item(0)->textContent;
        }
        throw new DMissingAppManifestDataException(
            $this->filename,
            self::ELEMENT_NAME
        );
    }

    /**
     * Returns the URL for the repository that contains updates for the App
     * represented by this manifest.
     *
     * @return    string    The repository URL, or null if there is no respority
     *                    information in the manifest.
     */
    public function getRepositoryUrl()
    {
        $query = $this->query('//manifest/respository/location');
        if ($query->length) {
            $url = $query->item(0)->textContent;
        } else {
            $url = null;
        }

        return $url;
    }

    /**
     * Returns the update method supported by the App represented
     * by this manifest.
     *
     * @return    string    The update method, or 'manual' if there is no
     *                    update method in the manifest.
     */
    public function getUpdateMethod()
    {
        $query = $this->query('//manifest/respository[@method]');
        if ($query->length) {
            $method = $query->item(0)->getAttribute('method');
        } else {
            $method = 'manual';
        }

        return $method;
    }

    /**
     * Returns the version for the App represented by this manifest.
     *
     * @return    string
     * @throws    DMissingAppManifestDataException    If the version is missing
     *                                                from the manifest.
     */
    public function getVersion()
    {
        $query = $this->query('//manifest/version');
        if ($query->length) {
            return $query->item(0)->textContent;
        }
        throw new DMissingAppManifestDataException(
            $this->filename,
            self::ELEMENT_VERSION
        );
    }
}


text:
package com.amazonaws.services.datapipeline.model.transform;

import java.util.Map;
import java.util.List;

import com.amazonaws.AmazonClientException;
import com.amazonaws.services.datapipeline.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.util.BinaryUtils;
import com.amazonaws.util.StringUtils;
import com.amazonaws.util.IdempotentUtils;
import com.amazonaws.util.StringInputStream;
import com.amazonaws.util.json.*;

/**
 * ValidationErrorMarshaller
 */
public class ValidationErrorJsonMarshaller {

    /**
     * Marshall the given parameter object, and output to a SdkJsonGenerator
     */
    public void marshall(ValidationError validationError,
            StructuredJsonGenerator jsonGenerator) {

        if (validationError == null) {
            throw new AmazonClientException(
                    "Invalid argument passed to marshall(...)");
        }

        try {
            jsonGenerator.writeStartObject();

            if (validationError.getId() != null) {
                jsonGenerator.writeFieldName("id").writeValue(
                        validationError.getId());
            }

            com.amazonaws.internal.SdkInternalList<String> errorsList = (com.amazonaws.internal.SdkInternalList<String>) validationError
                    .getErrors();
            if (!errorsList.isEmpty() || !errorsList.isAutoConstruct()) {
                jsonGenerator.writeFieldName("errors");
                jsonGenerator.writeStartArray();
                for (String errorsListValue : errorsList) {
                    if (errorsListValue != null) {
                        jsonGenerator.writeValue(errorsListValue);
                    }
                }
                jsonGenerator.writeEndArray();
            }

            jsonGenerator.writeEndObject();
        } catch (Throwable t) {
            throw new AmazonClientException(
                    "Unable to marshall request to JSON: " + t.getMessage(), t);
        }
    }

    private static ValidationErrorJsonMarshaller instance;

    public static ValidationErrorJsonMarshaller getInstance() {
        if (instance == null)
            instance = new ValidationErrorJsonMarshaller();
        return instance;
    }

}


text:
package org.apache.twill.internal.appmaster;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterators;
import com.google.common.collect.Maps;
import org.apache.hadoop.yarn.api.records.Resource;
import org.apache.twill.api.RuntimeSpecification;
import org.apache.twill.api.TwillSpecification;

import java.util.Collection;
import java.util.Iterator;
import java.util.Map;

/**
 * Data structure for holding set of runnable specifications based on resource capability.
 */
final class RunnableContainerRequest {
  private final TwillSpecification.Order.Type orderType;
  private final Iterator<Map.Entry<AllocationSpecification, Collection<RuntimeSpecification>>> requests;
  private volatile boolean isReadyToBeProvisioned;

  RunnableContainerRequest(TwillSpecification.Order.Type orderType,
                           Map<AllocationSpecification, Collection<RuntimeSpecification>> requests) {
    this(orderType, requests, true);
  }

  RunnableContainerRequest(TwillSpecification.Order.Type orderType,
                           Map<AllocationSpecification, Collection<RuntimeSpecification>> requests,
                           boolean isReadyToBeProvisioned) {
    this.orderType = orderType;
    this.requests = requests.entrySet().iterator();
    this.isReadyToBeProvisioned = isReadyToBeProvisioned;
  }

  TwillSpecification.Order.Type getOrderType() {
    return orderType;
  }

  public boolean isReadyToBeProvisioned() {
    return isReadyToBeProvisioned;
  }

  public void setReadyToBeProvisioned(boolean isProvisioned) {
    this.isReadyToBeProvisioned = isProvisioned;
  }

  /**
   * Remove a resource request and return it.
   * @return The {@link Resource} and {@link Collection} of {@link RuntimeSpecification} or
   *         {@code null} if there is no more request.
   */
  Map.Entry<AllocationSpecification, ? extends Collection<RuntimeSpecification>> takeRequest() {
    Map.Entry<AllocationSpecification, Collection<RuntimeSpecification>> next = Iterators.getNext(requests, null);
    return next == null ? null : Maps.immutableEntry(next.getKey(), ImmutableList.copyOf(next.getValue()));
  }
}


text:
module.exports = initSite

var createController = require('./controllers/controller')

function initSite() {
  return { notFound: [ 'article', 'section', 'sectionService', init ] }
}

function init(serviceLocator, done) {
  createController(serviceLocator)
  done()
}


text:
package org.kuali.kra.timeandmoney.history;

import org.kuali.rice.core.api.util.type.KualiDecimal;

import java.io.Serializable;
import java.sql.Date;

public class TimeAndMoneyActionSummary implements Serializable{

    private Date noticeDate;
    private String transactionType;
    private Date obligationStartDate;
    private Date obligationEndDate;
    private KualiDecimal obligationCumulative;
    private KualiDecimal changeAmount;

    /**
     * Gets the noticeDate attribute.
     * @return Returns the noticeDate.
     */
    public Date getNoticeDate() {
        return noticeDate;
    }
    /**
     * Sets the noticeDate attribute value.
     * @param noticeDate The noticeDate to set.
     */
    public void setNoticeDate(Date noticeDate) {
        this.noticeDate = noticeDate;
    }
    /**
     * Gets the transactionType attribute.
     * @return Returns the transactionType.
     */
    public String getTransactionType() {
        return transactionType;
    }
    /**
     * Sets the transactionType attribute value.
     * @param transactionType The transactionType to set.
     */
    public void setTransactionType(String transactionType) {
        this.transactionType = transactionType;
    }
    /**
     * Gets the obligationStartDate attribute.
     * @return Returns the obligationStartDate.
     */
    public Date getObligationStartDate() {
        return obligationStartDate;
    }
    /**
     * Sets the obligationStartDate attribute value.
     * @param obligationStartDate The obligationStartDate to set.
     */
    public void setObligationStartDate(Date obligationStartDate) {
        this.obligationStartDate = obligationStartDate;
    }
    /**
     * Gets the obligationEndDate attribute.
     * @return Returns the obligationEndDate.
     */
    public Date getObligationEndDate() {
        return obligationEndDate;
    }
    /**
     * Sets the obligationEndDate attribute value.
     * @param obligationEndDate The obligationEndDate to set.
     */
    public void setObligationEndDate(Date obligationEndDate) {
        this.obligationEndDate = obligationEndDate;
    }
    /**
     * Gets the obligationCumulative attribute.
     * @return Returns the obligationCumulative.
     */
    public KualiDecimal getObligationCumulative() {
        return obligationCumulative;
    }
    /**
     * Sets the obligationCumulative attribute value.
     * @param obligationCumulative The obligationCumulative to set.
     */
    public void setObligationCumulative(KualiDecimal obligationCumulative) {
        this.obligationCumulative = obligationCumulative;
    }
    /**
     * Gets the changeAmount attribute.
     * @return Returns the changeAmount.
     */
    public KualiDecimal getChangeAmount() {
        return changeAmount;
    }
    /**
     * Sets the changeAmount attribute value.
     * @param changeAmount The changeAmount to set.
     */
    public void setChangeAmount(KualiDecimal changeAmount) {
        this.changeAmount = changeAmount;
    }

}


text:
package org.w3c.domts.level2.core;

import org.w3c.dom.*;

import org.w3c.domts.DOMTestCase;
import org.w3c.domts.DOMTestDocumentBuilderFactory;

/**
 *     The "removeNamedItemNS(namespaceURI,localName)" method for a
 *    NamedNodeMap should raise NOT_FOUND_ERR DOMException if
 *    there is no node with the specified namespaceURI and localName in this map.
 *
 *    Retrieve a list of elements with tag name "address".
 *    Access the second element from the list and get its attributes.
 *    Try to remove an attribute node with local name "domest"
 *    and namespace uri "http://www.usa.com" with
 *    method removeNamedItemNS(namespaceURI,localName).
 *    This should raise NOT_FOUND_ERR DOMException.
* @author NIST
* @author Mary Brady
* @see http://www.w3.org/TR/DOM-Level-2-Core/core#xpointer(id('ID-258A00AF')/constant[@name='NOT_FOUND_ERR'])
* @see http://www.w3.org/TR/DOM-Level-2-Core/core#ID-removeNamedItemNS
* @see http://www.w3.org/TR/DOM-Level-2-Core/core#xpointer(id('ID-removeNamedItemNS')/raises/exception[@name='DOMException']/descr/p[substring-before(.,':')='NOT_FOUND_ERR'])
*/
public final class removeNamedItemNS02 extends DOMTestCase {

   /**
    * Constructor.
    * @param factory document factory, may not be null
    * @throws org.w3c.domts.DOMTestIncompatibleException Thrown if test is not compatible with parser configuration
    */
   public removeNamedItemNS02(final DOMTestDocumentBuilderFactory factory)  throws org.w3c.domts.DOMTestIncompatibleException {
      super(factory);

    //
    //   check if loaded documents are supported for content type
    //
    String contentType = getContentType();
    preload(contentType, "staffNS", true);
    }

   /**
    * Runs the test case.
    * @throws Throwable Any uncaught exception causes test to fail
    */
   public void runTest() throws Throwable {
      String namespaceURI = "http://www.usa.com";
      String localName = "domest";
      Document doc;
      NodeList elementList;
      Node testAddress;
      NamedNodeMap attributes;
      Node removedNode;
      doc = (Document) load("staffNS", true);
      elementList = doc.getElementsByTagName("address");
      testAddress = elementList.item(1);
      attributes = testAddress.getAttributes();

      {
         boolean success = false;
         try {
            removedNode = attributes.removeNamedItemNS(namespaceURI, localName);
          } catch (DOMException ex) {
            success = (ex.code == DOMException.NOT_FOUND_ERR);
         }
         assertTrue("throw_NOT_FOUND_ERR", success);
      }
}
   /**
    *  Gets URI that identifies the test.
    *  @return uri identifier of test
    */
   public String getTargetURI() {
      return "http://www.w3.org/2001/DOM-Test-Suite/level2/core/removeNamedItemNS02";
   }
   /**
    * Runs this test from the command line.
    * @param args command line arguments
    */
   public static void main(final String[] args) {
        DOMTestCase.doMain(removeNamedItemNS02.class, args);
   }
}


text:
namespace Dos.Common
{
    using System;

    public class EmailAccount
    {
        private string account;
        private string displayName;
        private bool enableSsl;
        private string host;
        private bool isUnnormal;
        private string password;
        private int port;

        public EmailAccount()
        {
            this.port = 0x19;
        }

        public EmailAccount(string account, string password, string host)
        {
            this.port = 0x19;
            this.host = host;
            this.password = password;
            this.account = account;
        }

        public EmailAccount(string account, string displayName, string password, string host)
        {
            this.port = 0x19;
            this.host = host;
            this.password = password;
            this.account = account;
            this.displayName = displayName;
        }

        public EmailAccount(string account, string displayName, string password, string host, int port, bool enableSsl, bool isUnnormal)
        {
            this.port = 0x19;
            this.host = host;
            this.password = password;
            this.account = account;
            this.displayName = displayName;
            this.port = port;
            this.enableSsl = enableSsl;
            this.isUnnormal = isUnnormal;
        }

        public string Account
        {
            get
            {
                return this.account;
            }
            set
            {
                this.account = value;
            }
        }

        public string DisplayName
        {
            get
            {
                return this.displayName;
            }
            set
            {
                this.displayName = value;
            }
        }

        public bool EnableSsl
        {
            get
            {
                return this.enableSsl;
            }
            set
            {
                this.enableSsl = value;
            }
        }

        public string Host
        {
            get
            {
                return this.host;
            }
            set
            {
                this.host = value;
            }
        }

        public bool IsUnnormal
        {
            get
            {
                return this.isUnnormal;
            }
            set
            {
                this.isUnnormal = value;
            }
        }

        public string Password
        {
            get
            {
                return this.password;
            }
            set
            {
                this.password = value;
            }
        }

        public int Port
        {
            get
            {
                return this.port;
            }
            set
            {
                this.port = value;
            }
        }
    }
}


text:
/**
 * Param3_Helper.java
 *
 * This file was auto-generated from WSDL
 * by the Apache Axis 1.4 Apr 22, 2006 (06:55:48 PDT) WSDL2Java emitter.
 */

package org.springframework.ws.axis1.case2.contractfirst.document_encoded_12_arraysplain;

public class Param3_Helper {
    // Type metadata
    private static org.apache.axis.description.TypeDesc typeDesc =
        new org.apache.axis.description.TypeDesc(Param3.class, true);

    static {
        typeDesc.setXmlType(new javax.xml.namespace.QName("http://codefirst.case2.axis1.ws.springframework.org", "Param3"));
        org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc();
        elemField.setFieldName("lvalue");
        elemField.setXmlName(new javax.xml.namespace.QName("http://codefirst.case2.axis1.ws.springframework.org", "lvalue"));
        elemField.setXmlType(new javax.xml.namespace.QName("http://schemas.xmlsoap.org/soap/encoding/", "long"));
        elemField.setNillable(true);
        typeDesc.addFieldDesc(elemField);
        elemField = new org.apache.axis.description.ElementDesc();
        elemField.setFieldName("svalue");
        elemField.setXmlName(new javax.xml.namespace.QName("http://codefirst.case2.axis1.ws.springframework.org", "svalue"));
        elemField.setXmlType(new javax.xml.namespace.QName("http://schemas.xmlsoap.org/soap/encoding/", "string"));
        elemField.setNillable(true);
        typeDesc.addFieldDesc(elemField);
    }

    /**
     * Return type metadata object
     */
    public static org.apache.axis.description.TypeDesc getTypeDesc() {
        return typeDesc;
    }

    /**
     * Get Custom Serializer
     */
    public static org.apache.axis.encoding.Serializer getSerializer(
           java.lang.String mechType,
           java.lang.Class _javaType,
           javax.xml.namespace.QName _xmlType) {
        return
          new  org.apache.axis.encoding.ser.BeanSerializer(
            _javaType, _xmlType, typeDesc);
    }

    /**
     * Get Custom Deserializer
     */
    public static org.apache.axis.encoding.Deserializer getDeserializer(
           java.lang.String mechType,
           java.lang.Class _javaType,
           javax.xml.namespace.QName _xmlType) {
        return
          new  org.apache.axis.encoding.ser.BeanDeserializer(
            _javaType, _xmlType, typeDesc);
    }

}


text:
{% import 'admin/static.html' as admin_static with context %}

{% macro dropdown(actions, btn_class='btn dropdown-toggle') -%}
    {{ _gettext('With selected') }}

        {% for p in actions %}

            {{ _gettext(p[1]) }}

        {% endfor %}

{% endmacro %}

{% macro form(actions, url) %}
    {% if actions %}
    <form id="action_form" action="{{ url }}" method="POST" style="display: none">
        {% if csrf_token %}
        <input type="hidden" name="csrf_token" value="{{ csrf_token() }}"/>
        {% endif %}
        <input type="hidden" id="action" name="action" />
    </form>
    {% endif %}
{% endmacro %}

{% macro script(message, actions, actions_confirmation) %}
    {% if actions %}

    {% endif %}
{% endmacro %}


text:
/* ────────╮
 │ truwrap │ Smarter 24bit SGR aware console text wrapping
 ╰─────────┴─────────────────────────────────────────────────────────────────── */

import columnify from 'columnify'
import createWrapTool from './lib/wrap-tool.js'
import createImage from './lib/image.js'
import parsePanel from './lib/panel.js'

/**
 * Truwrap - take input from write() and composed a wrapped text block.
 *
 * @class      Truwrap (name)
 */
export class Truwrap {
	/**
	 * The base Truwrap instance/api
	 *
	 * @param      {Object}           options                options object
	 * @param      {number}           [options.left=2]       Left margin.
	 * @param      {number}           [options.right=2]      Right margin.
	 * @param      {number}           options.width          Manually set view width.
	 * @param      {string}           [options.mode='soft']  [soft | hyphen | hard | keep | container
	 * @param      {number}           [options.tabWidth=4]   Desired width of TAB character.
	 * @param      {Stream.writable}  options.outStream      Where to direct output.
	 * @param      {Regexp}           options.tokenRegex     Override the tokenisers regexp.
	 */
	constructor({
		left = 2,
		right = 2,
		width,
		mode = 'soft',
		tabWidth = 4,
		outStream,
		tokenRegex
	}) {
		this.outStream = outStream
		this.buffer = ''
		this.mode = mode

		this.ttyActive = Boolean(width || (outStream && outStream.isTTY) || /keep|container/.test(mode))

		this.ttyWidth = (() => {
			if (width) {
				return width
			}

			if (outStream && outStream.isTTY) {
				return outStream.columns || outStream.getWindowSize()[0]
			}

			return 80
		})()

		this.viewWidth = (() => {
			if (this.ttyWidth - left - right > 1) {
				return this.ttyWidth - left - right
			}

			return 2
		})()

		this.viewHandler = (() => {
			if (this.ttyActive && mode !== 'container') {
				return createWrapTool({
					mode: this.mode,
					left,
					width: this.viewWidth,
					tabWidth,
					tokenRegex
				})
			}

			return {}
		})()
	}

	/**
	 * End a block, setting blocking mode and flushing buffers if needed.
	 *
	 * @return     {string}  The wrapped output, has side effect of writing to stream if defined.
	 */
	end() {
		if (this.outStream) {
			if (this.outStream._isStdio) {
				this.outStream.write('\n')
			} else {
				this.outStream.end()
			}
		}

		const output = this.buffer
		this.buffer=''

		return output
	}

	/**
	 * Fetch the width in characters of the wrapping view.
	 *
	 * @return     {number}  The width.
	 */
	getWidth() {
		switch (true) {
			case !this.ttyActive:
				return this.ttyWidth
			case this.mode === 'container':
				return this.ttyWidth
			default:
				return this.viewWidth
		}
	}

	/**
	 * Create a multicolumn panel within this view
	 *
	 * @param      {panelObject}  content_       Object for columnify
	 * @param      {Object}       configuration  Configuration for columnify
	 * @return     {Object}       this instance, to allow chaining
	 */
	panel(content_, configuration) {
		const content = (() => {
			switch (true) {
				case !this.ttyActive:
					return columnify(content_, configuration)
				case this.mode === 'container':
					return columnify(content_, configuration)
				default:
					return this.viewHandler.wrap(columnify(content_, configuration))
			}
		})()

		if (this.outStream) {
			this.outStream.write(content)
		}

		this.buffer += content

		return this
	}

	/**
	 * Generate linebreaks within this view
	 *
	 * @param  {number} newlines   number of new lines to add.
	 * @return {Object} this instance, to allow chaining
	 */
	break(newlines = 1) {
		const content = '\n'.repeat(newlines)
		if (this.outStream) {
			this.outStream.write(content)
		}

		this.buffer += content

		return this
	}

	/**
	 * Similar to css' clear. Write a clearing newline to the stream.
	 *
	 * @return     {Object}  this instance, to allow chaining
	 */
	clear() {
		const content = '\n'
		if (this.outStream) {
			this.outStream.write(content)
		}

		this.buffer += content

		return this
	}

	/**
	 * Write text via the wrapping logic
	 *
	 * @param      {string}  content_  The content
	 * @return     {Object}  this instance, to allow chaining
	 */
	write(content_) {
		const content = (() => {
			switch (true) {
				case !this.ttyActive:
					return content_
				case this.mode === 'container':
					return content_
				default:
					return this.viewHandler.wrap(content_)
			}
		})()

		if (this.outStream) {
			this.outStream.write(content)
		}

		this.buffer += content

		return this
	}
}

/**
 * Create a text wrapping instance.
 *
 * @param      {Object}           options                options object
 * @param      {number}           [options.left=2]       Left margin.
 * @param      {number}           [options.right=2]      Right margin.
 * @param      {number}           options.width          Manually set view width.
 * @param      {string}           [options.mode='soft']  [soft | hyphen | hard | keep | container
 * @param      {number}           [options.tabWidth=4]   Desired width of TAB character.
 * @param      {Stream.writable}  options.outStream      Where to direct output.
 * @param      {Regexp}           options.tokenRegex     Override the tokenisers regexp.
 * @return     {Truwrap}  { description_of_the_return_value }

 */
export function truwrap(options) {
	return new Truwrap(options)
}

export {createImage, parsePanel}


text:
package kubectl

import (
	"bytes"
	"errors"
	"io"
	"io/ioutil"
	"net/http"
	"reflect"
	"strings"
	"testing"

	"github.com/GoogleCloudPlatform/kubernetes/pkg/api"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/api/testapi"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/client"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/labels"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/runtime"
)

func objBody(obj runtime.Object) io.ReadCloser {
	return ioutil.NopCloser(bytes.NewReader([]byte(runtime.EncodeOrDie(testapi.Codec(), obj))))
}

// splitPath returns the segments for a URL path.
func splitPath(path string) []string {
	path = strings.Trim(path, "/")
	if path == "" {
		return []string{}
	}
	return strings.Split(path, "/")
}

func TestRESTHelperDelete(t *testing.T) {
	tests := []struct {
		Err     bool
		Req     func(*http.Request) bool
		Resp    *http.Response
		HttpErr error
	}{
		{
			HttpErr: errors.New("failure"),
			Err:     true,
		},
		{
			Resp: &http.Response{
				StatusCode: http.StatusNotFound,
				Body:       objBody(&api.Status{Status: api.StatusFailure}),
			},
			Err: true,
		},
		{
			Resp: &http.Response{
				StatusCode: http.StatusOK,
				Body:       objBody(&api.Status{Status: api.StatusSuccess}),
			},
			Req: func(req *http.Request) bool {
				if req.Method != "DELETE" {
					t.Errorf("unexpected method: %#v", req)
					return false
				}
				parts := splitPath(req.URL.Path)
				if parts[1] != "bar" {
					t.Errorf("url doesn't contain namespace: %#v", req)
					return false
				}
				if parts[2] != "foo" {
					t.Errorf("url doesn't contain name: %#v", req)
					return false
				}
				return true
			},
		},
	}
	for _, test := range tests {
		client := &client.FakeRESTClient{
			Codec: testapi.Codec(),
			Resp:  test.Resp,
			Err:   test.HttpErr,
		}
		modifier := &RESTHelper{
			RESTClient: client,
		}
		err := modifier.Delete("bar", "foo")
		if (err != nil) != test.Err {
			t.Errorf("unexpected error: %t %v", test.Err, err)
		}
		if err != nil {
			continue
		}
		if test.Req != nil && !test.Req(client.Req) {
			t.Errorf("unexpected request: %#v", client.Req)
		}
	}
}

func TestRESTHelperCreate(t *testing.T) {
	expectPost := func(req *http.Request) bool {
		if req.Method != "POST" {
			t.Errorf("unexpected method: %#v", req)
			return false
		}
		parts := splitPath(req.URL.Path)
		if parts[1] != "bar" {
			t.Errorf("url doesn't contain namespace: %#v", req)
			return false
		}
		return true
	}

	tests := []struct {
		Resp     *http.Response
		RespFunc client.HTTPClientFunc
		HttpErr  error
		Modify   bool
		Object   runtime.Object

		ExpectObject runtime.Object
		Err          bool
		Req          func(*http.Request) bool
	}{
		{
			HttpErr: errors.New("failure"),
			Err:     true,
		},
		{
			Resp: &http.Response{
				StatusCode: http.StatusNotFound,
				Body:       objBody(&api.Status{Status: api.StatusFailure}),
			},
			Err: true,
		},
		{
			Resp: &http.Response{
				StatusCode: http.StatusOK,
				Body:       objBody(&api.Status{Status: api.StatusSuccess}),
			},
			Object:       &api.Pod{ObjectMeta: api.ObjectMeta{Name: "foo"}},
			ExpectObject: &api.Pod{ObjectMeta: api.ObjectMeta{Name: "foo"}},
			Req:          expectPost,
		},
		{
			Modify:       false,
			Object:       &api.Pod{ObjectMeta: api.ObjectMeta{Name: "foo", ResourceVersion: "10"}},
			ExpectObject: &api.Pod{ObjectMeta: api.ObjectMeta{Name: "foo", ResourceVersion: "10"}},
			Resp:         &http.Response{StatusCode: http.StatusOK, Body: objBody(&api.Status{Status: api.StatusSuccess})},
			Req:          expectPost,
		},
		{
			Modify:       true,
			Object:       &api.Pod{ObjectMeta: api.ObjectMeta{Name: "foo", ResourceVersion: "10"}},
			ExpectObject: &api.Pod{ObjectMeta: api.ObjectMeta{Name: "foo"}},
			Resp:         &http.Response{StatusCode: http.StatusOK, Body: objBody(&api.Status{Status: api.StatusSuccess})},
			Req:          expectPost,
		},
	}
	for i, test := range tests {
		client := &client.FakeRESTClient{
			Codec: testapi.Codec(),
			Resp:  test.Resp,
			Err:   test.HttpErr,
		}
		if test.RespFunc != nil {
			client.Client = test.RespFunc
		}
		modifier := &RESTHelper{
			RESTClient: client,
			Codec:      testapi.Codec(),
			Versioner:  testapi.MetadataAccessor(),
		}
		data := []byte{}
		if test.Object != nil {
			data = []byte(runtime.EncodeOrDie(testapi.Codec(), test.Object))
		}
		err := modifier.Create("bar", test.Modify, data)
		if (err != nil) != test.Err {
			t.Errorf("%d: unexpected error: %t %v", i, test.Err, err)
		}
		if err != nil {
			continue
		}
		if test.Req != nil && !test.Req(client.Req) {
			t.Errorf("%d: unexpected request: %#v", i, client.Req)
		}
		body, err := ioutil.ReadAll(client.Req.Body)
		if err != nil {
			t.Fatalf("%d: unexpected error: %#v", i, err)
		}
		t.Logf("got body: %s", string(body))
		expect := []byte{}
		if test.ExpectObject != nil {
			expect = []byte(runtime.EncodeOrDie(testapi.Codec(), test.ExpectObject))
		}
		if !reflect.DeepEqual(expect, body) {
			t.Errorf("%d: unexpected body: %s", i, string(body))
		}

	}
}

func TestRESTHelperGet(t *testing.T) {
	tests := []struct {
		Err     bool
		Req     func(*http.Request) bool
		Resp    *http.Response
		HttpErr error
	}{
		{
			HttpErr: errors.New("failure"),
			Err:     true,
		},
		{
			Resp: &http.Response{
				StatusCode: http.StatusNotFound,
				Body:       objBody(&api.Status{Status: api.StatusFailure}),
			},
			Err: true,
		},
		{
			Resp: &http.Response{
				StatusCode: http.StatusOK,
				Body:       objBody(&api.Pod{ObjectMeta: api.ObjectMeta{Name: "foo"}}),
			},
			Req: func(req *http.Request) bool {
				if req.Method != "GET" {
					t.Errorf("unexpected method: %#v", req)
					return false
				}
				parts := splitPath(req.URL.Path)
				if parts[1] != "bar" {
					t.Errorf("url doesn't contain namespace: %#v", req)
					return false
				}
				if parts[2] != "foo" {
					t.Errorf("url doesn't contain name: %#v", req)
					return false
				}
				return true
			},
		},
	}
	for _, test := range tests {
		client := &client.FakeRESTClient{
			Codec: testapi.Codec(),
			Resp:  test.Resp,
			Err:   test.HttpErr,
		}
		modifier := &RESTHelper{
			RESTClient: client,
		}
		obj, err := modifier.Get("bar", "foo", labels.Everything())
		if (err != nil) != test.Err {
			t.Errorf("unexpected error: %t %v", test.Err, err)
		}
		if err != nil {
			continue
		}
		if obj.(*api.Pod).Name != "foo" {
			t.Errorf("unexpected object: %#v", obj)
		}
		if test.Req != nil && !test.Req(client.Req) {
			t.Errorf("unexpected request: %#v", client.Req)
		}
	}
}

func TestRESTHelperUpdate(t *testing.T) {
	expectPut := func(req *http.Request) bool {
		if req.Method != "PUT" {
			t.Errorf("unexpected method: %#v", req)
			return false
		}
		parts := splitPath(req.URL.Path)
		if parts[1] != "bar" {
			t.Errorf("url doesn't contain namespace: %#v", req.URL)
			return false
		}
		if parts[2] != "foo" {
			t.Errorf("url doesn't contain name: %#v", req)
			return false
		}
		return true
	}

	tests := []struct {
		Resp      *http.Response
		RespFunc  client.HTTPClientFunc
		HttpErr   error
		Overwrite bool
		Object    runtime.Object

		ExpectObject runtime.Object
		Err          bool
		Req          func(*http.Request) bool
	}{
		{
			HttpErr: errors.New("failure"),
			Err:     true,
		},
		{
			Object: &api.Pod{ObjectMeta: api.ObjectMeta{Name: "foo"}},
			Resp: &http.Response{
				StatusCode: http.StatusNotFound,
				Body:       objBody(&api.Status{Status: api.StatusFailure}),
			},
			Err: true,
		},
		{
			Object:       &api.Pod{ObjectMeta: api.ObjectMeta{Name: "foo"}},
			ExpectObject: &api.Pod{ObjectMeta: api.ObjectMeta{Name: "foo"}},
			Resp: &http.Response{
				StatusCode: http.StatusOK,
				Body:       objBody(&api.Status{Status: api.StatusSuccess}),
			},
			Req: expectPut,
		},
		{
			Object:       &api.Pod{ObjectMeta: api.ObjectMeta{Name: "foo"}},
			ExpectObject: &api.Pod{ObjectMeta: api.ObjectMeta{Name: "foo", ResourceVersion: "10"}},

			Overwrite: true,
			RespFunc: func(req *http.Request) (*http.Response, error) {
				if req.Method == "PUT" {
					return &http.Response{StatusCode: http.StatusOK, Body: objBody(&api.Status{Status: api.StatusSuccess})}, nil
				}
				return &http.Response{StatusCode: http.StatusOK, Body: objBody(&api.Pod{ObjectMeta: api.ObjectMeta{Name: "foo", ResourceVersion: "10"}})}, nil
			},
			Req: expectPut,
		},
		{
			Object:       &api.Pod{ObjectMeta: api.ObjectMeta{Name: "foo", ResourceVersion: "10"}},
			ExpectObject: &api.Pod{ObjectMeta: api.ObjectMeta{Name: "foo", ResourceVersion: "10"}},
			Resp:         &http.Response{StatusCode: http.StatusOK, Body: objBody(&api.Status{Status: api.StatusSuccess})},
			Req:          expectPut,
		},
	}
	for i, test := range tests {
		client := &client.FakeRESTClient{
			Codec: testapi.Codec(),
			Resp:  test.Resp,
			Err:   test.HttpErr,
		}
		if test.RespFunc != nil {
			client.Client = test.RespFunc
		}
		modifier := &RESTHelper{
			RESTClient: client,
			Codec:      testapi.Codec(),
			Versioner:  testapi.MetadataAccessor(),
		}
		data := []byte{}
		if test.Object != nil {
			data = []byte(runtime.EncodeOrDie(testapi.Codec(), test.Object))
		}
		err := modifier.Update("bar", "foo", test.Overwrite, data)
		if (err != nil) != test.Err {
			t.Errorf("%d: unexpected error: %t %v", i, test.Err, err)
		}
		if err != nil {
			continue
		}
		if test.Req != nil && !test.Req(client.Req) {
			t.Errorf("%d: unexpected request: %#v", i, client.Req)
		}
		body, err := ioutil.ReadAll(client.Req.Body)
		if err != nil {
			t.Fatalf("%d: unexpected error: %#v", i, err)
		}
		t.Logf("got body: %s", string(body))
		expect := []byte{}
		if test.ExpectObject != nil {
			expect = []byte(runtime.EncodeOrDie(testapi.Codec(), test.ExpectObject))
		}
		if !reflect.DeepEqual(expect, body) {
			t.Errorf("%d: unexpected body: %s", i, string(body))
		}
	}
}


text:
/** @jsx omom.h */
import omom     from '../../../../index'
import emit     from '../actions/todoAction'
import TodoItem from './todoItem'

const filters = {
  all() { return true }
, active(item) { return !item.get('complete') }
, completed(item) { return item.get('complete') }
}

export default omom.component((root /* cursor */) => {
  const items  = root.cursor('items')
  const filter = filters[root.cursor('filter').deref()]

  let todos          = []
  let areAllComplete = true
  items.forEach((item /* cursor */) => {
    if (filter(item)) {
      // passon sub cursor
      todos.push(<TodoItem {...item} />)
    }
    areAllComplete = areAllComplete && item.get('complete')
  })

  return (

      <input
        id="toggle-all"
        type="checkbox"
        onchange={emit.toggleAll.bind(emit, !areAllComplete)}
        checked={areAllComplete}
      />

{todos}

  )
})


text:
"""Constants for SavedModel save and restore operations.

"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

from tensorflow.python.util.tf_export import tf_export

# Subdirectory name containing the asset files.
ASSETS_DIRECTORY = "assets"
tf_export(
    "saved_model.ASSETS_DIRECTORY",
    v1=[
        "saved_model.ASSETS_DIRECTORY", "saved_model.constants.ASSETS_DIRECTORY"
    ]).export_constant(__name__, "ASSETS_DIRECTORY")

# Subdirectory name containing unmanaged files from higher-level APIs.
EXTRA_ASSETS_DIRECTORY = "assets.extra"

# CollectionDef key containing SavedModel assets.
ASSETS_KEY = "saved_model_assets"
tf_export(
    "saved_model.ASSETS_KEY",
    v1=["saved_model.ASSETS_KEY",
        "saved_model.constants.ASSETS_KEY"]).export_constant(
            __name__, "ASSETS_KEY")

# CollectionDef key for the legacy init op.
LEGACY_INIT_OP_KEY = "legacy_init_op"
tf_export(
    v1=[
        "saved_model.LEGACY_INIT_OP_KEY",
        "saved_model.constants.LEGACY_INIT_OP_KEY"
    ]).export_constant(__name__, "LEGACY_INIT_OP_KEY")

# CollectionDef key for the SavedModel main op.
MAIN_OP_KEY = "saved_model_main_op"
tf_export(
    v1=["saved_model.MAIN_OP_KEY",
        "saved_model.constants.MAIN_OP_KEY"]).export_constant(
            __name__, "MAIN_OP_KEY")

# CollectionDef key for the SavedModel train op.
# Not exported while export_all_saved_models is experimental.
TRAIN_OP_KEY = "saved_model_train_op"

# Schema version for SavedModel.
SAVED_MODEL_SCHEMA_VERSION = 1
tf_export(
    "saved_model.SAVED_MODEL_SCHEMA_VERSION",
    v1=[
        "saved_model.SAVED_MODEL_SCHEMA_VERSION",
        "saved_model.constants.SAVED_MODEL_SCHEMA_VERSION"
    ]).export_constant(__name__, "SAVED_MODEL_SCHEMA_VERSION")

# File name for SavedModel protocol buffer.
SAVED_MODEL_FILENAME_PB = "saved_model.pb"
tf_export(
    "saved_model.SAVED_MODEL_FILENAME_PB",
    v1=[
        "saved_model.SAVED_MODEL_FILENAME_PB",
        "saved_model.constants.SAVED_MODEL_FILENAME_PB"
    ]).export_constant(__name__, "SAVED_MODEL_FILENAME_PB")

# File name for text version of SavedModel protocol buffer.
SAVED_MODEL_FILENAME_PBTXT = "saved_model.pbtxt"
tf_export(
    "saved_model.SAVED_MODEL_FILENAME_PBTXT",
    v1=[
        "saved_model.SAVED_MODEL_FILENAME_PBTXT",
        "saved_model.constants.SAVED_MODEL_FILENAME_PBTXT"
    ]).export_constant(__name__, "SAVED_MODEL_FILENAME_PBTXT")

# Subdirectory where debugging related files are written.
DEBUG_DIRECTORY = "debug"
tf_export(
    "saved_model.DEBUG_DIRECTORY",
    v1=[
        "saved_model.DEBUG_DIRECTORY",
        "saved_model.constants.DEBUG_DIRECTORY",
    ]).export_constant(__name__, "DEBUG_DIRECTORY")

# File name for GraphDebugInfo protocol buffer which corresponds to the
# SavedModel.
DEBUG_INFO_FILENAME_PB = "saved_model_debug_info.pb"
tf_export(
    "saved_model.DEBUG_INFO_FILENAME_PB",
    v1=[
        "saved_model.DEBUG_INFO_FILENAME_PB",
        "saved_model.constants.DEBUG_INFO_FILENAME_PB"
    ]).export_constant(__name__, "DEBUG_INFO_FILENAME_PB")

# File name for json format of SavedModel.
# Not exported while keras_saved_model is in contrib.
SAVED_MODEL_FILENAME_JSON = "saved_model.json"

# Subdirectory name containing the variables/checkpoint files.
VARIABLES_DIRECTORY = "variables"
tf_export(
    "saved_model.VARIABLES_DIRECTORY",
    v1=[
        "saved_model.VARIABLES_DIRECTORY",
        "saved_model.constants.VARIABLES_DIRECTORY"
    ]).export_constant(__name__, "VARIABLES_DIRECTORY")

# File name used for variables.
VARIABLES_FILENAME = "variables"
tf_export(
    "saved_model.VARIABLES_FILENAME",
    v1=[
        "saved_model.VARIABLES_FILENAME",
        "saved_model.constants.VARIABLES_FILENAME"
    ]).export_constant(__name__, "VARIABLES_FILENAME")

# The initialization and train ops for a MetaGraph are stored in the
# signature def map. The ops are added to the map with the following keys.
INIT_OP_SIGNATURE_KEY = "__saved_model_init_op"
TRAIN_OP_SIGNATURE_KEY = "__saved_model_train_op"


text:
var n: number = 5;
var foo = function(s: string): boolean {
  return true;
};
var niln: null | number = null;
var bar = function(s: null | string): null | boolean {
  return null;
};
var sn: string | number = 9;
var snb: string | null | number | boolean = false;
var manyNulls: null | string | number | string = null;
var baz = function(s: number | null | string): null | boolean {
  return null;
};


text:
#pragma once
#include <aws/s3/S3_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>

namespace Aws
{
namespace S3
{
namespace Model
{
  enum class ExpirationStatus
  {
    NOT_SET,
    Enabled,
    Disabled
  };

namespace ExpirationStatusMapper
{
AWS_S3_API ExpirationStatus GetExpirationStatusForName(const Aws::String& name);

AWS_S3_API Aws::String GetNameForExpirationStatus(ExpirationStatus value);
} // namespace ExpirationStatusMapper
} // namespace Model
} // namespace S3
} // namespace Aws


text:
var one = 'I am script one';
var two = function two(p) {
	return p;
};

console.log(two(one));