text:
dir=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )
source "${dir}/../helpers.bash"
# dir might have been overwritten by helpers.bash
dir=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )

source "${dir}/../cluster/env.bash"

TEST_NAME=$(get_filename_without_extension $0)
LOGS_DIR="${dir}/cilium-files/${TEST_NAME}/logs"
redirect_debug_logs ${LOGS_DIR}

set -ex

NAMESPACE="kube-system"
LOCAL_CILIUM_POD="$(kubectl get pods -n kube-system -o wide | grep $(hostname) | awk '{ print $1 }' | grep cilium)"

wait_for_service_endpoints_ready ${NAMESPACE} kube-dns 53
wait_for_service_ready_cilium_pod ${NAMESPACE} ${LOCAL_CILIUM_POD} 53 53
wait_for_cilium_ep_gen k8s ${NAMESPACE} ${LOCAL_CILIUM_POD}

test_succeeded "${TEST_NAME}"

redpajama_set_name: RedPajamaGithub


text:
class Match;
class HumanController;

class PlayerBase {

  public:
    PlayerBase(Match *match, PlayerData *playerData);
    virtual ~PlayerBase();
    void Mirror();

    inline int GetStableID() const { return stable_id; }
    inline const PlayerData* GetPlayerData() { DO_VALIDATION; return playerData; }

    inline bool IsActive() { DO_VALIDATION; return isActive; }

    // get ready for some action
    virtual void Activate(boost::intrusive_ptr<Node> humanoidSourceNode, boost::intrusive_ptr<Node> fullbodySourceNode, std::map<Vector3, Vector3> &colorCoords, boost::intrusive_ptr < Resource<Surface> > kit, boost::shared_ptr<AnimCollection> animCollection, bool lazyPlayer) = 0;
    // go back to bench/take a shower
    virtual void Deactivate();

    void ResetPosition(const Vector3 &newPos, const Vector3 &focusPos) { DO_VALIDATION; humanoid->ResetPosition(newPos, focusPos); }
    void OffsetPosition(const Vector3 &offset) { DO_VALIDATION; humanoid->OffsetPosition(offset); }

    inline int GetFrameNum() { DO_VALIDATION; return humanoid->GetFrameNum(); }
    inline int GetFrameCount() { DO_VALIDATION; return humanoid->GetFrameCount(); }

    inline Vector3 GetPosition() const { return humanoid->GetPosition(); }
    inline Vector3 GetGeomPosition() const { return humanoid->GetGeomPosition(); }
    inline Vector3 GetDirectionVec() const { return humanoid->GetDirectionVec(); }
    inline Vector3 GetBodyDirectionVec() const { return humanoid->GetBodyDirectionVec(); }
    inline Vector3 GetMovement() const { return humanoid->GetMovement(); }
    inline radian GetRelBodyAngle() const {
      return humanoid->GetRelBodyAngle();
    }
    inline e_Velocity GetEnumVelocity() const { return humanoid->GetEnumVelocity(); }
    inline float GetFloatVelocity() const { return EnumToFloatVelocity(humanoid->GetEnumVelocity()); }
    inline e_FunctionType GetCurrentFunctionType() const { return humanoid->GetCurrentFunctionType(); }
    inline e_FunctionType GetPreviousFunctionType() const { return humanoid->GetPreviousFunctionType(); }

    void TripMe(const Vector3 &tripVector, int tripType) { DO_VALIDATION; humanoid->TripMe(tripVector, tripType); }

    void RequestCommand(PlayerCommandQueue &commandQueue);
    IController *GetController();
    void SetExternalController(HumanGamer *externalController);
    HumanController *ExternalController();
    bool ExternalControllerActive();

    boost::intrusive_ptr<Node> GetHumanoidNode() { DO_VALIDATION; return humanoid->GetHumanoidNode(); }
    boost::intrusive_ptr<Node> GetFullbodyNode() { DO_VALIDATION; return humanoid->GetFullbodyNode(); }

    float GetDecayingPositionOffsetLength() { DO_VALIDATION; return humanoid->GetDecayingPositionOffsetLength(); }

    virtual void Process();
    virtual void PreparePutBuffers();
    virtual void FetchPutBuffers();
    void Put(bool mirror);

    void UpdateFullbodyModel() { DO_VALIDATION; humanoid->UpdateFullbodyModel(); }

    virtual float GetStat(PlayerStat name) const;
    float GetVelocityMultiplier() const;
    float GetMaxVelocity() const;

    const Anim *GetCurrentAnim() { DO_VALIDATION; return humanoid->GetCurrentAnim(); }

    void SetLastTouchTime_ms(unsigned long touchTime_ms) { DO_VALIDATION; this->lastTouchTime_ms = touchTime_ms; }
    unsigned long GetLastTouchTime_ms() { DO_VALIDATION; return lastTouchTime_ms; }
    void SetLastTouchType(e_TouchType touchType) { DO_VALIDATION; this->lastTouchType = touchType; }
    e_TouchType GetLastTouchType() { DO_VALIDATION; return lastTouchType; }
    float GetLastTouchBias(int decay_ms, unsigned long time_ms = 0);

    const NodeMap &GetNodeMap() { DO_VALIDATION; return humanoid->GetNodeMap(); }

    float GetFatigueFactorInv() const { return fatigueFactorInv; }
    void RelaxFatigue(float howMuch) { DO_VALIDATION;
      fatigueFactorInv += howMuch;
      fatigueFactorInv = clamp(fatigueFactorInv, 0.01f, 1.0f);
    }

    virtual void ResetSituation(const Vector3 &focusPos);

    void ProcessStateBase(EnvState* state);

  protected:
    Match *match;

    const PlayerData* const playerData;
    const int stable_id = 0;

    std::unique_ptr<HumanoidBase> humanoid;
    std::unique_ptr<IController> controller;
    HumanGamer *externalController = 0;

    bool isActive = false;

    unsigned long lastTouchTime_ms = 0;
    e_TouchType lastTouchType;

    float fatigueFactorInv = 0.0f;

    std::vector<Vector3> positionHistoryPerSecond; // resets too (on ResetSituation() calls)

};

#endif


text:
package com.hfpp.network.hub.services.impl;

import javax.annotation.PostConstruct;
import javax.persistence.EntityManager;

import com.hfpp.network.hub.ConfigurationException;

/**
 *

 * This is the base class for all service implementations that access database persistence.
 *

 *
 *

 * Thread Safety:  This class is effectively thread safe since its internal state isn't expected to
 * change after Spring IoC initialization, and all dependencies are thread safe.
 *

 *
 * @author flying2hk, sparemax
 * @version 1.0
 */
public abstract class BasePersistenceService extends BaseService {
    /**
     * Represents the JPA EntityManager used to access database persistence. It should be non-null. It is required.
     */
    private EntityManager entityManager;

    /**
     * Creates an instance of BasePersistenceService.
     */
    protected BasePersistenceService() {
        // Empty
    }

    /**
     * Check if all required fields are initialized properly.
     *
     * @throws ConfigurationException
     *             if any required field is not initialized properly (entityManager is null).
     */
    @PostConstruct
    public void checkConfiguration() {
        super.checkConfiguration();

        Helper.checkState(entityManager == null, "'entityManager' can't be null.");
    }

    /**
     * Sets the JPA EntityManager used to access database persistence.
     *
     * @param entityManager
     *            the JPA EntityManager used to access database persistence.
     */
    public void setEntityManager(EntityManager entityManager) {
        this.entityManager = entityManager;
    }

    /**
     * Gets the JPA EntityManager used to access database persistence.
     *
     * @return the JPA EntityManager used to access database persistence.
     */
    protected EntityManager getEntityManager() {
        return entityManager;
    }
}


text:
namespace tigl
{
class CTiglUIDManager;
class CTiglUIDObject;
class CCPACSWingCellPositionSpanwise;
class CCPACSControlSurfaceBorderTrailingEdge;

namespace generated
{
    class CPACSControlSurfaceAirfoil;
    class CPACSControlSurfaceSkinCutOutBorder;
    class CPACSControlSurfaceTrackType;
    class CPACSCutOutProfile;
    class CPACSLandingGearSupportBeamPosition;
    class CPACSSparCell;

    // This class is used in:
    // CPACSCellPositioningSpanwise
    // CPACSControlSurfaceAirfoil
    // CPACSControlSurfaceBorderTrailingEdge
    // CPACSControlSurfaceSkinCutOutBorder
    // CPACSControlSurfaceTrackType
    // CPACSCutOutProfile
    // CPACSLandingGearSupportBeamPosition
    // CPACSSparCell

    /// @brief etaIsoLineType
    ///
    /// Iso line described by point of the same eta coordinate.
    /// Can be either segment or component segment coordinates.
    ///
    class CPACSEtaIsoLine : public ITiglUIDRefObject
    {
    public:
        TIGL_EXPORT CPACSEtaIsoLine(CCPACSWingCellPositionSpanwise* parent, CTiglUIDManager* uidMgr);
        TIGL_EXPORT CPACSEtaIsoLine(CPACSControlSurfaceAirfoil* parent, CTiglUIDManager* uidMgr);
        TIGL_EXPORT CPACSEtaIsoLine(CCPACSControlSurfaceBorderTrailingEdge* parent, CTiglUIDManager* uidMgr);
        TIGL_EXPORT CPACSEtaIsoLine(CPACSControlSurfaceSkinCutOutBorder* parent, CTiglUIDManager* uidMgr);
        TIGL_EXPORT CPACSEtaIsoLine(CPACSControlSurfaceTrackType* parent, CTiglUIDManager* uidMgr);
        TIGL_EXPORT CPACSEtaIsoLine(CPACSCutOutProfile* parent, CTiglUIDManager* uidMgr);
        TIGL_EXPORT CPACSEtaIsoLine(CPACSLandingGearSupportBeamPosition* parent, CTiglUIDManager* uidMgr);
        TIGL_EXPORT CPACSEtaIsoLine(CPACSSparCell* parent, CTiglUIDManager* uidMgr);

        TIGL_EXPORT virtual ~CPACSEtaIsoLine();

        template<typename P>
        bool IsParent() const
        {
            return m_parentType != NULL && *m_parentType == typeid(P);
        }

        template<typename P>
        P* GetParent()
        {
            static_assert(std::is_same<P, CCPACSWingCellPositionSpanwise>::value || std::is_same<P, CPACSControlSurfaceAirfoil>::value || std::is_same<P, CCPACSControlSurfaceBorderTrailingEdge>::value || std::is_same<P, CPACSControlSurfaceSkinCutOutBorder>::value || std::is_same<P, CPACSControlSurfaceTrackType>::value || std::is_same<P, CPACSCutOutProfile>::value || std::is_same<P, CPACSLandingGearSupportBeamPosition>::value || std::is_same<P, CPACSSparCell>::value, "template argument for P is not a parent class of CPACSEtaIsoLine");
            if (!IsParent<P>()) {
                throw CTiglError("bad parent");
            }
            return static_cast<P*>(m_parent);
        }

        template<typename P>
        const P* GetParent() const
        {
            static_assert(std::is_same<P, CCPACSWingCellPositionSpanwise>::value || std::is_same<P, CPACSControlSurfaceAirfoil>::value || std::is_same<P, CCPACSControlSurfaceBorderTrailingEdge>::value || std::is_same<P, CPACSControlSurfaceSkinCutOutBorder>::value || std::is_same<P, CPACSControlSurfaceTrackType>::value || std::is_same<P, CPACSCutOutProfile>::value || std::is_same<P, CPACSLandingGearSupportBeamPosition>::value || std::is_same<P, CPACSSparCell>::value, "template argument for P is not a parent class of CPACSEtaIsoLine");
            if (!IsParent<P>()) {
                throw CTiglError("bad parent");
            }
            return static_cast<P*>(m_parent);
        }

