text:
package de.mobilej;

import org.gradle.api.logging.Logger;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;

import javassist.CannotCompileException;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtConstructor;
import javassist.CtMethod;
import javassist.Modifier;
import javassist.NotFoundException;
import javassist.expr.ExprEditor;
import javassist.expr.MethodCall;

/**
 * Here the heavy lifting happens.
 *
 * We take the all-android.jar and copy the wanted classes to the destination.
 *
 * The copied classes will be non-final/non-private and also all methods contained.
 *
 * Additionally all native methods will be changed to delegate to de.mobilej.ABridge.callXXX methods
 * for easier mocking.
 */
public class ProcessRealAndroidJar {

    public static void process(File allAndroidFile,
                               File outputDir,
                               File unmockedOutputJar,
                               String[] keepClasses,
                               String[] renameClasses,
                               String[] delegateClasses,
                               Logger logger) throws Exception {

        List<ClassMapping> classesToMap = parseClassesToMap(renameClasses, logger);

        List<String> keepClassesList = new ArrayList<>(Arrays.asList(keepClasses));
        for (ClassMapping mapping : classesToMap) {
            keepClassesList.add(mapping.from);
        }
        keepClasses = keepClassesList.toArray(new String[0]);

        delete(outputDir);
        outputDir.mkdirs();

        ArrayList<String> clazzNames = findAllClazzesIn(
                allAndroidFile.getAbsolutePath());

        ClassPool pool = new ClassPool(null);
        pool.appendSystemPath();

        pool.insertClassPath(allAndroidFile.getAbsolutePath());

        createHelperClasses(outputDir, pool);

        List<CtClass> clazzes = new ArrayList<>();

        for (String clazzName : clazzNames) {
            CtClass clazz = pool.get(clazzName);

            boolean keep = false;
            for (String keepClass : keepClasses) {
                if (keepClass.startsWith("-")) {
                    String pureKeepClassName = keepClass.substring(1);
                    if (clazz.getName().equals(pureKeepClassName)) {
                        keep = true;
                        break;
                    } else if (clazz.getName().startsWith(pureKeepClassName + "$")) {
                        keep = true;
                        break;
                    }

                } else {
                    if (clazz.getName().startsWith(keepClass)) {
                        keep = true;
                        break;
                    }
                }
            }

            boolean delegate = false;
            for (String delegateClazzName : delegateClasses) {
                if (clazz.getName().equals(delegateClazzName)) {
                    delegate = true;
                    break;
                } else if (clazz.getName().startsWith(delegateClazzName + "$")) {
                    delegate = true;
                    break;
                }
            }

            if (!keep && !delegate) {
                continue;
            }

            try {
                if (keep) {
                    process(clazz, classesToMap);
                } else if (delegate) {
                    processDelegate(clazz, classesToMap);
                }
            } catch (Exception e) {
                logger.error("-> unable to process", e);
            }

            clazzes.add(clazz);
        }

        // Write the files after all CtClass objects have been modified, otherwise Javassist
        // doesn't allow modifying a nested class when the outer class has been written already
        // (it freezes the outer class again).
        for (CtClass clazz : clazzes) {
            clazz.writeFile(outputDir.getAbsolutePath());
        }

        // copy over non-classes matching "keepStartsWith" paths
        ArrayList<String> toCopy = new ArrayList<>();
        ArrayList<String> nonClasses = findAllNonClassFilesIn(allAndroidFile.getAbsolutePath());
        for (String keep : keepClasses) {
            if (!keep.startsWith("-")) {
                for (String file : nonClasses) {
                    if (file.startsWith(keep.replace(".", "/"))) {
                        toCopy.add(file);
                    }
                }
            }
        }
        copyFromJarToDirectory(allAndroidFile.getAbsolutePath(), toCopy, outputDir.getAbsoluteFile());

        createJarArchive(unmockedOutputJar.getAbsolutePath(), outputDir.getAbsolutePath());

    }

    private static List<ClassMapping> parseClassesToMap(String[] renameClasses, Logger logger) {
        ArrayList<ClassMapping> result = new ArrayList<>();

        if (renameClasses == null) {
            return result;
        }

        for (String classRenaming : renameClasses) {
            int indexOfEquals = classRenaming.indexOf("=");
            if (indexOfEquals > 0 && indexOfEquals < classRenaming.length()) {
                String from = classRenaming.substring(0, indexOfEquals);
                String to = classRenaming.substring(indexOfEquals + 1);
                result.add(new ClassMapping(from, to));

            } else {
                logger.error("Unparseable mapping:" + classRenaming);
            }
        }

        return result;
    }

    public static boolean createJarArchive(String outfile, String srcFolder) throws Exception {

        FileOutputStream dest = new FileOutputStream(new File(outfile));

        JarOutputStream out = new JarOutputStream(new BufferedOutputStream(dest));

        addToJar(out, new File(srcFolder), new File(srcFolder));

        out.flush();
        out.close();

        return true;
    }

    private static void addToJar(JarOutputStream out, File folder, File root) throws Exception {
        File[] files = folder.listFiles();

        if (files == null) {
            return;
        }

        for (File f : files) {
            if (f.isDirectory()) {
                addToJar(out, f, root);
            } else {
                addJarEntry(out, f, root);
            }
        }
    }

    private static BufferedInputStream addJarEntry(ZipOutputStream out, File f, File root)
            throws IOException {
        int BUFFER = 2048;
        byte data[] = new byte[BUFFER];

        BufferedInputStream origin;
        FileInputStream fi = new FileInputStream(f);
        origin = new BufferedInputStream(fi, BUFFER);
        String name = f.getCanonicalPath().substring(root.getCanonicalPath().length() + 1).replace('\\', '/');
        JarEntry entry = new JarEntry(name);
        out.putNextEntry(entry);
        int count;
        while ((count = origin.read(data, 0, BUFFER)) != -1) {
            out.write(data, 0, count);
            out.flush();
        }

        origin.close();

        return origin;
    }

    private static void createHelperClasses(File out, ClassPool pool)
            throws CannotCompileException, IOException {
        CtClass bridge = pool.makeClass("de.mobilej.ABridge");

        bridge.addMethod(CtMethod.make(
                "public static Object callObject(String signature, Object thiz, Object[] args){" +
                        "return (Object)null;" +
                        "}", bridge));

        bridge.addMethod(CtMethod.make(
                "public static int callInt(String signature, Object thiz, Object[] args){" +
                        "return 0;" +
                        "}", bridge));

        bridge.addMethod(CtMethod.make(
                "public static long callLong(String signature, Object thiz, Object[] args){" +
                        "return 0L;" +
                        "}", bridge));

        bridge.addMethod(CtMethod.make(
                "public static boolean callBoolean(String signature, Object thiz, Object[] args){" +
                        "return false;" +
                        "}", bridge));

        bridge.addMethod(CtMethod.make(
                "public static byte callByte(String signature, Object thiz, Object[] args){" +
                        "return 0;" +
                        "}", bridge));

        bridge.addMethod(CtMethod.make(
                "public static float callFloat(String signature, Object thiz, Object[] args){" +
                        "return 0f;" +
                        "}", bridge));

        bridge.addMethod(CtMethod.make(
                "public static double callDouble(String signature, Object thiz, Object[] args){" +
                        "return 0d;" +
                        "}", bridge));

        bridge.addMethod(CtMethod.make(
                "public static void callVoid(String signature, Object thiz, Object[] args){" +
                        "return;" +
                        "}", bridge));

        bridge.writeFile(out.getAbsolutePath());
    }

    private static ArrayList<String> findAllClazzesIn(String file) throws IOException {
        ArrayList<String> res = new ArrayList<String>();

        ZipFile f = new ZipFile(file);
        Enumeration<? extends ZipEntry> entries = f.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            if (entry.getName().endsWith(".class")) {
                res.add(entry.getName().replace(".class", "").replace("/", "."));
            }

        }

