text:
{-# LANGUAGE OverloadedStrings, DeriveDataTypeable, RecordWildCards #-}

module Bark.Options (
      Options(..)
    , parseOptions
    ) where

import Control.Applicative    ((<$>))
import Control.Monad          (when)
import Data.Version
import Network.BSD            (getHostName)
import System.Console.CmdArgs
import System.Environment     (getArgs, withArgs, getProgName)
import System.Exit            (ExitCode(..), exitWith)
import Bark.Types

import qualified Data.ByteString.Char8 as B

data Raw = Raw
    { rawDelim         :: String
    , rawHost          :: String
    , rawService       :: String
    , rawUri           :: String
    , rawReconnect     :: Int
    , rawReadBytes     :: Int
    , rawDeliverBuffer :: Int
    , rawTee           :: Bool
    , rawStrip         :: Bool
    } deriving (Data, Typeable, Show)

data Options = Options
    { optDelim         :: String
    , optHost          :: Host
    , optService       :: Service
    , optUri           :: URI
    , optReconnect     :: Int
    , optReadBytes     :: Int
    , optDeliverBuffer :: Int
    , optTee           :: Bool
    , optStrip         :: Bool
    } deriving (Show)

parseOptions :: IO Options
parseOptions = do
    arg <- getArgs
    raw <- (if null arg then withArgs ["--help"] else id) parse
    return . conv =<< validate raw

--
-- Internal
--

parse :: IO Raw
parse = do
    app <- getProgName
    let ver = summary $ concat [app, ": ", showVersion version]
    cmdArgs $ defaults
        &= versionArg [explicit, name "version", name "v", ver]
        &= summary ""
        &= helpArg [explicit, name "help", name "h"]
        &= program ("Usage: " ++ app)

conv :: Raw -> Options
conv Raw{..} = Options
    rawDelim
    (B.pack rawHost)
    (B.pack rawService)
    (parseURI rawUri)
    (rawReconnect * 1000)
    rawReadBytes
    rawDeliverBuffer
    rawTee
    rawStrip

version :: Version
version = Version
    { versionBranch = [0, 1, 0]
    , versionTags   = ["experimental"]
    }

validate :: Raw -> IO Raw
validate raw@Raw{..} = do
    exitWhen (null rawDelim)         "--delimiter cannot be blank"
    exitWhen (null rawService)       "--service cannot be blank"
    exitWhen (rawReadBytes <= 0)     "--read-bytes must be greater than zero"
    exitWhen (rawDeliverBuffer <= 0) "--deliver-buffer must be greater than zero"
    exitWhen (rawReconnect     <= 0) ""
    addHostName raw

exitWhen :: Bool -> String -> IO ()
exitWhen p msg = when p $ putStrLn msg >> exitWith (ExitFailure 1)

addHostName :: Raw -> IO Raw
addHostName raw@Raw{..} =
    addHost <$> map f <$> getHostName
  where
    f '.' = '_'
    f c   = c
    addHost h | null rawHost = raw { rawHost = h }
              | otherwise    = raw

defaults :: Raw
defaults = Raw
    { rawDelim = "\n"
        &= name "delimiter"
        &= typ  "STRING"
        &= help "A byte or string delimiting output (default: \\n)"
        &= explicit

    , rawService = ""
        &= name "service"
        &= typ  "SERVICE"
        &= help "Application service name (required)"
        &= explicit

    , rawHost = ""
        &= name "hostname"
        &= typ  "HOSTNAME"
        &= help "Overrideable local hostname (default: `hostname`)"
        &= explicit

    , rawUri = "amqp://guest:guest@127.0.0.1/"
        &= name "uri"
        &= typ  "URI"
        &= help "AMQP URI where events will be published (default: guest@localhost)"
        &= explicit

    , rawReconnect = 500
        &= name "reconnect-delay"
        &= typ  "INT"
        &= help "Number of milliseconds to delay before attempting a reconnect (default: 500)"
        &= explicit

    , rawReadBytes = 4096
        &= name "read-bytes"
        &= typ  "BYTES"
        &= help "Size of the stdin buffer (default: 4096)"
        &= explicit

    , rawDeliverBuffer = 2048
        &= name "deliver-buffer"
        &= typ  "INT"
        &= help "Number of parsed events to buffer during publish (default: 2048)"
        &= explicit

    , rawStrip = False
        &= name "strip"
        &= help "Remove the delimiter from output (default: false)"
        &= explicit

    , rawTee = False
        &= name "tee"
        &= help "Additionally write output to stdout (default: false)"
        &= explicit
    }


text:
package rootlessport

import (
	"context"
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"os"
	"os/exec"
	"os/signal"

	"github.com/containernetworking/plugins/pkg/ns"
	"github.com/containers/storage/pkg/reexec"
	"github.com/cri-o/ocicni/pkg/ocicni"
	"github.com/pkg/errors"
	rkport "github.com/rootless-containers/rootlesskit/pkg/port"
	rkbuiltin "github.com/rootless-containers/rootlesskit/pkg/port/builtin"
	rkportutil "github.com/rootless-containers/rootlesskit/pkg/port/portutil"
	"github.com/sirupsen/logrus"
	"golang.org/x/sys/unix"
)

const (
	// ReexecKey is the reexec key for the parent process.
	ReexecKey = "containers-rootlessport"
	// reexecChildKey is used internally for the second reexec
	reexecChildKey       = "containers-rootlessport-child"
	reexecChildEnvOpaque = "_CONTAINERS_ROOTLESSPORT_CHILD_OPAQUE"
)

// Config needs to be provided to the process via stdin as a JSON string.
// stdin needs to be closed after the message has been written.
type Config struct {
	Mappings  []ocicni.PortMapping
	NetNSPath string
	ExitFD    int
	ReadyFD   int
	TmpDir    string
	ChildIP   string
}

func init() {
	reexec.Register(ReexecKey, func() {
		if err := parent(); err != nil {
			fmt.Println(err)
			os.Exit(1)
		}
	})
	reexec.Register(reexecChildKey, func() {
		if err := child(); err != nil {
			fmt.Println(err)
			os.Exit(1)
		}
	})
}

func loadConfig(r io.Reader) (*Config, io.ReadCloser, io.WriteCloser, error) {
	stdin, err := ioutil.ReadAll(r)
	if err != nil {
		return nil, nil, nil, err
	}
	var cfg Config
	if err := json.Unmarshal(stdin, &cfg); err != nil {
		return nil, nil, nil, err
	}
	if cfg.NetNSPath == "" {
		return nil, nil, nil, errors.New("missing NetNSPath")
	}
	if cfg.ExitFD <= 0 {
		return nil, nil, nil, errors.New("missing ExitFD")
	}
	exitFile := os.NewFile(uintptr(cfg.ExitFD), "exitfile")
	if exitFile == nil {
		return nil, nil, nil, errors.New("invalid ExitFD")
	}
	if cfg.ReadyFD <= 0 {
		return nil, nil, nil, errors.New("missing ReadyFD")
	}
	readyFile := os.NewFile(uintptr(cfg.ReadyFD), "readyfile")
	if readyFile == nil {
		return nil, nil, nil, errors.New("invalid ReadyFD")
	}
	return &cfg, exitFile, readyFile, nil
}

func parent() error {
	// load config from stdin
	cfg, exitR, readyW, err := loadConfig(os.Stdin)
	if err != nil {
		return err
	}

	exitC := make(chan os.Signal, 1)
	defer close(exitC)

	go func() {
		sigC := make(chan os.Signal, 1)
		signal.Notify(sigC, unix.SIGPIPE)
		defer func() {
			signal.Stop(sigC)
			close(sigC)
		}()

		select {
		case s := <-sigC:
			if s == unix.SIGPIPE {
				if f, err := os.OpenFile("/dev/null", os.O_WRONLY, 0755); err == nil {
					unix.Dup2(int(f.Fd()), 1) // nolint:errcheck
					unix.Dup2(int(f.Fd()), 2) // nolint:errcheck
					f.Close()
				}
			}
		case <-exitC:
		}
	}()

	// create the parent driver
	stateDir, err := ioutil.TempDir(cfg.TmpDir, "rootlessport")
	if err != nil {
		return err
	}
	defer os.RemoveAll(stateDir)
	driver, err := rkbuiltin.NewParentDriver(&logrusWriter{prefix: "parent: "}, stateDir)
	if err != nil {
		return err
	}
	initComplete := make(chan struct{})
	quit := make(chan struct{})
	errCh := make(chan error)
	// start the parent driver. initComplete will be closed when the child connected to the parent.
	logrus.Infof("starting parent driver")
	go func() {
		driverErr := driver.RunParentDriver(initComplete, quit, nil)
		if driverErr != nil {
			logrus.WithError(driverErr).Warn("parent driver exited")
		}
		errCh <- driverErr
		close(errCh)
	}()
	opaque := driver.OpaqueForChild()
	logrus.Infof("opaque=%+v", opaque)
	opaqueJSON, err := json.Marshal(opaque)
	if err != nil {
		return err
	}
	childQuitR, childQuitW, err := os.Pipe()
	if err != nil {
		return err
	}
	defer func() {
		// stop the child
		logrus.Info("stopping child driver")
		if err := childQuitW.Close(); err != nil {
			logrus.WithError(err).Warn("unable to close childQuitW")
		}
	}()

	// reexec the child process in the child netns
	cmd := exec.Command("/proc/self/exe")
	cmd.Args = []string{reexecChildKey}
	cmd.Stdin = childQuitR
	cmd.Stdout = &logrusWriter{prefix: "child"}
	cmd.Stderr = cmd.Stdout
	cmd.Env = append(os.Environ(), reexecChildEnvOpaque+"="+string(opaqueJSON))
	childNS, err := ns.GetNS(cfg.NetNSPath)
	if err != nil {
		return err
	}
	if err := childNS.Do(func(_ ns.NetNS) error {
		logrus.Infof("starting child driver in child netns (%q %v)", cmd.Path, cmd.Args)
		return cmd.Start()
	}); err != nil {
		return err
	}

	childErrCh := make(chan error)
	go func() {
		err := cmd.Wait()
		childErrCh <- err
		close(childErrCh)
	}()

	defer func() {
		if err := unix.Kill(cmd.Process.Pid, unix.SIGTERM); err != nil {
			logrus.WithError(err).Warn("kill child process")
		}
	}()

	logrus.Info("waiting for initComplete")
	// wait for the child to connect to the parent
outer:
	for {
		select {
		case <-initComplete:
			logrus.Infof("initComplete is closed; parent and child established the communication channel")
			break outer
		case err := <-childErrCh:
			if err != nil {
				return err
			}
		case err := <-errCh:
			if err != nil {
				return err
			}
		}
	}

	defer func() {
		logrus.Info("stopping parent driver")
		quit <- struct{}{}
		if err := <-errCh; err != nil {
			logrus.WithError(err).Warn("parent driver returned error on exit")
		}
	}()

	// let parent expose ports
	logrus.Infof("exposing ports %v", cfg.Mappings)
	if err := exposePorts(driver, cfg.Mappings, cfg.ChildIP); err != nil {
		return err
	}

	// write and close ReadyFD (convention is same as slirp4netns --ready-fd)
	logrus.Info("ready")
	if _, err := readyW.Write([]byte("1")); err != nil {
		return err
	}
	if err := readyW.Close(); err != nil {
		return err
	}

	// wait for ExitFD to be closed
	logrus.Info("waiting for exitfd to be closed")
	if _, err := ioutil.ReadAll(exitR); err != nil {
		return err
	}
	return nil
}

func exposePorts(pm rkport.Manager, portMappings []ocicni.PortMapping, childIP string) error {
	ctx := context.TODO()
	for _, i := range portMappings {
		hostIP := i.HostIP
		if hostIP == "" {
			hostIP = "0.0.0.0"
		}
		spec := rkport.Spec{
			Proto:      i.Protocol,
			ParentIP:   hostIP,
			ParentPort: int(i.HostPort),
			ChildPort:  int(i.ContainerPort),
			ChildIP:    childIP,
		}
		if err := rkportutil.ValidatePortSpec(spec, nil); err != nil {
			return err
		}
		if _, err := pm.AddPort(ctx, spec); err != nil {
			return err
		}
	}
	return nil
}

func child() error {
	// load the config from the parent
	var opaque map[string]string
	if err := json.Unmarshal([]byte(os.Getenv(reexecChildEnvOpaque)), &opaque); err != nil {
		return err
	}

	// start the child driver
	quit := make(chan struct{})
	errCh := make(chan error)
	go func() {
		d := rkbuiltin.NewChildDriver(os.Stderr)
		dErr := d.RunChildDriver(opaque, quit)
		errCh <- dErr
	}()
	defer func() {
		logrus.Info("stopping child driver")
		quit <- struct{}{}
		if err := <-errCh; err != nil {
			logrus.WithError(err).Warn("child driver returned error on exit")
		}
	}()

	// wait for stdin to be closed
	if _, err := ioutil.ReadAll(os.Stdin); err != nil {
		return err
	}
	return nil
}

type logrusWriter struct {
	prefix string
}

func (w *logrusWriter) Write(p []byte) (int, error) {
	logrus.Infof("%s%s", w.prefix, string(p))
	return len(p), nil
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace core\util\map;
use \Iterator as Iterator;
use \Countable as Countable;
use core\util\param\Validator as Validator;
use core\util\map\Mappable as Mappable;

/**
 * This class is used to store any kind of objects and provide access to those.
 * @author Marc Bredt
 */
class Map implements Mappable,Iterator,Countable {

  /**
   * Positional iterator for the implementation of Iterator methods.
   */
  private $pos = 0;

  /**
   * Array storig all elements passed via Map::add().
   */
  protected $map = array();

  /**
   * Type for values gong to be stored. Defaults to "null" but could and should
   * be adjusted whenever an object inherits from this class.
   */
  protected $type = null;

  /**
   * Add a key and the corresponding value to the map.
   * @param $key string identifing the map element, should be unique
   * @param $value value that should be stored, need to be of the type defined
   * @return true if the $value was inserted at $key, otherwise false
   */
  public function add($key = null, $value = null) {
    global $filelogger;
    $filelogger->log("k=%, v=%, t=%, is?=%, ie?=%, hk?=%, it?=%",
                     array(
                       $key, $value, $this->type,
                       Validator::isa($key,"string"),
                       Validator::isempty($key),
                       $this->has($key),
                       Validator::isa($value,$this->type)
                     ),"DEBUG");
    if(Validator::isa($key,"string") && !Validator::isempty($key)
       && !$this->has($key) && Validator::isa($value,$this->type)){
      $this->map[$key] = $value;
      return true;
    }

    $filelogger->log("invalid map type (k=%,v=%) for %",
                     array($key,$value,$this), "WARNING");
    return false;
  }

  /**
   * Remove a $key from the map.
   * @param $key string identifing the map element, should be unique
   * @return true if there is an element gonna be removed and the removal was
   *              successful, otherwise fals
   */
  public function remove($key = null) {

    global $filelogger;
    $filelogger->log("key=%, str?=%, empty?=%, haskey?=%",
                     array($key, Validator::isa($key,"string"),Validator::isempty($key),
                           $this->has($key)),"DEBUG");

    if(Validator::isa($key,"string") && !Validator::isempty($key)
       && $this->has($key)) {
      unset($this->map[$key]);
      return true;

    } else if(!$this->has($key)) {
      return true;

    }

    return false;
  }

  /**
   * Check if a $key is available in the map.
   * @param $key string identifing the map element, should be unique
   * @return true if $key exists, otherwise false
   */
  public function has($key = null) {
    return (Validator::isa($key,"string") && !Validator::isempty($key)
            && array_key_exists($key,$this->map));
  }

  /**
   * Get a map element.
   * @param $key string identifing the map element, should be unique
   * @return the corresponding element, otherwise null
   */
  public function get($key = null) {
    return ($this->has($key) ? $this->map[$key] : null);
  }

  /**
   * Set a map element.
   * @param $key string identifing the map element, should be unique
   * @return true if setting succeeded, otherwise false
   */
  public function set($key = null, $value = null) {
    return ($this->remove($key) && $this->add($key,$value));
  }

  /**
   * Get the current map.
   * @return array containing all elements currently stored
   */
  public function get_map() {
    return $this->map;
  }

  public function set_type($type = "") {
    $this->type = $type;
  }

  /**
   * Print information on this map.
   * @return string representing this object
   */
  public function __toString() {
    $s = get_class($this)."-".spl_object_hash($this)."= [ ";
    foreach($this->map as $k => $v) $s .= $k."='".$v."', ";
    $s .= rtrim($s,", ")." ]"; // remove last ", "
    return $s;
  }

  /* inherited methods from Iterator interface */

  public function current() {
    return $this->map[$this->key()];
  }

  public function key() {
    if(count($this->map)>0 && $this->pos<count($this->map))
      return array_keys($this->map)[$this->pos];
    else return 0;
  }

  public function next() {
    $this->pos++;
  }

  public function rewind() {
    $this->pos = 0;
  }

  public function valid() {
    return isset($this->map[$this->key()]);
  }

  /* inherited method from Contable interface */

  public function count() {
    return count($this->map);
  }

}


text:
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.openapi.vfs.newvfs.persistent;

import com.intellij.openapi.vfs.newvfs.AttributeInputStream;
import com.intellij.openapi.vfs.newvfs.AttributeOutputStream;
import com.intellij.openapi.vfs.newvfs.FileAttribute;
import com.intellij.util.io.DataInputOutputUtil;
import it.unimi.dsi.fastutil.ints.IntList;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.io.IOException;

final class PersistentFSAttributeAccessor {

  @NotNull
  private final PersistentFSConnection connection;
  @NotNull
  private final AbstractAttributesStorage attributesStorage;

  PersistentFSAttributeAccessor(final @NotNull PersistentFSConnection connection) {
    this.connection = connection;
    attributesStorage = connection.getAttributes();
  }

  public boolean hasAttributePage(final int fileId,
                                  final @NotNull FileAttribute attribute) throws IOException {
    return attributesStorage.hasAttributePage(connection, fileId, attribute);
  }

  @Nullable
  public AttributeInputStream readAttribute(final int fileId,
                                            final @NotNull FileAttribute attribute) throws IOException {
    final AttributeInputStream attributeStream = attributesStorage.readAttribute(connection, fileId, attribute);
    if (attributeStream != null && attribute.isVersioned()) {
      try {
        final int actualVersion = DataInputOutputUtil.readINT(attributeStream);
        if (actualVersion != attribute.getVersion()) {
          return null;
        }
      }
      catch (IOException e) {
        return null;
      }
    }
    return attributeStream;
  }

  /**
   * Opens given attribute of given file for writing
   */
  @NotNull
  public AttributeOutputStream writeAttribute(final int fileId,
                                              final @NotNull FileAttribute attribute) {
    final AttributeOutputStream attributeStream = attributesStorage.writeAttribute(connection, fileId, attribute);
    if (attribute.isVersioned()) {
      try {
        DataInputOutputUtil.writeINT(attributeStream, attribute.getVersion());
      }
      catch (IOException e) {
        throw new AssertionError("Write to byte[]-backed stream should not throw IOException -- a bug?", e);
      }
    }

    return attributeStream;
  }

  public void deleteAttributes(final int fileId) throws IOException {
    attributesStorage.deleteAttributes(connection, fileId);
  }

  public int getLocalModificationCount() {
    return attributesStorage.getLocalModificationCount();
  }

  public void checkAttributesStorageSanity(final int fileId,
                                           final @NotNull IntList usedAttributeRecordIds,
                                           final @NotNull IntList validAttributeIds) throws IOException {
    attributesStorage.checkAttributesStorageSanity(connection, fileId, usedAttributeRecordIds, validAttributeIds);
  }
}


text:
#include "Tangram3D.h"
#include "../../../3Engine/src/Shapes/BasicShapes.h"
#include "../../../3Engine/src/Shapes/MeshLoader.h"
#include "../../../3Engine/src/Shader/TextureLoader.h"
#include "../../../3Engine/src/Camera/Perspective.h"
#include "../../../3Engine/src/Utilities/Managers.h"
#include "../../../3Engine/src/Utilities/Simulation.h"
#include "../../../3Engine/src/Actors/SkySphere.h"

#define VERTICES 0
#define COLORS 1

using json = nlohmann::json;

int main(int argc, char* argv[]) {
    srand(static_cast <unsigned> (time(0)));

    {
        ThreeEngine::Tangram3D engine;
        engine.Init(argc, argv);
        engine.Run();
    }

    exit(EXIT_SUCCESS);
}

namespace ThreeEngine {

    Tangram3D::Tangram3D()
            : Engine(), sceneGraph(new SceneGraph()), controller(this) {}

    Tangram3D::~Tangram3D() = default;

    void Tangram3D::OnInit() {
        setupShaders();
        setupMeshes();
        setupTextures();
        scene();
    }

    void Tangram3D::setupShaders() {
        auto colorProgram = std::make_shared<ShaderProgram>(
                "shaders/Color3D/program.json");
        colorProgram->Init();
        ShaderProgramManager::instance()->Add("color3d", colorProgram);
        ShaderProgramManager::instance()->Add("default", colorProgram);
        auto skysphere = std::make_shared<ShaderProgram>(
                "shaders/SkySphere/program.json");
        skysphere->Init();
        ShaderProgramManager::instance()->Add("skysphere", skysphere);
    }

    void Tangram3D::setupMeshes() {
        MeshManager::instance()->Add("Cube",
                                     MeshLoader::instance()->LoadFileOBJ("assets/Cube-vtn.obj"));
    }

    void Tangram3D::setupTextures() {
        TextureManager::instance()->Add("GGB3",
                                        TextureLoader::instance()->LoadCubemap(
                                                "assets/GoldenGateBridge3/negz.jpg",
                                                "assets/GoldenGateBridge3/posz.jpg",
                                                "assets/GoldenGateBridge3/posy.jpg",
                                                "assets/GoldenGateBridge3/negy.jpg",
                                                "assets/GoldenGateBridge3/negx.jpg",
                                                "assets/GoldenGateBridge3/posx.jpg"
                                        ));
    }

    void Tangram3D::scene() {
        actors.push_back(reinterpret_cast<IDrawable*&&>(sceneGraph));

        { // Camera handling
            number width = config["window"]["x"];
            number height = config["window"]["y"];
            number aspect = width / height;
            Camera* camera = new Camera(
                    static_cast<GLuint>(
                            ShaderProgramManager::instance()->Get(
                                    "default")->GetUniformBlockBidingId(
                                    "SharedMatrices")),
                    new Perspective(30, aspect, 1, 1000),
                    new Matrix(Matrix::TranslationMatrix(Vector(0, 0, -100)))
//                    new LookAt({5, 0.5f, 0}, {0, 0.5f, 0}, {0, 1, 0})
            );
            sceneGraph->SetCamera(camera);
            controller.camera = camera;
        }

        auto colorProgram = ShaderProgramManager::instance()->Get("color3d");
        auto root = new Actor();
        root->setShaderProgram(colorProgram);
        sceneGraph->SetRoot(root);

        float triangleSize = 0.7071f;

        {
            auto skySphere = new SkySphere();
            skySphere->setShaderProgram(
                    ShaderProgramManager::instance()->Get("skysphere"));
            skySphere->mesh = MeshManager::instance()->Get("Sphere");
            skySphere->textures.push_back(
                    TextureManager::instance()->Get("GGB3"));
            auto&& hTransform = skySphere->transform;
            hTransform.scale = Vector(100);
            skySphere->SetParent(root);
        }

        Vector4 defaultColor = {.1f, .1f, .5f, 1.0f};

        { // Big triangle to the Left
            auto* shape = new Actor();
            shape->mesh = BasicShapes::TriangularParallelepiped(triangleSize * 2);
            shape->transform.rotation = Quat::FromAngleAxis(135, Vector::UpVector);
            shape->SetParent(root);
            Vector4 color = defaultColor;
            color[0] = .5f;
            shape->preDraw = [shape, color]() {
                glUniform4f(shape->GetShaderProgram()->GetUniformLocationId("ModelColor"),
                            color[0],
                            color[1],
                            color[2],
                            color[3]);
            };
        }
        { // Big triangle to the Top

            auto* shape = new Actor();
            shape->mesh = BasicShapes::TriangularParallelepiped(triangleSize * 2);
            shape->transform.translation = {0, 0, .5f};
            shape->transform.rotation = Quat::FromAngleAxis(45, Vector::UpVector);
            shape->SetParent(root);
            Vector4 color = defaultColor;
            color[1] = .5f;
            shape->preDraw = [shape, color]() {
                glUniform4f(shape->GetShaderProgram()->GetUniformLocationId("ModelColor"),
                            color[0],
                            color[1],
                            color[2],
                            color[3]);
            };
        }
        { // Small triangle at the center
            auto* shape = new Actor();
            shape->mesh = BasicShapes::TriangularParallelepiped(triangleSize);
            shape->transform.translation = {0, 0, -.5f};
            shape->transform.rotation = Quat::FromAngleAxis(-135, Vector::UpVector);
            shape->SetParent(root);
            const Vector4& color = defaultColor;
            shape->preDraw = [shape, color]() {
                glUniform4f(shape->GetShaderProgram()->GetUniformLocationId("ModelColor"),
                            color[0],
                            color[1],
                            color[2],
                            color[3]);
            };
        }
        { // Small triangle at the top right
            auto* shape = new Actor();
            shape->mesh = BasicShapes::TriangularParallelepiped(triangleSize);
            shape->transform.translation = {0.5f, 0.5f, .2f};
            shape->transform.rotation = Quat::FromAngleAxis(-45, Vector::UpVector);
            shape->SetParent(root);
            Vector4 color = defaultColor;
            color[0] = .5f;
            color[1] = .5f;
            shape->preDraw = [shape, color]() {
                glUniform4f(shape->GetShaderProgram()->GetUniformLocationId("ModelColor"),
                            color[0],
                            color[1],
                            color[2],
                            color[3]);
            };
        }
        { // Medium triangle to the bottom right
            auto* shape = new Actor();
            shape->mesh = BasicShapes::TriangularParallelepiped();
            shape->transform.translation = {1, -1, -.2f};
            shape->transform.rotation = Quat::FromAngleAxis(90, Vector::UpVector);
            shape->SetParent(root);
            Vector4 color = defaultColor;
            color[0] = .2f;
            color[1] = .7f;
            shape->preDraw = [shape, color]() {
                glUniform4f(shape->GetShaderProgram()->GetUniformLocationId("ModelColor"),
                            color[0],
                            color[1],
                            color[2],
                            color[3]);
            };
        }
        { // Square
            auto* shape = new Actor();
            bool fromObj = true;
            if (fromObj) {
                shape->mesh = MeshManager::instance()->Get("Cube");
                shape->transform.scale = Vector(triangleSize / 2.0f);
                shape->transform.translation = {0, 0, 1};

            } else {
                shape->mesh = BasicShapes::Cube(triangleSize);
                shape->transform.translation = {.5f, 0, 1};
            }
            shape->transform.rotation = Quat::FromAngleAxis(-45, Vector::UpVector);
            shape->SetParent(root);
            Vector4 color = defaultColor;
            color[0] = .2f;
            color[2] = .7f;
            shape->preDraw = [shape, color]() {
                glUniform4f(shape->GetShaderProgram()->GetUniformLocationId("ModelColor"),
                            color[0],
                            color[1],
                            color[2],
                            color[3]);
            };

        }
        {
            auto* shape = new Actor();
            shape->mesh = BasicShapes::SquaredParallelepiped();
            shape->transform.translation = {-1, -1, -1};
            shape->SetParent(root);
            Vector4 color = defaultColor;
            color[1] = .2f;
            color[2] = .7f;
            shape->preDraw = [shape, color]() {
                glUniform4f(shape->GetShaderProgram()->GetUniformLocationId("ModelColor"),
                            color[0],
                            color[1],
                            color[2],
                            color[3]);
            };
        }

//        sceneGraph->Init();
        for (auto&& actor : actors) {
            actor->Init();
        }
    }

    void Tangram3D::OnReshape(int, int) {
//        number aspect = (number) w / (number) h,
//                angle = Maths::ToRadians(30.0f / 2.0f),
//                d = 1.0f / tanf(angle);
//        camera->projection.M[0][0] = d / aspect;
    }

    void Tangram3D::PreDraw() {
        controller.Update();
    }

    void Tangram3D::Update() {
        if (input.Click(27)) { // ESC
            Exit();
        }
        Simulation::instance()->Update();
    }

    void Tangram3D::OnCleanup() {
        ShaderProgramManager::instance()->cleanup();
        MeshManager::instance()->cleanup();
        Simulation::instance()->cleanup();
    }

} /* namespace Divisaction */


text:
namespace faint::tablet{

InitResult initialize(HINSTANCE, HWND);
void uninitialize();
bool is_wt_packet(unsigned int);
void msg_activate(WPARAM, LPARAM);
void activate(bool);
struct WTP{
  int x;
  int y;
  int pressure;
  int cursor;
};

WTP get_wt_packet(WPARAM wParam, LPARAM lParam);

} // namespace

#endif


text:
class CmOperate < ActiveRecord::Base
end


text:
  - Relax constraint on logstash-core-plugin-api to >= 1.60 <= 2.99

# 3.0.1
  - Force encoding the gemspec of this plugin into utf-8 to make sure updating all the plugin works see https://github.com/elastic/logstash/issues/5468
  - Use oracle JDK8 for travis build
# 3.0.0
  - Use new Event API defined in Logstash 5.x (backwards incompatible change)
# 2.0.4
  - Depend on logstash-core-plugin-api instead of logstash-core, removing the need to mass update plugins on major releases of logstash
# 2.0.3
  - New dependency requirements for logstash-core for the 5.0 release
## 2.0.0
 - Plugins were updated to follow the new shutdown semantic, this mainly allows Logstash to instruct input plugins to terminate gracefully,
   instead of using Thread.raise on the plugins' threads. Ref: https://github.com/elastic/logstash/pull/3895
 - Dependency on logstash-core update to 2.0

## 0.1.0
* First version of the webhdfs plugin output


text:
void NieRAutomataMediaUtil::convert_ffmpeg(){
    if(outputPath->text().isEmpty()){
        QMessageBox::warning(this, "ffmpeg conversion", "Output path not specified.");
        return;
    }else if(outputFileName->text().isEmpty()){
        QMessageBox::warning(this, "ffmpeg conversion", "Output filename not specified");
        return;
    }else if(outputBitrate->text().isEmpty()){
        QMessageBox::warning(this, "ffmpeg conversion", "Output bitrate not specified.");
        return;
    }
    outfile = outputPath->text() + "/" + outputFileName->text();
    if(QFile::exists(outfile)){
        if(QMessageBox::question(this, "ffmpeg conversion", "Specified output file already exists. Overwrite?", QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes) == QMessageBox::No){
            return;
        }else{
            QFile::remove(outfile);
            while(QFile::exists(outfile));
        }
    }
    ffmpeg = new QProcess;
    killed = false;
    QString command = "\"" + QCoreApplication::applicationDirPath() + "/ffmpeg/bin/ffmpeg.exe\" -f mpegvideo -hide_banner -i ";
    command.append("\"" + info->absoluteFilePath() + "\" ");
    command.append(extraFfmpegFlags->text());
    command.append(" -b:v " + outputBitrate->text() + " ");
    command.append("\"" + outfile + "\"");
    ffmpeg_stdoutstr.append(command + "\n");

    connect(ffmpeg, SIGNAL(readyReadStandardOutput()), this, SLOT(ffmpeg_readyOut()));
    connect(ffmpeg, SIGNAL(finished(int)), this, SLOT(ffmpeg_done()));
    connect(ffmpeg, SIGNAL(started()), this, SLOT(ffmpeg_started()));

    ffmpeg->setProcessChannelMode(QProcess::MergedChannels);

    ffmpeg_out = new QDialog;
    ffmpeg_stdout = new QTextEdit;
    openOutFile = new QPushButton;
    openOutDir = new QPushButton;
    saveLog = new QPushButton;
    closeStdout = new QPushButton;
    ffmpeg_out_layout = new QFormLayout;
    ffmpeg_out_controls = new QGridLayout;
    killFfmpeg = new QPushButton;

    openOutFile->setText("Open output file");
    openOutDir->setText("Open output directory");
    saveLog->setText("Save output log");
    closeStdout->setText("Close");
    killFfmpeg->setText("Kill ffmpeg");

    connect(openOutFile, SIGNAL(released()), this, SLOT(open_out_file()));
    connect(openOutDir, SIGNAL(released()), this, SLOT(open_out_dir()));
    connect(saveLog, SIGNAL(released()), this, SLOT(save_ffmpeg_log()));
    connect(closeStdout, SIGNAL(released()), this, SLOT(close_stdout_widget()));
    connect(killFfmpeg, SIGNAL(released()), this, SLOT(kill_ffmpeg()));

    ffmpeg_out_controls->addWidget(openOutFile, 0, 0, 1, 1);
    ffmpeg_out_controls->addWidget(openOutDir, 0, 1, 1, 1);
    ffmpeg_out_controls->addWidget(killFfmpeg, 1, 0, 1, 1);
    ffmpeg_out_controls->addWidget(saveLog, 1, 1, 1, 1);
    ffmpeg_out_controls->addWidget(closeStdout, 2, 1, 1, 1);

    ffmpeg_stdout->setFixedHeight(384);
    ffmpeg_stdout->setReadOnly(true);
    ffmpeg_out_layout->addRow(ffmpeg_stdout);
    ffmpeg_out_layout->addRow(ffmpeg_out_controls);
    ffmpeg_out->setLayout(ffmpeg_out_layout);
    ffmpeg_out->setModal(true);
    ffmpeg_out->setFixedWidth(512);
    ffmpeg_out->setWindowFlags(ffmpeg_out->windowFlags() & ~Qt::WindowCloseButtonHint);
    ffmpeg_out->setWindowTitle("ffmpeg conversion");
    ffmpeg_out->show();

    ffmpeg->start(command);
}

void NieRAutomataMediaUtil::ffmpeg_started(){
    openOutFile->setEnabled(false);
    openOutDir->setEnabled(false);
    saveLog->setEnabled(false);
    closeStdout->setEnabled(false);
    killFfmpeg->setEnabled(true);
}

void NieRAutomataMediaUtil::ffmpeg_readyOut(){
    ffmpeg_stdoutstr.append(ffmpeg->readAllStandardOutput());
    ffmpeg_stdout->setText(ffmpeg_stdoutstr);
    ffmpeg_stdout->verticalScrollBar()->setValue(ffmpeg_stdout->verticalScrollBar()->maximum());
}

void NieRAutomataMediaUtil::ffmpeg_done(){
    if(QFile::exists(outputPath->text() + "/" + outputFileName->text())){
        if(killed == true){
            ffmpeg_stdoutstr.append("ffmpeg killed");
        }else{
            ffmpeg_stdoutstr.append("ffmpeg finished.");
        }
    }else{
        ffmpeg_stdoutstr.append("Failure");
    }
    ffmpeg_stdout->setText(ffmpeg_stdoutstr);
    ffmpeg_stdout->verticalScrollBar()->setValue(ffmpeg_stdout->verticalScrollBar()->maximum());
    openOutFile->setEnabled(true);
    openOutDir->setEnabled(true);
    saveLog->setEnabled(true);
    closeStdout->setEnabled(true);
    killFfmpeg->setEnabled(false);
}

void NieRAutomataMediaUtil::kill_ffmpeg(){
    killed = true;
    disconnect(ffmpeg, 0, 0, 0);
    ffmpeg->close();
    while(ffmpeg->state() != QProcess::NotRunning);
    QFile::remove(outfile);
    while(QFile::exists(outfile));
    ffmpeg_done();
}

void NieRAutomataMediaUtil::save_ffmpeg_log(){
    QString ffmpeg_log;
    if(!outputPathPersistent.isEmpty()){
        ffmpeg_log = QFileDialog::getSaveFileName(this, "Save log file to", outputPathPersistent + "/ffmpeg_log_" + QDateTime::currentDateTime().toString("dd_MM_yyyy_HH_mm_ss") + ".txt", "All files (*.*)");
    }else{
        ffmpeg_log = QFileDialog::getSaveFileName(this, "Save log file to", QCoreApplication::applicationDirPath() + "/ffmpeg_log_" + QDateTime::currentDateTime().toString("dd_MM_yyyy_HH_mm_ss") + ".txt", "All files (*.*)");
    }
    QFile out(ffmpeg_log);
    if(out.open(QIODevice::WriteOnly)){
        QTextStream stream(&out);
        stream << ffmpeg_stdoutstr;
    }
}

void NieRAutomataMediaUtil::output_path_changed(const QString &text){
    outputPathPersistent = text;
}

void NieRAutomataMediaUtil::output_bitrate_changed(const QString &text){
    outputBitratePersistent = text;
}

void NieRAutomataMediaUtil::extra_ffmpeg_flags_changed(const QString &text){
    extraFfmpegFlagsPersistent = text;
}

void NieRAutomataMediaUtil::open_out_dir(){
    QDesktopServices::openUrl(outputPath->text());
}

void NieRAutomataMediaUtil::open_out_file(){
    QDesktopServices::openUrl(outfile);
}

void NieRAutomataMediaUtil::close_stdout_widget(){
    ffmpeg_out->close();
}

void NieRAutomataMediaUtil::proc_output_destination(){
    outputDir = QFileDialog::getExistingDirectory(this, "Select output directory", dir, QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks);
    outputPath->setText(outputDir);
}


text:
require 'spec_helper'
require 'support/shared/unit/resource/static_provider_resolution'

describe Chef::Resource::RpmPackage, "initialize" do

  %w{linux aix}.each do |os|
    static_provider_resolution(
      resource: Chef::Resource::RpmPackage,
      provider: Chef::Provider::Package::Rpm,
      name: :rpm_package,
      action: :install,
      os: os
    )
  end

end

describe Chef::Resource::RpmPackage, "allow_downgrade" do
  before(:each) do
    @resource = Chef::Resource::RpmPackage.new("foo")
  end

  it "should allow you to specify whether allow_downgrade is true or false" do
    expect { @resource.allow_downgrade true }.not_to raise_error
    expect { @resource.allow_downgrade false }.not_to raise_error
    expect { @resource.allow_downgrade "monkey" }.to raise_error(ArgumentError)
  end
end


text:
<?php

namespace Magento\Framework\EntityManager\Sequence;

use Magento\Framework\DB\Sequence\SequenceInterface;
use Magento\Framework\ObjectManagerInterface;

/**
 * Class SequenceFactory
 */
class SequenceFactory
{
    /**
     * @var ObjectManagerInterface
     */
    protected $objectManager;

    /**
     * @var SequenceRegistry
     */
    protected $sequenceRegistry;

    /**
     * @var string
     */
    protected $instanceName;

    /**
     * @param SequenceRegistry $sequenceRegistry
     * @param ObjectManagerInterface $objectManager
     * @param string $instanceName
     */
    public function __construct(
        SequenceRegistry $sequenceRegistry,
        ObjectManagerInterface $objectManager,
        $instanceName = 'Magento\\Framework\\EntityManager\\Sequence\\Sequence'
    ) {
        $this->sequenceRegistry = $sequenceRegistry;
        $this->objectManager = $objectManager;
        $this->instanceName = $instanceName;
    }

    /**
     * Creates sequence instance
     *
     * @param string $entityType
     * @param array $config
     * @return SequenceInterface
     */
    public function create($entityType, $config)
    {
        if ($this->sequenceRegistry->retrieve($entityType) === false) {
            if (isset($config[$entityType]['sequence'])) {
                $this->sequenceRegistry->register(
                    $entityType,
                    $config[$entityType]['sequence']
                );
            } elseif (isset($config[$entityType]['sequenceTable'])) {
                if (isset($config[$entityType]['connectionName'])) {
                    $connectionName = $config[$entityType]['connectionName'];
                } else {
                    $connectionName = 'default';
                }
                $this->sequenceRegistry->register(
                    $entityType,
                    $this->objectManager->create(
                        $this->instanceName,
                        [
                            'connectionName' => $connectionName,
                            'sequenceTable' => $config[$entityType]['sequenceTable'],
                        ]
                    ),
                    $config[$entityType]['sequenceTable']
                );
            } else {
                $this->sequenceRegistry->register($entityType);
            }
        }
        return $this->sequenceRegistry->retrieve($entityType)['sequence'];
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>AssociationRules</title>
<meta name="date" content="2015-09-10">
<link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

weka.associations

Class AssociationRules

java.lang.Object

weka.associations.AssociationRules

All Implemented Interfaces:

java.io.Serializable

Direct Known Subclasses:

FilteredAssociationRules

public class AssociationRules
extends java.lang.Object
implements java.io.Serializable

Class encapsulating a list of association rules.

Version:

$Revision: 8034 $

Author:

Mark Hall (mhall{[at]}pentaho{[dot]}com)

See Also:

Serialized Form

Constructor Summary

Constructors

Constructor and Description

AssociationRules(java.util.List<AssociationRule> rules)

Constructs a new AssociationRules.

AssociationRules(java.util.List<AssociationRule> rules,
                java.lang.Object producer)

Constructs a new AssociationRules.

AssociationRules(java.util.List<AssociationRule> rules,
                java.lang.String producer)

Constructs a new AssociationRules.

Method Summary

Methods

Modifier and Type
Method and Description

int
getNumRules()

Get the number of rules.

java.lang.String
getProducer()

Get a string describing the scheme that produced these rules.

java.util.List<AssociationRule>
getRules()

Get the rules.

void
setProducer(java.lang.String producer)

Set a textual description of the scheme that produced
 these rules.

void
setRules(java.util.List<AssociationRule> rules)

Set the rules to use.

Methods inherited from class java.lang.Object

equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

AssociationRules

public AssociationRules(java.util.List<AssociationRule> rules,
                java.lang.String producer)

Constructs a new AssociationRules.

Parameters:

rules - the list of rules.

producer - a string describing the scheme that produced these rules.

AssociationRules

public AssociationRules(java.util.List<AssociationRule> rules,
                java.lang.Object producer)

Constructs a new AssociationRules.

Parameters:

rules - the list of rules.

producer - the scheme that produced the rules.

AssociationRules

public AssociationRules(java.util.List<AssociationRule> rules)

Constructs a new AssociationRules.

Parameters:

rules - the list of rules.

Method Detail

setRules

public void setRules(java.util.List<AssociationRule> rules)

Set the rules to use.

Parameters:

rules - the rules to use.

getRules

public java.util.List<AssociationRule> getRules()

Get the rules.

Returns:

the rules.

getNumRules

public int getNumRules()

Get the number of rules.

Returns:

the number of rules.

setProducer

public void setProducer(java.lang.String producer)

Set a textual description of the scheme that produced
 these rules.

Parameters:

producer - a textual description of the scheme that produced
 these rules.

getProducer

public java.lang.String getProducer()

Get a string describing the scheme that produced these rules.

Returns:

producer

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
  ~ Copyright 2016 Substance Mobile
  ~
  ~ 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
  ~
  ~ http://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.
  -->

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="@dimen/now_playing_seekbar_size"
        android:layout_weight="100"
        android:background="@color/faithfulPrimaryLight">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="0:00"
            android:id="@+id/controls_current_pos"
            android:layout_marginEnd="@dimen/margin_small"
            android:layout_marginStart="@dimen/margin_small"
            android:layout_gravity="center_vertical"
            android:textColor="@color/secondary_text_default_material_light" />

        <android.support.v7.widget.AppCompatSeekBar
            android:layout_width="0dp"
            android:layout_height="@dimen/now_playing_seekbar_size"
            android:id="@+id/control_seek_bar"
            android:progress="100"
            android:layout_weight="10"
            android:layout_gravity="center_vertical"
            android:thumb="@drawable/slider_alternate_thumb" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="9:99"
            android:id="@+id/controls_total_pos"
            android:layout_marginStart="@dimen/margin_small"
            android:layout_marginEnd="@dimen/margin_small"
            android:layout_gravity="center_vertical"
            android:textColor="@color/secondary_text_default_material_light" />

    </LinearLayout>

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="@dimen/albums_info_toolbar_size">

        <LinearLayout
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical">

            <LinearLayout
                android:orientation="horizontal"
                android:layout_width="match_parent"
                android:layout_height="wrap_content">

                <Space
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="10" />

                <FrameLayout
                    android:layout_width="@dimen/listViewSizeBig"
                    android:layout_height="@dimen/listViewSizeBig"
                    android:padding="@dimen/margin_small"
                    android:id="@+id/frameLayout">

                    <ImageView
                        android:layout_width="match_parent"
                        android:layout_height="match_parent"
                        android:src="@drawable/ic_skip_previous_black_48dp"
                        android:id="@+id/controls_prev_button"
                        android:background="?attr/ripple_circle"
                        android:layout_gravity="center"
                        android:padding="@dimen/margin_medium"
                        android:clickable="true" />
                </FrameLayout>

                <FrameLayout
                    android:layout_width="@dimen/listViewSizeBig"
                    android:layout_height="@dimen/listViewSizeBig"
                    android:padding="@dimen/margin_small"
                    android:id="@+id/controls_play_button_root">

                    <ImageView
                        android:layout_width="match_parent"
                        android:layout_height="match_parent"
                        android:src="@drawable/ic_play_arrow_black_48dp"
                        android:id="@+id/controls_play_button"
                        android:background="?attr/ripple_circle"
                        android:layout_gravity="center"
                        android:padding="@dimen/margin_medium"
                        android:clickable="true" />
                </FrameLayout>

                <FrameLayout
                    android:layout_width="@dimen/listViewSizeBig"
                    android:layout_height="@dimen/listViewSizeBig"
                    android:padding="@dimen/margin_small"
                    android:id="@+id/controls_pause_button_root"
                    android:visibility="gone">

                    <ImageView
                        android:layout_width="match_parent"
                        android:layout_height="match_parent"
                        android:src="@drawable/ic_pause_black_48dp"
                        android:id="@+id/controls_pause_button"
                        android:background="?attr/ripple_circle"
                        android:layout_gravity="center"
                        android:padding="@dimen/margin_medium"
                        android:clickable="true" />
                </FrameLayout>

                <FrameLayout
                    android:layout_width="@dimen/listViewSizeBig"
                    android:layout_height="@dimen/listViewSizeBig"
                    android:padding="@dimen/margin_small"
                    android:id="@+id/frameLayout3">

                    <ImageView
                        android:layout_width="match_parent"
                        android:layout_height="match_parent"
                        android:src="@drawable/ic_skip_next_black_48dp"
                        android:id="@+id/controls_next_button"
                        android:background="?attr/ripple_circle"
                        android:layout_gravity="center"
                        android:padding="@dimen/margin_medium"
                        android:clickable="true" />
                </FrameLayout>

                <Space
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="10" />
            </LinearLayout>

            <LinearLayout
                android:orientation="horizontal"
                android:layout_width="match_parent"
                android:layout_height="wrap_content">

                <Space
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="10" />

                <LinearLayout
                    android:orientation="horizontal"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_weight="100">

                    <ImageView
                        android:layout_width="@dimen/listviewIconSize"
                        android:layout_height="@dimen/listviewIconSize"
                        android:src="@drawable/ic_volume_none"
                        android:id="@+id/controls_volume_icon_empty"
                        android:background="?attr/ripple_circle"
                        android:layout_gravity="center"
                        android:padding="@dimen/margin_small"
                        android:clickable="true" />

                    <android.support.v7.widget.AppCompatSeekBar
                        android:layout_width="0dp"
                        android:layout_height="wrap_content"
                        android:id="@+id/controls_volume_seekbar"
                        android:progress="100"
                        android:layout_weight="10"
                        android:layout_gravity="center_vertical" />

                    <ImageView
                        android:layout_width="@dimen/listviewIconSize"
                        android:layout_height="@dimen/listviewIconSize"
                        android:src="@drawable/ic_volume_up"
                        android:id="@+id/controls_volume_icon_full"
                        android:background="?attr/ripple_circle"
                        android:layout_gravity="center"
                        android:padding="@dimen/margin_small"
                        android:clickable="true" />

                </LinearLayout>

                <Space
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="10" />
            </LinearLayout>
        </LinearLayout>
    </FrameLayout>

</LinearLayout>


text:
<?php
$template = <<<THEVERYENDOFYOU
<form action="login.php?do=login" method="post">

Informativo

O jogo está desativado até a versão 3.0 e haverá infelizmente, um reset nas contas, devido ao bug, que alterou os stats de todos os personagens do jogo.

Não há previsão de lançamento do jogo, mas estou trabalhando árduamente para terminá-lo, sendo otimista, acho que ainda vai demorar uns meses, e também será testado para evitar novos bugs.

Nome da Conta:	<input type="text" size="30" name="username" />

Senha:	<input type="password" size="30" name="password" />

Lembrar-me?	<input type="checkbox" name="rememberme" value="yes" /> Sim

<input type="submit" name="submit" value="Entrar" />

Marcando a opção "Lembrar-me" sua informação será guardada num cookie e você não terá que fazer login da próxima vez que você entrar no jogo.

Quer jogar? Você precisa registrar seu próprio personagem.

Você também pode mudar sua senha, ou requerer uma nova senha se você perdeu a sua.

Caso você tenha se registrado e não tenha recebido o e-mail de confirmação, você pode ativar sua conta agora mesmo.

</form>
THEVERYENDOFYOU;
?>


text:
define(['utils'], function(utils) {
  'use strict';

  describe('Utils.trim()', function() {

    it('should trim whitespace', function() {
      expect(utils.trim(' foo ')).to.be('foo');
      expect(utils.trim(' foo  bar ')).to.be('foo  bar');
      expect(utils.trim(' foo\n')).to.be('foo');
      expect(utils.trim('\r foo \r\n')).to.be('foo');
    });

  });

});


text:
![0 stars](../../images/ic_star_border_black_18dp_1x.png)![0 stars](../../images/ic_star_border_black_18dp_1x.png)![0 stars](../../images/ic_star_border_black_18dp_1x.png)![0 stars](../../images/ic_star_border_black_18dp_1x.png)![0 stars](../../images/ic_star_border_black_18dp_1x.png) 0

To use the Tech Hunt skill, try saying...

* *Alexa, ask Tech Hunt for top products*

* *Top products*

* *Top posts*

Tech Hunt can help you know today's top tech products/apps on Product Hunt. Upon invoking, Alexa will tell you the product's name along with a short description of it.

Say, "Alexa, ask Tech Hunt for top products" and discover your next favorite thing.

***

### Skill Details

* **Invocation Name:** tech hunt
* **Category:** null
* **ID:** amzn1.echo-sdk-ams.app.d012cc18-478b-44e3-9f9d-992c47282e55
* **ASIN:** B01G7CQPUS
* **Author:** Abhishek Warokar
* **Release Date:** May 27, 2016 @ 17:38:28
* **In-App Purchasing:** No


text:
import 'backbone-route-filter/backbone-route-filter';
import Marionette from 'backbone.marionette';
import { mixin } from 'core-decorators';
import Session from 'services/session';
import routes from 'helpers/routes';

@mixin({
  before: {
    'dashboard(/*path)': 'redirectIfNotLoggedIn'
  }
})
export default class BaseRouter extends Marionette.AppRouter {
  redirectIfNotLoggedIn() {
    if (!Session.isLoggedIn()) {
      this.navigate(routes.rootPath(), { trigger: true });
      return false;
    }
  }
}


text:
from api import cmd_func, cmd_helper
import os

@cmd_func('pwd')
def print_dir(interpreter, line):
    interpreter.poutput(os.path.abspath(os.path.curdir))

@cmd_helper('pwd')
def help_print_dir(interpreter):
    interpreter.poutput("Print current directory")


text:
package com.sybil_ehrensberger.transvis;

import org.xml.sax.SAXException;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import java.io.File;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Base class for each transcript and thus each individual process.
 *
 * @author Sybil Ehrensberger
 */
public class Transcript {

    /**
     * Participant ID
     */
    public String participant;
    /**
     * Group the participant belongs to
     */
    public String group;
    /**
     * Competence level (i.e. Beg, Pro)
     */
    public String competence;
    /**
     * Language version
     */
    public String version;
    /**
     * Name of the source text
     */
    public String sourcetextname;
    /**
     * Recording information added in the XML file
     */
    public Recording recording = null;
    /**
     * Adjustment time [in sec]
     */
    public int startAdjustment;
    /**
     * Total time of process (specified by start and end in recording tag)
     */
    public int totalTime;
    /**
     * Beginning of the drafting phase (first write incident)
     */
    public Double startDrafting = null;
    /**
     * Beginning of the revision phase (specified in recording tag)
     */
    public int startRevision;
    /**
     * Whether this transcript is from a workplace environment
     */
    public boolean workPlace;
    /**
     * Name of the selection (e.g. Complete Process, Orientation Phase, ...)
     */
    public String selection;
    /**
     * Beginning of the selection [in sec]
     */
    public double startSelection;
    /**
     * End of the selection [in sec]
     */
    public double endSelection;
    /**
     * Total duration of the selection [in sec]
     */
    public double durationSelection;
    /**
     * List of all found incidents
     */
    List<BaseIncident> incidents;
    /**
     * List of all incidents within the selection
     */
    List<BaseIncident> validIncidents;
    private String name;

    /**
     * Public constructor for a Transcript.
     *
     * @param fxmlFile the file to be parsed.
     * @throws ParserConfigurationException problem with the parser configuration
     * @throws SAXException                 problem with the xml parser
     * @throws IOException                  problem with reading the file
     */
    public Transcript(File fxmlFile) throws ParserConfigurationException, SAXException, IOException {

        incidents = new LinkedList<>();

        SAXParserFactory parserFactor = SAXParserFactory.newInstance();
        SAXParser parser = parserFactor.newSAXParser();
        TranscriptHandler handler = new TranscriptHandler(this);
        parser.parse(fxmlFile, handler);

        if (name == null || name.isEmpty())
            throw new TranscriptParseError("Missing name attribute!");

        if (recording == null)
            throw new TranscriptParseError("Missing recording attribute!");

    }

    public Transcript() {
    }

    /**
     * Converts the given timestring of the format HH:MM:SS to seconds
     * (an int).
     *
     * @param timestring the time (format HH:MM:SS)
     * @return the elapsed time in seconds
     */
    public static int convertToSeconds(String timestring) {

        String[] times = timestring.trim().split(":");
        int time = Integer.parseInt(times[0]) * 3600
                + Integer.parseInt(times[1]) * 60 + Integer.parseInt(times[2]);

        return time;
    }

    /**
     * The name of the file to be analyzed (also specified in the name attribute)
     *
     * @return the name of the file to be analyzed
     */
    public String getName() {
        return name;
    }

    /**
     * Parse the name attribute of the document in to individual parts and throw a fatal error if is malformed.
     *
     * @param n the name attribute from the XML file
     * @throws TranscriptParseError if the transcript is invalid
     */
    public void setName(String n) throws TranscriptParseError {

        if (n == null)
            throw new TranscriptParseError(n + ": Invalid name attribute");

        String[] parts = n.split("_");
        if (parts.length >= 4) {
            participant = parts[0];
            group = participant.replaceAll("(.{4})(\\d)*", "$1");
            competence = parts[1];
            version = parts[2];
            sourcetextname = parts[3];
        } else
            throw new TranscriptParseError(n + ": Invalid name attribute. ");
        name = n;
    }

    /**
     * Add the recording information to the transcript and validate it. If it is not valid, throw a fatal error.
     *
     * @param r the recording information to be added
     * @throws TranscriptParseError if the transcript is invalid
     */
    public void addRecording(Recording r) throws TranscriptParseError {

        if (recording != null) {
            throw new TranscriptParseError(name + ": Multiple recording attributes found.");
        }

        r.validate(this);

        recording = r;

    }

    // TODO: Better error handling!
    public void error(String s) {

        Main.note(getName() + ": " + s);
        System.out.println("ERROR: " + s);
    }

    /**
     * Set the selection according to the given type and given start and end times. Filter the incidents accordingly
     * so only incidents within that time span will be used.
     *
     * @param type  number indicating which type was chosen in the GUI (0: partial, 1: complete, 2: orientation, 3: drafting, 4: revision)
     * @param start the start time in seconds for partial processes
     * @param end   the end time in seconds for partial processes
     */
    public void setSelection(int type, int start, int end) {

        System.out.println("Start process: " + 0);
        System.out.println("Start drafting: " + startDrafting);
        System.out.println("Start revision: " + startRevision);
        System.out.println("End process: " + totalTime);

        switch (type) {
            case 0: // partial
                selection = "Partial Process";
                startSelection = start;
                endSelection = end;
                break;

            case 2: // orientation
                selection = "Orientation Phase";
                startSelection = 0;
                endSelection = startDrafting;
                break;
            case 3: // drafting
                selection = "Drafting Phase";
                startSelection = startDrafting;
                endSelection = startRevision;
                break;
            case 4: // revision
                selection = "Revision Phase";
                startSelection = startRevision;
                endSelection = totalTime;
                break;
            case 1: // complete
            default:
                selection = "Complete Process";
                startSelection = 0;
                endSelection = totalTime;
                break;
        }

        if (endSelection > totalTime) {
            error("Selected end time is after the end of the process");
            endSelection = totalTime;
        }

        if (startSelection < 0) {
            error("Selected start time is negative");
            startSelection = 0;
        }
        durationSelection = endSelection - startSelection;

        System.out.println("Start selection: " + startSelection);
        System.out.println("End selection: " + endSelection);
        System.out.println("Total time selection: " + durationSelection);

        validIncidents = incidents.stream().filter(inc -> inc.valid()).collect(Collectors.toList());
    }

    /**
     * Adjust the times of each incident to the current selection. Only adjust if the boolean adjust is true.
     * <p>
     * Function to be used in the graphs so that an incident a the start of a phase (orientation, drafting, revision)
     * will always have start time 0. This way, processes with different phase lengths can be compared accurately.
     * Beware this function adjusts the times in place (i.e. each incident is modified).
     *
     * @param adjust whether to adjust the times or not
     */
    public void adjustTimesToSelection(boolean adjust) {

        if (adjust) {
            for (BaseIncident b : validIncidents) {
                b.start = b.start - startSelection;
                b.end = b.end - startSelection;
            }
        }

    }

    /**
     * Converts a time (String) of the format HH:MM:SS to seconds and adjusts
     * it to the adjustment start time.
     *
     * @param timestring a String representing a time (HH:MM:SS)
     * @return an int representing the time in seconds
     */
    public int adjustTime(String timestring) {
        int time = convertToSeconds(timestring);
        return adjustTime(time);
    }

    /**
     * Adjust the given time t to ignore the warm-up phase.
     *
     * @param t the time in seconds
     * @return the adjusted time in seconds
     */
    public int adjustTime(int t) {
        return t - startAdjustment;
    }

}


text:
@interface SHOmniAuthTwitter ()
@end

@interface SHViewController ()

@end

@implementation SHViewController

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

    [SHOmniAuthTwitter performLoginWithListOfAccounts:^(NSArray *accounts, SHOmniAuthAccountPickerHandler pickAccountBlock) {
      pickAccountBlock(accounts.lastObject);
    } onComplete:^(id<account> account, id response, NSError *error, BOOL isSuccess) {
      NSLog(@"%@ - %@ -%@ - %d", account, response, error, isSuccess);
    }];

}

@end


text:
![](images/icon.png)

PullRefreshLayout for Android,like SwipeRefreshLayout,which support pull-down to refresh and pull-up to load more data, and is very streamlined.

In principle, it supports a variety of contentview, such as: RecyclerView, ListView, Webview, Scrollview and so on. But I have only tested RecyclerView, if you are using other contentview encounter problems, please contact me or sumbit issue.

Use this library,you can make any pull-down and pull-up animation,but i only finished two style. If you have another requirements,you can contact me.

## Preview

## Gradle
Step 1. Add the JitPack repository to your build file
```
allprojects {
	repositories {
		...
		maven { url 'https://jitpack.io' }
	}
}
```
Step 2. Add the dependency
```
dependencies {
        compile 'com.github.JayFang1993:PullRefreshLayout:v1.0-beta1'
}
```

## Usage

```xml
<info.fangjie.pulltorefresh.PullRefreshLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:PullRefreshLayout="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:id="@+id/pullrefreshlayout"
    android:layout_height="match_parent"
    android:background="#353739"
    PullRefreshLayout:enableload="true"
    >
  <TextView
      android:layout_width="match_parent"
      android:layout_centerVertical="true"
      android:background="#353739"
      android:id="@+id/tv_refresh_header"
      android:textColor="#ffffff"
      android:layout_height="60dp"
      android:gravity="center"
      />
  <android.support.v7.widget.RecyclerView
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:background="#ffffff"
      android:id="@+id/recyclerview"
      />
  <TextView
      android:background="#353739"
      android:layout_width="match_parent"
      android:layout_centerVertical="true"
      android:text="上拉加载"
      android:textColor="#ffffff"
      android:id="@+id/tv_refresh_footer"
      android:layout_height="60dp"
      android:gravity="center"
      />
</info.fangjie.pulltorefresh.PullRefreshLayout>
```
PullRefreshLayout has up 3 child view.
* 3 child view: first as header view,second as content view,last as footer
* 2 child view: first as header view,second as content view,no footer
* 1 child view: only one content view

### Pull-Down
```java
pullrefreshlayout.setRefreshListener(new RefreshListener(){
    //下拉到临界值后又上滑小于临界值
  @Override public void onPullBelowTarget() {}
    //下拉超过临界值
  @Override public void onPullOverTarget() {}
    //正在刷新
  @Override public void onRefreshing() {}
    //开始下拉
  @Override public void onPullBegin() { }
    //刷新完成
  @Override public void onRefreshComplete() {}
    //拉不到临界值的复原
  @Override public void onReset() {}
    //拉的过程中的偏移值
  @Override public void onPull(int offset) {}
});

//异步数据加载完成
pullrefreshlayout.setRefresh(false);
```

### Pull-Up
similar to `Pull-Down`

## Thanks
* [liaohuqiu/android-Ultra-Pull-To-Refresh](https://github.com/liaohuqiu/android-Ultra-Pull-To-Refresh)

## Contact
* Twitter: [@JayFang1993](https://twitter.com/jayfang1993)
* Weibo:[@方杰_Jay](http://weibo.com/ncuitstudent/)
* E-Mail:[JayFang1993@gmail.com](mailto:jayfang1993@gmail.com)
* Blog:[https://fangjie.info](https://fangjie.info)

## Licence

```
Copyright 2016 JayFang1993

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

   http://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.
```


text:
/* global $, APP, AJS, interfaceConfig */
import { LANGUAGES } from "../../../../react/features/base/i18n";
import { openDeviceSelectionDialog }
    from '../../../../react/features/device-selection';

import UIUtil from "../../util/UIUtil";
import UIEvents from "../../../../service/UI/UIEvents";

const sidePanelsContainerId = 'sideToolbarContainer';
const deviceSelectionButtonClasses
    = 'button-control button-control_primary button-control_full-width';
const htmlStr = `

        <form class="aui">

                <select id="languagesSelect"></select>

                    <button
                        class="${deviceSelectionButtonClasses}"
                        data-i18n="deviceSelection.deviceSettings"
                        id="deviceSelection"
                        type="button"></button>

                        <input type="checkbox" id="startAudioMuted">

                        <input type="checkbox" id="startVideoMuted">

                        <input type="checkbox" id="followMeCheckBox">

        </form>

`;

function initHTML() {
    $(`#${sidePanelsContainerId}`)
        .append(htmlStr);
    // make sure we translate the panel, as adding it can be after i18n
    // library had initialized and translated already present html
    APP.translation.translateElement($(`#${sidePanelsContainerId}`));
}

/**
 * Generate html select options for available languages.
 *
 * @param {string[]} items available languages
 * @param {string} [currentLang] current language
 * @returns {string}
 */
function generateLanguagesOptions(items, currentLang) {
    return items.map(function (lang) {
        let attrs = {
            value: lang,
            'data-i18n': `languages:${lang}`
        };

        if (lang === currentLang) {
            attrs.selected = 'selected';
        }

        let attrsStr = UIUtil.attrsToString(attrs);
        return `<option ${attrsStr}></option>`;
    }).join('');
}

/**
 * Replace html select element to select2 custom dropdown
 *
 * @param {jQueryElement} $el native select element
 * @param {function} onSelectedCb fired if item is selected
 */
function initSelect2($el, onSelectedCb) {
    $el.auiSelect2({
        minimumResultsForSearch: Infinity
    });
    if (typeof onSelectedCb === 'function') {
        $el.change(onSelectedCb);
    }
}

export default {
    init (emitter) {
        initHTML();
        //LANGUAGES BOX
        if (UIUtil.isSettingEnabled('language')) {
            const wrapperId = 'languagesSelectWrapper';
            const selectId = 'languagesSelect';
            const selectEl = AJS.$(`#${selectId}`);
            let selectInput;

            selectEl.html(generateLanguagesOptions(
                LANGUAGES,
                APP.translation.getCurrentLanguage()
            ));
            initSelect2(selectEl, () => {
                const val = selectEl.val();

                selectInput[0].dataset.i18n = `languages:${val}`;
                APP.translation.translateElement(selectInput);
                emitter.emit(UIEvents.LANG_CHANGED, val);
            });
            //find new selectInput element
            selectInput = $(`#s2id_${selectId} .select2-chosen`);
            //first select fix for languages options
            selectInput[0].dataset.i18n =
                `languages:${APP.translation.getCurrentLanguage()}`;

            // translate selectInput, which is the currently selected language
            // otherwise there will be no selected option
            APP.translation.translateElement(selectInput);
            APP.translation.translateElement(selectEl);

            APP.translation.addLanguageChangedListener(
                lng => selectInput[0].dataset.i18n = `languages:${lng}`);

            UIUtil.setVisible(wrapperId, true);
        }
        // DEVICES LIST
        if (UIUtil.isSettingEnabled('devices')) {
            const wrapperId = 'deviceOptionsWrapper';

            $('#deviceSelection').on('click', () =>
                APP.store.dispatch(openDeviceSelectionDialog()));

            // Only show the subtitle if this isn't the only setting section.
            if (interfaceConfig.SETTINGS_SECTIONS.length > 1)
                UIUtil.setVisible("deviceOptionsTitle", true);

            UIUtil.setVisible(wrapperId, true);
        }
        // MODERATOR
        if (UIUtil.isSettingEnabled('moderator')) {
            const wrapperId = 'moderatorOptionsWrapper';

            // START MUTED
            $("#startMutedOptions").change(function () {
                let startAudioMuted = $("#startAudioMuted").is(":checked");
                let startVideoMuted = $("#startVideoMuted").is(":checked");

                emitter.emit(
                    UIEvents.START_MUTED_CHANGED,
                    startAudioMuted,
                    startVideoMuted
                );
            });

            // FOLLOW ME
            const followMeToggle = document.getElementById('followMeCheckBox');
            followMeToggle.addEventListener('change', () => {
                const isFollowMeEnabled = followMeToggle.checked;
                emitter.emit(UIEvents.FOLLOW_ME_ENABLED, isFollowMeEnabled);
            });

            UIUtil.setVisible(wrapperId, true);
        }
    },

    /**
     * If start audio muted/start video muted options should be visible or not.
     * @param {boolean} show
     */
    showStartMutedOptions (show) {
        if (show && UIUtil.isSettingEnabled('moderator')) {
            // Only show the subtitle if this isn't the only setting section.
            if (!$("#moderatorOptionsTitle").is(":visible")
                    && interfaceConfig.SETTINGS_SECTIONS.length > 1)
                UIUtil.setVisible("moderatorOptionsTitle", true);

            UIUtil.setVisible("startMutedOptions", true);
        } else {
            // Only show the subtitle if this isn't the only setting section.
            if ($("#moderatorOptionsTitle").is(":visible"))
                UIUtil.setVisible("moderatorOptionsTitle", false);

            UIUtil.setVisible("startMutedOptions", false);
        }
    },

    updateStartMutedBox (startAudioMuted, startVideoMuted) {
        $("#startAudioMuted").attr("checked", startAudioMuted);
        $("#startVideoMuted").attr("checked", startVideoMuted);
    },

    /**
     * Shows/hides the follow me options in the settings dialog.
     *
     * @param {boolean} show {true} to show those options, {false} to hide them
     */
    showFollowMeOptions (show) {
        UIUtil.setVisible(
            "followMeOptions",
            show && UIUtil.isSettingEnabled('moderator'));
    },

    /**
     * Check if settings menu is visible or not.
     * @returns {boolean}
     */
    isVisible () {
        return UIUtil.isVisible(document.getElementById("settings_container"));
    }
};


text:
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <display-name>Jcms</display-name>
    <listener>
        <listener-class>com.bright.boot.ServiceBootListener</listener-class>
    </listener>
    <filter>
        <filter-name>base</filter-name>
        <filter-class>com.bright.mvc.ControlCenter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>base</filter-name>
        <url-pattern>/*</url-pattern>
        <dispatcher>REQUEST</dispatcher>
        <dispatcher>FORWARD</dispatcher>
    </filter-mapping>
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
    </welcome-file-list>
</web-app>


text:
'use strict';

var config = require('../../config');

/*
 * Code samples from:
 * http://docs.basho.com/riak/latest/dev/search/document-store/
 */

var async = require('async');
var fs = require('fs');
var https = require('https');
var logger = require('winston');
var path = require('path');

var Riak = require('basho-riak-client');

var BlogPost = require('./blog-post');
var BlogPostRepository = require('./blog-post-repository');

function maybeDownloadSchemaFile(callback) {
    var blogPostSchema =
        'https://raw.githubusercontent.com/basho/basho_docs/master/source/data/blog_post_schema.xml';
    var blogPostSchemaXmlFile = 'blog_post_schema.xml';

    fs.exists(blogPostSchemaXmlFile, function (exists) {
        var filePath = path.join(process.cwd(), blogPostSchemaXmlFile);
        if (exists) {
            callback(filePath);
        } else {
            logger.info("[DevSearchDocumentStore] downloading '%s'", filePath);
            var file = fs.createWriteStream(blogPostSchemaXmlFile);
            var request = https.get(blogPostSchema, function(response) {
                response.pipe(file);
                file.on('finish', function () {
                    file.close(callback(filePath));
                });
            });
        }
    });
}

function throwIfErr(err) {
    if (err) {
        throw new Error(err);
    }
}

function Init(done) {
    config.createClient(function (err, client) {
        throwIfErr(err);

        function createIndexInRiak() {
            var options = {
                schemaName: 'blog_post_schema',
                indexName: 'blog_posts'
            };
            client.storeIndex(options, function (err, rslt) {
                throwIfErr(err);
                client.stop(function (err) {
                    if (err) {
                        logger.error('[DevSearchDocumentStore|Init] err: %s', err);
                    }
                    done();
                });
            });
        }

        function storeSchemaInRiak(schemaXml) {
            var options = {
                schemaName: 'blog_post_schema',
                schema: schemaXml
            };
            client.storeSchema(options, function (err, rslt) {
                throwIfErr(err);
                createIndexInRiak();
            });
        }

        maybeDownloadSchemaFile(function (schemaFile) {
            fs.readFile(schemaFile, function (err, data) {
                throwIfErr(err);
                storeSchemaInRiak(data.toString('utf8'));
            });
        });
    });
}

function DevSearchDocumentStore(done) {
    config.createClient(function (err, client) {
        throwIfErr(err);

        storeBlogPost();

        function storeBlogPost() {
            var post = new BlogPost(
                'This one is so lulz!',
                'Cat Stevens',
                'Please check out these cat pics!',
                [ 'adorbs', 'cheshire', 'funny' ],
                new Date(),
                true
            );

            var repo = new BlogPostRepository(client, 'cat_pics_quarterly');

            repo.save(post, function (err, rslt) {
                throwIfErr(err);

                logger.debug("[DevSearchDocumentStore] rslt: '%s'", JSON.stringify(rslt));

                logger.info("[DevSearchDocumentStore] key: '%s', model: '%s'",
                    rslt.key, JSON.stringify(rslt.model));

                queryBlogPosts();
            });
        }

        function queryBlogPosts() {

            function search_cb(err, rslt) {
                logger.info("[DevSearchDocumentStore] numFound: '%d', docs: '%s'",
                    rslt.numFound, JSON.stringify(rslt.docs));
                client.stop(function (err) {
                    if (err) {
                        logger.error('[DevSearchDocumentStore] err: %s', err);
                    }
                    done();
                });
            }

            var searchCmd = new Riak.Commands.YZ.Search.Builder()
                .withIndexName('blog_posts')
                .withQuery('keywords_set:funny')
                .withCallback(search_cb)
                .build();

            // Note: YZ is about 1 second behind Riak when indexing
            setTimeout(function () {
                client.execute(searchCmd);
            }, 1000);
        }
    });
}

module.exports = DevSearchDocumentStore;
module.exports.Init = Init;


text:
import {Link, Redirect, useParams} from "react-router-dom";
import {useState, useEffect} from 'react';
import {getPage, deletePage} from "api/page";
import Page from "componenets/Page/Page";
import {Breadcrumbs, Crumb} from "componenets/Breadcrumns/Breadcrumbs";
import {Book, BookOpen, Delete, Home} from "Icons/Icons";
import {Button, Form, Text} from "componenets/Form/Form";

export default () => {

  const {id} = useParams();
  const [{label}, setPage] = useState({});
  const [loading, setLoading] = useState(false);
  const [redirect, setRedirect] = useState(false);

  const handleDelete = async () => {
    setLoading(true);
    await deletePage({id});
    setRedirect(true);
  }

  useEffect(async() => {
    const {data: page} = await getPage(id);
    setPage(page);
  }, []);

  if (redirect) {
    return <Redirect to={"/front/pages"} />;
  }

  return <Page
    notch={"small"}
    activePage="frontSite"
    topContent={
      <>
        <Breadcrumbs crumbs={[
          <Crumb title={'Home'} icon={<Home/>}/>,
          <Crumb title={'Front site'} icon={<Book/>}/>,
          <Crumb title={'Pages'} icon={<BookOpen/>}/>,
          <Crumb title={'Delete page'} icon={<Delete />}/>,
        ]}/>
      </>
    }>

    <Form title={Are you sure?} actions={<>
      <Link to={"/front/pages"}><Button type={"ok"}>No</Button></Link>
      <Button type={"error"} waiting={loading} onClick={() => {handleDelete()}}>Yes</Button>
    </>}>
      <Text>
        You going to delete the page {label} from the system. This action cannot be undone.
      </Text>
    </Form>
  </Page>
};


text:
/*
  <<<<<>>>>> CONDITION <<<<<>>>>>
  @ Using the extension methods OrderBy() and ThenBy() with lambda expressions sort the students by first name and last name in descending order.
  @ Rewrite the same with LINQ.
*/
namespace Problem_5.Order_students
{
    public class Student
    {
        public string Name { get; set; }
        public string LastName { get; set; }
        public int Age { get; set; }

        public override string ToString()
        {
            return this.Name + " " + this.LastName + " " + this.Age;
        }
    }
}


text:
NS_ASSUME_NONNULL_BEGIN

@implementation SDLPresetBankCapabilities

- (void)setOnScreenPresetsAvailable:(NSNumber<SDLBool> *)onScreenPresetsAvailable {
    [store sdl_setObject:onScreenPresetsAvailable forName:SDLNameOnScreenPresetsAvailable];
}

- (NSNumber<SDLBool> *)onScreenPresetsAvailable {
    return [store sdl_objectForName:SDLNameOnScreenPresetsAvailable];
}

@end

NS_ASSUME_NONNULL_END


text:
package androidx.appcompat.widget;

import static androidx.annotation.RestrictTo.Scope.LIBRARY_GROUP;

import androidx.annotation.Nullable;
import androidx.annotation.RestrictTo;

/**
 * @hide
 */
@RestrictTo(LIBRARY_GROUP)
public interface WithHint {
    /**
     * Returns the hint which is displayed in the floating label, if enabled.
     *
     * @return the hint, or null if there isn't one set, or the hint is not enabled.
     */
    @Nullable
    CharSequence getHint();
}


text:
Sponsors & Community Supporters

NetHui wouldn’t be possible without the generous support of a large number of community partners. If you would like to be a community support organisation and help us make NetHui 2017 the best yet please contact nethui@internetnz.net.nz.

If you would like to sponsor NetHui 2017 please take a look at our sponsorship prospectus, or contact us at nethui@internetnz.net.nz.


text:
// Copyright (c) 2012 Ecma International.  All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.

/*---
es5id: 15.4.4.14-2-6
description: Array.prototype.indexOf - 'length' is an inherited data property
---*/

        var proto = { length: 2 };

        var Con = function () {};
        Con.prototype = proto;

        var childOne = new Con();
        childOne[1] = true;
        var childTwo = new Con();
        childTwo[2] = true;

assert.sameValue(Array.prototype.indexOf.call(childOne, true), 1, 'Array.prototype.indexOf.call(childOne, true)');
assert.sameValue(Array.prototype.indexOf.call(childTwo, true), -1, 'Array.prototype.indexOf.call(childTwo, true)');


text:
module RemovePdfRestrictions
  VERSION = "0.1.0"
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.github.nhojpatrick</groupId>
    <artifactId>apache.maven.maven-core.MNG-5956-complex-parent</artifactId>
    <version>1</version>
    <packaging>pom</packaging>
    <modules>
        <module>application-one</module>
        <module>application-two</module>
        <module>application-three</module>
        <module>application-four</module>
        <module>audit</module>
        <module>common</module>
        <module>xmlbeans</module>
        <module>xsd</module>
    </modules>
</project>


text:
from enable.api import Container, TextField, Window
from enable.example_support import DemoFrame, demo_main

size = (500, 400)

class MyFrame(DemoFrame):
    def _create_window(self):
        text_field = TextField(position=[25,100], width=200)

        text = "This a test with a text field\nthat has more text than\n"
        text += "can fit in it."
        text_field2 = TextField(position=[25,200], width=200,
                                height=50, multiline=True,
                                text=text, font="Courier New 14")

        text_field3 = TextField(position=[250,50], height=300,
                                width=200, multiline=True,
                                font="Courier New 14")

        container = Container(bounds=size, bgcolor='grey')
        container.add(text_field, text_field2, text_field3)
        return Window(self, -1, component=container)

if __name__ == '__main__':
    # Save demo so that it doesn't get garbage collected when run within
    # existing event loop (i.e. from ipython).
    demo = demo_main(MyFrame, size=size)