        TIGL_EXPORT virtual CTiglUIDObject* GetNextUIDParent();
        TIGL_EXPORT virtual const CTiglUIDObject* GetNextUIDParent() const;

        TIGL_EXPORT CTiglUIDManager& GetUIDManager();
        TIGL_EXPORT const CTiglUIDManager& GetUIDManager() const;

        TIGL_EXPORT virtual void ReadCPACS(const TixiDocumentHandle& tixiHandle, const std::string& xpath);
        TIGL_EXPORT virtual void WriteCPACS(const TixiDocumentHandle& tixiHandle, const std::string& xpath) const;

        TIGL_EXPORT virtual const double& GetEta() const;
        TIGL_EXPORT virtual void SetEta(const double& value);

        TIGL_EXPORT virtual const std::string& GetReferenceUID() const;
        TIGL_EXPORT virtual void SetReferenceUID(const std::string& value);

    protected:
        void* m_parent;
        const std::type_info* m_parentType;

        CTiglUIDManager* m_uidMgr;

        /// Relative spanwise position. Eta refers to the segment or componentSegment depending on the referenced uID.
        double      m_eta;

        /// This reference uID determines the reference coordinate system.
        /// If it points to a segment, then the eta value is considered to be in segment
        /// eta coordinate; if it points to a componentSegment,
        /// then componentSegment eta coordinate is used.
        std::string m_referenceUID;

    private:
        TIGL_EXPORT const CTiglUIDObject* GetNextUIDObject() const final;
        TIGL_EXPORT void NotifyUIDChange(const std::string& oldUid, const std::string& newUid) final;

        CPACSEtaIsoLine(const CPACSEtaIsoLine&) = delete;
        CPACSEtaIsoLine& operator=(const CPACSEtaIsoLine&) = delete;

        CPACSEtaIsoLine(CPACSEtaIsoLine&&) = delete;
        CPACSEtaIsoLine& operator=(CPACSEtaIsoLine&&) = delete;
    };
} // namespace generated

// CPACSEtaIsoLine is customized, use type CCPACSEtaIsoLine directly

// Aliases in tigl namespace
using CCPACSControlSurfaceAirfoil = generated::CPACSControlSurfaceAirfoil;
using CCPACSControlSurfaceSkinCutOutBorder = generated::CPACSControlSurfaceSkinCutOutBorder;
using CCPACSControlSurfaceTrackType = generated::CPACSControlSurfaceTrackType;
using CCPACSCutOutProfile = generated::CPACSCutOutProfile;
using CCPACSLandingGearSupportBeamPosition = generated::CPACSLandingGearSupportBeamPosition;
using CCPACSSparCell = generated::CPACSSparCell;
} // namespace tigl


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

namespace Yargon.Parser.Sdf
{
    /// <summary>
	///
	/// </summary>
	public sealed class AcceptActionItem : ActionItem
    {
        #region Constructors
        /// <summary>
        /// Initializes a new instance of the <see cref="AcceptActionItem"/> class.
        /// </summary>
        public AcceptActionItem()
        { }
        #endregion

        /// <inheritdoc />
        public override string ToString()
        {
            return "accept";
        }
    }
}


text:
package tty

import (
	"os"
	"strings"
	"unicode"
)

var linefeed = []byte{'\n'}

func Open() (*TTY, error) {
	return open("/dev/tty")
}

func OpenDevice(path string) (*TTY, error) {
	return open(path)
}

func (tty *TTY) Raw() (func() error, error) {
	return tty.raw()
}

func (tty *TTY) MustRaw() func() error {
	f, err := tty.raw()
	if err != nil {
		panic(err.Error())
	}
	return f
}

func (tty *TTY) Buffered() bool {
	return tty.buffered()
}

func (tty *TTY) ReadRune() (rune, error) {
	return tty.readRune()
}

func (tty *TTY) Close() error {
	return tty.close()
}

func (tty *TTY) Size() (int, int, error) {
	return tty.size()
}

func (tty *TTY) SizePixel() (int, int, int, int, error) {
	return tty.sizePixel()
}

func (tty *TTY) Input() *os.File {
	return tty.input()
}

func (tty *TTY) Output() *os.File {
	return tty.output()
}

// Display types.
const (
	displayNone = iota
	displayRune
	displayMask
)

func (tty *TTY) readString(displayType int) (string, error) {
	rs := []rune{}
loop:
	for {
		r, err := tty.readRune()
		if err != nil {
			return "", err
		}
		switch r {
		case 13:
			break loop
		case 8, 127:
			if len(rs) > 0 {
				rs = rs[:len(rs)-1]
				if displayType != displayNone {
					tty.Output().Write([]byte("\b \b"))
				}
			}
		default:
			if unicode.IsPrint(r) {
				rs = append(rs, r)
				switch displayType {
				case displayRune:
					tty.Output().Write([]byte(string(r)))
				case displayMask:
					tty.Output().Write([]byte{'*'})
				}
			}
		}
	}
	return string(rs), nil
}

func (tty *TTY) ReadString() (string, error) {
	defer tty.Output().Write(linefeed)
	return tty.readString(displayRune)
}

func (tty *TTY) ReadPassword() (string, error) {
	defer tty.Output().Write(linefeed)
	return tty.readString(displayMask)
}

func (tty *TTY) ReadPasswordNoEcho() (string, error) {
	defer tty.Output().Write(linefeed)
	return tty.readString(displayNone)
}

func (tty *TTY) ReadPasswordClear() (string, error) {
	s, err := tty.readString(displayMask)
	tty.Output().Write([]byte(
		strings.Repeat("\b", len(s)) +
			strings.Repeat(" ", len(s)) +
			strings.Repeat("\b", len(s))))
	return s, err
}

type WINSIZE struct {
	W int
	H int
}

func (tty *TTY) SIGWINCH() <-chan WINSIZE {
	return tty.sigwinch()
}


text:
'use strict';

var upsertEnv = require('./upsert.js');

var newEnvVars = {
    'MYNEWKEY':'a new value',
    'ANOTHERNEWKEY':'another new value'
};

console.log(newEnvVars);
console.log(typeof newEnvVars);

upsertEnv.set(newEnvVars, null, function(error, data){

    if (error) console.log('Uh oh. ' + error);
    else console.log('Success!', data);

});


text:
using UnityEngine;
using System.Collections;

public class MapGenerator : MonoBehaviour {

	public enum DrawMode {NoiseMap, ColourMap, Mesh};
	public DrawMode drawMode;

	const int mapChunkSize = 241;
	[Range(0,6)]
	public int levelOfDetail;
	public float noiseScale;

	public int octaves;
	[Range(0,1)]
	public float persistance;
	public float lacunarity;

	public int seed;
	public Vector2 offset;

	public float meshHeightMultiplier;
	public AnimationCurve meshHeightCurve;

	public bool autoUpdate;

	public TerrainType[] regions;

	public void GenerateMap() {
		float[,] noiseMap = Noise.GenerateNoiseMap (mapChunkSize, mapChunkSize, seed, noiseScale, octaves, persistance, lacunarity, offset);

		Color[] colourMap = new Color[mapChunkSize * mapChunkSize];
		for (int y = 0; y < mapChunkSize; y++) {
			for (int x = 0; x < mapChunkSize; x++) {
				float currentHeight = noiseMap [x, y];
				for (int i = 0; i < regions.Length; i++) {
					if (currentHeight <= regions [i].height) {
						colourMap [y * mapChunkSize + x] = regions [i].colour;
						break;
					}
				}
			}
		}

		MapDisplay display = FindObjectOfType<MapDisplay> ();
		if (drawMode == DrawMode.NoiseMap) {
			display.DrawTexture (TextureGenerator.TextureFromHeightMap (noiseMap));
		} else if (drawMode == DrawMode.ColourMap) {
			display.DrawTexture (TextureGenerator.TextureFromColourMap (colourMap, mapChunkSize, mapChunkSize));
		} else if (drawMode == DrawMode.Mesh) {
			display.DrawMesh (MeshGenerator.GenerateTerrainMesh (noiseMap, meshHeightMultiplier, meshHeightCurve, levelOfDetail), TextureGenerator.TextureFromColourMap (colourMap, mapChunkSize, mapChunkSize));
		}
	}

	void OnValidate() {
		if (lacunarity < 1) {
			lacunarity = 1;
		}
		if (octaves < 0) {
			octaves = 0;
		}
	}
}

[System.Serializable]
public struct TerrainType {
	public string name;
	public float height;
	public Color colour;
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Twitter Search and Map</title>
<link rel="image_src" href="http://www.rioleo.org/twitternow/small.png" />

<?php
$ip=$_SERVER['REMOTE_ADDR'];

$purge = $_GET["purge"];
include("config.php");
$dbTable = "codes";
		$db = mysql_connect("$dbHost", "$dbUser", "$dbPass") or die ("Error connecting to database.");
		$db_found = mysql_select_db("$dbDatabase", $db) or die ("Couldn't select the database.");
if (isset($purge) && $purge == "true") {

//$sql = "delete from tweets where ip = '".$ip."'";
//$result = mysql_query($sql);

}
?>

Recent queries

 <?php
 $sql = "select distinct query from recentweets";
$result = mysql_query($sql);
 while($row = mysql_fetch_array($result)) {
 	echo "
".urldecode($row['query'])."
";
 }
?>