        return res;
    }

    private static ArrayList<String> findAllNonClassFilesIn(String file) throws IOException {
        ArrayList<String> res = new ArrayList<String>();

        ZipFile f = new ZipFile(file);
        Enumeration<? extends ZipEntry> entries = f.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            if (!entry.isDirectory() && !entry.getName().endsWith(".class")) {
                res.add(entry.getName());
            }

        }

        return res;
    }

    private static void copyFromJarToDirectory(String file, List<String> files, File destDir) throws IOException {
        try (FileSystem fileSystem = FileSystems.newFileSystem(Paths.get(file), null)) {
            for (String toCopy : files) {
                Path source = fileSystem.getPath(toCopy);
                File dst = new File(destDir, toCopy);
                dst.getParentFile().mkdirs();
                Files.copy(source, dst.toPath());
            }
        }
    }

    private static void processDelegate(CtClass clazz, List<ClassMapping> classMappings) throws Exception {
        if (clazz.isInterface()) {
            return;
        }

        clazz.defrost();

        clazz.setModifiers(clazz.getModifiers() | Modifier.PUBLIC);
        clazz.setModifiers(clazz.getModifiers() & ~Modifier.FINAL);
        clazz.setModifiers(clazz.getModifiers() & ~Modifier.PRIVATE);
        clazz.setModifiers(clazz.getModifiers() & ~Modifier.PROTECTED);

        CtMethod[] methods = clazz.getDeclaredMethods();
        for (CtMethod m : methods) {
            // we delegate every method here
            delegateMethod(m);

            m.setModifiers(m.getModifiers() | Modifier.PUBLIC);
            m.setModifiers(m.getModifiers() & ~Modifier.FINAL);
            m.setModifiers(m.getModifiers() & ~Modifier.PRIVATE);
            m.setModifiers(m.getModifiers() & ~Modifier.PROTECTED);
            m.setModifiers(m.getModifiers() & ~Modifier.NATIVE);
        }

        CtConstructor[] ctors = clazz.getDeclaredConstructors();
        for (CtConstructor c : ctors) {
            // we also delegate every ctor here
            String signature = c.getLongName();
            String thiz = "$0";

            c.setBody("{ de.mobilej.ABridge.callVoid(\"" + signature + "\", " + thiz
                    + ", $args); } ");

            c.setModifiers(c.getModifiers() | Modifier.PUBLIC);
            c.setModifiers(c.getModifiers() & ~Modifier.FINAL);
            c.setModifiers(c.getModifiers() & ~Modifier.PRIVATE);
            c.setModifiers(c.getModifiers() & ~Modifier.PROTECTED);
            c.setModifiers(c.getModifiers() & ~Modifier.NATIVE);
        }

        for (ClassMapping mapping : classMappings) {
            clazz.replaceClassName(mapping.from, mapping.to);
        }
    }

    private static void delegateMethod(CtMethod m) throws NotFoundException, CannotCompileException {
        String signature = m.getLongName();
        String thiz = "$0";
        if ((m.getModifiers() & Modifier.STATIC) == Modifier.STATIC) {
            thiz = "null";
        }

        String retType = m.getReturnType().getName();

        switch (retType) {
            case "void":
                m.setBody("{ de.mobilej.ABridge.callVoid(\"" + signature + "\", " + thiz
                        + ", $args); } ");
                break;
            case "boolean":
                m.setBody(
                        "{ return de.mobilej.ABridge.callBoolean(\"" + signature + "\", "
                                + thiz
                                + ", $args); } ");
                break;
            case "int":
                m.setBody(
                        "{ return de.mobilej.ABridge.callInt(\"" + signature + "\", " + thiz
                                + ", $args); } ");
                break;
            case "long":
                m.setBody("{ return de.mobilej.ABridge.callLong(\"" + signature + "\", "
                        + thiz
                        + ", $args); } ");
                break;
            case "byte":
                m.setBody("{ return de.mobilej.ABridge.callByte(\"" + signature + "\", "
                        + thiz
                        + ", $args); } ");
                break;
            case "float":
                m.setBody("{ return de.mobilej.ABridge.callFloat(\"" + signature + "\", "
                        + thiz
                        + ", $args); } ");
                break;
            case "double":
                m.setBody("{ return de.mobilej.ABridge.callDouble(\"" + signature + "\", "
                        + thiz
                        + ", $args); } ");
                break;
            default:
                m.setBody(
                        "{ return ($r)de.mobilej.ABridge.callObject(\"" + signature + "\","
                                + thiz + ", $args); } ");
                break;
        }
    }

    private static void process(CtClass clazz, List<ClassMapping> classMappings) throws Exception {

        if (clazz.isInterface()) {
            return;
        }

        clazz.defrost();

        clazz.setModifiers(clazz.getModifiers() | Modifier.PUBLIC);
        clazz.setModifiers(clazz.getModifiers() & ~Modifier.FINAL);
        clazz.setModifiers(clazz.getModifiers() & ~Modifier.PRIVATE);
        clazz.setModifiers(clazz.getModifiers() & ~Modifier.PROTECTED);

        CtMethod[] methods = clazz.getDeclaredMethods();

        for (CtMethod m : methods) {

            // we change native to normal method but need to
            // delegate
            if ((m.getModifiers() & Modifier.NATIVE) == Modifier.NATIVE) {
                delegateMethod(m);
            } else {
                instumentMethod(m);
            }

            m.setModifiers(m.getModifiers() | Modifier.PUBLIC);
            m.setModifiers(m.getModifiers() & ~Modifier.FINAL);
            m.setModifiers(m.getModifiers() & ~Modifier.PRIVATE);
            m.setModifiers(m.getModifiers() & ~Modifier.PROTECTED);
            m.setModifiers(m.getModifiers() & ~Modifier.NATIVE);

        }

        for (ClassMapping mapping : classMappings) {
            clazz.replaceClassName(mapping.from, mapping.to);
        }
    }

    private static void instumentMethod(CtMethod m) throws CannotCompileException {
        m.instrument(new ExprEditor() {
            public void edit(MethodCall m) throws CannotCompileException {
                // special handling for System.arrraycopy and VMRuntime
                if (m.getClassName().equals("java.lang.System") && m.getMethodName().equals("arraycopy")) {
                    m.replace("{java.lang.System.arraycopy($1,$2,$3,$4,$5);}");
                } else if (m.getClassName().equals("dalvik.system.VMRuntime") && m.getMethodName().equals("newUnpaddedArray")) {
                    m.replace("{$_ = java.lang.reflect.Array.newInstance($1,$2);}");
                } else if (m.getClassName().equals("dalvik.system.VMRuntime") && m.getMethodName().equals("getRuntime")) {
                    m.replace("{$_ = null;}");
                }
            }
        });
    }

    public static boolean delete(File file) {
        File[] flist = null;

        if (file == null) {
            return false;
        }

        if (file.isFile()) {
            return file.delete();
        }

        if (!file.isDirectory()) {
            return false;
        }

        flist = file.listFiles();
        if (flist != null && flist.length > 0) {
            for (File f : flist) {
                if (!delete(f)) {
                    return false;
                }
            }
        }

        return file.delete();
    }

    public static class ClassMapping {
        public final String from;
        public final String to;

        public ClassMapping(String from, String to) {
            this.from = from;
            this.to = to;
        }
    }
}


text: module.exports=angular.module('main', []);

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Aoite.Samples
{
    class SampleUser
    {
        [Aoite.Data.Column(true)]
        public long Id { get; set; }
        public string Username { get; set; }
        public string Password { get; set; }
    }
}


text:
Shindo.tests("Fog::Compute[:brightbox] | DatabaseServer model", ["brightbox"]) do
  pending if Fog.mocking?

  @service = Fog::Compute[:brightbox]

  tests("success") do
    tests("#create") do
      test("a new database server is returned") do
        @database_server = @service.database_servers.create
        !@database_server.nil?
      end

      test("state is not nil") do
        !@database_server.state.nil?
      end

      test("database_version is not nil") do
        !@database_server.database_version.nil?
      end

      test("admin_username is not nil") do
        !@database_server.admin_username.nil?
      end

      test("admin_password is not nil") do
        !@database_server.admin_password.nil?
      end
    end

    @sample_identifier = @database_server.id
    pending if @sample_identifier.nil?

    tests("#all") do
      test("returns results") do
        @database_servers = @service.database_servers.all
        @database_servers.any? do |dbs|
          dbs.identity == @database_server.identity
        end
      end
    end

    tests("#get('#{@sample_identifier}')") do
      @database_server = @service.database_servers.get(@sample_identifier)

      @database_server.wait_for { ready? }

      test("admin_username is not nil") do
        !@database_server.admin_username.nil?
      end

      test("admin_password is nil") do
        @database_server.admin_password.nil?
      end
    end

    @database_server.wait_for { ready? }

    tests("#snapshot") do
      # Very messy but there is no feedback about if snapshotting or what the ID will be
      existing_snapshots = @service.database_snapshots.all.map(&:identity)
      test do
        @database_server.snapshot
      end

      current_snapshots = @service.database_snapshots.all.map(&:identity)
      snapshot_id = (current_snapshots - existing_snapshots).last

      @snapshot = @service.database_snapshots.get(snapshot_id)
      @snapshot.wait_for { ready? }
      @snapshot.destroy
    end

    # Can no longer destroy when snapshotting
    tests("#destroy") do
      @database_server.destroy
    end
  end
end


text:
class LoginController < ApplicationController

  before_filter :check_user, only: :destroy

  def index
    render_view
  end

  def try_auth
    bc_client = BitcoinRPC.new params[:username], params[:password]
    begin
      bc_client.getbalance
      session[:username] = params[:username]
      session[:password] = params[:password]
      redirect_to '/home'
    rescue
      @error = true
      render_view
    end
  end

  def dispatcher
    if session.has_key? :username
      redirect_to '/home'
    else
      redirect_to '/login'
    end
  end

  def destroy
    @bitcoin_client.walletlock
    reset_session
    redirect_to '/'
  end

  private

    def render_view
      render :index, layout: nil
    end

end


text:
if which swiftlint >/dev/null; then
    swiftlint autocorrect
    swiftlint
else
    echo "warning: SwiftLint not installed. Install using brew update && brew install swiftlint or download from https://github.com/realm/SwiftLint."
fi


text:
package objectserver

import (
	"errors"
	"fmt"
	"io"
	"io/ioutil"
	"math"
	"net/http"
	"os"
	"strconv"
	"sync"
	"sync/atomic"

	"github.com/troubling/hummingbird/common"
	"github.com/troubling/hummingbird/common/fs"
	"github.com/troubling/hummingbird/common/ring"
)

var _ Object = &repObject{}

type repObject struct {
	IndexDBItem
	reserve          int64
	asyncWG          *sync.WaitGroup
	idb              *IndexDB
	ring             ring.Ring
	policy           int
	loaded           bool
	atomicFileWriter fs.AtomicFileWriter
	metadata         map[string]string
	client           *http.Client
	txnId            string
}

func (ro *repObject) Metadata() map[string]string {
	return ro.metadata
}

func (ro *repObject) ContentLength() int64 {
	if contentLength, err := strconv.ParseInt(ro.metadata["Content-Length"], 10, 64); err != nil {
		return -1
	} else {
		return contentLength
	}
}

func (ro *repObject) Quarantine() error {
	return QuarantineItem(ro.idb, &ro.IndexDBItem)
}

func (ro *repObject) Exists() bool {
	if ro.Deletion == true {
		return false
	}
	return ro.Path != ""
}

func (ro *repObject) Copy(dsts ...io.Writer) (written int64, err error) {
	var f *os.File
	f, err = os.Open(ro.Path)
	if err != nil {
		return 0, err
	}
	if len(dsts) == 1 {
		written, err = io.Copy(dsts[0], f)
	} else {
		written, err = common.Copy(f, dsts...)
	}
	if f != nil {
		if err == nil {
			err = f.Close()
		} else {
			f.Close()
		}
	}
	return written, err
}

func (ro *repObject) CopyRange(w io.Writer, start int64, end int64) (int64, error) {
	f, err := os.Open(ro.Path)
	if err != nil {
		return 0, err
	}
	if _, err := f.Seek(start, os.SEEK_SET); err != nil {
		f.Close()
		return 0, err
	}
	written, err := common.CopyN(f, end-start, w)
	if err == nil {
		err = f.Close()
	} else {
		f.Close()
	}
	return written, err
}

func (ro *repObject) Repr() string {
	return fmt.Sprintf("repObject<%s, %d>", ro.Hash, ro.Timestamp)
}

func (ro *repObject) Uuid() string {
	return ro.Hash
}

func (ro *repObject) MetadataMd5() string {
	return ro.Metahash
}

func (ro *repObject) SetData(size int64) (io.Writer, error) {
	if ro.atomicFileWriter != nil {
		ro.atomicFileWriter.Abandon()
	}
	var err error
	ro.atomicFileWriter, err = ro.idb.TempFile(ro.Hash, roShard, math.MaxInt64, size, true)
	return ro.atomicFileWriter, err
}

func (ro *repObject) commit(metadata map[string]string, method string, nursery bool) error {
	var timestamp int64
	timestampStr, ok := metadata["X-Timestamp"]
	if !ok {
		return errors.New("no timestamp in metadata")
	}
	timestampTime, err := common.ParseDate(timestampStr)
	if err != nil {
		return err
	}
	timestamp = timestampTime.UnixNano()
	err = ro.idb.Commit(ro.atomicFileWriter, ro.Hash, roShard, timestamp, method, metadata, nursery, "")
	ro.atomicFileWriter = nil
	return err
}

func (ro *repObject) Commit(metadata map[string]string) error {
	return ro.commit(metadata, "PUT", true)
}

func (ro *repObject) Delete(metadata map[string]string) error {
	return ro.commit(metadata, "DELETE", true)
}

func (ro *repObject) CommitMetadata(metadata map[string]string) error {
	return ro.commit(metadata, "POST", ro.Nursery)
}

func (ro *repObject) Close() error {
	if ro.atomicFileWriter != nil {
		ro.atomicFileWriter.Abandon()
		ro.atomicFileWriter = nil
	}
	return nil
}

func (ro *repObject) isStable(dev *ring.Device) (bool, []*ring.Device, error) {
	if ro.Deletion {
		return false, nil, fmt.Errorf("you just send deletions")
	}
	partition, err := ro.ring.PartitionForHash(ro.Hash)
	if err != nil {
		return false, nil, err
	}
	nodes := ro.ring.GetNodes(partition)
	goodNodes := uint64(0)
	notFoundNodes := []*ring.Device{}
	for _, node := range nodes {
		if node.Ip == dev.Ip && node.Port == dev.Port && node.Device == dev.Device {
			goodNodes++
			continue
		}
		url := fmt.Sprintf("%s://%s:%d/%s/%d%s", node.Scheme, node.Ip, node.Port, node.Device, partition, common.Urlencode(ro.metadata["name"]))
		req, err := http.NewRequest("HEAD", url, nil)
		req.Header.Set("X-Backend-Storage-Policy-Index", strconv.FormatInt(int64(ro.policy), 10))
		req.Header.Set("User-Agent", "nursery-stabilizer")
		resp, err := ro.client.Do(req)
		if err == nil && (resp.StatusCode/100 == 2) &&
			resp.Header.Get("X-Timestamp") != "" &&
			resp.Header.Get("X-Timestamp") ==
				ro.metadata["X-Timestamp"] {
			goodNodes++
		} else {
			notFoundNodes = append(notFoundNodes, node)
		}
		if resp != nil {
			resp.Body.Close()
		}
	}
	return goodNodes == ro.ring.ReplicaCount(), notFoundNodes, nil
}

func (ro *repObject) stabilizeDelete(dev *ring.Device) error {
	partition, err := ro.ring.PartitionForHash(ro.Hash)
	if err != nil {
		return err
	}
	nodes := ro.ring.GetNodes(partition)
	var successes int64
	wg := sync.WaitGroup{}
	for _, node := range nodes {
		if node.Ip == dev.Ip && node.Port == dev.Port && node.Device == dev.Device {
			continue
		}
		req, err := http.NewRequest("DELETE", fmt.Sprintf("%s://%s:%d/rep-obj/%s/%s", node.Scheme, node.ReplicationIp, node.ReplicationPort, node.Device, ro.Hash), nil)
		if err != nil {
			return err
		}
		req.Header.Set("X-Timestamp", ro.metadata["X-Timestamp"])
		req.Header.Set("X-Backend-Storage-Policy-Index", strconv.Itoa(ro.policy))
		req.Header.Set("X-Trans-Id", ro.txnId)
		wg.Add(1)
		go func(req *http.Request) {
			defer wg.Done()
			if resp, err := ro.client.Do(req); err == nil {
				io.Copy(ioutil.Discard, resp.Body)
				resp.Body.Close()
				if resp.StatusCode/100 == 2 || resp.StatusCode == http.StatusConflict || resp.StatusCode == 404 {
					atomic.AddInt64(&successes, 1)
				}
			}
		}(req)
	}
	wg.Wait()
	if successes+1 != int64(len(nodes)) {
		return fmt.Errorf("could not stabilize DELETE to all primaries %d/%d", successes, len(nodes)-1)
	}
	_, err = ro.idb.Remove(ro.Hash, ro.Shard, ro.Timestamp, ro.Nursery, ro.Metahash)
	return err
}

func (ro *repObject) restabilize(dev *ring.Device) error {
	wg := sync.WaitGroup{}
	var successes int64
	partition, err := ro.ring.PartitionForHash(ro.Hash)
	if err != nil {
		return err
	}
	nodes := ro.ring.GetNodes(partition)
	for _, node := range nodes {
		if node.Ip == dev.Ip && node.Port == dev.Port && node.Device == dev.Device {
			continue
		}
		req, err := http.NewRequest("POST", fmt.Sprintf("%s://%s:%d/rep-obj/%s/%s", node.Scheme, node.ReplicationIp, node.ReplicationPort, node.Device, ro.Hash), nil)
		if err != nil {
			return err
		}
		req.Header.Set("X-Timestamp", ro.metadata["X-Timestamp"])
		req.Header.Set("X-Backend-Storage-Policy-Index", strconv.Itoa(ro.policy))
		req.Header.Set("X-Trans-Id", ro.txnId)
		for k, v := range ro.metadata {
			req.Header.Set("Meta-"+k, v)
		}
		wg.Add(1)
		go func(req *http.Request) {
			defer wg.Done()
			if resp, err := ro.client.Do(req); err == nil {
				io.Copy(ioutil.Discard, resp.Body)
				resp.Body.Close()
				if resp.StatusCode/100 == 2 || resp.StatusCode == http.StatusConflict {
					atomic.AddInt64(&successes, 1)
				}
			}
		}(req)
	}
	wg.Wait()
	if successes != int64(len(nodes)-1) {
		return fmt.Errorf("could not restabilize all primaries %d/%d", successes, len(nodes))
	}
	return ro.idb.SetStabilized(ro.Hash, ro.Shard, ro.Timestamp, false)
}

func (ro *repObject) Stabilize(dev *ring.Device) error {
	partition, err := ro.ring.PartitionForHash(ro.Hash)
	if err != nil {
		return err
	}
	if ro.Restabilize {
		return ro.restabilize(dev)
	}
	if !ro.Nursery {
		return nil
	}
	if ro.Deletion {
		return ro.stabilizeDelete(dev)
	}
	isStable, notFoundNodes, err := ro.isStable(dev)
	if err != nil {
		return err
	}
	if isStable {
		if _, isHandoff := ro.ring.GetJobNodes(partition, dev.Id); isHandoff {
			_, err = ro.idb.Remove(ro.Hash, ro.Shard, ro.Timestamp, ro.Nursery, ro.Metahash)
			return err
		} else {
			return ro.idb.SetStabilized(ro.Hash, roShard, ro.Timestamp, true)
		}
	}
	errs := []error{}
	for _, notFoundNode := range notFoundNodes {
		// try to replicate, try to Stabilize next time
		if err := ro.Replicate(PriorityRepJob{Partition: partition,
			FromDevice: dev,
			ToDevice:   notFoundNode,
			Policy:     ro.policy}); err != nil {
			errs = append(errs, err)
		}
	}
	if len(errs) > 0 {
		return errs[0]
	}
	return fmt.Errorf("could not stabilize: fixed %d nodes", len(notFoundNodes))
}

func (ro *repObject) Replicate(prirep PriorityRepJob) error {
	_, isHandoff := ro.ring.GetJobNodes(prirep.Partition, prirep.FromDevice.Id)
	fp, err := os.Open(ro.Path)
	if err != nil {
		return err
	}
	defer fp.Close()
	req, err := http.NewRequest("PUT",
		fmt.Sprintf("%s://%s:%d/rep-obj/%s/%s",
			prirep.ToDevice.Scheme, prirep.ToDevice.Ip, prirep.ToDevice.Port,
			prirep.ToDevice.Device, ro.Hash), fp)
	if err != nil {
		return err
	}
	req.ContentLength = ro.ContentLength()
	req.Header.Set("X-Timestamp", ro.metadata["X-Timestamp"])
	req.Header.Set("X-Backend-Storage-Policy-Index", strconv.Itoa(ro.policy))
	req.Header.Set("X-Trans-Id", ro.txnId)
	for k, v := range ro.metadata {
		req.Header.Set("Meta-"+k, v)
	}
	resp, err := ro.client.Do(req)
	if err != nil {
		return fmt.Errorf("error syncing obj %s: %v", ro.Hash, err)
	}
	defer resp.Body.Close()
	if !(resp.StatusCode/100 == 2 || resp.StatusCode == 409) {
		return fmt.Errorf("bad status code %d syncing obj with  %s", resp.StatusCode, ro.Hash)
	}
	if isHandoff {
		_, err = ro.idb.Remove(ro.Hash, ro.Shard, ro.Timestamp, ro.Nursery, ro.Metahash)
		return err
	}
	return nil
}


text:
package com.yang.young.common.sso.persistance.jpa.entity;

import java.util.HashSet;
import java.util.Set;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.ManyToMany;
import javax.persistence.Table;

import org.hibernate.validator.constraints.NotEmpty;

@SuppressWarnings("serial")
@Entity
@Table(name="ROLE")
public class RoleEntity extends BaseEntity {

	@Column(name="ROLE_NAME")
	@NotEmpty
	private String name ;

	@ManyToMany(mappedBy="roles")
	private Set<GroupEntity> groups = new HashSet<GroupEntity>();

	RoleEntity() {}

	public RoleEntity(String name) {
		this.name = name;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Set<GroupEntity> getGroups() {
		return groups;
	}

	public void setGroups(Set<GroupEntity> groups) {
		this.groups = groups;
	}

}


text:
from dgcastle.exceptions import ValidationException

def _validate_result(result):
        """Matchplay results can have 1 of 3 different types of values...
            1. A victory that ended before all 18 holes were played
                "<X>&<Y> where X > 1 and X > Y >= 1 and X - Y <= 2
            2. A victory that ended at 18 holes
                "<X>up" where 0 < X < 3
            3. A tie or "all square"
                a. "tie" or "as"
        """
        if '.' in result:
            raise ValidationException("Result '{}' should not contain decimals".format(result))
        elif '-' in result:
            # Challonge results are output in the format X-Y... need to normalize that
            try:
                p1_score, p2_score = result.split('-')
                if p1_score == '0' or p2_score == '0':
                    # This is an Xup result
                    X = int(p1_score) + int(p2_score)
                    return _validate_result('{}up'.format(X))
                else:
                    # Should be a X&Y result (no ties in tournament brackets)
                    x, y = [p1_score, p2_score] if p1_score > p2_score else [p2_score, p1_score]
                    return _validate_result('{}&{}'.format(x, y))
            except ValueError:
                raise ValidationException("Challonge result '{}' failed validation".format(result))

        elif result in ['tie', 'as']:
            # Simplest case, already valid, good to go
            pass
        elif "up" in result:
            tmp = result.split("up")
            if len(tmp) != 2 or tmp[1] != '':
                # We've got extra info here
                raise ValidationException("Result '{}' not in the format 'Xup'".format(result))
            try:
                tmp = int(tmp[0])
                if 0 < tmp < 3:
                    # we're good here
                    pass
                else:
                    raise ValueError()
            except ValueError:
                raise ValidationException("Result '{}' must start with an integer of value 1 or 2".format(result))
        elif ('&' in result) != ('+' in result):
            sep = '&' if '&' in result else '+'
            tmp = result.split(sep)
            if len(tmp) != 2:
                # We've got extra info here
                raise ValidationException("Result '{}' not in the format 'X{}Y'".format(result, sep))
            try:
                X = int(tmp[0])
                Y = int(tmp[1])
                if X > 1  and X > Y >= 1 and X - Y <= 2:
                    # we're good here
                    pass
                else:
                    raise ValidationException("Result '{}' is not a valid score. Given the format 'X{}Y' must have X > 1 and X > Y >= 1".format(result, sep))
            except ValueError:
                raise ValidationException("Result '{}' must use integers".format(result))
        else:
            raise ValidationException("Result '{}' does not appear to match any valid result format".format(result))
        return result

class Match():
    def __init__(self, winner='', loser='', result='', dbRecord=None):
        if dbRecord:
            self.winner = dbRecord['winner'].strip()
            self.loser = dbRecord['loser'].strip()
            self.result = _validate_result(dbRecord['result'].lower().strip())
        else:
            self.winner = winner.name.strip()
            self.loser = loser.name.strip()
            self.result = _validate_result(result.lower().strip())

    def __eq__(self, other):
        return self.winner == other.winner and self.loser == other.loser and self.result == other.result

    def __repr__(self):
        return "Winner: {}, Loser: {}, Result: {}".format(self.winner, self.loser, self.result)