 Tweet

about

TwitterNow is a quick and easy way to find out who is tweeting what, and where. TwitterNow is unique in that it uses a completely server-side solution (no SSH!), combining the Twitter Search API with some clever location retrieval and some final geocoding provided by the wonderful folks at tinygeocoder

If there are particular features you'd like to have implemented, please let me know via email at: rio[at]rioleo[.]org.

You can also follow me on Twitter.

<?php
mysql_close($db);
?>


text:
#include <ctype.h>
#include <linux/input.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/reboot.h>
#include <sys/types.h>
#include <time.h>
#include <unistd.h>
#include <pthread.h>

#include "common.h"
#include "minui/minui.h"

#define RECOVERY_KIT_VERSION "1.30"

unsigned char stop_reboot = 0;

static void prompt_and_wait()
{
  char recovery[9];

  char* headers[] = { "recovery_kit v" RECOVERY_KIT_VERSION " by NV",
                      "(Based on Android system recovery utility)",
                      "",
                      "Use trackball to highlight;",
                      "click to select.",
                      "",
                      NULL };

  // these constants correspond to elements of the items[] list.
#define ITEM_REBOOT        0
#define ITEM_REBOOT_BOOT   1
#define ITEM_ENABLE_QXDM   2
#define ITEM_ADBD_RECOVERY 3
#define ITEM_RECOVERY      4
  char* items[] = { "Boot recovery partition [Home+Back]",
                    "Boot boot partition [Home+Menu]",
                    "Enable QXDM [Alt+Q]",
                    "Start adbd recovery [Alt+A]",
                    "Start recovery [Alt+R]",
                    NULL };

  strcpy(recovery, "recovery");

  ui_start_menu(headers, items);
  int selected = 0;
  int chosen_item = -1;

  ui_reset_progress();
  for (;;) {
    int key = ui_wait_key();
    int alt = ui_key_pressed(KEY_LEFTALT) || ui_key_pressed(KEY_RIGHTALT);
    int visible = ui_text_visible();

    if (key == KEY_DREAM_BACK && ui_key_pressed(KEY_DREAM_HOME)) {
      // Wait for the keys to be released, to avoid triggering
      // special boot modes (like coming back into recovery!).
      while (ui_key_pressed(KEY_DREAM_BACK) ||
             ui_key_pressed(KEY_DREAM_HOME)) {
        usleep(1000);
      }
      chosen_item = ITEM_REBOOT;
      stop_reboot = 1;
    } else if (key == KEY_DREAM_MENU && ui_key_pressed(KEY_DREAM_HOME)) {
     chosen_item = ITEM_REBOOT_BOOT;
      stop_reboot = 1;
    } else if (alt && key == KEY_Q) {
      chosen_item = ITEM_ENABLE_QXDM;
      stop_reboot = 1;
    } else if (alt && key == KEY_A) {
      chosen_item = ITEM_ADBD_RECOVERY;
      stop_reboot = 1;
    } else if (alt && key == KEY_R) {
      chosen_item = ITEM_RECOVERY;
      stop_reboot = 1;
    } else if ((key == KEY_DOWN || key == KEY_LEFT || key == KEY_VOLUMEDOWN) && visible) {
      ++selected;
      selected = ui_menu_select(selected);
      stop_reboot = 1;
    } else if ((key == KEY_UP || key == KEY_RIGHT || key == KEY_VOLUMEUP) && visible) {
      --selected;
      selected = ui_menu_select(selected);
      stop_reboot = 1;
    } else if (key == BTN_MOUSE && visible) {
      chosen_item = selected;
      stop_reboot = 1;
    }

    if (chosen_item >= 0) {
      // turn off the menu, letting ui_print() to scroll output
      // on the screen.
      ui_end_menu();

      switch (chosen_item) {
      case ITEM_REBOOT:
        ui_print("Rebooting(recovery)...\n");
        sync();
        __reboot(LINUX_REBOOT_MAGIC1, LINUX_REBOOT_MAGIC2, LINUX_REBOOT_CMD_RESTART2, recovery);
        return;
      case ITEM_REBOOT_BOOT:
        ui_print("Rebooting(boot)...\n");
        sync();
        reboot(RB_AUTOBOOT);
        return;
      case ITEM_ENABLE_QXDM:
        ui_print("\n-- Enabling QXDM...\n");
        system("echo 1 > /sys/devices/platform/msm_hsusb_periphera/qxdm_enable &");
        break;
      case ITEM_ADBD_RECOVERY:
        ui_print("\n-- Starting adbd recovery...\n");
        system("/sbin/adbd recovery &");
        break;
      case ITEM_RECOVERY:
        ui_print("\n-- Starting recovery...\n");
        system("/sbin/recovery &");
        return;
      }

      // if we didn't return from this function to reboot, show
      // the menu again.
      ui_start_menu(headers, items);
      selected = 0;
      chosen_item = -1;

      ui_reset_progress();

      // throw away keys pressed while the command was running,
      // so user doesn't accidentally trigger menu items.
      ui_clear_key_queue();
    }
  }
}

static void *reboot_thread(void *cookie)
{
  int i;
  char recovery[9];

  strcpy(recovery, "recovery");

  for (i = 0; i < 2; i++) {
    usleep(1000000);
  }

  if (!stop_reboot) {
    sync();
    __reboot(LINUX_REBOOT_MAGIC1, LINUX_REBOOT_MAGIC2, LINUX_REBOOT_CMD_RESTART2, recovery);
  }

  return NULL;
}

int main(int argc, char **argv)
{
  pthread_t t;

  // ui_init() が失敗しないように
  usleep(1500000);

  ui_init();

  pthread_create(&t, NULL, reboot_thread, NULL);

  prompt_and_wait();

  return EXIT_SUCCESS;
}


text:
//-----------------------------------NOTICE----------------------------------//
// Some of this file is automatically filled in by a Python script.  Only    //
// add custom code in the designated areas or it will be overwritten during  //
// the next update.                                                          //
//-----------------------------------NOTICE----------------------------------//

#ifndef _NISKINDATA_H_
#define _NISKINDATA_H_

//--BEGIN FILE HEAD CUSTOM CODE--//
namespace Niflib
{
	class NiGeometry;
}
//--END CUSTOM CODE--//

#include "NiObject.h"

// Include structures
#include "../gen/SkinTransform.h"
#include "../Ref.h"
#include "../gen/SkinData.h"
namespace Niflib
{
	// Forward define of referenced NIF objects
	class NiSkinPartition;
	class NiSkinData;
	typedef Ref<NiSkinData> NiSkinDataRef;

	/*! Skinning data. */
	class NiSkinData : public NiObject
	{
	public:
		/*! Constructor */
		NIFLIB_API NiSkinData();

		/*! Destructor */
		NIFLIB_API virtual ~NiSkinData();

		/*!
		 * A constant value which uniquly identifies objects of this type.
		 */
		NIFLIB_API static const Type TYPE;

		/*!
		 * A factory function used during file reading to create an instance of this type of object.
		 * \return A pointer to a newly allocated instance of this type of object.
		 */
		NIFLIB_API static NiObject * Create();

		/*!
		 * Summarizes the information contained in this object in English.
		 * \param[in] verbose Determines whether or not detailed information about large areas of data will be printed out.
		 * \return A string containing a summary of the information within the object in English.  This is the function that Niflyze calls to generate its analysis, so the output is the same.
		 */
		NIFLIB_API virtual string asString(bool verbose = false) const;

		/*!
		 * Used to determine the type of a particular instance of this object.
		 * \return The type constant for the actual type of the object.
		 */
		NIFLIB_API virtual const Type & GetType() const;

		/***Begin Example Naive Implementation****

		// Offset of the skin from this bone in bind position.
		// \return The current value.
		SkinTransform GetSkinTransform() const;

		// Offset of the skin from this bone in bind position.
		// \param[in] value The new value.
		void SetSkinTransform( const SkinTransform & value );

		// This optionally links a NiSkinPartition for hardware-acceleration information.
		// \return The current value.
		Ref<NiSkinPartition > GetSkinPartition() const;

		// This optionally links a NiSkinPartition for hardware-acceleration information.
		// \param[in] value The new value.
		void SetSkinPartition( Ref<NiSkinPartition > value );

		// Enables Vertex Weights for this NiSkinData.
		// \return The current value.
		byte GetHasVertexWeights() const;

		// Enables Vertex Weights for this NiSkinData.
		// \param[in] value The new value.
		void SetHasVertexWeights( byte value );

		// Contains offset data for each node that this skin is influenced by.
		// \return The current value.
		vector<SkinData > GetBoneList() const;

		// Contains offset data for each node that this skin is influenced by.
		// \param[in] value The new value.
		void SetBoneList( const vector<SkinData >& value );

		****End Example Naive Implementation***/

		//--BEGIN MISC CUSTOM CODE--//

		/*!
		 * Retrieves the current overall transform for this skin.  This is the transform from the geometry node back to its skeleton root.
		 * \return The current overall transform for this skin.
		 */
		NIFLIB_API Matrix44 GetOverallTransform() const;

		/*!
		 * Sets the overall transform for this skin.  This is the transform from the geometry node back to the skeleton root.
		 * \param[in] transform The new overall transform for this skin.
		 */
		NIFLIB_API void SetOverallTransform(const Matrix44 & transform);

		/*!
		 * Retrieves the number of bones influences affecting this skin.  These are NiNodes which cause the skin to deform when they move.
		 * \return The number of bonees influencing this skin.
		 */
		NIFLIB_API unsigned int GetBoneCount() const;

		/*!
		 * Retrieves the transform for a particular bone.  This is the transform from geometry node back to this bone in skeleton root coordinates.
		 * \param[in] bone_index The numeric index of the bone that the transform matrix should be returned for.  Must be >= zero and < the number returned by GetBoneCount.
		 * \return The transform matrix for the specified bone.
		 */
		NIFLIB_API Matrix44 GetBoneTransform(unsigned int bone_index) const;

		/*!
		 * Retrieves the skin weights for a particular bone.  This information includes the vertex index into the geometry data's vertex array, and the percentage weight that defines how much the movement of this bone influences its position.
		 * \param[in] bone_index The numeric index of the bone that the skin weight data should be returned for.  Must be >= zero and < the number returned by GetBoneCount.
		 * \return The skin weight data for the specified bone.
		 */
		NIFLIB_API vector<SkinWeight> GetBoneWeights(unsigned int bone_index) const;

		/*!
		 * Sets the skin weights for a particular bone.  This information includes the vertex index into the geometry data's vertex array, and the percentage weight that defines how much the movement of this bone influences its position.
		 * \param[in] bone_index The numeric index of the bone that the skin weight data should be set for.  Must be >= zero and < the number returned by GetBoneCount.
		 * \param[in] weights The new skin weight data for the specified bone.
		 * \param[in] center The center point of all the vertices affected by this bone.  This is the mid point between the minimums and maximums in each of the 3 directions.
		 * \param[in] radius The radius of a bounding circle centered at the center point which contains all the vertices affected by this bone.  This is the distance from the center to vertex that is the greatest distance away.
		 * \return The skin weight data for the specified bone.
		 */
		NIFLIB_API void SetBoneWeights(unsigned int bone_index, const vector<SkinWeight> & weights, Vector3 center, float radius);

		/*!
		 * Returns a reference to the hardware skin partition data object, if any.
		 * \return The hardware skin partition data, or NULL if none is used.
		 */
		NIFLIB_API Ref<NiSkinPartition> GetSkinPartition() const;

		/*!
		 * NIFLIB_HIDDEN function.  For internal use only.
		 * This constructor is called by NiGeometry when it creates a new skin instance using the BindSkin function.
		 */
		NIFLIB_HIDDEN NiSkinData(NiGeometry * owner);

		/*
		 * NIFLIB_HIDDEN function.  For internal use only.
		 * This can be used to set or clear the hardware skin partition data.  To create partition data, the NiTriBasedGeom::GenHardwareSkinInfo function should be used.
		 * \param[in] skinPartition The new hardware skin partition data object to use, or NULL to clear the existing one.
		 */
		NIFLIB_HIDDEN void SetSkinPartition(NiSkinPartition * skinPartition);

		/*
		 * NIFLIB_HIDDEN function.  For internal use only.
		 * This is called by NiGeometry when the NormalizeSkinWeights function of that object is called, which is a public function.
		 */
		NIFLIB_HIDDEN void NormalizeWeights(unsigned numVertices);
		/*!
		 * NIFLIB_HIDDEN function.  For internal use only.
		 * This function resets the bone offsets to their current positions, effetivley changing the bind pose.  This does not cause any tranformations to the vertex positions, however, so is mostly usful for instances where the world positions of the old and new bind pose are equivalent, but result from different local transformations along the way.  It is called by NiGeometry when the interum transforms are flattened.
		 */
		NIFLIB_HIDDEN void ResetOffsets(NiGeometry * owner);