    def insert(self, db):
        db.match_play.insert_one({'winner': self.winner,
                                  'loser': self.loser,
                                  'result': self.result})


text:
import React from 'react'

const TitleAndDescription = ({ title, description }) => (

              {title}

            {description}

)

export default TitleAndDescription


text:
<?php

declare(strict_types=1);

namespace spec\Sylius\Bundle\CoreBundle\Fixture;

use Doctrine\Persistence\ObjectManager;
use PhpSpec\ObjectBehavior;
use Sylius\Bundle\FixturesBundle\Fixture\FixtureInterface;
use Sylius\Component\Addressing\Factory\ZoneFactoryInterface;
use Sylius\Component\Addressing\Model\CountryInterface;
use Sylius\Component\Addressing\Model\ProvinceInterface;
use Sylius\Component\Addressing\Model\ZoneInterface;
use Sylius\Component\Resource\Factory\FactoryInterface;

final class GeographicalFixtureSpec extends ObjectBehavior
{
    function let(
        FactoryInterface $countryFactory,
        ObjectManager $countryManager,
        FactoryInterface $provinceFactory,
        ObjectManager $provinceManager,
        ZoneFactoryInterface $zoneFactory,
        ObjectManager $zoneManager
    ): void {
        $this->beConstructedWith(
            $countryFactory,
            $countryManager,
            $provinceFactory,
            $provinceManager,
            $zoneFactory,
            $zoneManager
        );
    }

    function it_is_a_fixture(): void
    {
        $this->shouldImplement(FixtureInterface::class);
    }

    function it_creates_and_persist_a_country(
        FactoryInterface $countryFactory,
        ObjectManager $countryManager,
        CountryInterface $country
    ): void {
        $countryFactory->createNew()->willReturn($country);
        $country->setCode('PL')->shouldBeCalled();
        $country->enable()->shouldBeCalled();

        $countryManager->persist($country)->shouldBeCalled();
        $countryManager->flush()->shouldBeCalled();

        $this->load(['countries' => ['PL'], 'provinces' => [], 'zones' => []]);
    }

    function it_creates_and_persist_a_country_province(
        FactoryInterface $countryFactory,
        ObjectManager $countryManager,
        FactoryInterface $provinceFactory,
        ObjectManager $provinceManager,
        CountryInterface $country,
        ProvinceInterface $province
    ): void {
        $countryFactory->createNew()->willReturn($country);
        $country->setCode('PL')->shouldBeCalled();
        $country->enable()->shouldBeCalled();

        $provinceFactory->createNew()->willReturn($province);
        $province->setCode('PL-SL')->shouldBeCalled();
        $province->setName('Silesia')->shouldBeCalled();

        $country->addProvince($province)->shouldBeCalled();

        $countryManager->persist($country)->shouldBeCalled();
        $provinceManager->persist($province)->shouldBeCalled();

        $countryManager->flush()->shouldBeCalled();
        $provinceManager->flush()->shouldBeCalled();

        $this->load(['countries' => ['PL'], 'provinces' => ['PL' => ['PL-SL' => 'Silesia']], 'zones' => []]);
    }

    function it_throws_an_exception_if_trying_to_create_a_province_for_unexisting_country(): void
    {
        $this->shouldThrow(\InvalidArgumentException::class)->during('load', [['countries' => [], 'provinces' => ['PL' => ['PL-SL' => 'Silesia']], 'zones' => []]]);
    }

    function it_creates_and_persist_a_country_and_a_zone_containing_it(
        FactoryInterface $countryFactory,
        ObjectManager $countryManager,
        ZoneFactoryInterface $zoneFactory,
        ObjectManager $zoneManager,
        CountryInterface $country,
        ZoneInterface $zone
    ): void {
        $countryFactory->createNew()->willReturn($country);
        $country->setCode('PL')->shouldBeCalled();
        $country->enable()->shouldBeCalled();

        $zoneFactory->createWithMembers(['PL'])->willReturn($zone);
        $zone->setCode('POLAND')->shouldBeCalled();
        $zone->setName('Poland')->shouldBeCalled();
        $zone->setType(ZoneInterface::TYPE_COUNTRY)->shouldBeCalled();

        $countryManager->persist($country)->shouldBeCalled();
        $zoneManager->persist($zone)->shouldBeCalled();

        $countryManager->flush()->shouldBeCalled();
        $zoneManager->flush()->shouldBeCalled();

        $this->load(['countries' => ['PL'], 'provinces' => [], 'zones' => [
            'POLAND' => [
                'name' => 'Poland',
                'countries' => ['PL'],
                'provinces' => [],
                'zones' => [],
            ],
        ]]);
    }

    function it_creates_and_persist_a_country_and_a_zone_with_scope_containing_it(
        FactoryInterface $countryFactory,
        ObjectManager $countryManager,
        ZoneFactoryInterface $zoneFactory,
        ObjectManager $zoneManager,
        CountryInterface $country,
        ZoneInterface $zone
    ): void {
        $countryFactory->createNew()->willReturn($country);
        $country->setCode('PL')->shouldBeCalled();
        $country->enable()->shouldBeCalled();

        $zoneFactory->createWithMembers(['PL'])->willReturn($zone);
        $zone->setCode('POLAND')->shouldBeCalled();
        $zone->setName('Poland')->shouldBeCalled();
        $zone->setType(ZoneInterface::TYPE_COUNTRY)->shouldBeCalled();
        $zone->setScope('tax')->shouldBeCalled();

        $countryManager->persist($country)->shouldBeCalled();
        $zoneManager->persist($zone)->shouldBeCalled();

        $countryManager->flush()->shouldBeCalled();
        $zoneManager->flush()->shouldBeCalled();

        $this->load(['countries' => ['PL'], 'provinces' => [], 'zones' => [
            'POLAND' => [
                'name' => 'Poland',
                'countries' => ['PL'],
                'provinces' => [],
                'zones' => [],
                'scope' => 'tax',
            ],
        ]]);
    }

    function it_creates_and_persist_a_country_province_and_a_zone_containing_it(
        FactoryInterface $countryFactory,
        ObjectManager $countryManager,
        FactoryInterface $provinceFactory,
        ObjectManager $provinceManager,
        ZoneFactoryInterface $zoneFactory,
        ObjectManager $zoneManager,
        CountryInterface $country,
        ProvinceInterface $province,
        ZoneInterface $zone
    ): void {
        $countryFactory->createNew()->willReturn($country);
        $country->setCode('PL')->shouldBeCalled();
        $country->enable()->shouldBeCalled();

        $provinceFactory->createNew()->willReturn($province);
        $province->setCode('PL-SL')->shouldBeCalled();
        $province->setName('Silesia')->shouldBeCalled();

        $country->addProvince($province)->shouldBeCalled();

        $zoneFactory->createWithMembers(['PL-SL'])->willReturn($zone);
        $zone->setCode('SILESIA')->shouldBeCalled();
        $zone->setName('Silesia')->shouldBeCalled();
        $zone->setType(ZoneInterface::TYPE_PROVINCE)->shouldBeCalled();

        $countryManager->persist($country)->shouldBeCalled();
        $provinceManager->persist($province)->shouldBeCalled();
        $zoneManager->persist($zone)->shouldBeCalled();

        $countryManager->flush()->shouldBeCalled();
        $provinceManager->flush()->shouldBeCalled();
        $zoneManager->flush()->shouldBeCalled();

        $this->load(['countries' => ['PL'], 'provinces' => ['PL' => ['PL-SL' => 'Silesia']], 'zones' => [
            'SILESIA' => [
                'name' => 'Silesia',
                'countries' => [],
                'provinces' => ['PL-SL'],
                'zones' => [],
            ],
        ]]);
    }

    function it_creates_and_persist_a_country_type_zone_and_a_zone_containing_it(
        FactoryInterface $countryFactory,
        ObjectManager $countryManager,
        ZoneFactoryInterface $zoneFactory,
        ObjectManager $zoneManager,
        CountryInterface $country,
        ZoneInterface $countryTypeZone,
        ZoneInterface $zoneTypeZone
    ): void {
        $countryFactory->createNew()->willReturn($country);
        $country->setCode('PL')->shouldBeCalled();
        $country->enable()->shouldBeCalled();

        $zoneFactory->createWithMembers(['PL'])->willReturn($countryTypeZone);
        $countryTypeZone->setCode('POLAND')->shouldBeCalled();
        $countryTypeZone->setName('Poland')->shouldBeCalled();
        $countryTypeZone->setType(ZoneInterface::TYPE_COUNTRY)->shouldBeCalled();

        $zoneFactory->createWithMembers(['POLAND'])->willReturn($zoneTypeZone);
        $zoneTypeZone->setCode('YO-DAWG')->shouldBeCalled();
        $zoneTypeZone->setName('Yo dawg')->shouldBeCalled();
        $zoneTypeZone->setType(ZoneInterface::TYPE_ZONE)->shouldBeCalled();

        $countryManager->persist($country)->shouldBeCalled();
        $zoneManager->persist($countryTypeZone)->shouldBeCalled();
        $zoneManager->persist($zoneTypeZone)->shouldBeCalled();

        $countryManager->flush()->shouldBeCalled();
        $zoneManager->flush()->shouldBeCalled();

        $this->load(['countries' => ['PL'], 'provinces' => [], 'zones' => [
            'POLAND' => [
                'name' => 'Poland',
                'countries' => ['PL'],
                'provinces' => [],
                'zones' => [],
            ],
            'YO-DAWG' => [
                'name' => 'Yo dawg',
                'countries' => [],
                'provinces' => [],
                'zones' => ['POLAND'],
            ],
        ]]);
    }

    function it_throws_an_exception_if_trying_to_create_a_zone_with_unexisting_country(): void
    {
        $this->shouldThrow(\InvalidArgumentException::class)->during('load', [['countries' => [], 'provinces' => [], 'zones' => [
            'ZONE' => [
                'name' => 'Zone',
                'countries' => ['PL'],
                'provinces' => [],
                'zones' => [],
            ],
        ]]]);
    }

    function it_throws_an_exception_if_trying_to_create_a_zone_with_unexisting_province(): void
    {
        $this->shouldThrow(\InvalidArgumentException::class)->during('load', [['countries' => [], 'provinces' => [], 'zones' => [
            'ZONE' => [
                'name' => 'Zone',
                'countries' => [],
                'provinces' => ['PL-SL'],
                'zones' => [],
            ],
        ]]]);
    }

    function it_throws_an_exception_if_trying_to_create_a_zone_with_unexisting_zone(): void
    {
        $this->shouldThrow(\InvalidArgumentException::class)->during('load', [['countries' => [], 'provinces' => [], 'zones' => [
            'ZONE' => [
                'name' => 'Zone',
                'countries' => [],
                'provinces' => [],
                'zones' => ['DAWG'],
            ],
        ]]]);
    }
}


text:
require 'rubygems'
require 'test/unit'
require 'shoulda'

$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
$LOAD_PATH.unshift(File.dirname(__FILE__))
require 'testr'

class Test::Unit::TestCase
end


text:
#import "AppDelegate_iPhone.h"
#import "ChartListViewController.h"

@implementation AppDelegate_iPhone

#pragma mark -
#pragma mark Application lifecycle

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    [self.window makeKeyAndVisible];

	ChartListViewController *chartListViewController = [[ChartListViewController alloc] init];
	UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:chartListViewController];
	[self.window setRootViewController:navigationController];

    return YES;
}

@end


text:
@interface RootViewController () <UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSArray *setting;

@end

@implementation RootViewController

#pragma mark - Propertys

- (NSArray *)setting {
    if (!_setting) {
        _setting = [[NSArray alloc] init];
    }
    return _setting;
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [self.view addSubview:_tableView];
    }
    return _tableView;
}

#pragma mark - Left cycle init

- (void)_loadLoginViewControllers {
    dispatch_async(dispatch_queue_create("Load LoginViewControllers", NULL), ^{
        NSMutableArray *setting = [[NSMutableArray alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Settings" ofType:@"plist"]];
        dispatch_async(dispatch_get_main_queue(), ^{
            self.setting = setting;
            [self.tableView reloadData];
        });
    });
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self _loadLoginViewControllers];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    self.title = NSLocalizedString(@"设置组件", @"");
    self.view.backgroundColor = [UIColor whiteColor];
    if ([self respondsToSelector:@selector(edgesForExtendedLayout)]) {
        self.edgesForExtendedLayout = UIRectEdgeNone;
        self.extendedLayoutIncludesOpaqueBars = NO;
        self.modalPresentationCapturesStatusBarAppearance = NO;
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark -  UITableView dataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.setting.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellIdentifier = @"cellIdentifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    NSString *className = [self.setting[indexPath.row] valueForKey:XHKControllerTitleKey];
    cell.textLabel.text = className;
    cell.imageView.image = [UIImage imageNamed:[NSString stringWithFormat:@"%@.png", className]];

    return cell;
}

#pragma mark - UITableView delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSDictionary *settingDictionary = self.setting[indexPath.row];

    BaseSettingViewController *baseSettingViewController = [[BaseSettingViewController alloc] init];
    baseSettingViewController.settingDictionary = settingDictionary;
    baseSettingViewController.title = [settingDictionary valueForKey:XHKControllerTitleKey];

    [self.navigationController pushViewController:baseSettingViewController animated:YES];
}

@end


text:
{% extends "base.html" %}
{% block content %}

        {% for media in carousel_items %}
            {% if loop.first %}

            {% else %}

            {% endif %}
        {% endfor %}

		{% for media in carousel_items %}
			{% if loop.first %}

			{% else %}

			{% endif %}

		{% endfor %}

		Previous

		Next

{% endblock %}


text:
class Frobber
{
private:
	char const* m_FrobName;
	int m_FrobId;
public:
	__declspec(noinline) Frobber(char const* FrobName)
		: m_FrobName(FrobName), m_FrobId(42)
	{
	}
	__declspec(noinline) void FrobIt()
	{
		printf("Frobbing %c (id %d)\n", m_FrobName[0], m_FrobId);
	}
};

enum OPCODE
{
	OPCODE_FROB,
	OPCODE_FROB_WITH_CB
};

#pragma pack(4)
struct CALLBACK_OUTPUT
{
	__int32* ErrorCodeArray;
	unsigned __int64 NumberOfErrors;
};

typedef __int32(__stdcall *FROB_WIDGET_CALLBACK)(
	__int32 OperationCode,
	CALLBACK_OUTPUT* CallbackOutput
	);

extern "C" __declspec(dllexport) void __stdcall FrobWidgetWithCallback(
	char const* FrobName,
	FROB_WIDGET_CALLBACK Callback
	)
{
	CALLBACK_OUTPUT CallbackOutput = { 0 };
	Frobber frobber(FrobName);
	if (0 == Callback(OPCODE_FROB_WITH_CB, &CallbackOutput))
	{
		frobber.FrobIt();
	}
}


text:
import { pushJob } from './queue'
import {
  on,
  off,
  bind,
  addClass,
  removeClass,
  cancellable,
  transitionEndEvent,
  animationEndEvent,
  transitionProp,
  animationProp,
  warn
} from '../util/index'

const TYPE_TRANSITION = 'transition'
const TYPE_ANIMATION = 'animation'
const transDurationProp = transitionProp + 'Duration'
const animDurationProp = animationProp + 'Duration'

/**
 * A Transition object that encapsulates the state and logic
 * of the transition.
 *
 * @param {Element} el
 * @param {String} id
 * @param {Object} hooks
 * @param {Vue} vm
 */

export default function Transition (el, id, hooks, vm) {
  this.id = id
  this.el = el
  this.enterClass = (hooks && hooks.enterClass) || id + '-enter'
  this.leaveClass = (hooks && hooks.leaveClass) || id + '-leave'
  this.hooks = hooks
  this.vm = vm
  // async state
  this.pendingCssEvent =
  this.pendingCssCb =
  this.cancel =
  this.pendingJsCb =
  this.op =
  this.cb = null
  this.justEntered = false
  this.entered = this.left = false
  this.typeCache = {}
  // check css transition type
  this.type = hooks && hooks.type
  /* istanbul ignore if */
  if (process.env.NODE_ENV !== 'production') {
    if (
      this.type &&
      this.type !== TYPE_TRANSITION &&
      this.type !== TYPE_ANIMATION
    ) {
      warn(
        'invalid CSS transition type for transition="' +
        this.id + '": ' + this.type
      )
    }
  }
  // bind
  var self = this
  ;['enterNextTick', 'enterDone', 'leaveNextTick', 'leaveDone']
    .forEach(function (m) {
      self[m] = bind(self[m], self)
    })
}

var p = Transition.prototype

/**
 * Start an entering transition.
 *
 * 1. enter transition triggered
 * 2. call beforeEnter hook
 * 3. add enter class
 * 4. insert/show element
 * 5. call enter hook (with possible explicit js callback)
 * 6. reflow
 * 7. based on transition type:
 *    - transition:
 *        remove class now, wait for transitionend,
 *        then done if there's no explicit js callback.
 *    - animation:
 *        wait for animationend, remove class,
 *        then done if there's no explicit js callback.
 *    - no css transition:
 *        done now if there's no explicit js callback.
 * 8. wait for either done or js callback, then call
 *    afterEnter hook.
 *
 * @param {Function} op - insert/show the element
 * @param {Function} [cb]
 */

p.enter = function (op, cb) {
  this.cancelPending()
  this.callHook('beforeEnter')
  this.cb = cb
  addClass(this.el, this.enterClass)
  op()
  this.entered = false
  this.callHookWithCb('enter')
  if (this.entered) {
    return // user called done synchronously.
  }
  this.cancel = this.hooks && this.hooks.enterCancelled
  pushJob(this.enterNextTick)
}

/**
 * The "nextTick" phase of an entering transition, which is
 * to be pushed into a queue and executed after a reflow so
 * that removing the class can trigger a CSS transition.
 */

p.enterNextTick = function () {
  // Important hack:
  // in Chrome, if a just-entered element is applied the
  // leave class while its interpolated property still has
  // a very small value (within one frame), Chrome will
  // skip the leave transition entirely and not firing the
  // transtionend event. Therefore we need to protected
  // against such cases using a one-frame timeout.
  this.justEntered = true
  var self = this
  setTimeout(function () {
    self.justEntered = false
  }, 17)

  var enterDone = this.enterDone
  var type = this.getCssTransitionType(this.enterClass)
  if (!this.pendingJsCb) {
    if (type === TYPE_TRANSITION) {
      // trigger transition by removing enter class now
      removeClass(this.el, this.enterClass)
      this.setupCssCb(transitionEndEvent, enterDone)
    } else if (type === TYPE_ANIMATION) {
      this.setupCssCb(animationEndEvent, enterDone)
    } else {
      enterDone()
    }
  } else if (type === TYPE_TRANSITION) {
    removeClass(this.el, this.enterClass)
  }
}

/**
 * The "cleanup" phase of an entering transition.
 */

p.enterDone = function () {
  this.entered = true
  this.cancel = this.pendingJsCb = null
  removeClass(this.el, this.enterClass)
  this.callHook('afterEnter')
  if (this.cb) this.cb()
}

/**
 * Start a leaving transition.
 *
 * 1. leave transition triggered.
 * 2. call beforeLeave hook
 * 3. add leave class (trigger css transition)
 * 4. call leave hook (with possible explicit js callback)
 * 5. reflow if no explicit js callback is provided
 * 6. based on transition type:
 *    - transition or animation:
 *        wait for end event, remove class, then done if
 *        there's no explicit js callback.
 *    - no css transition:
 *        done if there's no explicit js callback.
 * 7. wait for either done or js callback, then call
 *    afterLeave hook.
 *
 * @param {Function} op - remove/hide the element
 * @param {Function} [cb]
 */

p.leave = function (op, cb) {
  this.cancelPending()
  this.callHook('beforeLeave')
  this.op = op
  this.cb = cb
  addClass(this.el, this.leaveClass)
  this.left = false
  this.callHookWithCb('leave')
  if (this.left) {
    return // user called done synchronously.
  }
  this.cancel = this.hooks && this.hooks.leaveCancelled
  // only need to handle leaveDone if
  // 1. the transition is already done (synchronously called
  //    by the user, which causes this.op set to null)
  // 2. there's no explicit js callback
  if (this.op && !this.pendingJsCb) {
    // if a CSS transition leaves immediately after enter,
    // the transitionend event never fires. therefore we
    // detect such cases and end the leave immediately.
    if (this.justEntered) {
      this.leaveDone()
    } else {
      pushJob(this.leaveNextTick)
    }
  }
}

/**
 * The "nextTick" phase of a leaving transition.
 */

p.leaveNextTick = function () {
  var type = this.getCssTransitionType(this.leaveClass)
  if (type) {
    var event = type === TYPE_TRANSITION
      ? transitionEndEvent
      : animationEndEvent
    this.setupCssCb(event, this.leaveDone)
  } else {
    this.leaveDone()
  }
}

/**
 * The "cleanup" phase of a leaving transition.
 */

p.leaveDone = function () {
  this.left = true
  this.cancel = this.pendingJsCb = null
  this.op()
  removeClass(this.el, this.leaveClass)
  this.callHook('afterLeave')
  if (this.cb) this.cb()
  this.op = null
}

/**
 * Cancel any pending callbacks from a previously running
 * but not finished transition.
 */

p.cancelPending = function () {
  this.op = this.cb = null
  var hasPending = false
  if (this.pendingCssCb) {
    hasPending = true
    off(this.el, this.pendingCssEvent, this.pendingCssCb)
    this.pendingCssEvent = this.pendingCssCb = null
  }
  if (this.pendingJsCb) {
    hasPending = true
    this.pendingJsCb.cancel()
    this.pendingJsCb = null
  }
  if (hasPending) {
    removeClass(this.el, this.enterClass)
    removeClass(this.el, this.leaveClass)
  }
  if (this.cancel) {
    this.cancel.call(this.vm, this.el)
    this.cancel = null
  }
}

/**
 * Call a user-provided synchronous hook function.
 *
 * @param {String} type
 */

p.callHook = function (type) {
  if (this.hooks && this.hooks[type]) {
    this.hooks[type].call(this.vm, this.el)
  }
}

/**
 * Call a user-provided, potentially-async hook function.
 * We check for the length of arguments to see if the hook
 * expects a `done` callback. If true, the transition's end
 * will be determined by when the user calls that callback;
 * otherwise, the end is determined by the CSS transition or
 * animation.
 *
 * @param {String} type
 */

p.callHookWithCb = function (type) {
  var hook = this.hooks && this.hooks[type]
  if (hook) {
    if (hook.length > 1) {
      this.pendingJsCb = cancellable(this[type + 'Done'])
    }
    hook.call(this.vm, this.el, this.pendingJsCb)
  }
}

/**
 * Get an element's transition type based on the
 * calculated styles.
 *
 * @param {String} className
 * @return {Number}
 */

p.getCssTransitionType = function (className) {
  /* istanbul ignore if */
  if (
    !transitionEndEvent ||
    // skip CSS transitions if page is not visible -
    // this solves the issue of transitionend events not
    // firing until the page is visible again.
    // pageVisibility API is supported in IE10+, same as
    // CSS transitions.
    document.hidden ||
    // explicit js-only transition
    (this.hooks && this.hooks.css === false) ||
    // element is hidden
    isHidden(this.el)
  ) {
    return
  }
  var type = this.type || this.typeCache[className]
  if (type) return type
  var inlineStyles = this.el.style
  var computedStyles = window.getComputedStyle(this.el)
  var transDuration =
    inlineStyles[transDurationProp] ||
    computedStyles[transDurationProp]
  if (transDuration && transDuration !== '0s') {
    type = TYPE_TRANSITION
  } else {
    var animDuration =
      inlineStyles[animDurationProp] ||
      computedStyles[animDurationProp]
    if (animDuration && animDuration !== '0s') {
      type = TYPE_ANIMATION
    }
  }
  if (type) {
    this.typeCache[className] = type
  }
  return type
}

/**
 * Setup a CSS transitionend/animationend callback.
 *
 * @param {String} event
 * @param {Function} cb
 */

p.setupCssCb = function (event, cb) {
  this.pendingCssEvent = event
  var self = this
  var el = this.el
  var onEnd = this.pendingCssCb = function (e) {
    if (e.target === el) {
      off(el, event, onEnd)
      self.pendingCssEvent = self.pendingCssCb = null
      if (!self.pendingJsCb && cb) {
        cb()
      }
    }
  }
  on(el, event, onEnd)
}

/**
 * Check if an element is hidden - in that case we can just
 * skip the transition alltogether.
 *
 * @param {Element} el
 * @return {Boolean}
 */

function isHidden (el) {
  return !(
    el.offsetWidth ||
    el.offsetHeight ||
    el.getClientRects().length
  )
}


text:
"""API integration tests"""

from nass.api import NassApi
from util import api

def test_key():
    api = NassApi('api key')
    assert api.key == 'api key'

def test_sources(api):
    data = api.param_values('source_desc')
    assert data

def test_api_count(api):
    query = api.query()
    query.filter('commodity_desc', 'CORN')
    query.filter('year', 2012, 'ge')
    query.filter('county_code', 187)
    count = query.count()
    assert count
    assert isinstance(count, int)

def test_api_query(api):
    query = api.query()
    query.filter('commodity_desc', 'CORN')
    query.filter('year', 2012, 'ge')
    query.filter('county_code', 187)
    data = query.execute()
    assert data


text:
    // *** COMMAND - CONSTRUCTOR

    var Command = function (context, request, session) {
        this.id = context.id;
        this.context = context;
        this.request = request;
        this.session = session;
        // --
        // Implementing:
        // this.master = null;
    };

    // *** COMMAND BUILDER - OBJECT

    var CommandBuilder = {

        // --- METHODS

        createCommand: function(context, request, session) {
            var command = new Command(context, request, session);
            command.master = this._buildMaster(context, request, session);
            return command;
        },

        _buildMaster: function(context, request, session) {

            var masterClass,
                master,
                type = Utils.trim(context.type).toLowerCase();

            if (type != "") {
                masterClass = session.commandMasters["_" + type];
            } else {
                masterClass = session.defaultCommandMasterClass;
            }

            if (masterClass) {
                if (typeof masterClass == "function") {
                    master = new masterClass(context, request, session);
                } else {
                    Log.error("The type " + type + " in " + context.id + " cannot create a new command");
                }
            } else {
                Log.error("The type " + type + " cannot be resolved in command: " + context.id);
            }

            return master;

        }

    };


text:
package main

import (
	"fmt"
	"image"
	"image/color"
	"image/draw"
)

const (
	Margins = 200 // width of image's white margins
	Frame   = 10
)

func traverseTiles(Style style, Area area) (image.Image, error) {
	m := image.NewRGBA(image.Rect(-Margins, -Margins, Area.TileRange.Dx()*TileSize+Margins, Area.TileRange.Dy()*TileSize+Margins))

	whiteColor := color.RGBA{255, 255, 255, 255}
	draw.Draw(m, m.Bounds(), &image.Uniform{whiteColor}, image.ZP, draw.Src)

	frameColor := color.RGBA{50, 50, 50, 255}
	draw.Draw(m, image.Rect(-Frame, -Frame, Area.TileRange.Dx()*TileSize+Frame, Area.TileRange.Dy()*TileSize+Frame), &image.Uniform{frameColor}, image.ZP, draw.Src)

	position := image.Rectangle{image.ZP, image.Point{X: TileSize, Y: TileSize}}
	for y := Area.TileRange.Min.Y; y < Area.TileRange.Max.Y; y++ {
		for x := Area.TileRange.Min.X; x < Area.TileRange.Max.X; x++ {
			img, err := readTile(Style.Mapid, Area.Z, uint(x), uint(y))
			if err != nil {
				fmt.Printf("no luck reading this tile: z:%v, %vx %v \n", Area.Z, x, y)
				fmt.Println(err)
				break
			}
			fmt.Printf("...adding %vx%v \n", x, y)
			draw.Draw(m, position, img, image.ZP, draw.Src)
			position = position.Add(image.Point{X: TileSize, Y: 0})
		}
		position = image.Rectangle{image.Point{X: 0, Y: (y - Area.TileRange.Min.Y + 1) * TileSize}, image.Point{X: TileSize, Y: (y - Area.TileRange.Min.Y + 2) * TileSize}}
	}
	fmt.Println("Great success!")
	return m, nil
}


text:
FROM node:10.15-slim
MAINTAINER HMPPS Digital Studio <info@digital.justice.gov.uk>
ARG BUILD_NUMBER
ARG GIT_REF

# Create app directory
RUN mkdir -p /app
WORKDIR /app
ADD . .

# Install AWS RDS Root cert
RUN curl https://s3.amazonaws.com/rds-downloads/rds-ca-2015-root.pem > /app/root.cert

RUN npm install && \
    npm run build && \
    export BUILD_NUMBER=${BUILD_NUMBER} && \
    export GIT_REF=${GIT_REF} && \
    npm run record-build-info

ENV PORT=3000

EXPOSE 3000
CMD [ "npm", "start" ]


text:
<?php

namespace Grav\Framework\Collection;

use Doctrine\Common\Collections\ArrayCollection as BaseArrayCollection;

/**
 * General JSON serializable collection.
 *
 * @package Grav\Framework\Collection
 */
class ArrayCollection extends BaseArrayCollection implements CollectionInterface
{
    /**
     * Reverse the order of the items.
     *
     * @return static
     */
    public function reverse()
    {
        return $this->createFrom(array_reverse($this->toArray()));
    }

    /**
     * Shuffle items.
     *
     * @return static
     */
    public function shuffle()
    {
        $keys = $this->getKeys();
        shuffle($keys);

        return $this->createFrom(array_replace(array_flip($keys), $this->toArray()));
    }

    /**
     * Split collection into chunks.
     *
     * @param int $size     Size of each chunk.
     * @return array
     */
    public function chunk($size)
    {
        return array_chunk($this->toArray(), $size, true);
    }

    /**
     * Select items from collection.
     *
     * Collection is returned in the order of $keys given to the function.
     *
     * @param array $keys
     * @return static
     */
    public function select(array $keys)
    {
        $list = [];
        foreach ($keys as $key) {
            if ($this->containsKey($key)) {
                $list[$key] = $this->get($key);
            }
        }

        return $this->createFrom($list);
    }

    /**
     * Un-select items from collection.
     *
     * @param array $keys
     * @return static
     */
    public function unselect(array $keys)
    {
        return $this->select(array_diff($this->getKeys(), $keys));
    }

    /**
     * Implementes JsonSerializable interface.
     *
     * @return array
     */
    public function jsonSerialize()
    {
        return $this->toArray();
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BatchGbViewer.Models
{
   public class UserGradeBook
   {
      public UserGradeBook()
      {
         Batches = new Dictionary<int, string>();
         gradebook = new List<ExamAssessment>();
      }

      public User user { get; set; }
      public Dictionary<int, string> Batches { get; set; } // gradebook ID as key, batch name as value
      public virtual List<ExamAssessment> gradebook { get; set; }
   }
}


text:
/**
 *
 * Config for grunt-jasmine-node
 *
 */
/*jslint indent:4 */
/*globals module */
module.exports = {
    options: {
        match: '.',
        verbose: true,
        matchall: false,
        forceExit: true,
        extensions: 'js',
        specNameMatcher: 'spec'
    },
    all: []
};


text:
package com.mysql.jdbc.util;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.Properties;

import com.mysql.jdbc.StringUtils;

/**
 * Controls a MySQL server using Java RunTime methods
 */
public class ServerController {

    /**
     * Where is the server installed?
     */
    public static final String BASEDIR_KEY = "basedir";

    /**
     * Where are the databases installed?
     */
    public static final String DATADIR_KEY = "datadir";

    /**
     * Where is the config file located?
     */

    public static final String DEFAULTS_FILE_KEY = "defaults-file";

    /**
     * What is the name of the executable to run?
     */

    public static final String EXECUTABLE_NAME_KEY = "executable";

    /**
     * What is the path to the mysql server executable (if not standard?)
     */

    public static final String EXECUTABLE_PATH_KEY = "executablePath";

    /**
     * The default executable to run
     */

    /**
     * The process representing the MySQL server
     */
    private Process serverProcess = null;

    /**
     * The list of properties for this server
     */
    private Properties serverProps = null;

    /**
     * The system properties
     */
    private Properties systemProps = null;

    /**
     * Creates a ServerController with the directory for the MySQL server.
     *
     * The 'datadir' is set to the same directory.
     *
     * @param baseDir
     *            the base directory for the MySQL server.
     */
    public ServerController(String baseDir) {
        setBaseDir(baseDir);
    }

    /**
     * Creates a server controller for the MySQL server with the given basedir
     * and datadir.
     *
     * @param basedir
     *            the basedir to use when starting MySQL.
     * @param datadir
     *            the datadir to use when starting MySQL.
     */
    public ServerController(String basedir, String datadir) {
    }

    /**
     * Sets the basedir to use when starting MySQL.
     *
     * @param baseDir
     *            the basedir to use when starting MySQL.
     */
    public void setBaseDir(String baseDir) {
        getServerProps().setProperty(BASEDIR_KEY, baseDir);
    }

    /**
     * Sets the data to use when starting MySQL.
     *
     * @param dataDir
     *            the basedir to use when starting MySQL.
     */
    public void setDataDir(String dataDir) {
        getServerProps().setProperty(DATADIR_KEY, dataDir);
    }

    /**
     * Starts the server, returning a java.lang.Process instance that represents
     * the mysql server.
     *
     * @return Process a java.lang.Process instance representing the mysql
     *         server process.
     * @throws IOException
     *             if an error occurs while starting the mysql server.
     */
    public Process start() throws IOException {
        if (this.serverProcess != null) {
            throw new IllegalArgumentException("Server already started");
        }
        this.serverProcess = Runtime.getRuntime().exec(getCommandLine());

        return this.serverProcess;
    }

    /**
     * Stops the server (if started)
     *
     * @param forceIfNecessary
     *            use forceStop if mysqladmin doesn't shut the server down
     *
     * @throws IOException
     *             if an error occurs while stopping the server
     */
    public void stop(boolean forceIfNecessary) throws IOException {
        if (this.serverProcess != null) {

            String basedir = getServerProps().getProperty(BASEDIR_KEY);

            StringBuffer pathBuf = new StringBuffer(basedir);

            if (!basedir.endsWith(File.separator)) {
                pathBuf.append(File.separator);
            }

            //String defaultsFilePath = getServerProps().getProperty(DEFAULTS_FILE_KEY);

            pathBuf.append("bin");
            pathBuf.append(File.separator);
            pathBuf.append("mysqladmin shutdown");

            System.out.println(pathBuf.toString());

            Process mysqladmin = Runtime.getRuntime().exec(pathBuf.toString());

            int exitStatus = -1;

            try {
                exitStatus = mysqladmin.waitFor();
            } catch (InterruptedException ie) {
                // ignore
            }

            //
            // Terminate the process if mysqladmin couldn't do it, and the user requested a force stop.
            //
            if (exitStatus != 0 && forceIfNecessary) {
                forceStop();
            }
        }
    }

    /**
     * Forcefully terminates the server process (if started).
     */
    public void forceStop() {
        if (this.serverProcess != null) {
            this.serverProcess.destroy();
            this.serverProcess = null;
        }
    }

    /**
     * Returns the list of properties that will be used to start/control the
     * server.
     *
     * @return Properties the list of properties.
     */
    public synchronized Properties getServerProps() {
        if (this.serverProps == null) {
            this.serverProps = new Properties();
        }

        return this.serverProps;
    }

    /**
     * Returns the full commandline used to start the mysql server, including
     * and arguments to be passed to the server process.
     *
     * @return String the commandline used to start the mysql server.
     */
    private String getCommandLine() {
        StringBuffer commandLine = new StringBuffer(getFullExecutablePath());
        commandLine.append(buildOptionalCommandLine());

        return commandLine.toString();
    }

    /**
     * Returns the fully-qualifed path to the 'mysqld' executable
     *
     * @return String the path to the server executable.
     */
    private String getFullExecutablePath() {
        StringBuffer pathBuf = new StringBuffer();

        String optionalExecutablePath = getServerProps().getProperty(EXECUTABLE_PATH_KEY);

        if (optionalExecutablePath == null) {
            // build the path using the defaults
            String basedir = getServerProps().getProperty(BASEDIR_KEY);
            pathBuf.append(basedir);

            if (!basedir.endsWith(File.separator)) {
                pathBuf.append(File.separatorChar);
            }

            if (runningOnWindows()) {
                pathBuf.append("bin");
            } else {
                pathBuf.append("libexec");
            }

            pathBuf.append(File.separatorChar);
        } else {
            pathBuf.append(optionalExecutablePath);

            if (!optionalExecutablePath.endsWith(File.separator)) {
                pathBuf.append(File.separatorChar);
            }
        }

        String executableName = getServerProps().getProperty(EXECUTABLE_NAME_KEY, "mysqld");

        pathBuf.append(executableName);

        return pathBuf.toString();
    }

    /**
     * Builds the list of command-line arguments that will be passed to the
     * mysql server to be started.
     *
     * @return String the list of command-line arguments.
     */
    private String buildOptionalCommandLine() {
        StringBuffer commandLineBuf = new StringBuffer();

        if (this.serverProps != null) {

            for (Iterator<Object> iter = this.serverProps.keySet().iterator(); iter.hasNext();) {
                String key = (String) iter.next();
                String value = this.serverProps.getProperty(key);

                if (!isNonCommandLineArgument(key)) {
                    if (value != null && value.length() > 0) {
                        commandLineBuf.append(" \"");
                        commandLineBuf.append("--");
                        commandLineBuf.append(key);
                        commandLineBuf.append("=");
                        commandLineBuf.append(value);
                        commandLineBuf.append("\"");
                    } else {
                        commandLineBuf.append(" --");
                        commandLineBuf.append(key);
                    }
                }
            }
        }

        return commandLineBuf.toString();
    }

    /**
     * Returns true if the property does not belong as a command-line argument
     *
     * @return boolean if the property should not be a command-line argument.
     */
    private boolean isNonCommandLineArgument(String propName) {
        return propName.equals(EXECUTABLE_NAME_KEY) || propName.equals(EXECUTABLE_PATH_KEY);
    }

    /**
     * Lazily creates a list of system properties.
     *
     * @return Properties the properties from System.getProperties()
     */
    private synchronized Properties getSystemProperties() {
        if (this.systemProps == null) {
            this.systemProps = System.getProperties();
        }

        return this.systemProps;
    }

    /**
     * Is this ServerController running on a Windows operating system?
     *
     * @return boolean if this ServerController is running on Windows
     */
    private boolean runningOnWindows() {
        return StringUtils.indexOfIgnoreCase(getSystemProperties().getProperty("os.name"), "WINDOWS") != -1;
    }
}


text:
package org.apache.druid.query.groupby.orderby;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Function;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Maps;
import org.apache.druid.data.input.MapBasedRow;
import org.apache.druid.data.input.Row;
import org.apache.druid.java.util.common.DateTimes;
import org.apache.druid.java.util.common.granularity.Granularities;
import org.apache.druid.java.util.common.guava.Sequence;
import org.apache.druid.java.util.common.guava.Sequences;
import org.apache.druid.query.aggregation.LongSumAggregatorFactory;
import org.apache.druid.query.aggregation.post.ArithmeticPostAggregator;
import org.apache.druid.query.aggregation.post.ConstantPostAggregator;
import org.apache.druid.query.aggregation.post.ExpressionPostAggregator;
import org.apache.druid.query.dimension.DefaultDimensionSpec;
import org.apache.druid.query.expression.TestExprMacroTable;
import org.apache.druid.query.ordering.StringComparators;
import org.apache.druid.segment.TestHelper;
import org.apache.druid.segment.column.ValueType;
import org.junit.Assert;
import org.junit.Test;

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

/**
 */
public class DefaultLimitSpecTest
{
  private final List<Row> testRowsList;
  private final Sequence<Row> testRowsSequence;

  public DefaultLimitSpecTest()
  {
    testRowsList = ImmutableList.of(
        createRow("2011-04-01", "k1", 10.0, "k2", 1L, "k3", 2L),
        createRow("2011-04-01", "k1", 20.0, "k2", 3L, "k3", 1L),
        createRow("2011-04-01", "k1", 9.0, "k2", 2L, "k3", 3L)
    );

    testRowsSequence = Sequences.simple(testRowsList);
  }

  @Test
  public void testSerde() throws Exception
  {
    ObjectMapper mapper = TestHelper.makeJsonMapper();

    //defaults
    String json = "{\"type\": \"default\"}";

    DefaultLimitSpec spec = (DefaultLimitSpec) mapper.readValue(
        mapper.writeValueAsString(mapper.readValue(json, LimitSpec.class)),
        LimitSpec.class
    );

    Assert.assertEquals(
        new DefaultLimitSpec(null, null),
        spec
    );

    //non-defaults
    json = "{\n"
           + "  \"type\":\"default\",\n"
           + "  \"columns\":[{\"dimension\":\"d\",\"direction\":\"DESCENDING\", \"dimensionOrder\":\"numeric\"}],\n"
           + "  \"limit\":10\n"
           + "}";
    spec = (DefaultLimitSpec) mapper.readValue(
        mapper.writeValueAsString(mapper.readValue(json, LimitSpec.class)),
        LimitSpec.class
    );
    Assert.assertEquals(
        new DefaultLimitSpec(ImmutableList.of(new OrderByColumnSpec("d", OrderByColumnSpec.Direction.DESCENDING,
                                                                    StringComparators.NUMERIC)), 10),
        spec
    );

    json = "{\n"
           + "  \"type\":\"default\",\n"
           + "  \"columns\":[{\"dimension\":\"d\",\"direction\":\"DES\", \"dimensionOrder\":\"numeric\"}],\n"
           + "  \"limit\":10\n"
           + "}";

    spec = (DefaultLimitSpec) mapper.readValue(
        mapper.writeValueAsString(mapper.readValue(json, LimitSpec.class)),
        LimitSpec.class
    );

    Assert.assertEquals(
        new DefaultLimitSpec(ImmutableList.of(new OrderByColumnSpec("d", OrderByColumnSpec.Direction.DESCENDING,
                                                                    StringComparators.NUMERIC)), 10),
        spec
    );

    json = "{\n"
           + "  \"type\":\"default\",\n"
           + "  \"columns\":[{\"dimension\":\"d\"}],\n"
           + "  \"limit\":10\n"
           + "}";
    spec = (DefaultLimitSpec) mapper.readValue(
        mapper.writeValueAsString(mapper.readValue(json, LimitSpec.class)),
        LimitSpec.class
    );
    Assert.assertEquals(
        new DefaultLimitSpec(ImmutableList.of(new OrderByColumnSpec("d", OrderByColumnSpec.Direction.ASCENDING,
                                                                    StringComparators.LEXICOGRAPHIC)), 10),
        spec
    );

    json = "{\n"
           + "  \"type\":\"default\",\n"
           + "  \"columns\":[\"d\"],\n"
           + "  \"limit\":10\n"
           + "}";
    spec = (DefaultLimitSpec) mapper.readValue(
        mapper.writeValueAsString(mapper.readValue(json, LimitSpec.class)),
        LimitSpec.class
    );
    Assert.assertEquals(
        new DefaultLimitSpec(ImmutableList.of(new OrderByColumnSpec("d", OrderByColumnSpec.Direction.ASCENDING,
                                                                    StringComparators.LEXICOGRAPHIC)), 10),
        spec
    );

  }

  @Test
  public void testBuildSimple()
  {
    DefaultLimitSpec limitSpec = new DefaultLimitSpec(
        ImmutableList.of(),
        2
    );

    Function<Sequence<Row>, Sequence<Row>> limitFn = limitSpec.build(
        ImmutableList.of(),
        ImmutableList.of(),
        ImmutableList.of(),
        Granularities.NONE,
        false
    );

    Assert.assertEquals(
        ImmutableList.of(testRowsList.get(0), testRowsList.get(1)),
        limitFn.apply(testRowsSequence).toList()
    );
  }

  @Test
  public void testWithAllGranularity()
  {
    DefaultLimitSpec limitSpec = new DefaultLimitSpec(
        ImmutableList.of(new OrderByColumnSpec("k1", OrderByColumnSpec.Direction.ASCENDING, StringComparators.NUMERIC)),
        2
    );

    Function<Sequence<Row>, Sequence<Row>> limitFn = limitSpec.build(
        ImmutableList.of(new DefaultDimensionSpec("k1", "k1", ValueType.DOUBLE)),
        ImmutableList.of(),
        ImmutableList.of(),
        Granularities.ALL,
        true
    );

    Assert.assertEquals(
        ImmutableList.of(testRowsList.get(0), testRowsList.get(1)),
        limitFn.apply(testRowsSequence).toList()
    );
  }

  @Test
  public void testWithSortByDimsFirst()
  {
    DefaultLimitSpec limitSpec = new DefaultLimitSpec(
        ImmutableList.of(new OrderByColumnSpec("k1", OrderByColumnSpec.Direction.ASCENDING, StringComparators.NUMERIC)),
        2
    );

    Function<Sequence<Row>, Sequence<Row>> limitFn = limitSpec.build(
        ImmutableList.of(new DefaultDimensionSpec("k1", "k1", ValueType.DOUBLE)),
        ImmutableList.of(),
        ImmutableList.of(),
        Granularities.NONE,
        true
    );

    Assert.assertEquals(
        ImmutableList.of(testRowsList.get(2), testRowsList.get(0)),
        limitFn.apply(testRowsSequence).toList()
    );
  }

  @Test
  public void testSortDimensionDescending()
  {
    DefaultLimitSpec limitSpec = new DefaultLimitSpec(
        ImmutableList.of(new OrderByColumnSpec("k1", OrderByColumnSpec.Direction.DESCENDING)),
        2
    );

    Function<Sequence<Row>, Sequence<Row>> limitFn = limitSpec.build(
        ImmutableList.of(new DefaultDimensionSpec("k1", "k1")),
        ImmutableList.of(),
        ImmutableList.of(),
        Granularities.NONE,
        false
    );

    // Note: This test encodes the fact that limitSpec sorts numbers like strings; we might want to change this
    // in the future.
    Assert.assertEquals(
        ImmutableList.of(testRowsList.get(2), testRowsList.get(1)),
        limitFn.apply(testRowsSequence).toList()
    );
  }

  @Test
  public void testBuildWithExplicitOrder()
  {
    DefaultLimitSpec limitSpec = new DefaultLimitSpec(
        ImmutableList.of(
            new OrderByColumnSpec("k1", OrderByColumnSpec.Direction.ASCENDING)
        ),
        2
    );

    Function<Sequence<Row>, Sequence<Row>> limitFn = limitSpec.build(
        ImmutableList.of(
            new DefaultDimensionSpec("k1", "k1")
        ),
        ImmutableList.of(
            new LongSumAggregatorFactory("k2", "k2")
        ),
        ImmutableList.of(
            new ConstantPostAggregator("k3", 1L)
        ),
        Granularities.NONE,
        false
    );
    Assert.assertEquals(
        ImmutableList.of(testRowsList.get(0), testRowsList.get(1)),
        limitFn.apply(testRowsSequence).toList()
    );

    // if there is an aggregator with same name then that is used to build ordering
    limitFn = limitSpec.build(
        ImmutableList.of(
            new DefaultDimensionSpec("k1", "k1")
        ),
        ImmutableList.of(
            new LongSumAggregatorFactory("k1", "k1")
        ),
        ImmutableList.of(
            new ConstantPostAggregator("k3", 1L)
        ),
        Granularities.NONE,
        false
    );
    Assert.assertEquals(
        ImmutableList.of(testRowsList.get(2), testRowsList.get(0)),
        limitFn.apply(testRowsSequence).toList()
    );

    // if there is a post-aggregator with same name then that is used to build ordering
    limitFn = limitSpec.build(
        ImmutableList.of(
            new DefaultDimensionSpec("k1", "k1")
        ),
        ImmutableList.of(
            new LongSumAggregatorFactory("k2", "k2")
        ),
        ImmutableList.of(
            new ArithmeticPostAggregator(
                "k1",
                "+",
                ImmutableList.of(
                    new ConstantPostAggregator("x", 1),
                    new ConstantPostAggregator("y", 1))
            )
        ),
        Granularities.NONE,
        false
    );
    Assert.assertEquals(
        (List) ImmutableList.of(testRowsList.get(2), testRowsList.get(0)),
        (List) limitFn.apply(testRowsSequence).toList()
    );

    // makes same result
    limitFn = limitSpec.build(
        ImmutableList.of(new DefaultDimensionSpec("k1", "k1")),
        ImmutableList.of(new LongSumAggregatorFactory("k2", "k2")),
        ImmutableList.of(new ExpressionPostAggregator("k1", "1 + 1", null, TestExprMacroTable.INSTANCE)),
        Granularities.NONE,
        false
    );
    Assert.assertEquals(
        (List) ImmutableList.of(testRowsList.get(2), testRowsList.get(0)),
        (List) limitFn.apply(testRowsSequence).toList()
    );
  }

  private Row createRow(String timestamp, Object... vals)
  {
    Preconditions.checkArgument(vals.length % 2 == 0);

    Map<String, Object> theVals = Maps.newHashMap();
    for (int i = 0; i < vals.length; i += 2) {
      theVals.put(vals[i].toString(), vals[i + 1]);
    }

    return new MapBasedRow(DateTimes.of(timestamp), theVals);
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
  ~ Copyright 2021 The Android Open Source Project
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~     https://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
-->
<resources>
    <string name="app_name">AnimationCodelab</string>
    <string name="home">Home</string>
    <string name="work">Work</string>
    <string name="weather">Weather</string>
    <string name="temperature">18 ℃</string>
    <string name="tasks">Tasks</string>
    <string name="add_tasks">ADD TASKS</string>
    <string-array name="tasks">
        <item>Buy milk</item>
        <item>Choose curtain</item>
        <item>Plant rosemary</item>
        <item>Finish the essay</item>
        <item>Receive new packages</item>
        <item>Take a photo</item>
    </string-array>
    <string name="topics">Topics</string>
    <string-array name="topics">
        <item>2 new packages arrived</item>
        <item>DIY project recommendation</item>
        <item>Festival next month</item>
        <item>New flower seeds available</item>
    </string-array>
    <string name="lorem_ipsum">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</string>
    <string name="edit">EDIT</string>
    <string name="edit_message">Edit feature is not supported</string>
    <string name="refresh">Refresh</string>
</resources>


text:
package pointGroups.gui.event;

import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.logging.Logger;

import pointGroups.util.LoggerFactory;

/**
 * The EventDispatcher is the central object in the event handling flow that
 * accepts {@link Event}s that get fired and dispatches these events to their
 * according (registered) {@link EventHandler}. Event handler can be added and
 * removed using the {@link #addHandler(Class, EventHandler)} and
 * {@link #removeHandler(Class, EventHandler)} methods (respectively).
 *
 * @author Marcel, Alex
 */
public class EventDispatcher
{
  protected final static EventDispatcher dispatcher = new EventDispatcher();
  protected final static Logger logger =
      LoggerFactory.getSingle(EventDispatcher.class);

  /**
   * Return a singleton instance of {@link EventDispatcher}
   *
   * @return The dispatcher singleton
   */
  public static EventDispatcher get() {
    return dispatcher;
  }

  public Map<Class<? extends EventHandler>, Collection<? extends EventHandler>> eventTypeHandlerMap =
      Collections.synchronizedMap(new HashMap<Class<? extends EventHandler>, Collection<? extends EventHandler>>());

  /**
   * Adds the specified {@link EventHandler} to be invoked on firing the
   * according {@link Event} with {@link #fireEvent(Event)}.
   *
   * @param handlerType The type of the event handler
   * @param handler The handler to be added
   */
  public <H extends EventHandler> void addHandler(final Class<H> handlerType,
      final H handler) {
    Collection<H> handlers = forceHandlerCollection(handlerType);
    handlers.add(handler);
  }

  /**
   * Removes the specified {@link EventHandler} from the registered handlers.
   * After calling this method, that handler will not be invoked on firing the
   * according {@link Event} with {@link #fireEvent(Event)} anymore.
   *
   * @param handlerType The type of the event handler
   * @param handler The handler to be removed
   */
  public <H extends EventHandler> void removeHandler(
      final Class<H> handlerType, final H handler) {
    Collection<H> handlers = forceHandlerCollection(handlerType);
    handlers.remove(handler);
  }

  /**
   * Fires an {@link Event} which will cause the {@link EventDispatcher} to
   * dispatch this event to all registered {@link EventHandler}s (of that
   * according type).
   *
   * @param event The event to be fired
   */
  public void fireEvent(final Event<?> event) {
    logger.info("Event fired: " + event);

    fireEvent0(event);
  }

  private <H extends EventHandler> void fireEvent0(final Event<H> event) {
    Collection<H> handlers = this.getHandlers(event.getType());

    synchronized (handlers) {
      for (H h : handlers) {
        event.dispatch(h);
      }
    }
  }

  private <H extends EventHandler> Collection<H> forceHandlerCollection(
      final Class<H> handlerType) {
    @SuppressWarnings("unchecked")
    // Cast is safe, since addHandler checks the types
    Collection<H> existingHandlers =
        (Collection<H>) eventTypeHandlerMap.get(handlerType);

    if (existingHandlers == null) {
      existingHandlers = Collections.synchronizedList(new LinkedList<H>());
      eventTypeHandlerMap.put(handlerType, existingHandlers);
    }

    return existingHandlers;
  }

  private <H extends EventHandler> Collection<H> getHandlers(
      final Class<H> handlerType) {
    @SuppressWarnings("unchecked")
    // Cast is safe, since addHandler checks the types
    Collection<H> handlers =
        (Collection<H>) eventTypeHandlerMap.get(handlerType);
    if (handlers == null) {
      return Collections.emptyList();
    }
    else {
      return handlers;
    }
  }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>APP.GUI.pager - CMDI Maker</title>
    <link rel="stylesheet" href="http://yui.yahooapis.com/3.9.1/build/cssgrids/cssgrids-min.css">
    <link rel="stylesheet" href="../assets/vendor/prettify/prettify-min.css">
    <link rel="stylesheet" href="../assets/css/main.css" id="site_styles">
    <link rel="icon" href="../assets/favicon.ico">

            API Docs for: 2.10

APIs

Classes

Modules

                            <input type="search" id="api-filter" placeholder="Type to filter APIs">

APP

APP.CONF

APP.environments

APP.forms

APP.GUI

APP.GUI.FORMS

APP.GUI.pager

APP.intl

APP.save_and_recall

APP.settings

HELPERS

CORE

HELPERS

                    Show:

                        <input type="checkbox" id="api-show-inherited" checked>
                        Inherited

                        <input type="checkbox" id="api-show-protected">
                        Protected

                        <input type="checkbox" id="api-show-private">
                        Private

                        <input type="checkbox" id="api-show-deprecated">
                        Deprecated

APP.GUI.pager Class

            Defined in: src\js\core\app.gui.pager.js:18

            Module: CORE

A sub module of APP.GUI that allows to create a pager for splitting lots of screen elements on several pages.

Index

Item Index


text:
package org.mosspaper.objects;

import org.mosspaper.Common;

public class Swap extends AbsMossObject implements MossObject {

    /**
     * Display the amount of swap memory being used.
     */
    public Swap() { }

    public DataProvider getDataProvider() {
        return memInfo;
    }

    @Override
    public String toString() {
        return Common.humanReadble(memInfo.getSwapTotal() - memInfo.getSwapFree());
    }

    private ProcMemInfo memInfo = ProcMemInfo.INSTANCE;
}