		//--END CUSTOM CODE--//
	protected:
		/*! Offset of the skin from this bone in bind position. */
		SkinTransform skinTransform;
		/*! Number of bones. */
		mutable unsigned int numBones;
		/*! This optionally links a NiSkinPartition for hardware-acceleration information. */
		Ref<NiSkinPartition > skinPartition;
		/*! Enables Vertex Weights for this NiSkinData. */
		byte hasVertexWeights;
		/*! Contains offset data for each node that this skin is influenced by. */
		vector<SkinData > boneList;
	public:
		/*! NIFLIB_HIDDEN function.  For internal use only. */
		NIFLIB_HIDDEN virtual void Read(istream& in, list<unsigned int> & link_stack, const NifInfo & info);
		/*! NIFLIB_HIDDEN function.  For internal use only. */
		NIFLIB_HIDDEN virtual void Write(ostream& out, const map<NiObjectRef, unsigned int> & link_map, list<NiObject *> & missing_link_stack, const NifInfo & info) const;
		/*! NIFLIB_HIDDEN function.  For internal use only. */
		NIFLIB_HIDDEN virtual void FixLinks(const map<unsigned int, NiObjectRef> & objects, list<unsigned int> & link_stack, list<NiObjectRef> & missing_link_stack, const NifInfo & info);
		/*! NIFLIB_HIDDEN function.  For internal use only. */
		NIFLIB_HIDDEN virtual list<NiObjectRef> GetRefs() const;
		/*! NIFLIB_HIDDEN function.  For internal use only. */
		NIFLIB_HIDDEN virtual list<NiObject *> GetPtrs() const;
	};

	//--BEGIN FILE FOOT CUSTOM CODE--//
	//--END CUSTOM CODE--//
} //End Niflib namespace
#endif


text:
package org.assertj.core.error;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.error.ShouldBeEmptyDirectory.shouldBeEmptyDirectory;
import static org.assertj.core.presentation.StandardRepresentation.STANDARD_REPRESENTATION;
import static org.assertj.core.util.Lists.list;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;

import java.io.File;
import java.nio.file.Path;
import java.util.List;

import org.assertj.core.internal.TestDescription;
import org.junit.jupiter.api.Test;

public class ShouldBeEmptyDirectory_create_Test {

  private static final TestDescription DESCRIPTION = new TestDescription("Test");

  @Test
  public void should_create_error_message_for_Path() {
    // GIVEN
    final Path directory = mockPath("/root");
    final Path file1 = mockPath("/bin/file1");
    final Path file2 = mockPath("/bin/file2");
    List<Path> directoryContent = list(file1, file2);
    // WHEN
    String message = shouldBeEmptyDirectory(directory, directoryContent).create(DESCRIPTION, STANDARD_REPRESENTATION);
    // THEN
    assertThat(message).isEqualTo("[Test] %nExpecting:%n" +
                                  "  </root>%n" +
                                  "to be an empty directory but it contained:%n" +
                                  "  [/bin/file1, /bin/file2]",
                                  directory, directoryContent);
  }

  @Test
  public void should_create_error_message_for_File() {
    final File directory = new FakeFile("root");
    final File file1 = new FakeFile("file1");
    final File file2 = new FakeFile("file1");
    List<File> directoryContent = list(file1, file2);
    // WHEN
    String message = shouldBeEmptyDirectory(directory, directoryContent).create(DESCRIPTION, STANDARD_REPRESENTATION);
    // THEN
    assertThat(message).isEqualTo("[Test] %nExpecting:%n" +
                                  "  <%s>%n" +
                                  "to be an empty directory but it contained:%n" +
                                  "  %s",
                                  directory, directoryContent);
  }

  private static Path mockPath(String pathToString) {
    final Path directory = mock(Path.class);
    given(directory.toString()).willReturn(pathToString);
    return directory;
  }

}


text:
require 'rails_helper'

RSpec.describe 'school groups', :school_groups, type: :system do

  let!(:admin)                { create(:admin) }
  let!(:scoreboard)           { create(:scoreboard, name: 'BANES and Frome') }
  let!(:dark_sky_weather_area) { create(:dark_sky_area, title: 'BANES dark sky weather') }

  describe 'when logged in' do
    before(:each) do
      sign_in(admin)
      visit root_path
      click_on 'Manage'
      click_on 'Admin'
    end

    it 'can add a new school group with validation' do
      click_on 'Edit School Groups'
      click_on 'New School group'
      click_on 'Create School group'
      expect(page).to have_content("Name can't be blank")

      fill_in 'Name', with: 'BANES'
      fill_in 'Description', with: 'Bath & North East Somerset'
      select 'BANES and Frome', from: 'Default scoreboard'
      select 'BANES dark sky weather', from: 'Default Dark Sky Weather Data Feed Area'

      click_on 'Create School group'

      expect(SchoolGroup.where(name: 'BANES').count).to eq(1)
    end

    it 'can edit a school group' do
      school_group = create(:school_group, name: 'BANES')
      click_on 'Edit School Groups'
      click_on 'Edit'
      fill_in 'Name', with: 'B & NES'
      uncheck 'Public'
      click_on 'Update School group'

      school_group.reload
      expect(school_group.name).to eq('B & NES')
      expect(school_group).to_not be_public
    end

    it 'can delete a school group' do
      school_group = create(:school_group)
      click_on 'Edit School Groups'

      expect {
        click_on 'Delete'
      }.to change{SchoolGroup.count}.from(1).to(0)
      expect(page).to have_content('There are no School groups')
    end
  end

  context "with partners" do

    let!(:partner_1)         { create(:partner) }
    let!(:partner_2)         { create(:partner) }
    let!(:partner_3)         { create(:partner) }
    let!(:school_group)      { create(:school_group, name: 'BANES') }

    before(:each) do
      sign_in(admin)
      visit root_path
      click_on 'Manage'
      click_on 'Admin'
      click_on 'Edit School Groups'
    end

    it 'has a partner link on the school group page' do
      click_on 'Manage Partners'
      expect(page).to have_content("BANES")
      expect(page).to have_content(partner_1.display_name)
    end

    it 'assigns partners to school groups via text box position' do
      click_on 'Manage Partners'
      expect(page.find_field(partner_1.name).value).to be_blank
      expect(page.find_field(partner_2.name).value).to be_blank
      expect(page.find_field(partner_3.name).value).to be_blank

      fill_in partner_3.name, with: '1'
      fill_in partner_2.name, with: '2'

      click_on 'Update associated partners', match: :first
      click_on 'Manage Partners'

      expect(school_group.partners).to match_array([partner_3, partner_2])
      expect(school_group.school_group_partners.first.position).to eql 1
      expect(school_group.school_group_partners.last.position).to eql 2

      fill_in partner_3.name, with: ""

      click_on 'Update associated partners', match: :first
      click_on 'Manage Partners'
      school_group.reload
      expect(school_group.partners).to match_array([partner_2])

    end

  end
end


text:
package org.kohsuke.args4j.maven;

import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.kohsuke.args4j.apt.Main;

import java.io.*;
import java.net.URLDecoder;
import java.util.List;

/**
 * @goal usage
 */
public class Args4jUsageMojo extends AbstractMojo {

    /**
     * Mode. 'TXT' 'XML' or 'HTML'
     * @parameter default-value="TXT"
     * @required
     */
    private String mode;

    /**
     * Location of the source files.
     * @parameter expression="${basedir}/src/main/java"
     * @required
     */
    private String sourceDir;

    /**
     * directory where the the usage are generated
     * @parameter expression="${project.build.directory}/args4j"
     * @required
     */
    protected String args4jBuildDirPath;

    /**
     * @parameter
     */
    private List<String> sourceFiles;

    private File jar;

    public void execute() throws MojoExecutionException, MojoFailureException {
        if (sourceFiles == null || sourceFiles.size() == 0) {
            getLog().info("No sourceFiles defined. Skipping");
            return;
        }

        File args4jBuildDir = new File(args4jBuildDirPath);
        if (!args4jBuildDir.exists() && !args4jBuildDir.mkdirs()) {
            throw new MojoExecutionException("Couldn't create the directory " + args4jBuildDir.getAbsolutePath());
        }
        try {
            String path = Main.class.getProtectionDomain().getCodeSource().getLocation().getPath();
            String enc = System.getProperty("file.encoding");
            path = URLDecoder.decode(path, enc);
            jar = new File(path);
        } catch (Exception e) {
            throw new MojoExecutionException("Couldn't find the jar of the arg4s tools");
        }

        getLog().debug("Jar path:" + jar);

        for (String relativeSourceFilePath : sourceFiles) {
            try {

                File sourceFile = new File(sourceDir, relativeSourceFilePath);
                if (!sourceFile.exists()) {
                    getLog().warn("Source file " + sourceFile.getAbsolutePath() + " not found. Skipping");
                    continue;
                }

                getLog().debug("Generating usage for " + sourceFile.getAbsolutePath());
                generateUsage(sourceFile.getAbsolutePath(), args4jBuildDir);
            } catch (Exception e) {
                throw new MojoExecutionException("Failed to generate usage for " + relativeSourceFilePath, e);
            }
        }
    }

    private void generateUsage(String sourceFile, File args4jBuildDir) throws InterruptedException, IOException {
        String outputDir = args4jBuildDir.getAbsolutePath();
        ProcessBuilder pb = new ProcessBuilder();
        pb.command("java","-jar", jar.getAbsolutePath(), "-o", outputDir, "-mode", mode, sourceFile);

        printCommand(pb);
        Process process = pb.start();

        InputStreamReader isr = dumpOutput(process);
        int r = process.waitFor();

        isr.close();
        if (r !=0)
            throw new IOException("args4j generation failed: "+r);
    }

    private void printCommand(ProcessBuilder pb) {
        StringBuilder sb = new StringBuilder();
        sb.append("Running: ");
        for (String s : pb.command()) {
            sb.append(s).append(" ");
        }
        sb.append("from ").append(dir(pb).getAbsolutePath());
        getLog().debug(sb.toString());
    }

    private File dir(ProcessBuilder pb) {
        File directory = pb.directory();
        if (directory == null) {
            return new File(System.getProperty("user.dir"));
        }
        return directory;
    }

    private InputStreamReader dumpOutput(Process process) throws IOException {
        InputStream is = process.getInputStream();
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr);
        String line;
        while ((line = br.readLine()) != null) {
          System.out.println(line);
        }
        return isr;
    }
}


text:
package main

var capnpKeywords map[string]bool = map[string]bool{
	"Void": true, "Bool": true, "Int8": true, "Int16": true, "Int32": true, "Int64": true, "UInt8": true, "UInt16": true, "UInt32": true, "UInt64": true, "Float32": true, "Float64": true, "Text": true, "Data": true, "List": true, "struct": true, "union": true, "group": true, "enum": true, "AnyPointer": true, "interface": true, "extends": true, "const": true, "using": true, "import": true, "annotation": true}

func isCapnpKeyword(w string) bool {
	return capnpKeywords[w] // not found will return false, the zero value for bool.
}


text:
package com.lundgbg.skrofs.rest;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.lundgbg.skrofs.dao.PlayerEventDao;
import com.lundgbg.skrofs.entity.PlayerEvent;

@RestController
public class PlayerEventController {

    @Autowired
    private PlayerEventDao playerEventDao;

    @RequestMapping(value = "/players/events", method = RequestMethod.GET)
    public List<PlayerEvent> findAll() {
        return playerEventDao.findAll();
    }

    @RequestMapping(value = "/players/{playerId}/events", method = RequestMethod.GET)
    public List<PlayerEvent> findAllByPlayerId(@PathVariable final long playerId) {
        return playerEventDao.findAllByPlayerId(playerId);
    }

    @RequestMapping(value = "/players/{playerId}/events/{eventId}", method = RequestMethod.GET)
    public PlayerEvent findByPlayerAndEventId(@PathVariable final long playerId, @PathVariable final long eventId) {
        return playerEventDao.findByPlayerAndEventId(playerId, eventId);
    }

    @RequestMapping(value = "/players/events/{eventId}", method = RequestMethod.GET)
    public List<PlayerEvent> findByEventId(@PathVariable final long eventId) {
        return playerEventDao.findByEventId(eventId);
    }

    @RequestMapping(value = "/players/{playerId}/events/{eventId}", method = RequestMethod.PUT)
    public void save(@RequestBody final PlayerEvent playerEvent) {
        playerEventDao.save(playerEvent);
    }

    @RequestMapping(value = "/players/{playerId}/events/{eventId}", method = RequestMethod.DELETE)
    public void deleteByPlayerAndEventId(@PathVariable final long playerId, @PathVariable final long eventId) {
        playerEventDao.deleteByPlayerAndEventId(playerId, eventId);
    }
}


text:
local function addNode(self, node, nextNode, ed)
	if not self._pathDB[node] then self._pathDB[node] = {} end
	self._pathDB[node][ed] = (nextNode == ed and node or nextNode)
end

-- Path lookupTable
local lookupTable = {}
lookupTable.__index = lookupTable

function lookupTable:new()
	local lut = {_pathDB = {}}
	return setmetatable(lut, lookupTable)
end

function lookupTable:addPath(path)
	local st, ed = path._nodes[1], path._nodes[#path._nodes]
	for node, count in path:nodes() do
		local nextNode = path._nodes[count+1]
		if nextNode then addNode(self, node, nextNode, ed) end
	end
end

function lookupTable:hasPath(nodeA, nodeB)
	local found
	found = self._pathDB[nodeA] and self._path[nodeA][nodeB]
	if found then return true, true end
	found = self._pathDB[nodeB] and self._path[nodeB][nodeA]
	if found then return true, false end
	return false
end

return lookupTable


text:
package org.apache.lucene.store;

/**
 *
A FlushInfo provides information required for a FLUSH context.
 *  It is used as part of an {@link IOContext} in case of FLUSH context.

 */

public class FlushInfo {

  public final int numDocs;

  public final long estimatedSegmentSize;

  /**
   *
Creates a new {@link FlushInfo} instance from
   * the values required for a FLUSH {@link IOContext} context.
   *
   * These values are only estimates and are not the actual values.
   *
   */

  public FlushInfo(int numDocs, long estimatedSegmentSize) {
    this.numDocs = numDocs;
    this.estimatedSegmentSize = estimatedSegmentSize;
  }

  @Override
  public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result
        + (int) (estimatedSegmentSize ^ (estimatedSegmentSize >>> 32));
    result = prime * result + numDocs;
    return result;
  }

  @Override
  public boolean equals(Object obj) {
    if (this == obj)
      return true;
    if (obj == null)
      return false;
    if (getClass() != obj.getClass())
      return false;
    FlushInfo other = (FlushInfo) obj;
    if (estimatedSegmentSize != other.estimatedSegmentSize)
      return false;
    if (numDocs != other.numDocs)
      return false;
    return true;
  }

  @Override
  public String toString() {
    return "FlushInfo [numDocs=" + numDocs + ", estimatedSegmentSize="
        + estimatedSegmentSize + "]";
  }

}


text:
<?php

namespace Rauma\Sitemap;

class SitemapUrl
{
    /**
     * @var string
     */
    private $location;

    /**
     * @var float
     */
    private $priority;

    /**
     * Constructor.
     *
     * @param string $location Location.
     * @param float  $priority Priority.
     */
    public function __construct($location, $priority = 0.5)
    {
        $this->location = $location;
        $this->priority = $priority;
    }

    /**
     * Get the location.
     *
     * @return string
     */
    public function getLocation()
    {
        return $this->location;
    }

    /**
     * Get priority.
     *
     * @return float
     */
    public function getPriority()
    {
        return $this->priority;
    }
}


text:
package org.sunflow.core;

import org.sunflow.image.Color;

/**
 * A shader represents a particular light-surface interaction.
 */
public interface Shader extends RenderObject {
    /**
     * Gets the radiance for a specified rendering state. When this method is
     * called, you can assume that a hit has been registered in the state and
     * that the hit surface information has been computed.
     *
     * @param state current render state
     * @return color emitted or reflected by the shader
     */
    public Color getRadiance(ShadingState state);

    /**
     * Scatter a photon with the specied power. Incoming photon direction is
     * specified by the ray attached to the current render state. This method
     * can safely do nothing if photon scattering is not supported or relevant
     * for the shader type.
     *
     * @param state current state
     * @param power power of the incoming photon.
     */
    public void scatterPhoton(ShadingState state, Color power);
}


text:
package de.calette.mephisto3.resources;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Used for load images and stuff.
 */
public class ResourceLoader {
  private final static Logger LOG = LoggerFactory.getLogger(ResourceLoader.class);

  public static String getResource(String s) {
    try {
      return ResourceLoader.class.getResource(s).toExternalForm();
    } catch (Exception e) {
      LOG.error("Resource not found: " + s);
    }
    return null;
  }
}


text:
CREATE TABLE [dwh].[CustomerLink]
(
	[CustomerId] Int
	, [CustomerInfoId] Int
	, [DateId] Int
	, [IsFirstDate] Bit
	, [IsLastDate] Bit
)

CREATE UNIQUE INDEX [UX_CustomerLink]
	ON [dwh].[CustomerLink]
	(
		[CustomerId]
		, [DateId]
	)

CREATE INDEX [IX_CustomerLink_DateId]
	ON [dwh].[CustomerLink]
	(
		[DateId]
	)
	INCLUDE
	(
		[CustomerId]
		, [CustomerInfoId]
	)

CREATE INDEX [FIX_CustomerLink_IsFirstDate]
ON [dwh].[CustomerLink]
	(
		[CustomerId]
	)
	INCLUDE
	(
		[CustomerId]
		, [CustomerInfoId]
		, [DateId]
	)
	WHERE
		IsFirstDate = 1

CREATE INDEX [FIX_CustomerLink_IsLastDate]
ON [dwh].[CustomerLink]
	(
		[CustomerId]
	)
	INCLUDE
	(
		[CustomerId]
		, [CustomerInfoId]
		, [DateId]
	)
	WHERE
		IsLastDate = 1


text:
namespace theia {

class Camera;
struct FeatureCorrespondence;

// Calculates Sampson distance for two correspondances and an essential or
// fundamental matrix by eq. 11.9 in Hartley and Zisserman. For an E or F
// that is defined such that y^t * E * x = 0
double SquaredSampsonDistance(const Eigen::Matrix3d& F,
                              const Eigen::Vector2d& x,
                              const Eigen::Vector2d& y);

// Returns the cross product matrix of a vector: if cross_vec = [x y z] then
//                        [ 0  -z   y]
// cross product matrix = [ z   0  -y]
//                        [-y   x   0]
Eigen::Matrix3d CrossProductMatrix(const Eigen::Vector3d& cross_vec);

// Given a 2xN matrix of image points (of the form [x, y]), this method
// calculates the matrix that will shift the points so that the centroid is at
// the origin and the average distance from the centroid is sqrt(2). Returns the
// transformation matrix and the transformed points.
bool NormalizeImagePoints(
    const std::vector<Eigen::Vector2d>& image_points,
    std::vector<Eigen::Vector2d>* normalized_image_points,
    Eigen::Matrix3d* normalization_matrix);

// Projects a 3x3 matrix to the rotation matrix in SO3 space with the closest
// Frobenius norm. For a matrix with an SVD decomposition M = USV, the nearest
// rotation matrix is R = UV'.
Eigen::Matrix3d ProjectToRotationMatrix(const Eigen::Matrix3d& matrix);

}  // namespace theia

#endif  // THEIA_SFM_POSE_UTIL_H_


text:
using System;
using System.Collections.Generic;
using System.Text;

namespace Ku.Core.CMS.Domain
{
    public static class CacheKeyDefinition
    {
        public static readonly string VerifyCode = "verify.code:{0}";
        public static readonly string PageLock = "page.lock:{0}";

        public static readonly string UserAuthCode = "ku.cache.user.authcode:{0}";
        public static readonly string UserAuthCodeEncrypt = "ku.cache.user.authcode.encrypt:{0}";

        public static readonly string EventSubscribers = "ku.cache.event.subscribers:{0}";

        public static readonly string ProductSkuTemp = "ku.cache.product.sku.temp:{0}";

        #region WebApi

        public static readonly string ApiUserToken = "api.user.token:{0}.{1}";
        public static readonly string ApiExpiredToken = "api.expired.token:{0}";

        #endregion

        public static readonly string DataCenter_AppFeedback_Unsolved = "dc.app.feedback.unsolved:{0}";

        /// <summary>
        /// 短信验证码
        /// </summary>
        public const string SmsVerifyCode = "sms.verify.code:{0}:{1}";

        /// <summary>
        /// 短信验证码(注册)
        /// </summary>
        public const string SmsVerifyCode_Register = "sms.verify.code:register:{0}";

        /// <summary>
        /// 短信验证码(绑定)
        /// </summary>
        public const string SmsVerifyCode_Bind = "sms.verify.code:bind:{0}";

        /// <summary>
        /// 短信验证码(密码重置)
        /// </summary>
        public const string SmsVerifyCode_Pwd = "sms.verify.code:Password:{0}";

        /// <summary>
        /// 栏目数据缓存
        /// </summary>
        public const string ContentColumnList = "content.column.list";

        /// <summary>
        /// 配置缓存
        /// </summary>
        public const string Config = "config:{0}";
    }
}


text:
using namespace std;
using namespace Eigen;

template <typename CoefficientType>
PiecewisePolynomial<CoefficientType>::PiecewisePolynomial(std::vector<PolynomialMatrix> const& polynomials, std::vector<double> const& segment_times) :
    PiecewisePolynomialBase(segment_times),
    polynomials(polynomials)
{
  assert(segment_times.size() == (polynomials.size() + 1));
  for (int i = 1; i < getNumberOfSegments(); i++) {
    if (polynomials[i].rows() != polynomials[0].rows())
      throw std::runtime_error("The polynomial matrix for each segment must have the same number of rows.");
    if (polynomials[i].cols() != polynomials[0].cols())
      throw std::runtime_error("The polynomial matrix for each segment must have the same number of columns.");
  }
}

template <typename CoefficientType>
PiecewisePolynomial<CoefficientType>::PiecewisePolynomial(std::vector<PolynomialType> const& polynomials, std::vector<double> const& segment_times) :
    PiecewisePolynomialBase(segment_times)
{
  assert(segment_times.size() == (polynomials.size() + 1));

  for (int i = 0; i < polynomials.size(); i++) {
    PolynomialMatrix matrix(1, 1);
    matrix(0, 0) = polynomials[i];
    this->polynomials.push_back(matrix);
  }
}

template <typename CoefficientType>
PiecewisePolynomial<CoefficientType>::PiecewisePolynomial() {
  // empty
}

template <typename CoefficientType>
PiecewisePolynomial<CoefficientType> PiecewisePolynomial<CoefficientType>::derivative(int derivative_order) const {
  PiecewisePolynomial ret = *this;
  for (auto it = ret.polynomials.begin(); it != ret.polynomials.end(); ++it) {
    PolynomialMatrix& matrix = *it;
    for (DenseIndex row = 0; row < rows(); row++) {
      for (DenseIndex col = 0; col < cols(); col++) {
        matrix(row, col) = matrix(row, col).derivative(derivative_order);
      }
    }
  }
  return ret;
}

template <typename CoefficientType>
PiecewisePolynomial<CoefficientType> PiecewisePolynomial<CoefficientType>::integral(double value_at_start_time) const {
  CoefficientMatrix matrix_value_at_start_time = CoefficientMatrix::Constant(rows(), cols(), value_at_start_time);
  return integral(matrix_value_at_start_time);
}

template <typename CoefficientType>
PiecewisePolynomial<CoefficientType> PiecewisePolynomial<CoefficientType>::integral(const typename PiecewisePolynomial<CoefficientType>::CoefficientMatrixRef & value_at_start_time) const {
  PiecewisePolynomial ret = *this;
  for (int segment_index = 0; segment_index < getNumberOfSegments(); segment_index++) {
    PolynomialMatrix& matrix = ret.polynomials[segment_index];
    for (DenseIndex row = 0; row < rows(); row++) {
      for (DenseIndex col = 0; col < cols(); col++) {
        if (segment_index == 0) {
          matrix(row, col) = matrix(row, col).integral(value_at_start_time(row, col));
        }
        else {
          matrix(row, col) = matrix(row, col).integral(ret.segmentValueAtGlobalAbscissa(segment_index - 1, getStartTime(segment_index), row, col));
        }
      }
    }
  }
  return ret;
}

template <typename CoefficientType>
double PiecewisePolynomial<CoefficientType>::scalarValue(double t, Eigen::DenseIndex row, Eigen::DenseIndex col) {
  int segment_index = getSegmentIndex(t);
  return segmentValueAtGlobalAbscissa(segment_index, t, row, col);
}

template <typename CoefficientType>
Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> PiecewisePolynomial<CoefficientType>::value(double t) const {
  int segment_index = getSegmentIndex(t);
  t = std::min(std::max(t, getStartTime()), getEndTime());
  Eigen::Matrix<double, PolynomialMatrix::RowsAtCompileTime, PolynomialMatrix::ColsAtCompileTime> ret(rows(), cols());
  for (DenseIndex row = 0; row < rows(); row++) {
    for (DenseIndex col = 0; col < cols(); col++) {
      ret(row, col) = segmentValueAtGlobalAbscissa(segment_index, t, row, col);
    }
  }
  return ret;
}

template <typename CoefficientType>
const typename PiecewisePolynomial<CoefficientType>::PolynomialMatrix& PiecewisePolynomial<CoefficientType>::getPolynomialMatrix(int segment_index) const {
  return polynomials[segment_index];
}

template <typename CoefficientType>
const Polynomial<CoefficientType>& PiecewisePolynomial<CoefficientType>::getPolynomial(int segment_index, Eigen::DenseIndex row, Eigen::DenseIndex col) const {
  segmentNumberRangeCheck(segment_index);
  return polynomials[segment_index](row, col);
}

template <typename CoefficientType>
int PiecewisePolynomial<CoefficientType>::getSegmentPolynomialDegree(int segment_index, Eigen::DenseIndex row, Eigen::DenseIndex col) const {
  segmentNumberRangeCheck(segment_index);
  return polynomials[segment_index](row, col).getDegree();
}

template <typename CoefficientType>
PiecewisePolynomial<CoefficientType>& PiecewisePolynomial<CoefficientType>::operator+=(const PiecewisePolynomial<CoefficientType>& other) {
  if (!segmentTimesEqual(other, 1e-10))
    throw runtime_error("Addition not yet implemented when segment times are not equal");
  for (int i = 0; i < polynomials.size(); i++)
    polynomials[i] += other.polynomials[i];
  return *this;
}

template <typename CoefficientType>
PiecewisePolynomial<CoefficientType>& PiecewisePolynomial<CoefficientType>::operator-=(const PiecewisePolynomial<CoefficientType>& other) {
  if (!segmentTimesEqual(other, 1e-10))
    throw runtime_error("Addition not yet implemented when segment times are not equal");
  for (int i = 0; i < polynomials.size(); i++)
    polynomials[i] -= other.polynomials[i];
  return *this;
}

template <typename CoefficientType>
PiecewisePolynomial<CoefficientType>& PiecewisePolynomial<CoefficientType>::operator*=(const PiecewisePolynomial<CoefficientType>& other) {
  if (!segmentTimesEqual(other, 1e-10))
    throw runtime_error("Multiplication not yet implemented when segment times are not equal");
  for (int i = 0; i < polynomials.size(); i++)
    polynomials[i] *= other.polynomials[i];
  return *this;
}

template <typename CoefficientType>
PiecewisePolynomial<CoefficientType>& PiecewisePolynomial<CoefficientType>::operator+=(const typename PiecewisePolynomial<CoefficientType>::CoefficientMatrix& offset) {
  for (int i = 0; i < polynomials.size(); i++)
    polynomials[i] += offset.template cast<PolynomialType>();
  return *this;
}

template <typename CoefficientType>
PiecewisePolynomial<CoefficientType>& PiecewisePolynomial<CoefficientType>::operator-=(const typename PiecewisePolynomial<CoefficientType>::CoefficientMatrix& offset) {
  for (int i = 0; i < polynomials.size(); i++)
    polynomials[i] -= offset.template cast<PolynomialType>();
  return *this;
}

template <typename CoefficientType>
const PiecewisePolynomial<CoefficientType> PiecewisePolynomial<CoefficientType>::operator+(const PiecewisePolynomial<CoefficientType>& other) const {
  PiecewisePolynomial<CoefficientType> ret = *this;
  ret += other;
  return ret;
}

template <typename CoefficientType>
const PiecewisePolynomial<CoefficientType> PiecewisePolynomial<CoefficientType>::operator-(const PiecewisePolynomial<CoefficientType>& other) const {
  PiecewisePolynomial<CoefficientType> ret = *this;
  ret -= other;
  return ret;
}

template <typename CoefficientType>
const PiecewisePolynomial<CoefficientType> PiecewisePolynomial<CoefficientType>::operator*(const PiecewisePolynomial<CoefficientType>& other) const {
  PiecewisePolynomial<CoefficientType> ret = *this;
  ret *= other;
  return ret;
}

template <typename CoefficientType>
const PiecewisePolynomial<CoefficientType> PiecewisePolynomial<CoefficientType>::operator+(const typename PiecewisePolynomial<CoefficientType>::CoefficientMatrix& offset) const {
  PiecewisePolynomial<CoefficientType> ret = *this;
  ret += offset;
  return ret;
}

template <typename CoefficientType>
const PiecewisePolynomial<CoefficientType> PiecewisePolynomial<CoefficientType>::operator-(const typename PiecewisePolynomial<CoefficientType>::CoefficientMatrix& offset) const {
  PiecewisePolynomial<CoefficientType> ret = *this;
  ret -= offset;
  return ret;
}

template <typename CoefficientType>
bool PiecewisePolynomial<CoefficientType>::isApprox(const PiecewisePolynomial<CoefficientType>& other, double tol) const {
  if (rows() != other.rows() || cols() != other.cols())
    return false;

  if (!segmentTimesEqual(other, tol))
    return false;

  for (int segment_index = 0; segment_index < getNumberOfSegments(); segment_index++) {
    const PolynomialMatrix& matrix = polynomials[segment_index];
    const PolynomialMatrix& other_matrix = other.polynomials[segment_index];
    for (DenseIndex row = 0; row < rows(); row++) {
      for (DenseIndex col = 0; col < cols(); col++) {
      if (!matrix(row, col).isApprox(other_matrix(row, col), tol))
        return false;
      }
    }
  }
  return true;
}

template<typename CoefficientType>
void PiecewisePolynomial<CoefficientType>::shiftRight(double offset) {
  for (auto it = segment_times.begin(); it != segment_times.end(); ++it) {
    *it += offset;
  }
}

template<typename CoefficientType>
void PiecewisePolynomial<CoefficientType>::setPolynomialMatrixBlock(const typename PiecewisePolynomial<CoefficientType>::PolynomialMatrix& replacement, int segment_number, Eigen::DenseIndex row_start, Eigen::DenseIndex col_start)
{
  segmentNumberRangeCheck(segment_number);
  polynomials[segment_number].block(row_start, col_start, replacement.rows(), replacement.cols()) = replacement;
}

template<typename CoefficientType>
PiecewisePolynomial<CoefficientType> PiecewisePolynomial<CoefficientType>::slice(int start_segment_index, int num_segments) {
  segmentNumberRangeCheck(start_segment_index);
  segmentNumberRangeCheck(start_segment_index + num_segments - 1);

  auto segment_times_start_it = segment_times.begin() + start_segment_index;
  auto segment_times_slice = vector<double>(segment_times_start_it, segment_times_start_it + num_segments + 1); // + 1 because there's one more segment times than segments

  auto polynomials_start_it = polynomials.begin() + start_segment_index;
  auto polynomials_slice = vector<PolynomialMatrix>(polynomials_start_it, polynomials_start_it + num_segments);

  return PiecewisePolynomial<CoefficientType>(polynomials_slice, segment_times_slice);
}

template <typename CoefficientType>
double PiecewisePolynomial<CoefficientType>::segmentValueAtGlobalAbscissa(int segment_index, double t, Eigen::DenseIndex row, Eigen::DenseIndex col) const {
  return polynomials[segment_index](row, col).value(t - getStartTime(segment_index));
}

template <typename CoefficientType>
Eigen::DenseIndex PiecewisePolynomial<CoefficientType>::rows() const
{
  if (polynomials.size() > 0)
    return polynomials[0].rows();
  else
    throw std::runtime_error("PiecewisePolynomial has no segments. Number of rows is undefined.");
}

template <typename CoefficientType>
Eigen::DenseIndex PiecewisePolynomial<CoefficientType>::cols() const
{
    if (polynomials.size() > 0)
    return polynomials[0].cols();
  else
    throw std::runtime_error("PiecewisePolynomial has no segments. Number of columns is undefined.");
}

template<typename CoefficientType>
PiecewisePolynomial<CoefficientType> PiecewisePolynomial<CoefficientType>::random(
    Eigen::DenseIndex rows, Eigen::DenseIndex cols, Eigen::DenseIndex num_coefficients_per_polynomial,
    const std::vector<double>& segment_times)
{
  Eigen::DenseIndex num_segments = static_cast<Eigen::DenseIndex>(segment_times.size() - 1);
  std::vector<PolynomialMatrix> polynomials;
  for (Eigen::DenseIndex segment_index = 0; segment_index < num_segments; ++segment_index) {
    polynomials.push_back(PolynomialType::randomPolynomialMatrix(num_coefficients_per_polynomial, rows, cols));
  }
  return PiecewisePolynomial<CoefficientType>(polynomials, segment_times);
}

template class DLLEXPORT PiecewisePolynomial<double>;
//template class DLLEXPORT PiecewisePolynomial<std::complex<double>>; // doesn't work yet


text:
package org.hibernate.envers.test.integration.collection.norevision;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;

import org.hibernate.envers.Audited;

@Audited
@Entity
public class Name implements Serializable {
    @Id
    @GeneratedValue
    private Integer id;

    private String name;
    @ManyToOne
    @JoinColumn(name = "person_id", insertable = false, updatable = false)
    private Person person;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

    public Person getPerson() {
        return person;
    }

    public void setPerson(Person person) {
        this.person = person;
    }
}


text:
#ifndef SkCornerPathEffect_DEFINED
#define SkCornerPathEffect_DEFINED

#include "SkPathEffect.h"

/** \class SkCornerPathEffect

    SkCornerPathEffect is a subclass of SkPathEffect that can turn sharp corners
    into various treatments (e.g. rounded corners)
*/
class SkCornerPathEffect : public SkPathEffect {
public:
    /** radius must be > 0 to have an effect. It specifies the distance from each corner
        that should be "rounded".
    */
    SkCornerPathEffect(SkScalar radius);
    virtual ~SkCornerPathEffect();

    // overrides for SkPathEffect
    //  This method is not exported to java.
    virtual bool filterPath(SkPath* dst, const SkPath& src, SkScalar* width);

    // overrides for SkFlattenable
    //  This method is not exported to java.
    virtual Factory getFactory();
    //  This method is not exported to java.
    virtual void flatten(SkFlattenableWriteBuffer&);

protected:
    SkCornerPathEffect(SkFlattenableReadBuffer&);

private:
    SkScalar    fRadius;

    static SkFlattenable* CreateProc(SkFlattenableReadBuffer&);

    // illegal
    SkCornerPathEffect(const SkCornerPathEffect&);
    SkCornerPathEffect& operator=(const SkCornerPathEffect&);

    typedef SkPathEffect INHERITED;
};

#endif


text:
var express = require('express');
var bodyParser = require('body-parser');

var jwt = require('jsonwebtoken');  //https://npmjs.org/package/node-jsonwebtoken
var expressJwt = require('express-jwt'); //https://npmjs.org/package/express-jwt

var secret = 'this is the secret secret secret 12356';

var app = express();

// Add headers
app.use(function (req, res, next) {

    // Website you wish to allow to connect
    res.setHeader('Access-Control-Allow-Origin', 'http://localhost:9000');

    // Request methods you wish to allow
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

    // Request headers you wish to allow
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type, Accept, Authorization');

    // Set to true if you need the website to include cookies in the requests sent
    // to the API (e.g. in case you use sessions)
    res.setHeader('Access-Control-Allow-Credentials', true);

    // Pass to next layer of middleware
    next();
});

// We are going to protect /api routes with JWT
app.use('/api', expressJwt({secret: secret}));

app.use(bodyParser.json());
app.use('/', express.static(__dirname + '/'));

app.use(function(err, req, res, next){
  if (err.constructor.name === 'UnauthorizedError') {
    res.status(401).send('Unauthorized');
  }
});

app.post('/authenticate', function (req, res) {
  //TODO validate req.body.username and req.body.password
  //if is invalid, return 401
  if (!(req.body.username === 'essi' && req.body.password === 'essi')) {
    res.status(401).send('Wrong user or password');
    return;
  }

  var profile = {
    first_name: 'abhi',
    last_name: 'n',
    email: 'abhi@gmail.com',
    id: 123
  };

  // We are sending the profile inside the token
  var token = jwt.sign(profile, secret, { expiresInMinutes: 60*5 });

  res.json({ token: token });
});

app.get('/api/restricted', function (req, res) {
  console.log('user ' + req.user.email + ' is calling /api/restricted');
  res.json({
    name: 'foo'
  });
});

app.listen(8080, function () {
  console.log('listening on http://localhost:8080');
});


text:
using System;
using System.Collections.Generic;

namespace JS.Entities.ExtensionMethods
{

    /// <summary>
    /// Extension Methods for Booleans
    /// </summary>
    public static class BooleanExtensions
    {

        /// <summary>
        /// The internal string representation of yes.
        /// </summary>
        public static string YesString = "Yes";

        /// <summary>
        /// The internal string representation of no.
        /// </summary>
        public static string NoString = "No";

        /// <summary>
        /// The internal string representation of yes shortened.
        /// </summary>
        public static string YesStringShort = "Y";

        /// <summary>
        /// The internal string representation of no shortened.
        /// </summary>
        public static string NoStringShort = "N";

        /// <summary>
        ///
        /// </summary>
        public static string[] BooleanConstants
        {
            get
            {
                List<string> boolConstants = new List<string>();

                boolConstants.AddRange(TrueConstants);

                boolConstants.AddRange(FalseConstants);

                return boolConstants.ToArray();
            }
        }

        /// <summary>
        /// True boolean english constants
        /// </summary>
        public static string[] TrueConstants
        {
            get
            {
                return new[]
                    {
                        bool.TrueString,
                        YesString,
                        YesStringShort
                    };

            }
        }

        /// <summary>
        /// False boolean english constants
        /// </summary>
        public static string[] FalseConstants
        {
            get
            {
                return new[]
                    {
                        bool.FalseString,
                        NoString,
                        NoStringShort
                    };

            }
        }

        /// <summary>
        /// Returns a friendly string representation of the boolean value
        /// </summary>
        /// <param name="value"></param>
        /// <param name="trueString">Custom value if desired</param>
        /// <param name="falseString">Custom value if desired</param>
        /// <returns>A string</returns>
        public static string ToFormattedString(this bool value, string trueString = "Yes", string falseString = "No")
        {
            return value ? trueString : falseString;
        }

        /// <summary>
        /// Attempts to parse a boolean value using english constants
        /// </summary>
        /// <param name="valueToParse"></param>
        /// <param name="parsedValue"></param>
        /// <returns>True if parsed, false otherwise</returns>
        public static bool TryParseBooleanConstants(string valueToParse, out bool parsedValue)
        {
            parsedValue = false;

            if (valueToParse.IsNullOrWhiteSpace())
            {
                return false;
            }

            string trimmedValue = valueToParse.TrimSafely();

            if (BooleanConstants.Contains(trimmedValue, StringComparison.CurrentCultureIgnoreCase))
            {
                if (TrueConstants.Contains(trimmedValue, StringComparison.CurrentCultureIgnoreCase))
                {
                    parsedValue = true;
                }
                else if (FalseConstants.Contains(trimmedValue, StringComparison.CurrentCultureIgnoreCase))
                {
                    parsedValue = false;
                }

                return true;
            }
            return false;
        }

        /// <summary>
        /// Attempts to parse a boolean string using boolean strings
        /// </summary>
        /// <param name="valueToParse"></param>
        /// <param name="parsedValue"></param>
        /// <returns>True if parsed, false otherwise</returns>
        public static bool TryParse(string valueToParse, out bool parsedValue)
        {
            return bool.TryParse(valueToParse, out parsedValue);
        }

    }
}


text:
<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>MaxERP</title>

    {{-- css --}}

    <link href="{{ asset('/gentelella/vendors/bootstrap/dist/css/bootstrap.min.css')}}" rel="stylesheet">

    <link href="{{ asset('/gentelella/vendors/font-awesome/css/font-awesome.min.css')}}" rel="stylesheet">

    <link href="{{ asset('/gentelella/vendors/nprogress/nprogress.css')}}" rel="stylesheet">

    <link href="{{ asset('/gentelella/build/css/custom.min.css')}}" rel="stylesheet">
    @yield('css')

        {{-- Sidebar --}}

               MaxERP

General

 Dashboard

 Home

Dashboard

Dashboard2

Dashboard3

        {{-- Topnav --}}

                    John Doe

 Profile

                        50%
                        Settings

Help

 Log Out

                    6

                          John Smith
                          3 mins ago

                          Film festivals used to be do-or-die moments for movie makers. They were where...

                          John Smith
                          3 mins ago

                          Film festivals used to be do-or-die moments for movie makers. They were where...

                          John Smith
                          3 mins ago

                          Film festivals used to be do-or-die moments for movie makers. They were where...

                          John Smith
                          3 mins ago

                          Film festivals used to be do-or-die moments for movie makers. They were where...

                          See All Alerts

        {{-- Content --}}

Plain Page

                    <input type="text" class="form-control" placeholder="Search for...">

                      <button class="btn btn-default" type="button">Go!</button>

Plain Page

Settings 1

Settings 2

                      Add content to the page ...

        {{-- Footer --}}

            Gentelella - Bootstrap Admin Template by Colorlib

    @yield('js')
    {{-- Js --}}


text:
require File.expand_path('../spec_helper', __FILE__)

describe IO::Buffer do

  let :buffer do
    IO::Buffer.new
  end

  it "provides a subset of the methods available in Strings" do
    expect(buffer << "foo").to eq "foo"
    expect(buffer << "bar").to eq "bar"
    expect(buffer.to_str).to eq "foobar"
    expect(buffer.to_str).to eq "foobar"
    expect(buffer.size).to eq 6
  end

  it "provides append and prepend" do
    expect(buffer.append "bar").to eq "bar"
    expect(buffer.prepend "foo").to eq "foo"
    expect(buffer.append "baz").to eq "baz"
    expect(buffer.to_str).to eq "foobarbaz"
  end

  context "#read" do
    it "can be used to retrieve the contents of a buffer" do
      expect(buffer << "foo").to eq "foo"
      expect(buffer.read 2).to eq "fo"
      expect(buffer << "bar").to eq "bar"
      expect(buffer.read 2).to eq "ob"
      expect(buffer << "baz").to eq "baz"
      expect(buffer.read 3).to eq "arb"
    end
  end

  describe "provides methods for performing non-blocking I/O" do
    require "tempfile"

    context "#read_from" do
      context "using local file", :env => :exclude_win do
        let :tmp do
          t = Tempfile.open "read_from"
          t << "foobar"
          t.rewind
          t
        end

        it "will read as much data as possible" do
          expect(buffer.read_from tmp).to eq 6
          expect(buffer.to_str).to eq "foobar"
        end
      end

      context "using udp socket" do
        before :each do
          @receiver = UDPSocket.open
          @receiver.bind nil, 0

          @sender = UDPSocket.open
          @sender.connect "localhost", @receiver.addr[1]
        end
        after :each do
          @receiver.close
          @sender.close
        end

        it "will read as much data as possible" do
          select [], [@sender]
          @sender.send "foo", 0
          select [@receiver]
          expect(buffer.read_from @receiver).to eq 3
          expect(buffer.to_str).to eq "foo"

          select [], [@sender]
          @sender.send "barbaz", 0
          select [@receiver]
          expect(buffer.read_from @receiver).to eq 6
          expect(buffer.to_str).to eq "foobarbaz"
        end
      end
    end

    context "#write_to" do
      context "using local file", :env => :exclude_win do
        let :tmp do
          Tempfile.open "write_to"
        end
        it "writes the contents of the buffer" do
          buffer << "foo"
          expect(buffer.write_to tmp).to eq 3
          tmp.rewind
          expect(tmp.read 3).to eq "foo"
        end
      end

      context "using udp socket" do
        before :each do
          @receiver = UDPSocket.open
          @receiver.bind nil, 0

          @sender = UDPSocket.open
          @sender.connect "localhost", @receiver.addr[1]
        end
        after :each do
          @receiver.close
          @sender.close
        end

        it "will read as much data as possible" do
          buffer << "foo"
          select [], [@sender]
          expect(buffer.write_to @sender).to eq 3
          select [@receiver]
          expect(@receiver.recvfrom_nonblock(3)[0]).to eq "foo"
        end
      end
    end
  end

  context "#clear" do
    it "clear all data" do
      buffer << "foo"
      expect(buffer.size).to eq 3
      expect(buffer.empty?).to eq false
      buffer.clear
      expect(buffer.size).to eq 0
      expect(buffer.empty?).to eq true
    end
  end

  context "#read_frame" do
    it "Read up to and including the given frame marker" do
      buffer << "foo\nbarbaz"
      data = ""
      expect(buffer.read_frame data, "\n".ord).to eq true
      expect(buffer.empty?).to eq false
      expect(data).to eq "foo\n"
      expect(buffer.to_str).to eq "barbaz"

      expect(buffer.read_frame data, "\n".ord).to eq false
      expect(buffer.empty?).to eq true
      expect(data).to eq "foo\nbarbaz"
      expect(buffer.to_str).to eq ""
    end
  end

end


text:
package com.abewy.android.apps.contacts.app;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.webkit.WebView;
import com.abewy.android.apps.contacts.R;
import com.inscription.ChangeLogDialog;

public class ChangeLogActivity extends Activity
{
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_changelog);

		setTitle(R.string.changelog);

		WebView webView = (WebView) findViewById(R.id.webView);

		ChangeLogDialog cld = new ChangeLogDialog(this);
		webView.loadDataWithBaseURL(null, cld.getHTML(), "text/html", "utf-8", null);
	}

	@Override
	public boolean  onCreateOptionsMenu(Menu menu)
	{
		return false;
	}
}


text:
@interface ZJRegistItem : NSObject

@end


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

    <meta http-equiv="Content-Type"
          content="text/html; charset=UTF-8" />
    <meta http-equiv="cache-control" content="no-cache" />
    <title>Convert TLP synonyms for Wikipedia</title>
    <link rel="stylesheet" type="text/css" href="http://www.pxc.me.uk/common/css/pagex.css"/>

Convert TLP synonyms for Wikipedia
      <input type="button" value="Help"
        onclick="helpTPLSynonyms(); return false;" />

       <input type="button" value="Convert" onclick="run(); return false;" />
       <input id="hideSynonymsBox" type="checkbox" />
          Include Wikipedia code to hide (collapse) the synonym list

       <input type="text" id="urlEntered"/> enter the URL for the species or genus from www.theplantlist.org

Enter synonym lines from TPL:

    <textarea name="input" id="input" rows="10" cols="120" wrap="physical">Input text here</textarea>

Output:

    <textarea id="output" style="border:solid black 1px" rows="10" cols="120" wrap="physical"></textarea>


text:
// Copyright (c) Benjamin Proemmer. All rights reserved.
// See License in the project root for license information.

using System;

namespace Dacs7.Protocols
{
    internal sealed class CallbackHandler<T>
    {
        public ushort Id { get; }
        public Exception Exception { get; set; }
        public AsyncAutoResetEvent<T> Event { get; }

        public CallbackHandler()
        {
        }

        public CallbackHandler(ushort id)
        {
            Id = id;
            Event = new AsyncAutoResetEvent<T>();
            Exception = null;
        }

    }
}


text:
<?xml version="1.0" encoding="utf-8" standalone="no"?>
<resources>
    <string name="location">Location</string>
    <string name="cant_read_folder">folder can\'t be read!</string>
    <string name="nnew">New</string>
    <string name="select">Select</string>
    <string name="file_name">File name:</string>
    <string name="cancel">Cancel</string>
    <string name="create">Save</string>
    <string name="no_data">No Data</string>
    <color name="gray">#ffff0000</color>
    <string name="err">Error</string>
</resources>


text:
<!doctype html>

	<meta charset="utf-8">
	<meta http-equiv="x-ua-compatible" content="ie=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
	<title>FormatIdentifier | stdlib</title>
	<meta name="description" content="stdlib is a standard library for JavaScript and Node.js, with an emphasis on numerical and scientific computing.">
	<meta name="author" content="stdlib">
	<meta name="apple-mobile-web-app-capable" content="yes">
	<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">

	<link rel="apple-touch-icon" sizes="180x180" href="../apple-touch-icon.png">
	<link rel="icon" type="image/png" sizes="32x32" href="../favicon-32x32.png">
	<link rel="icon" type="image/png" sizes="16x16" href="../favicon-16x16.png">
	<link rel="manifest" href="../manifest.json">
	<link rel="mask-icon" href="../safari-pinned-tab.svg" color="#5bbad5">
	<meta name="theme-color" content="#ffffff">

	<meta property="og:type" content="website">
	<meta property="og:site_name" content="stdlib">
	<meta property="og:url" content="https://stdlib.io/">
	<meta property="og:title" content="A standard library for JavaScript and Node.js.">
	<meta property="og:description" content="stdlib is a standard library for JavaScript and Node.js, with an emphasis on numerical and scientific computing.">
	<meta property="og:locale" content="en_US">
	<meta property="og:image" content="">

	<meta name="twitter:card" content="A standard library for JavaScript and Node.js.">
	<meta name="twitter:site" content="@stdlibjs">
	<meta name="twitter:url" content="https://stdlib.io/">
	<meta name="twitter:title" content="stdlib">
	<meta name="twitter:description" content="stdlib is a standard library for JavaScript and Node.js, with an emphasis on numerical and scientific computing.">
	<meta name="twitter:image" content="">
	<link rel="stylesheet" href="../assets/css/main.css">
	<link rel="stylesheet" href="../assets/css/theme.css">

						Search
						<input id="tsd-search-field" type="text" />

Preparing search index...

The search index is not available

						Options

								All

Public

Public/Protected

All

							<input type="checkbox" id="tsd-filter-inherited" checked />
							Inherited
							<input type="checkbox" id="tsd-filter-only-exported" />
							Only exported

					Menu

					Globals

					"string/base/format-tokenize/docs/types/index.d"

					FormatIdentifier

Interface FormatIdentifier

Format identifier object.

Hierarchy

						FormatIdentifier

Index

Properties

flags

mapping

precision

specifier

width

Properties

flags

flags: string

Defined in lib/node_modules/@stdlib/string/base/format-tokenize/docs/types/index.d.ts:33

Flags.

mapping

mapping: number

Defined in lib/node_modules/@stdlib/string/base/format-tokenize/docs/types/index.d.ts:48

Positional mapping from format specifier to argument index.

precision

precision: string

Defined in lib/node_modules/@stdlib/string/base/format-tokenize/docs/types/index.d.ts:43

Precision (integer or '*').

specifier

specifier: string

Defined in lib/node_modules/@stdlib/string/base/format-tokenize/docs/types/index.d.ts:28

Format specifier (one of 's', 'c', 'd', 'i', 'u', 'b', 'o', 'x', 'X', 'e', 'E', 'f', 'F', 'g', 'G').

width

width: string

Defined in lib/node_modules/@stdlib/string/base/format-tokenize/docs/types/index.d.ts:38

Minimum field width (integer or '*').

						Packages

						"string/base/format-<wbr>tokenize/docs/types/index.d"

						Format<wbr>Identifier

								flags

								mapping

								precision

								specifier

								width

						String<wbr>OrToken

						format<wbr>Tokenize

Legend

Module

Object literal

Variable

Function

Function with type parameter

Index signature

Type alias

Type alias with type parameter

Enumeration

Enumeration member

Property

Method

Interface

Interface with type parameter

Constructor

Property

Method

Index signature

Class

Class with type parameter

Constructor

Property

Method

Accessor

Index signature

Inherited constructor

Inherited property

Inherited method

Inherited accessor

Protected property

Protected method

Protected accessor

Private property

Private method

Private accessor

Static property

Static method

		Donate
		/
		Docs
		/
		Chat
		/
		Twitter
		/
		Contribute


text:
using System;
using System.IO;
using NUnit.Framework;
using RestSharp;
using RestSharp.Deserializers;

namespace Twilio.Monitor.Tests.Model
{
    [TestFixture]
    public class EventTests
    {
        [Test]
        public void testDeserializeResponse()
        {
            var doc = File.ReadAllText(Path.Combine("Resources", "event.json"));
            var json = new JsonDeserializer();
            var output = json.Deserialize<Event>(new RestResponse { Content = doc });

            Assert.NotNull(output);
            Assert.NotNull(output.EventData);
            Assert.NotNull(output.Links);
            Assert.True(output.Links.ContainsKey("actor"));
            Assert.True(output.Links.ContainsKey("resource"));
        }
    }
}


text:
package org.apache.camel.opentracing.decorators;

import org.apache.camel.Exchange;
import org.apache.camel.Message;
import org.junit.Test;
import org.mockito.Mockito;

import static org.junit.Assert.assertEquals;

public class JmsSpanDecoratorTest {

    @Test
    public void testGetMessageId() {
        String messageId = "abcd";
        Exchange exchange = Mockito.mock(Exchange.class);
        Message message = Mockito.mock(Message.class);

        Mockito.when(exchange.getIn()).thenReturn(message);
        Mockito.when(message.getHeader(JmsSpanDecorator.JMS_MESSAGE_ID)).thenReturn(messageId);

        JmsSpanDecorator decorator = new JmsSpanDecorator();

        assertEquals(messageId, decorator.getMessageId(exchange));
    }

}


text:
#ifndef __ORCA_PRINTF_H
#define __ORCA_PRINTF_H

/*
 * VectorBlox modifications:
 *
 * To avoid having to run init_printf() at startup a static global is
 * used to check if printf() has been initialized, and if not putp is
 * initialized from the function default_putc(void *, char) and putf
 * to the value DEFAULT_PUTF provided by uart.h.
 *
 */

#include "uart.h"
#ifndef DEFAULT_PUTP
#error "DEFAULT_PUTP must be defined (default UART pointer) before including orca_printf.h; it should be defined in uart.h"
#endif //#ifndef DEFAULT_PUTP

#include <stdarg.h>

void init_printf(void* putp,void (*putf) (void*,char));

void tfp_printf(char *fmt, ...) __attribute__((format (printf,1,2)));
void tfp_sprintf(char* s,char *fmt, ...) __attribute__((format (printf,2,3)));

void tfp_format(void* putp,void (*putf) (void*,char),char *fmt, va_list va);

#define printf tfp_printf
#define sprintf tfp_sprintf

#ifndef debug
#define debug(var) printf("%s:%d  %s = %d \r\n",__FILE__,__LINE__,#var,(signed)(var))
#define debugx(var) printf("%s:%d  %s = %08X \r\n",__FILE__,__LINE__,#var,(unsigned)(var))
#endif //debug

#endif //#ifndef __ORCA_PRINTF_H


text:
package com.teamparkin.mtdapp.databases;

import com.teamparkin.mtdapp.util.TableUtil;

import android.database.sqlite.SQLiteDatabase;

public class PlacesTable {

	private PlacesTable() {
	}

	public static final String TABLE = "mylocations_places";

	// Columns in the table.
	public interface Columns {
		public static final String AUTO_ID = "_id";
	}

	private static final String COLUMN_INFO = "(" + Columns.AUTO_ID
			+ " INTEGER PRIMARY KEY NOT NULL ON CONFLICT REPLACE, FOREIGN KEY("
			+ Columns.AUTO_ID + ") REFERENCES " + MyLocationTable.TABLE + "("
			+ MyLocationTable.Columns._ID + ") ON DELETE CASCADE)";

	protected static void onCreate(SQLiteDatabase db) {
		db.execSQL("CREATE TABLE " + TABLE + COLUMN_INFO);
	}

	protected static void onUpgrade(SQLiteDatabase database, int oldVersion,
			int newVersion) {
		TableUtil.onUpgrade(database, oldVersion, newVersion, TABLE,
				COLUMN_INFO);
	}

}