text:
<?xml version='1.0' encoding='UTF-8'?>
<project>
  <actions/>
  <description></description>
  <logRotator class="hudson.tasks.LogRotator">
    <daysToKeep>-1</daysToKeep>
    <numToKeep>50</numToKeep>
    <artifactDaysToKeep>-1</artifactDaysToKeep>
    <artifactNumToKeep>50</artifactNumToKeep>
  </logRotator>
  <keepDependencies>false</keepDependencies>
  <properties>
    <hudson.model.ParametersDefinitionProperty>
      <parameterDefinitions>
        <hudson.model.StringParameterDefinition>
          <name>ref</name>
          <description>The ref that the repository should be reset to.</description>
          <defaultValue></defaultValue>
        </hudson.model.StringParameterDefinition>
        <hudson.model.StringParameterDefinition>
          <name>pr_id</name>
          <description>The PR on which to comment on with success or failure message.</description>
          <defaultValue></defaultValue>
        </hudson.model.StringParameterDefinition>
      </parameterDefinitions>
    </hudson.model.ParametersDefinitionProperty>
  </properties>
  <scm class="hudson.plugins.git.GitSCM" plugin="git@2.3.5">
    <configVersion>2</configVersion>
    <userRemoteConfigs>
      <hudson.plugins.git.UserRemoteConfig>
        <url>{repo}</url>
        <credentialsId>{repo-creds-id}</credentialsId>
      </hudson.plugins.git.UserRemoteConfig>
    </userRemoteConfigs>
    <branches>
      <hudson.plugins.git.BranchSpec>
        <name>**</name>
      </hudson.plugins.git.BranchSpec>
    </branches>
    <doGenerateSubmoduleConfigurations>false</doGenerateSubmoduleConfigurations>
    <submoduleCfg class="list"/>
    <extensions/>
  </scm>
  <canRoam>true</canRoam>
  <disabled>false</disabled>
  <blockBuildWhenDownstreamBuilding>false</blockBuildWhenDownstreamBuilding>
  <blockBuildWhenUpstreamBuilding>false</blockBuildWhenUpstreamBuilding>
  <authToken>trigger</authToken>
  <triggers/>
  <concurrentBuild>false</concurrentBuild>
  <builders>
    <hudson.tasks.Shell>
      <command>#!/bin/bash
env
# Comments with success message if verify is good
report_success () {
  url="$1"
  user="$2"
  pass="$3"
  job_url="$4"
  echo {\"text\":\"SUCCESS ${job_url}\"} > successdata
  curl -s -k -u "${user}":"${pass}" -X POST -H "Content-Type: application/json" -d @successdata "${url}"
  rm -f successdata
  echo "Reporting success"
}
# Comments with failure message if verify is not good
report_failure () {
  url="$1"
  user="$2"
  pass="$3"
  job_url="$4"
  echo {\"text\":\"FAILURE ${job_url}\"} > failuredata
  curl -s -k -u "${user}":"${pass}" -X POST -H "Content-Type: application/json" -d @failuredata "${url}"
  rm -f failuredata
  echo "Reporting failure"
}
# Set up some options
set +e
set +x
set +H
git reset --hard
git clean -xfd
echo ${stashuser}
echo ${stashuserpassword}
# grab origin fetch URL and generate all the other pieces from that, i.e. these
# can be discovered from current repo and do not need to be passed in as parameters
# jenkins URL on the other hand will need to be passed in from somewhere because
# we can not discover it
origin_url=$(git remote -v | grep origin | grep fetch | awk '{print $2}')
# grab project, repo, and stash URL
project=$(echo $origin_url | awk -F/ '{print $(NF-1)}')
stash_repo=$(echo $origin_url | awk -F/ '{print $(NF)}' | sed 's/.git//g')
stash_url=$(echo $origin_url | sed 's|/scm/.*$||')
api_url="${stash_url}/rest/api/1.0/projects/${project}/repos/${stash_repo}"
# Debug output
echo "Project: " $project
echo "Repo: " $repo
echo "Stash URL: " $stash_url
echo "API URL: " $api_url
# Assume jq binary will be available
if [[ ! $(which jq) ]]; then
  echo "Need jq to be available in path"
  exit 1
fi
echo "PR id: ${pr_id}"
git_ref="${ref}"
info_link="${HOSTNAME}:{jenkinsport}/job/${JOB_NAME}/${BUILD_NUMBER}"
marker="VERIFYING ${git_ref} ${info_link}"
echo "Marker: ${marker}"
echo "Git ref: ${git_ref}"
comment_url="${api_url}/pull-requests/${pr_id}/comments"
echo {\"text\":\"${marker}\"} > commentdata
curl -X POST -H "Content-Type: application/json" -d @commentdata -s -k -u "${stashuser}":"${stashuserpassword}" "${comment_url}"
rm -f commentdata
echo "Hard resetting to ${git_ref} and running verify script at scripts/verify.sh"
git reset --hard ${git_ref}
# If verify exits with success then submit success along with job link
# otherwise submit failure comment with job link
(/bin/bash scripts/verify.sh && report_success "${comment_url}" "${stashuser}" "${stashuserpassword}" "${info_link}") || (report_failure "${comment_url}" "${stashuser}" "${stashuserpassword}" "${info_link}" && /bin/false)</command>
    </hudson.tasks.Shell>
  </builders>
  <publishers/>
  <buildWrappers>
    <org.jenkinsci.plugins.credentialsbinding.impl.SecretBuildWrapper plugin="credentials-binding@1.4">
      <bindings>
        <org.jenkinsci.plugins.credentialsbinding.impl.UsernamePasswordMultiBinding>
          <credentialsId>{stash-creds-id}</credentialsId>
          <usernameVariable>stashuser</usernameVariable>
          <passwordVariable>stashuserpassword</passwordVariable>
        </org.jenkinsci.plugins.credentialsbinding.impl.UsernamePasswordMultiBinding>
      </bindings>
    </org.jenkinsci.plugins.credentialsbinding.impl.SecretBuildWrapper>
  </buildWrappers>
</project>


text:
typedef void(^ConfirmBlock)(NSString *province,NSString *city,NSString *area);

@interface CityPickerView : UIView

@property (nonatomic,copy)ConfirmBlock confirmBlock;

- (void)popupPickerView;
- (void)closePickerView;
@end

redpajama_set_name: RedPajamaGithub


text:
package org.atreus.impl.core.mappings.entities.builders;

import org.atreus.impl.core.Environment;
import org.atreus.impl.core.mappings.BaseFieldEntityMetaComponentBuilder;
import org.atreus.impl.core.mappings.entities.meta.MetaEntityImpl;

import java.lang.reflect.Field;

/**
 * Make field accessible meta field builder.
 *
 * @author Martin Crawford
 */
public class MakeAccessibleComponentBuilder extends BaseFieldEntityMetaComponentBuilder {

  // Constants ---------------------------------------------------------------------------------------------- Constants

  // Instance Variables ---------------------------------------------------------------------------- Instance Variables

  // Constructors ---------------------------------------------------------------------------------------- Constructors

  public MakeAccessibleComponentBuilder(Environment environment) {
    super(environment);
  }

  // Public Methods ------------------------------------------------------------------------------------ Public Methods

  @Override
  public boolean handleField(MetaEntityImpl metaEntity, Field field) {
    field.setAccessible(true);
    return false;
  }

  // Protected Methods ------------------------------------------------------------------------------ Protected Methods

  // Private Methods ---------------------------------------------------------------------------------- Private Methods

  // Getters & Setters ------------------------------------------------------------------------------ Getters & Setters

} // end of class


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

  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta name="description" content="">
  <meta name="author" content="Josh Karns">
  <title>Josh Karns</title>

Joshua Karns' Work Site

          This page contains all of the work I have done for my CS2 course in the fall semester of 2016.
          The different projects are listed chronologically (oldest at the top).

Works

Review Programming Challenges

                Hello World ~ Source | Demo

                Collatz Sequence ~ Source | Demo

               Longest Word ~ Source | Demo

                Longer Words ~ Source | Demo

                Number Classifications ~ Source | Demo

Work Site Assignment ~ This is a superfluous link

GUI

		            GUI1 ~ Source |
		            Output

	              GUI2 ~ Source |
		            Output

		            GUI3 ~ Source |
		            Output

		            GUI4 ~ Source |
		            Output

		            GUI5 ~ Source |
		            Output

                GUI6 ~ Source |
                Output

                GUI7 ~ Source |
                Output

                GUI8P ~ Source |
                Output

                GUI8 ~ Source | Output

Inerface Implementations

                NameADT ~ Source |
                Output

                Triangle ~ Source |
                Output

List Play

                ArrayListPlay ~ Source |
                Output

                LinkedListPlay ~ Source |
                Output

                LongerWords ~ Source |
                Output

Sorts

                MultiwaySort ~ Source |
                Output

Trees

                BinaryTree Implementation and Tester ~ Source |
                Output

                Word Frequency Counter ~ Source |
                Output

Hashing

                Word Frequency Counter ~ Source |
                Output

Thats everything!

Other Projects

c-pipes ~ Source |

Java Resources

From Professor Graci

              Oracle's Java Page - A look at the commercial/promotional side of the language

              Wikipedia Page - Lots of information on the history and nature of Java

              Java Tutorial (text) - A straightforward tutorial that might be used to fill gaps in your knowledge

              Java Tutorial (video) - This one appears to be better than most of the videos designed for the purpose of learning something about Java

              Java Structures - A book written by a guy at Williams on Data Structures and Programming in Java

              Open Data Structures - A book written by a guy whose publishing approach is influence by the open source software projects

My Sources

StackOverflow - I've found answers to almost ever programming question I've ever had here

Java 8 Cheat Sheet - A cheat sheet for all of Java 8's neat features (lambdas, streams, etc.)

See How Java is Used in Android - See how to use java to create Android applications

LWJGL - LWJGL, The Light Weight Java Game Library, is an easy way to tinker with OpenGL (Graphics) in java, along with audio

Email: jkarns@oswego.edu

© 2016 Josh Karns

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous">


text:
package pe.joedayz.libreria.servicios;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for listarLibrosPaginacion complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="listarLibrosPaginacion">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="arg0" type="{http://www.w3.org/2001/XMLSchema}int"/>
 *         <element name="arg1" type="{http://www.w3.org/2001/XMLSchema}int"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "listarLibrosPaginacion", propOrder = {
    "arg0",
    "arg1"
})
public class ListarLibrosPaginacion {

    protected int arg0;
    protected int arg1;

    /**
     * Gets the value of the arg0 property.
     *
     */
    public int getArg0() {
        return arg0;
    }

    /**
     * Sets the value of the arg0 property.
     *
     */
    public void setArg0(int value) {
        this.arg0 = value;
    }

    /**
     * Gets the value of the arg1 property.
     *
     */
    public int getArg1() {
        return arg1;
    }

    /**
     * Sets the value of the arg1 property.
     *
     */
    public void setArg1(int value) {
        this.arg1 = value;
    }

}


text:
const { CheckboxControl } = wp.components;
const { withState }       = wp.compose;
const { Component }       = wp.element;

class RoleCheckbox extends Component {

	render() {
		let props = this.props;

		const { setState, roleName, roleLabel } = this.props;

		let { blockPermissionsRoles = [] } = this.props.attributes;

		return (
			<CheckboxControl
				disabled={ ! membersBlockPermissions.userCanAssignPermissions }
				className="members-bp-checklist__control"
				label={ roleLabel }
				checked={ blockPermissionsRoles.includes( roleName ) }
				onChange={ ( isChecked ) => {

					if ( isChecked && ! blockPermissionsRoles.includes( roleName ) ) {

						blockPermissionsRoles.push( roleName );

						props.setAttributes( {
							blockPermissionsRoles: blockPermissionsRoles
						} );

					} else if ( ! isChecked && blockPermissionsRoles.includes( roleName ) ) {

						blockPermissionsRoles = blockPermissionsRoles.filter( role => role !== roleName );

						props.setAttributes( {
							blockPermissionsRoles: blockPermissionsRoles
						} );
					}

					setState( { blockPermissionsRoles: blockPermissionsRoles } );
				} }
			/>
		);
	}
}

export default withState()(RoleCheckbox);


text:
class CategoryManager;
using CategoryManagerPtr = RefPtr<CategoryManager>;

class CategoryManager
	: public Object
{
public:
	CategoryManager(Manager* manager);

	//void Initialize(Manager* manager, const PathName& categoriesFile);

	Manager* GetManager() const { return m_manager; }

	String MakeNavBarListText(Page* curPage) const;

private:
	void MakeNavBarItemText(StringWriter* writer, Page* curPage, CategoryItem* item, bool active) const;

	friend class Serializer;
	Manager*	m_manager;
	Array<CategoryItemPtr>	m_rootCategoryList;
};


text:
using UnityEngine;
using UnityEngine.EventSystems;

public class Blue_Node : MonoBehaviour
{
    public Color hColor;
    public Color notEnoughMoneyColor;
    public Vector3 positonOffset;

    [Header("Optional")]
    public GameObject turret;
	public TurretBlueprint turretBlueprint;

    private Renderer rend;
    private Color startColor;

    Blue_BuildManager buildManger;

    void Start()
    {
        rend = GetComponent<Renderer>();
        startColor = rend.material.color;

        buildManger = Blue_BuildManager.instance;
    }

    public Vector3 GetBuildPosition()
    {
        return transform.position + positonOffset;
    }

    /*
    void OnMouseDown()
    {
        if (EventSystem.current.IsPointerOverGameObject())
        {
            return;
        }

        if (buildManger.GetTurretToBuild() == null)
            return;

        if (turret != null)
        {
            Debug.Log("Can't build here! ");
            return;
        }

        GameObject turretToBuild = Blue_BuildManager.instance.GetTurretToBuild();
        turret = (GameObject)Instantiate(turretToBuild, transform.position + positonOffset, transform.rotation);
    }

    void OnMouseEnter()
    {
        if (EventSystem.current.IsPointerOverGameObject())
        {
            return;
        }
        if (buildManger.GetTurretToBuild() != null)
        {
            rend.material.color = hColor;
        }
        return;
    }

    void OnMouseExit()
    {
        rend.material.color = startColor;
    }
    */

	public void SellTurret() {
		BluePlayerStats.Money += turretBlueprint.GetSellAmount();
		Destroy (turret);
		buildManger.DeselectNode ();
	}
    public void onClick()
    {
        if (EventSystem.current.IsPointerOverGameObject())
        {
            return;
        }

		if (turret != null)
		{
			buildManger.SelectNode (this);
			return;
		}

        if (!buildManger.CanBuild)
            return;

        //buildManger.BuildTurretOn(this);
		BuildTurret(buildManger.GetTurretToBuild());

    }

	void BuildTurret(TurretBlueprint blueprint) {
		if (BluePlayerStats.Money < blueprint.cost)
		{
			Debug.Log("Not enough money to build turret!!");
			return;
		}

		BluePlayerStats.Money -= blueprint.cost;

		GameObject _turret = (GameObject)Instantiate(blueprint.prefab, GetBuildPosition(), Quaternion.identity);
		turret = _turret;

		turretBlueprint = blueprint;

		Debug.Log("Money Left:" + BluePlayerStats.Money);

	}

    public void onSelect()
    {
        if (EventSystem.current.IsPointerOverGameObject())
        {
            return;
        }
        if (buildManger.CanBuild && buildManger.HasMoney)
        {
            rend.material.color = hColor;
        }
        else
        {
            rend.material.color = notEnoughMoneyColor;
        }
        return;
    }

    public void onRelease()
    {
        rend.material.color = startColor;
    }
}


text:
layout: documentation
title: ReactiveX - Async Operators
id: async
---

#Async Operators

The operators described on this page are part of the distinct `rxjava-async` module. They are used to convert synchronous methods into Observables.

* [**`start( )`**](Async-Operators#wiki-start) — create an Observable that emits the return value of a function
* [**`toAsync( )` or `asyncAction( )` or `asyncFunc( )`**](Async-Operators#wiki-toasync-or-asyncaction-or-asyncfunc) — convert a function or Action into an Observable that executes the function and emits its return value
* [**`startFuture( )`**](Async-Operators#wiki-startfuture) — convert a function that returns Future into an Observable that emits that Future's return value
* [**`deferFuture( )`**](Async-Operators#wiki-deferfuture) — convert a Future that returns an Observable into an Observable, but do not attempt to get the Observable that the Future returns until a Subscriber subscribes
* [**`forEachFuture( )`**](Async-Operators#wiki-foreachfuture) — pass Subscriber methods to an Observable but also have it behave like a Future that blocks until it completes
* [**`fromAction( )`**](Async-Operators#wiki-fromaction) — convert an Action into an Observable that invokes the action and emits its result when a Subscriber subscribes
* [**`fromCallable( )`**](Async-Operators#wiki-fromcallable) — convert a Callable into an Observable that invokes the callable and emits its result or exception when a Subscriber subscribes
* [**`fromRunnable( )`**](Async-Operators#wiki-fromrunnable) — convert a Runnable into an Observable that invokes the runable and emits its result when a Subscriber subscribes
* [**`runAsync( )`**](Async-Operators#wiki-runasync) — returns a `StoppableObservable` that emits multiple actions as generated by a specified Action on a Scheduler

***

## start( )
#### create an Observable that emits the return value of a function

Pass the `start( )` method a function that returns a value, and `start( )` will execute that function asynchronously and return an Observable that will emit that value to any subsequent Subscribers.

#### see also:
* RxJS: `start`
* Linq: `Start`

***

## toAsync( ) or asyncAction( ) or asyncFunc( )
#### convert a function into an Observable that executes the function and emits its return value

With `toAsync( )` you can create an Observable that, when it is subscribed to, executes a function (or Action) of your choosing and emits its return value before completing. In the case of an `Action`, it will emit `null` before completing. Note that even if the resulting Observable is subscribed to more than once, the function will only be executed once, and its sole return value will be emitted to all future Subscribers.

#### see also:
* Linq: `ToAsync`
* RxJS: `toAsync`

***

## startFuture( )
#### convert a function that returns Future into an Observable that emits that Future's return value

The `startFuture( )` method is similar to the `fromFuture( )` method except that it calls the function to obtain the Future immediately, and attempts to get its value even before a Subscriber subscribes to the resulting Observable. It then holds this value and returns it to any future Subscriber.

***

## deferFuture( )
#### convert a Future that returns an Observable into an Observable, but do not attempt to get the Observable that the Future returns until a Subscriber subscribes

You can use the `deferFuture( )` operator to convert a Future that returns an Observable into an Observable that emits the values of that returned Observable in such a way that the Future is not invoked until a Subscriber subscribes to the resulting Observable.

***

## forEachFuture( )
#### pass Subscriber methods to an Observable but also have it behave like a Future that blocks until it completes

You pass `forEachFuture( )` some subset of the Subscriber methods (`onNext`, `onError`, and `onCompleted`) and the Observable will call them in the usual way. But `forEachFuture( )` itself returns a `Future` that blocks until the source Observable completes, and then returns either the completion or the error, depending on how the Observable completed.

***

## fromAction( )
#### convert an Action into an Observable that invokes the action and emits its result when a Subscriber subscribes

***

## fromCallable( )
#### convert a Callable into an Observable that invokes the callable and emits its result or exception when a Subscriber subscribes

***

## fromRunnable( )
#### convert a Runnable into an Observable that invokes the runable and emits its result when a Subscriber subscribes

***

## runAsync( )
#### returns a `StoppableObservable` that emits multiple actions as generated by a specified `Action` on a `Scheduler`

Pass `runAsync( )` an `Action` and a `Scheduler`, and it will return a `StoppableObservable` that uses the specified `Action` to generate items that it emits. The `Action` accepts an `Observer` and a `Subscription`. It uses the `Subscription` to check for the unsubscribed condition, upon which it will stop emitting items. You can also manually stop a `StoppableObservable` at any time by calling its `unsubscribe( )` method (which will also unsubscribe the `Subscription` you have associated with the `StoppableObservable`).

Because `runAsync( )` immediately invokes the `Action` and begins emitting the items, it is possible that some items may be lost in the interval between when you establish the `StoppableObservable` with this method and when your `Observer` is ready to receive items. If this is a problem, you can use the variant of `runAsync( )` that also accepts a `Subject` and pass a `ReplaySubject` with which you can retrieve the otherwise-missing items.


text:
void
QPDFObject::doResolve()
{
    auto og = value->og;
    QPDF::Resolver::resolve(value->qpdf, og);
}

void
QPDFObject::destroy()
{
    value = QPDF_Destroyed::getInstance();
}


text:
static const int default_report_interval = 2; // 2 seconds!

#ifndef NOTHREADS
#define CRBEG_P process->sync.lock ();
#define CREND_P process->sync.unlock ();
#define CRBEG sync.lock ();
#define CREND sync.unlock ();;
#else
#define CRBEG_P ;
#define CREND_P ;
#define CRBEG ;
#define CREND ;
#endif

void process_thread_function (void* arglist)
{
    Process* process = (Process*) arglist;
    bool finish = false;
    time_t prev_check = time (NULL);
    time_t report_interval = process->report_interval_;

    // record start time
    CRBEG_P
    process->start_time_ = time (NULL);
    CREND_P

    do
    {
        time_t cur_check = time (NULL);
        if (cur_check - prev_check > report_interval)
        {
            prev_check = cur_check;
            CRBEG_P
            finish = process->interrupt_;
            CREND_P
        }
        if (finish) break;

        // process next
        if (!process->next ())
        {
            CRBEG_P
            finish = true;
            CREND_P
        }
        if (process->error_) // no need for synchronisation here
            process->save_results_ = false;
    }
    while (!finish);

    // record end time
    CRBEG_P
    process->end_time_ = time (NULL);
    CREND_P

    // report results and close
    if (process->save_results_)
        process->report_results ();

    process->close ();
}

Process::Process ()
:
last_current_ (0),
report_interval_ (default_report_interval),
interrupt_ (false),
save_results_ (true),
error_ (false),
state_ (APS_NOT_INIT),
total_ (0),
current_ (0),
subphase_start_current_ (0),
skipped_ (0),
res_no_ (0),
phase_ (0),
subphase_ (0)
{
}

Process::~Process ()
{
}

bool Process::run (Process_params* params)
{
    if (!init (params)) return false;
    if (!start ()) return false;
    return true;
}

bool Process::wait (unsigned msec)
{
    if (state () != APS_RUNNING) return true;
    // WaitForSingleObject ((HANDLE) processing_thread_, msec);
#ifndef NOTHREADS
    sync.wait (msec);
    if (state () != APS_RUNNING) return true;
#endif
    return false;
}

bool Process::start ()
{
    if (state () != APS_READY) return false;
    CRBEG
    state_ = APS_RUNNING;
    CREND

    start_time_sec_ = time (NULL);
    subphase_start_time_ = start_time_ = last_time_ = time (NULL);
    subphase_start_current_ = current_;

#ifndef NOTHREADS
    sync.begin (process_thread_function, this);
#else
    process_thread_function (this);
#endif
    return true;
}

bool Process::stop (bool save_results)
{
    CRBEG
    interrupt_ = true;
    save_results_ = save_results;
    CREND
    return true;
}

bool Process::init (Process_params* params)
{
    STATE curstate = state ();
    if (curstate == APS_RUNNING || curstate == APS_READY) return false;
    CRBEG
    total_ = 0;
    current_ = 0;
    subphase_start_current_ = 0;
    skipped_ = 0;
    res_no_ = 0;
    phase_ = 0;
    subphase_ = 0;
    interrupt_ = false;
    error_ = false;
    error_string_.erase ();
    CREND
    bool toRet = false;
    try
    {
        toRet = init_handler (params);
    }
    catch (Rerror& e)
    {
        std::ostringstream str;
        str << "Error during INITIALIZATION stage: " << (const char*) e << std::endl << std::flush;
        error (str);
    }
#if !defined (DONT_CATCH_UNKNOWN)
    catch (std::exception& e)
    {
        std::ostringstream str;
        str << "Standard exception: " << e.what () << " caught during INITIALIZATION stage " << std::endl << std::flush;
        error (str);
    }
    catch (...)
    {
        std::ostringstream str;
        str << "Unhandled exception caught during INITIALIZATION stage " << std::endl << std::flush;
        error (str);
    }
#endif
    if (toRet)
    {
        CRBEG
        save_results_ = true;
        state_ = APS_READY;
        CREND
    }
    else
        state_ = APS_ERROR;
    return toRet;
}

bool Process::next ()
{
    // process next
    bool toRet = false;
    try
    {
        toRet = next_handler ();
    }
    catch (Rerror& e)
    {
        std::ostringstream str;
        str << "Error during PROCESSING stage: " << (const char*) e << std::endl
            << "phase " << phase () << " (" << phase_name (phase ())
            << ") , subphase " << subphase () << " (" << subphase_name (phase (), subphase ())
            << ") at " << processing_item_name () << " " << current () << " of " << total () << "." << std::endl << std::flush;
        error (str);
    }
#if !defined (DONT_CATCH_UNKNOWN)
    catch (std::exception& e)
    {
        std::ostringstream str;
        str << "Standard exception: " << e.what () << " caught during PROCESSING stage " << std::endl
            << "phase " << phase () << " (" << phase_name (phase ())
            << ") , subphase " << subphase () << " (" << subphase_name (phase (), subphase ())
            << ") at " << processing_item_name () << " " << current () << " of " << total () << "." << std::endl << std::flush;
        error (str);
    }
    catch (...)
    {
        std::ostringstream str;
        str << "Unhandled exception caught during PROCESSING stage " << std::endl
            << "phase " << phase () << " (" << phase_name (phase ())
            << ") , subphase " << subphase () << " (" << subphase_name (phase (), subphase ())
            << ") at " << processing_item_name () << " " << current () << " of " << total () << "." << std::endl << std::flush;
        error (str);
    }
#endif
    // toRet could be false in the case of error or in the case of finished processing.
    // They are distinguished by the state of _error member of ProcessThread
    return toRet;
}

bool Process::report_results ()
{
    end_time_sec_ = time (NULL);
    bool toRet = false;

    try
    {
        toRet = report_results_handler ();
    }
    catch (Rerror& e)
    {
        std::ostringstream str;
        str << "Error during REPORT stage: " << (const char*) e << std::endl << std::flush;
        error (str);
    }
#if !defined (DONT_CATCH_UNKNOWN)
    catch (std::exception& e)
    {
        std::ostringstream str;
        str << "Exception: " << e.what () << " caught during results reproting" << std::endl << std::flush;
        error (str);
    }
    catch (...)
    {
        std::ostringstream str;
        str << "Unhandled exception caught during reporting results" << std::endl << std::flush;
        error (str);
    }
#endif
    return toRet;
}

bool Process::close ()
{
    STATE curstate = state ();
    if (curstate != APS_RUNNING)
    {
        error ("State error: closing running process");
        return false;
    }
    bool toRet = false;
    try
    {
        toRet = close_handler ();
    }
    catch (Rerror& e)
    {
        std::ostringstream str;
        str << "Error during CLOSE stage: " << (const char*) e << std::endl << std::flush;
        error (str);
    }
#if !defined (DONT_CATCH_UNKNOWN)
    catch (std::exception& e)
    {
        error (e.what ());
    }
    catch (...)
    {
        std::ostringstream str;
        str << "Unhandled exception caught during CLOSE stage " << std::endl << std::flush;
        error (str);
    }
#endif

    CRBEG
    if (!toRet)
    {
        state_ = APS_ERROR;
    }
    else
    {
        if (error_) state_ = APS_ERROR;
        else if (interrupt_) state_ = APS_INTERRUPTED;
        else state_ = APS_COMPLETE;
    }
    CREND
    return toRet;
}

longlong Process::total   ()
{
    CRBEG
    longlong toRet = total_;
    CREND
    return toRet;
}

longlong Process::current ()
{
    CRBEG
    longlong toRet = current_;
    CREND
    return toRet;
}

longlong Process::skipped   ()
{
    CRBEG
    longlong toRet = skipped_;
    CREND
    return toRet;
}

longlong Process::res_no  ()
{
    CRBEG
    longlong toRet = res_no_;
    CREND
    return toRet;
}

long Process::phase ()
{
    CRBEG
    long toRet = phase_;
    CREND
    return toRet;
}

long Process::subphase ()
{
    CRBEG
    long toRet = subphase_;
    CREND
    return toRet;
}

void Process::total   (longlong val)
{
    CRBEG
    total_ = val;
    CREND
}

void Process::current (longlong val)
{
    CRBEG
    current_ = val;
    CREND
}

void Process::skipped   (longlong val)
{
    CRBEG
    skipped_ = val;
    CREND
}

void Process::res_no  (longlong val)
{
    CRBEG
    res_no_ = val;
    CREND
}

void Process::phase (long phase_no)
{
    CRBEG
    phase_ = phase_no;
    subphase_ = 0;
    subphase_start_time_ = time (NULL);
    subphase_start_current_ = current_;
    CREND
}

void Process::subphase (long subphase_no)
{
    CRBEG
    subphase_ = subphase_no;
    subphase_start_time_ = time (NULL);
    subphase_start_current_ = current_;
    CREND
}

longlong Process::incrcur (longlong incr)
{
    CRBEG
    longlong toR = current_ += incr;
    CREND
    return toR;
}

longlong  Process::incrskipped (longlong incr)
{
    CRBEG
    longlong toR = skipped_ += incr;
    CREND
    return toR;
}

longlong Process::incrresno (longlong incr)
{
    CRBEG
    longlong toR = res_no_ += incr;
    CREND
    return toR;
}

long Process::incrphase ()
{
    bool err = false;
    CRBEG
    long toR = phase_ ++;
    if (phase_ >= phases_total ()) err = true;
    subphase_= 0;
    CREND
    if (err) ERR("Phase number overflow");
    return toR;
}

long Process::incrsubphase ()
{
    bool err = false;
    CRBEG
    long toR = subphase_ ++;
    if (subphase_ >= subphases_total (phase_)) err = true;
    CREND
    if (err) ERR("Subphase number overflow");
    return toR;
}

void Process::report_state (std::ostream& o)
{
    o << "\r" << phase_name (phase ()) << " : " << subphase_name (phase (), subphase ()) << ": "
      << processing_item_name () << " " << current () << " of " << total ()
      << " (" << std::setprecision (2) << std::setiosflags (std::ios::fixed) << percent_done () << "%), speed is "
      << average_speed () << " " << processing_item_name () << "/sec; "
      << res_no () << " " << result_item_name () << " produced.    "
      << std::flush;
}

void Process::report_self (std::ostream& o)
{
    //report_header (o);
}

void Process::report_phase_switch (std::ostream& o)
{
    o << std::endl;
}

void Process::report_header (std::ostream& o, const char* procname)
{
    o << (procname ? procname : process_name ()) << " version " << version () << ", by Scientific Data Management (SciDM.org)" << std::endl << "  " << description () << std::endl << std::flush;
}

void Process::report_final (std::ostream& o)
{
    o << std::endl << process_name () << " completed succesfully." << std::endl;
}

double Process::percent_done ()
{
    longlong tot = total ();
    longlong cur = current ();
    if (tot < 1)
        return 100.0;
    if (cur < 0)
        cur = 0;
    return double (cur) * 100.0 / tot;
}

double Process::average_speed ()
{
    time_t cur_time = time (NULL);
    int t_diff = cur_time - subphase_start_time_;
    if (!t_diff) t_diff = 1;
    longlong cur_current = current () - subphase_start_current_;
    double speed = double (cur_current) / double (t_diff);
    return speed;
}

double Process::last_speed ()
{
    time_t cur_time = time (NULL);
    int t_diff = cur_time - last_time_;
    if (!t_diff) t_diff = 1;
    longlong cur_current = current ();
    double speed = double (cur_current - last_current_) / double (t_diff);
    last_current_ = cur_current;
    last_time_ = cur_time;
    return speed;
}

int Process::report_interval ()
{
    CRBEG
    int toRet = report_interval_;
    CREND
    return toRet;
}

void Process::error (const char* errstr)
{
    if (error_string_.length ())
      error_string_.append ("\n");
    error_string_.append (errstr);
    error_ = true;
}

void Process::error (std::string& errstr)
{
    if (error_string_.length ())
      error_string_.append ("\n");
    error_string_.append (errstr);
    error_ = true;
}
void Process::error (std::ostringstream& errstr)
{
    if (error_string_.length ())
      error_string_.append ("\n");
    error_string_.append (errstr.str ());
    error_ = true;
}

Process::STATE Process::state ()
{
    CRBEG
    STATE toRet = state_;
    CREND
    return toRet;
}

const char* Process::getError ()
{
    return error_string_.c_str ();
}

time_t Process::cur_time_sec () const
{
    return time (NULL);
}


text:
const getSyllables = require('./syllables')

const defaultObj = { normal: true, text: true, terms: false }

const addMethod = function(Doc) {
  /** split each term by typical pronounciation */
  Doc.prototype.syllables = function(obj) {
    let n = null
    if (typeof obj === 'number') {
      n = obj
      obj = {}
    }
    let data = this.json(obj || defaultObj)
    //add syllable data to each phrase
    data = data.map(o => {
      o.syllables = getSyllables(o.normal || o.text)
      return o
    })
    if (typeof n === 'number') {
      data = data[n]
    }
    return data
  }

  return Doc
}
module.exports = addMethod


text:
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">

                </button>
                English Cloud

 Tra cặp câu

 Luyện phát âm

 Luyện nói

 Luyện viết

 Đăng nhập

 Tạo tài khoản


text:
/**
 * DO NOT EDIT
 *
 * This file was automatically generated by
 *   https://github.com/Polymer/gen-typescript-declarations
 *
 * To modify these typings, edit the source file(s):
 *   lib/utils/debounce.html
 */

/// <reference path="boot.d.ts" />
/// <reference path="mixin.d.ts" />
/// <reference path="async.d.ts" />

declare namespace Polymer {

  class Debouncer {

    /**
     * Creates a debouncer if no debouncer is passed as a parameter
     * or it cancels an active debouncer otherwise. The following
     * example shows how a debouncer can be called multiple times within a
     * microtask and "debounced" such that the provided callback function is
     * called once. Add this method to a custom element:
     *
     * _debounceWork() {
     *   this._debounceJob = Polymer.Debouncer.debounce(this._debounceJob,
     *       Polymer.Async.microTask, () => {
     *     this._doWork();
     *   });
     * }
     *
     * If the `_debounceWork` method is called multiple times within the same
     * microtask, the `_doWork` function will be called only once at the next
     * microtask checkpoint.
     *
     * Note: In testing it is often convenient to avoid asynchrony. To accomplish
     * this with a debouncer, you can use `Polymer.enqueueDebouncer` and
     * `Polymer.flush`. For example, extend the above example by adding
     * `Polymer.enqueueDebouncer(this._debounceJob)` at the end of the
     * `_debounceWork` method. Then in a test, call `Polymer.flush` to ensure
     * the debouncer has completed.
     *
     * @param debouncer Debouncer object.
     * @param asyncModule Object with Async interface
     * @param callback Callback to run.
     * @returns Returns a debouncer object.
     */
    static debounce(debouncer: Debouncer|null, asyncModule: AsyncInterface, callback: () => any): Debouncer;

    /**
     * Sets the scheduler; that is, a module with the Async interface,
     * a callback and optional arguments to be passed to the run function
     * from the async module.
     *
     * @param asyncModule Object with Async interface.
     * @param callback Callback to run.
     */
    setConfig(asyncModule: AsyncInterface, callback: () => any): void;

    /**
     * Cancels an active debouncer and returns a reference to itself.
     */
    cancel(): void;

    /**
     * Flushes an active debouncer and returns a reference to itself.
     */
    flush(): void;

    /**
     * Returns true if the debouncer is active.
     *
     * @returns True if active.
     */
    isActive(): boolean;
  }
}


text:
package main

import (
	"github.com/mackerelio/go-osstat/network"
)

type networkGenerator struct {
	networks []network.Stats
	err      error
}

func (gen *networkGenerator) Get() {
	gen.networks, gen.err = network.Get()
}

func (gen *networkGenerator) Error() error {
	return gen.err
}

func (gen *networkGenerator) Print(out chan<- value) {
	for _, network := range gen.networks {
		out <- value{"network." + network.Name + ".rx_bytes", network.RxBytes, "bytes"}
		out <- value{"network." + network.Name + ".tx_bytes", network.TxBytes, "bytes"}
	}
}


text:
"""The WaveBlocks Project

This file contains the class for representing the hyperbolic cut
basis shape which is a special type of sparse basis set.

@author: R. Bourquin
@copyright: Copyright (C) 2012, 2013, 2014, 2015 R. Bourquin
@license: Modified BSD License
"""

from numpy import eye, vstack, integer

from WaveBlocksND.BasisShape import BasisShape
from functools import reduce

__all__ = ["HyperbolicCutShape"]

class HyperbolicCutShape(BasisShape):
    r"""This class implements the hyperbolic cut basis shape which
    is a special type of sparse basis set. A basis shape is essentially
    all information and operations related to the set :math:`\mathfrak{K}`
    of multi-indices :math:`k`. The hyperbolic cut shape in :math:`D` dimensions
    and with `sparsity` :math:`K` is defined as the set

    .. math::
        \mathfrak{K}(D, K) := \{ (k_0, \ldots, k_{D-1}) |
                                 k_d \geq 0 \forall d \in [0,\ldots,D-1]
                                 \land \prod_{d=0}^{D-1}(1+k_d) \leq K \}
    """

    def __init__(self, D, K):
        r"""
        :param D: The dimension :math:`D`
        :param K: The sparsity parameter :math:`K`
        """
        # The dimension of K
        self._dimension = D

        # The sparsity parameter
        self._sparsity = K

        # The linear mapping k -> index for the basis
        iil = self._get_index_iterator_lex()
        self._lima = {k: index for index, k in enumerate(iil)}
        # And the inverse mapping
        self._lima_inv = {v: k for k, v in self._lima.items()}

        # The basis size
        self._basissize = len(self._lima)

    def __str__(self):
        r""":return: A string describing the basis shape :math:`\mathfrak{K}`.
        """
        s = ("Hyperbolic cut basis shape of dimension "+str(self._dimension)+" and sparsity "+str(self._sparsity)+".")
        return s

    def __hash__(self):
        r"""Compute a unique hash for the basis shape. In the case of hyperbolic
        cut basis shapes :math:`\mathfrak{K}` the basis is fully specified by its
        dimension :math:`D` and the sparsity parameter :math:`K`.
        """
        return hash(("HyperbolicCutShape", self._dimension, self._sparsity))

    def __getitem__(self, k):
        r"""Make map look ups.
        """
        if type(k) is tuple or type(k) is list:
            k = tuple(k)
            assert len(k) == self._dimension
            if k in self._lima:
                return self._lima[k]
        elif type(k) is int:
            if k in self._lima_inv:
                return self._lima_inv[k]
        else:
            raise IndexError("Wrong index type")

    def __contains__(self, k):
        r"""
        Checks if a given multi-index :math:`k` is part of the basis set :math:`\mathfrak{K}`.

        :param k: The multi-index :math:`k` we want to test.
        :type k: tuple
        """
        assert len(tuple(k)) == self._dimension
        return tuple(k) in self._lima

    def __iter__(self):
        r"""Implements iteration over the multi-indices :math:`k`
        of the basis set :math:`\mathfrak{K}`.

        Note: The order of iteration is NOT fixed. If you need a special
        iteration scheme, use :py:meth:`get_node_iterator`.
        """
        # TODO: Better remove this as it may cause unexpected behaviour?
        return iter(self._lima)

    def contains(self, k):
        r"""
        Checks if a given multi-index :math:`k` is part of the basis set :math:`\mathfrak{K}`.

        :param k: The multi-index :math:`k` we want to test.
        :type k: tuple
        """
        return tuple(k) in self._lima

    def get_description(self):
        r"""Return a description of this basis shape object.
        A description is a ``dict`` containing all key-value pairs
        necessary to reconstruct the current basis shape. A description
        never contains any data.
        """
        d = {}
        d["type"] = "HyperbolicCutShape"
        d["dimension"] = self._dimension
        d["K"] = self._sparsity
        return d

    def extend(self):
        r"""Extend the basis shape such that (at least) all neighbours of all
        boundary nodes are included in the extended basis shape.
        """
        D = self._dimension
        K = self._sparsity
        if D > 1:
            # This formula is more narrow than: K = 2**(D-1) * (K+1)
            # but works only for D >= 2
            extended_sparsity = 2**(D - 1) * K
        else:
            # Special casing K = 2**(D-1) * (K+1) for D = 1
            extended_sparsity = K + 1
        return HyperbolicCutShape(D, extended_sparsity)

    def _get_index_iterator_lex(self):
        r"""
        """
        # The hyperbolic cut parameter
        Kmax = self._sparsity

        def index_iterator_lex(Kmax):
            # Initialize a counter
            z = [0 for i in range(self._dimension + 1)]

            while z[self._dimension] == 0:
                # Yield the current index vector
                yield tuple(reversed(z[:-1]))

                # Increment fastest varying bit
                z[0] += 1

                # Reset overflows
                for d in range(self._dimension):
                    K = reduce(lambda x, y: x * (y + 1), z[:-1], 1)
                    if K > Kmax:
                        z[d] = 0
                        z[d + 1] += 1

        return index_iterator_lex(Kmax)

    def _get_index_iterator_chain(self, direction=0):
        r"""
        """
        def index_iterator_chain(Kmax, d):
            D = self._dimension
            # The counter
            z = [0 for i in range(D + 1)]

            # Iterate over all valid stencil points
            while z[D] == 0:
                yield tuple(reversed(z[:-1]))

                # Increase index in the dimension we build the chain
                z[D - d - 1] += 1

                # Check if we are done with the current base point
                # If yes, move base point and start a new chain
                # Reset overflows
                for i in range(D - d - 1, D):
                    K = reduce(lambda x, y: x * (y + 1), z[(D - d - 1):-1], 1)
                    if K > Kmax:
                        z[i] = 0
                        z[i + 1] += 1

        return index_iterator_chain(self._sparsity, direction)

    def _get_index_iterator_mag(self):
        r"""
        """
        # Nodes sorted by l_1 magnitude
        nodes = sorted(self._lima.keys(), key=sum)

        def index_iterator_mag(nodes):
            for node in nodes:
                yield node

        return index_iterator_mag(nodes)

    def get_node_iterator(self, mode="lex", direction=None):
        r"""
        Returns an iterator to iterate over all basis elements :math:`k \in \mathfrak{K}`.

        :param mode: The mode by which we iterate over the indices. Default is ``lex``
                     for lexicographical order. Supported is also ``chain``, for
                     the chain-like mode, details see the manual.
        :type mode: string
        :param direction: If iterating in `chainmode` this specifies the direction
                          the chains go.
        :type direction: integer.
        """
        if mode == "lex":
            return self._get_index_iterator_lex()
        elif mode == "chain":
            if direction < self._dimension:
                return self._get_index_iterator_chain(direction=direction)
            else:
                raise ValueError("Can not build iterator for this direction.")
        elif mode == "mag":
            return self._get_index_iterator_mag()
        # TODO: Consider boundary node only iterator
        else:
            raise ValueError("Unknown iterator mode: {}.".format(mode))

    def get_limits(self):
        r"""Returns the upper limit :math:`K` which is the same for all directions :math:`d`.

        :return: A tuple of the maximum of the multi-index in each direction.
        """
        return tuple(self._dimension * [self._sparsity - 1])

    def get_neighbours(self, k, selection=None, direction=None):
        r"""
        Returns a list of all multi-indices that are neighbours of a given
        multi-index :math:`k`. A direct neighbour is defined as
        :math:`(k_0, \ldots, k_d \pm 1, \ldots, k_{D-1}) \forall d \in [0 \ldots D-1]`.

        :param k: The multi-index of which we want to get the neighbours.
        :type k: tuple
        :param selection:
        :type selection: string with fixed values ``forward``, ``backward`` or ``all``.
                         The values ``all`` is equivalent to the value ``None`` (default).
        :param direction: The direction :math:`0 \leq d < D` in which we want to find
                          the neighbours :math:`k \pm e_d`.
        :type direction: int
        :return: A list containing the pairs :math:`(d, k^\prime)`.
        """
        assert len(tuple(k)) == self._dimension

        # First build a list of potential neighbours
        I = eye(self._dimension, dtype=integer)
        ki = vstack(k)

        # Forward and backward direct neighbours
        nbfw = ki + I
        nbbw = ki - I

        # Keep only the valid ones
        nbh = []

        if direction is not None:
            directions = [direction]
        else:
            directions = range(self._dimension)

        for d in directions:
            nfw = tuple(nbfw[:, d])
            nbw = tuple(nbbw[:, d])

            # TODO: Try to simplify these nested if blocks
            if selection in ("backward", "all", None):
                if nbw in self:
                    nbh.append((d, nbw))

            if selection in ("forward", "all", None):
                if nfw in self:
                    nbh.append((d, nfw))

        return nbh


text:
"use strict";

var fs = require('fs');
var recursive = require('recursive-readdir');
var outFile = './dist/timely.json';
var finalObject = {};
var timelyEvents = [];
var recursiveReadSync = require('recursive-readdir-sync')
var common = require('./common/common.js');

var files = recursiveReadSync('./data');
for (var i = 0; i < files.length; i++) {
  var filename = files[i];
  var o = JSON.parse(fs.readFileSync(filename, 'utf8'));
  for (var year in o) {
    if (!finalObject[year]) {
      finalObject[year] = o[year];
    } else {
      finalObject[year] = finalObject[year].concat(o[year]);
    }

    var events = o[year];
    events = common.standardizeEventDates(events);
    events = common.sortEvents(events);
    events = common.removeDuplicates(events);

    for (var x = 0; x < events.length; x++) {
      var type = filename.split('/')[1];
      var event = events[x];
      var eventDates = events[x].dates.split('-');
      var startDate = eventDates[0].trim();
      timelyEvents.push({
        name: event.name,
        handle: event.name.trim().toLowerCase().replace(/\s/g, '_'),
        info: event.overview,
        startDate: startDate + '/' + year,
        endDate: ( eventDates[1] ? eventDates[1].trim() : startDate) + '/' + year,
        location: event.location,
        url: event.links[0],
        type: type
      });

    }
    timelyEvents.push[events];
  }

}

fs.writeFile(outFile, JSON.stringify(timelyEvents, null, 4), function (err) {
  if (err) {
    return console.log(err);
  }
  console.log('Finished writing ' + outFile);
});


text:
/* Mark that an item (such as an array cell) is currently being processed
   by the algorithm. This color is a medium blue. */
.processing {
  background-color: #ddf !important;
}

/* For array cells and the like that are unused */
.unused {
  background-color: #ddd;
}

/* For marking a node (array cell, etc) as "special". This is a light red. */
.special {
  background-color: #FFB6C1 !important;
}

/* For de-emphasizing the label/value of a node (array cell, etc). Light grey. */
.deemph .jsavvalue {
  color: #ccc;
}

.invisnode { /* Make a tree node invisible in a slideshow */
  background-color: #eed;
  color: #eed;
  border-color: #eed;
  box-shadow: 2px 2px 2px rgba(120, 120, 120, 0.0);
}

/* Make a node's edge thick */
.thicknode {
  border-width: 2px;
}

/* Make a slideshow tree node invisible (except for label) */
.clearnode {
  background-color: #eed;
  border-color: #eed;
  box-shadow: 2px 2px 2px rgba(120, 120, 120, 0.0);
}

/* Make font bigger, used typically with click handler setting up swap */
.enlarge .jsavvalue {
  font-size: 120%;
}

/* Makes (just) the text of a node or array cell to be green */
.greentext .jsavvalue {
  color: #0b0;
  font-weight: bold;
}

.redback {
  background-color: #f00 !important;
}

.jsavcontainer {
  border: 0;
}

.jsavnode.sorted {
  background-color: #ffffcc !important;
}

.jsavautoresize .jsavnode {
  min-width: 30px;
  min-height: 30px;
}

.jsavhorizontalarray .jsavnode {
  line-height: 30px !important;
  min-width: 30px !important;
  max-width: 30px !important;
  min-height: 30px !important;
  max-height: 30px !important;
}

.jsavverticalarray .jsavnode {
  line-height: 30px !important;
  min-width: 30px !important;
  max-width: 30px !important;
  min-height: 30px !important;
  max-height: 30px !important;
}

.jsavnode.jsavtreenode {
  min-width: 30px;
  max-width: 30px;
  min-height: 30px;
  max-height: 30px;
}

.jsavhorizontallist.jsavautoresize .jsavnode {
  min-width: 30px;
  max-width: 30px;
  min-height: 30px;
  max-height: 30px;
  line-height: 30px;
  padding-right: 12px;
}

.jsavnode .jsavhorizontalarray .jsavvalue { /* Center array cell values vertically */
  height: 30px;
}

.jsavnode .jsavverticalarray .jsavvalue { /* Center array cell values vertically */
  height: 30px;
}

.jsavnode .jsavvalue { /* Center tree node values vertically */
  height: 30px;
}

.jsavlist .jsavvalue { /* Center linked list cell values vertically */
  height: 30px;
}

.jsavarray .jsavvalue { /* Center array cell values vertically */
  height: 30px;
}

.jsavcodeline {
  margin-bottom: 1px;
  font-size: 14px;
  line-height: 16px;
}

/* Put a white border around the code block. Do it this way to
   keep from putting border around the line numbers. */
.jsavcodeline {
  border-left: 1px solid #fff;
  border-right: 1px solid #fff;
}

.jsavcodeline:first-child {
  border-top: 1px solid #fff;
  padding-top: 1px;
}

.jsavcodeline:last-child {
  border-bottom: 1px solid #fff;
  padding-bottom: 1px;
}

.jsavcodeline.jsavhighlight {
  background-color: #ccc !important;
}

.jsavcodeline:hover {
  border-top: 1px solid #ccc;
  border-bottom: 1px solid #ccc;
  font-size: 14px;
  line-height: 16px;
  padding: 1px 10px;
}

.jsavbararray .jsavindex {
  background-color: #eee;
}

.jsavbararray.jsavindexed {
  margin-bottom: 0;
}

.jsavstack {
  position: relative;
  background-color: inherit;
}

.jsavstack .jsavstacknode {
  font-size: 120%;
  position: absolute;
  border-radius: 5px;
  width: 30px;
  height: 30px;
  z-index: 100;
}

.jsavtreenode.emptynode {
  border: 1px dashed #777 !important;
  background-color: #fff !important;
  color: #777 !important;
  cursor: pointer;
}

.jsavtreenode.rednode {
  background-color: #f00;
  color: #fff;
}

.jsavtreenode.blacknode {
  background-color: #000;
  color: #fff;
}

.selected, .selected .jsavvalue, .jsavarray.jsavbararray .jsavindex.selected .jsavvalue {
  font-size: 110%;
  background-color: #ddf;
}

.jsavtreenode.jsavredblacknode.rednode.selected {
  background-color: #f00;
}

.jsavtreenode.jsavredblacknode.blacknode.selected {
  background-color: #000;
}

.jsavtreenode.jsavredblacknode.selected {
  box-shadow: 0 0 5px 10px #ddf;
}

.greybg, .greybg.jsavvalue, .jsavarray.jsavbararray .jsavindex.greybg .jsavvalue {
  background-color: #eee;
}

.greenbg, .greenbg.jsavvalue, .jsavarray.jsavbararray .jsavindex.greenbg .jsavvalue {
  background-color: #3f5;
}

.jsavgraph .jsavedge {
  stroke-width: 1.5px;
}


text:
package org.apache.commons.exec.launcher;

import java.io.File;
import java.io.IOException;
import java.util.Map;

import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.environment.EnvironmentUtils;

/**
 * A command launcher for JDK/JRE 1.3 (and higher). Uses the built-in
 * Runtime.exec() command
 *
 * @version $Id$
 */
public class Java13CommandLauncher extends CommandLauncherImpl {

    /**
     * Constructor
     */
    public Java13CommandLauncher() {
    }

    /**
     * Launches the given command in a new process, in the given working
     * directory
     *
     * @param cmd
     *            the command line to execute as an array of strings
     * @param env
     *            the environment to set as an array of strings
     * @param workingDir
     *            the working directory where the command should run
     * @throws IOException
     *             probably forwarded from Runtime#exec
     */
    @Override
    public Process exec(final CommandLine cmd, final Map<String, String> env,
            final File workingDir) throws IOException {

        final String[] envVars = EnvironmentUtils.toStrings(env);

        return Runtime.getRuntime().exec(cmd.toStrings(),
                envVars, workingDir);
    }
}


text:
package org.jikesrvm.compilers.opt.ir.operand.ppc;

import org.jikesrvm.compilers.opt.ir.operand.ConditionOperand;
import org.jikesrvm.compilers.opt.ir.operand.Operand;

/**
 * Encodes the BO & BI condition fields for PowerPC
 *
 * @see Operand
 */
public final class PowerPCConditionOperand extends Operand {
  public static final int ALWAYS = (20 << 5);
  public static final int EQUAL = (12 << 5) | 2;
  public static final int NOT_EQUAL = (4 << 5) | 2;
  public static final int LESS = (12 << 5) | 0;
  public static final int GREATER_EQUAL = (4 << 5) | 0;
  public static final int GREATER = (12 << 5) | 1;
  public static final int LESS_EQUAL = (4 << 5) | 1;
  public static final int OVERFLOW = (12 << 5) | 3;
  public static final int NOT_OVERFLOW = (4 << 5) | 3;

  /* interpretation for floating-point values */
  public static final int UNORDERED = (12 << 5) | 3;
  public static final int NOT_UNORDERED = (4 << 5) | 3;

  // --CTR == 0
  public static final int CTRZ = (17 << 5) | 0;
  // --CTR != 0
  public static final int CTRNZ = (16 << 5) | 0;
  // (--CTR == 0) & condition
  public static final int CTRZ_EQUAL = (10 << 5) | 2;
  public static final int CTRZ_NOT_EQUAL = (2 << 5) | 2;
  public static final int CTRZ_LESS = (10 << 5) | 0;
  public static final int CTRZ_GREATER_EQUAL = (2 << 5) | 0;
  public static final int CTRZ_GREATER = (10 << 5) | 1;
  public static final int CTRZ_LESS_EQUAL = (2 << 5) | 1;
  public static final int CTRZ_OVERFLOW = (10 << 5) | 3;
  public static final int CTRZ_NOT_OVERFLOW = (2 << 5) | 3;
  // (--CTR != 0) & condition
  public static final int CTRNZ_EQUAL = (8 << 5) | 2;
  public static final int CTRNZ_NOT_EQUAL = (0 << 5) | 2;
  public static final int CTRNZ_LESS = (8 << 5) | 0;
  public static final int CTRNZ_GREATER_EQUAL = (0 << 5) | 0;
  public static final int CTRNZ_GREATER = (8 << 5) | 1;
  public static final int CTRNZ_LESS_EQUAL = (0 << 5) | 1;
  public static final int CTRNZ_OVERFLOW = (8 << 5) | 3;
  public static final int CTRNZ_NOT_OVERFLOW = (0 << 5) | 3;

  /**
   * Value of this operand.
   */
  public int value;

  // TODO: add the things with the CTR register also.
  public PowerPCConditionOperand(int Code) {
    value = Code;
  }

  public static PowerPCConditionOperand EQUAL() {
    return new PowerPCConditionOperand(EQUAL);
  }

  public static PowerPCConditionOperand NOT_EQUAL() {
    return new PowerPCConditionOperand(NOT_EQUAL);
  }

  public static PowerPCConditionOperand LESS() {
    return new PowerPCConditionOperand(LESS);
  }

  public static PowerPCConditionOperand LESS_EQUAL() {
    return new PowerPCConditionOperand(LESS_EQUAL);
  }

  public static PowerPCConditionOperand GREATER() {
    return new PowerPCConditionOperand(GREATER);
  }

  public static PowerPCConditionOperand GREATER_EQUAL() {
    return new PowerPCConditionOperand(GREATER_EQUAL);
  }

  public static PowerPCConditionOperand UNORDERED() {
    return new PowerPCConditionOperand(UNORDERED);
  }

  public static PowerPCConditionOperand get(ConditionOperand cond) {
    return new PowerPCConditionOperand(cond);
  }

  public Operand copy() {
    return new PowerPCConditionOperand(value);
  }

  public boolean similar(Operand op) {
    return (op instanceof PowerPCConditionOperand) && (((PowerPCConditionOperand) op).value == value);
  }

  /**
   * flips the direction of the condition
   */
  public PowerPCConditionOperand flipCode() {
    switch (value) {
      case EQUAL:
        value = NOT_EQUAL;
        break;
      case NOT_EQUAL:
        value = EQUAL;
        break;
      case LESS:
        value = GREATER_EQUAL;
        break;
      case LESS_EQUAL:
        value = GREATER;
        break;
      case GREATER:
        value = LESS_EQUAL;
        break;
      case GREATER_EQUAL:
        value = LESS;
        break;
      case OVERFLOW:
        value = NOT_OVERFLOW;
        break;
      case NOT_OVERFLOW:
        value = OVERFLOW;
        break;
      case CTRZ:
        value = CTRNZ;
        break;
      case CTRNZ:
        value = CTRZ;
        break;
      default:
        throw new org.jikesrvm.compilers.opt.OptimizingCompilerException("Unhandled case in flipCode");
    }
    return this;
  }

  /**
   * this could be used if you want to flip the order of the operands
   * you will notice that there are some differences
   */
  public PowerPCConditionOperand flipOperands() {
    switch (value) {
      case EQUAL:
        value = NOT_EQUAL;
        break;
      case NOT_EQUAL:
        value = EQUAL;
        break;
      case LESS:
        value = GREATER;
        break;
      case LESS_EQUAL:
        value = GREATER_EQUAL;
        break;
      case GREATER:
        value = LESS;
        break;
      case GREATER_EQUAL:
        value = LESS_EQUAL;
        break;
      case OVERFLOW:
        value = NOT_OVERFLOW;
        break;
      case NOT_OVERFLOW:
        value = OVERFLOW;
        break;
        // TODO remaining
    }
    return this;
  }

  public PowerPCConditionOperand(ConditionOperand c) {
    translate(c);
  }

  /**
   * translate from ConditionOperand: used by BURS
   */
  public void translate(ConditionOperand c) {
    switch (c.value) {
      case ConditionOperand.EQUAL:
      case ConditionOperand.SAME:
      case ConditionOperand.CMPL_EQUAL:
        value = EQUAL;
        break;
      case ConditionOperand.NOT_EQUAL:
      case ConditionOperand.NOT_SAME:
      case ConditionOperand.CMPL_NOT_EQUAL: // Extra unordered test required
        value = NOT_EQUAL;
        break;
      case ConditionOperand.LESS:
      case ConditionOperand.LOWER:
      case ConditionOperand.CMPG_LESS:
      case ConditionOperand.CMPL_LESS: // Extra unordered test required
        value = LESS;
        break;
      case ConditionOperand.LESS_EQUAL:
      case ConditionOperand.LOWER_EQUAL:
      case ConditionOperand.CMPG_LESS_EQUAL:
      case ConditionOperand.CMPL_LESS_EQUAL: // Extra unordered test required
        value = LESS_EQUAL;
        break;
      case ConditionOperand.GREATER:
      case ConditionOperand.HIGHER:
      case ConditionOperand.CMPL_GREATER:
      case ConditionOperand.CMPG_GREATER: // Extra unordered test required
        value = GREATER;
        break;
      case ConditionOperand.GREATER_EQUAL:
      case ConditionOperand.HIGHER_EQUAL:
      case ConditionOperand.CMPL_GREATER_EQUAL:
      case ConditionOperand.CMPG_GREATER_EQUAL: // Extra unordered test required
        value = GREATER_EQUAL;
        break;
      default:
        org.jikesrvm.compilers.opt.OptimizingCompilerException.UNREACHABLE();
    }
  }

  /**
   * Returns the string representation of this operand.
   */
  public String toString() {
    String result = "ppc ";
    if ((value & 0x1C0) == 0) {
      result = result + "--ctr!=0 && ";
    }
    if ((value & 0x1C0) == 0x40) {
      result = result + "--ctr==0 && ";
    }
    String temp = null;
    if ((value & 0x300) == 0x100) {             // true
      switch (value & 0x3) {
        case 0:
          temp = "<";
          break;
        case 1:
          temp = ">";
          break;
        case 2:
          temp = "==";
          break;
        case 3:
          temp = "overflow";
          break;
      }
    }
    if ((value & 0x300) == 0x000) {             // false
      switch (value & 0x3) {
        case 0:
          temp = ">=";
          break;
        case 1:
          temp = "<=";
          break;
        case 2:
          temp = "!=";
          break;
        case 3:
          temp = "not_overflow";
          break;
      }
    }
    return result + temp;
  }
}


text:
        <input id="{{ id }}"
               uib-tooltip="{{ view.tooltipMsg }}"
               tooltip-trigger="focus"
               ng-blur="runHandler($event)"
               ng-keypress="runHandler($event)"
               ng-if="view.mode === 'transform'"
               ng-disabled="view.disabled"
               type="text"
               class="form-control"
               ng-model="view.transform.script"
               ng-readonly="!view.disabled">

        <input id="{{ id }}"
               uib-tooltip="{{ view.tooltipMsg }}"
               tooltip-trigger="focus"
               ng-blur="runHandler($event)"
               ng-keypress="runHandler($event)"
               ng-if="view.mode === 'literal'"
               ng-disabled="view.disabled"
               type="{{ view.type }}"
               min="{{ view.min }}"
               class="form-control"
               ng-model="view.literal"
               placeholder="{{ view.placeholder }}"
               ng-readonly="onlyExpr && !view.disabled">

            <a href
               ng-if="view.longLiteral"
               ng-disabled="view.disabled"
               class="btn"
               uib-tooltip="{{ !view.transform.script && view.transform ? view.transform : 'Click to add a literal'}}"
               ng-click="editLiteral()"
               ng-class="{'btn-primary': (view.mode === 'literal' && view.literal && !view.exprError), 'btn-default': (view.mode === 'transform' || !view.literal && !view.exprError), 'btn-warning': (view.mode === 'literal' && view.literal && view.exprError)}">


text:
<?php
require_once '../PHPWord.php';

// New Word Document
$PHPWord = new PHPWord();

// New portrait section
$section = $PHPWord->createSection();

// Add table
$table = $section->addTable();

for($r = 1; $r <= 10; $r++) { // Loop through rows
	// Add row
	$table->addRow();

	for($c = 1; $c <= 5; $c++) { // Loop through cells
		// Add Cell
		$table->addCell(1750)->addText("Row $r, Cell $c");
	}
}

// Save File
$objWriter = PHPWord_IOFactory::createWriter($PHPWord, 'Word2007');
$objWriter->save('BasicTable.docx');
?>


text:
Now that you have some tools in your toolbelt to detect
some basic data problems, what will you do about it?

## Concepts

### Kill

You may decide that you don't want to get rid of rows that
contain missing data or that your outliers should be removed
from the dataset completely. In this case you will want to
get rid of it (or kill it if you're being dramatic)

### Impute

Maybe the data that you found to be missing our outliers are
fixable and you don't want to part with any of the data. In
this case, you can replace the missings our outliers with
values that are more representative of your population.

## Next steps

Enter the `example`s directory to open and run the notebooks in order. When you are done, enter the `titanic` directory and run your own analysis on the titanic dataset.


text:
<?php

namespace App\Services;

use Webklex\IMAP\Facades\Client;

class EmailClient
{
	protected $delegate;

	public function __construct($connexion = 'default')
	{
        $this->delegate = Client::account($connexion);
        $this->delegate->connect();
	}

    public function getUnseenMails(): Iterable
    {
        $oFolder = $this->delegate->getFolder(config('imap.folders.inbox'));

        return $oFolder->query()->whereUnseen()->get();
    }

    /**
     * Proxies all methods to the delegate.
     *
     * @param string $method
     * @param array  $args
     *
     * @return mixed
     */
    public function __call($method, $args)
    {
        return call_user_func_array([$this->delegate, $method], $args);
    }
}


text:
Ti=Security Safeguards

0.sec=—A {_covered_entity} shall develop, document, implement, and maintain a comprehensive data security program that contains administrative, technical, and physical safeguards that are appropriate to the size and complexity of the {_covered_entity}, the nature and scope of the {_covered_entity}'s activities, and the sensitivity of any {_personal_data} {_process}ed by the {_covered_entity}. Such data security program shall, at a minimum:

1.sec=Ensure the security, confidentiality, integrity, and availability of {_personal_data};

2.sec=Protect against any anticipated threats or hazards to the security or integrity of such {_personal_data}; and

3.sec=Protect against unauthorized {_process}ing of such {_personal_data}.

=[G/Z/ol/s3]


text:
import React from 'react'
import { shallow } from 'enzyme'
import * as ViewportUtils from 'utils/viewport'
import autoScaleContent from '../autoScaleContent'

jest.useFakeTimers()

const DummyComponent = props => <div {...props}>foo</div>
const Enhanced = autoScaleContent(DummyComponent)

let tree, instance

describe('higher-order-components/autoScaleContent', () => {
  beforeAll(() => {
    window.addEventListener = jest.fn()
    window.removeEventListener = jest.fn()
    ViewportUtils.elementFitsViewport = jest.fn()
    ViewportUtils.scaleElementToFit = jest.fn()
  })

  afterAll(() => {
    jest.resetAllMocks()
  })

  beforeEach(() => {
    tree = shallow(<Enhanced index={1} />)
    instance = tree.instance()
  })

  afterEach(() => {
    jest.clearAllMocks()
  })

  it('enhances a component with autoscale capabilities', () => {
    expect(typeof instance.checkForScaling === 'function').toBeTruthy()
  })

  describe('componentDidMount', () => {
    it('checks if scaling is needed', () => {
      instance.checkForScaling = jest.fn()
      expect(instance.checkForScaling).not.toHaveBeenCalled()

      instance.componentDidMount()
      expect(instance.checkForScaling).toHaveBeenCalledTimes(1)
    })

    it('adds a window resize listener', () => {
      instance.componentDidMount()

      expect(window.addEventListener).toHaveBeenCalledTimes(1)
      expect(window.addEventListener).toBeCalledWith(
        'resize',
        instance.checkForScaling
      )
    })
  })

  describe('componentWillUnMount', () => {
    it('removes the window resize listener', () => {
      instance.checkForScaling.cancel = jest.fn()
      instance.componentWillUnMount()

      expect(window.removeEventListener).toHaveBeenCalledTimes(1)
      expect(window.removeEventListener).toBeCalledWith(
        'resize',
        instance.checkForScaling
      )
    })

    it('cancels debounced methods', () => {
      instance.checkForScaling.cancel = jest.fn()
      instance.componentWillUnMount()

      expect(instance.checkForScaling.cancel).toHaveBeenCalledTimes(1)
    })
  })

  describe('componentWillReceiveProps', () => {
    it('checks if scaling is needed', () => {
      instance.checkForScaling = jest.fn()
      expect(instance.checkForScaling).not.toHaveBeenCalled()

      tree.setProps({ index: 2 })
      tree.update()

      expect(instance.checkForScaling).toHaveBeenCalledTimes(1)
    })
  })

  describe('checkForScaling', () => {
    it("doesn't apply scaling when content fits viewport", () => {
      const setStateArguements = {
        style: {
          opacity: 1,
          position: 'relative',
          transform: 'scale(1)',
          width: 'auto'
        }
      }

      instance.setState = jest.fn()
      ViewportUtils.elementFitsViewport.mockReturnValue(true)

      expect(instance.setState).not.toHaveBeenCalled()

      instance.checkForScaling()
      jest.runAllTimers()

      expect(instance.setState).toHaveBeenCalledTimes(1)
      expect(instance.setState).toBeCalledWith(setStateArguements)
    })

    it("applies scaling when content doesn't fit viewport", () => {
      const setStateArguements = {
        style: {
          opacity: 1,
          position: 'absolute',
          transform: 'scale(0.5)',
          width: '180%'
        }
      }

      instance.setState = jest.fn()
      ViewportUtils.elementFitsViewport.mockReturnValue(false)

      ViewportUtils.scaleElementToFit.mockReturnValue(0.5)

      expect(instance.setState).not.toHaveBeenCalled()

      instance.checkForScaling()
      jest.runAllTimers()

      expect(instance.setState).toHaveBeenCalledTimes(1)
      expect(instance.setState).toBeCalledWith(setStateArguements)
    })
  })
})


text:
<?php
namespace PSFS\base\types\traits;

/**
 * Trait TestTrait
 * @package PSFS\base\types\traits
 */
trait TestTrait {
    /**
     * @var bool
     */
    private static $test = false;

    /**
     * @return bool
     */
    public static function isTest()
    {
        return defined('PSFS_UNIT_TESTING_EXECUTION') ? self::$test : false;
    }

    /**
     * @param bool $test
     */
    public static function setTest($test)
    {
        self::$test = $test;
    }

}


text:
"""Generic FAQ Wizard.

This is a CGI program that maintains a user-editable FAQ.  It uses RCS
to keep track of changes to individual FAQ entries.  It is fully
configurable; everything you might want to change when using this
program to maintain some other FAQ than the Python FAQ is contained in
the configuration module, faqconf.py.

Note that this is not an executable script; it's an importable module.
The actual script to place in cgi-bin is faqw.py.

"""

import sys, time, os, stat, re, cgi, faqconf
from faqconf import *                   # This imports all uppercase names
now = time.time()

class FileError:
    def __init__(self, file):
        self.file = file

class InvalidFile(FileError):
    pass

class NoSuchSection(FileError):
    def __init__(self, section):
        FileError.__init__(self, NEWFILENAME %(section, 1))
        self.section = section

class NoSuchFile(FileError):
    def __init__(self, file, why=None):
        FileError.__init__(self, file)
        self.why = why

def escape(s):
    s = s.replace('&', '&')
    s = s.replace('<', '<')
    s = s.replace('>', '>')
    return s

def escapeq(s):
    s = escape(s)
    s = s.replace('"', '"')
    return s

def _interpolate(format, args, kw):
    try:
        quote = kw['_quote']
    except KeyError:
        quote = 1
    d = (kw,) + args + (faqconf.__dict__,)
    m = MagicDict(d, quote)
    return format % m

def interpolate(format, *args, **kw):
    return _interpolate(format, args, kw)

def emit(format, *args, **kw):
    try:
        f = kw['_file']
    except KeyError:
        f = sys.stdout
    f.write(_interpolate(format, args, kw))

translate_prog = None

def translate(text, pre=0):
    global translate_prog
    if not translate_prog:
        translate_prog = prog = re.compile(
            r'\b(http|ftp|https)://\S+(\b|/)|\b[-.\w]+@[-.\w]+')
    else:
        prog = translate_prog
    i = 0
    list = []
    while 1:
        m = prog.search(text, i)
        if not m:
            break
        j = m.start()
        list.append(escape(text[i:j]))
        i = j
        url = m.group(0)
        while url[-1] in '();:,.?\'"<>':
            url = url[:-1]
        i = i + len(url)
        url = escape(url)
        if not pre or (pre and PROCESS_PREFORMAT):
            if ':' in url:
                repl = '%s' % (url, url)
            else:
                repl = '%s' % (url, url)
        else:
            repl = url
        list.append(repl)
    j = len(text)
    list.append(escape(text[i:j]))
    return ''.join(list)

def emphasize(line):
    return re.sub(r'\*([a-zA-Z]+)\*', r'\1', line)

revparse_prog = None

def revparse(rev):
    global revparse_prog
    if not revparse_prog:
        revparse_prog = re.compile(r'^(\d{1,3})\.(\d{1,4})$')
    m = revparse_prog.match(rev)
    if not m:
        return None
    [major, minor] = map(int, m.group(1, 2))
    return major, minor

logon = 0
def log(text):
    if logon:
        logfile = open("logfile", "a")
        logfile.write(text + "\n")
        logfile.close()

def load_cookies():
    if not os.environ.has_key('HTTP_COOKIE'):
        return {}
    raw = os.environ['HTTP_COOKIE']
    words = [s.strip() for s in raw.split(';')]
    cookies = {}
    for word in words:
        i = word.find('=')
        if i >= 0:
            key, value = word[:i], word[i+1:]
            cookies[key] = value
    return cookies

def load_my_cookie():
    cookies = load_cookies()
    try:
        value = cookies[COOKIE_NAME]
    except KeyError:
        return {}
    import urllib
    value = urllib.unquote(value)
    words = value.split('/')
    while len(words) < 3:
        words.append('')
    author = '/'.join(words[:-2])
    email = words[-2]
    password = words[-1]
    return {'author': author,
            'email': email,
            'password': password}

def send_my_cookie(ui):
    name = COOKIE_NAME
    value = "%s/%s/%s" % (ui.author, ui.email, ui.password)
    import urllib
    value = urllib.quote(value)
    then = now + COOKIE_LIFETIME
    gmt = time.gmtime(then)
    path = os.environ.get('SCRIPT_NAME', '/cgi-bin/')
    print "Set-Cookie: %s=%s; path=%s;" % (name, value, path),
    print time.strftime("expires=%a, %d-%b-%y %X GMT", gmt)

class MagicDict:

    def __init__(self, d, quote):
        self.__d = d
        self.__quote = quote

    def __getitem__(self, key):
        for d in self.__d:
            try:
                value = d[key]
                if value:
                    value = str(value)
                    if self.__quote:
                        value = escapeq(value)
                    return value
            except KeyError:
                pass
        return ''

class UserInput:

    def __init__(self):
        self.__form = cgi.FieldStorage()
        #log("\n\nbody: " + self.body)

    def __getattr__(self, name):
        if name[0] == '_':
            raise AttributeError
        try:
            value = self.__form[name].value
        except (TypeError, KeyError):
            value = ''
        else:
            value = value.strip()
        setattr(self, name, value)
        return value

    def __getitem__(self, key):
        return getattr(self, key)

class FaqEntry:

    def __init__(self, fp, file, sec_num):
        self.file = file
        self.sec, self.num = sec_num
        if fp:
            import rfc822
            self.__headers = rfc822.Message(fp)
            self.body = fp.read().strip()
        else:
            self.__headers = {'title': "%d.%d. " % sec_num}
            self.body = ''

    def __getattr__(self, name):
        if name[0] == '_':
            raise AttributeError
        key = '-'.join(name.split('_'))
        try:
            value = self.__headers[key]
        except KeyError:
            value = ''
        setattr(self, name, value)
        return value

    def __getitem__(self, key):
        return getattr(self, key)

    def load_version(self):
        command = interpolate(SH_RLOG_H, self)
        p = os.popen(command)
        version = ''
        while 1:
            line = p.readline()
            if not line:
                break
            if line[:5] == 'head:':
                version = line[5:].strip()
        p.close()
        self.version = version

    def getmtime(self):
        if not self.last_changed_date:
            return 0
        try:
            return os.stat(self.file)[stat.ST_MTIME]
        except os.error:
            return 0

    def emit_marks(self):
        mtime = self.getmtime()
        if mtime >= now - DT_VERY_RECENT:
            emit(MARK_VERY_RECENT, self)
        elif mtime >= now - DT_RECENT:
            emit(MARK_RECENT, self)

    def show(self, edit=1):
        emit(ENTRY_HEADER1, self)
        self.emit_marks()
        emit(ENTRY_HEADER2, self)
        pre = 0
        raw = 0
        for line in self.body.split('\n'):
            # Allow the user to insert raw html into a FAQ answer
            # (Skip Montanaro, with changes by Guido)
            tag = line.rstrip().lower()
            if tag == '':
                raw = 1
                continue
            if tag == '':
                raw = 0
                continue
            if raw:
                print line
                continue
            if not line.strip():
                if pre:
                    print '
'
                    pre = 0
                else:
                    print '
'
            else:
                if not line[0].isspace():
                    if pre:
                        print '
'
                        pre = 0
                else:
                    if not pre:
                        print '
'
                        pre = 1
                if '/' in line or '@' in line:
                    line = translate(line, pre)
                elif '<' in line or '&' in line:
                    line = escape(line)
                if not pre and '*' in line:
                    line = emphasize(line)
                print line
        if pre:
            print '
'
            pre = 0
        if edit:
            print '
'
            emit(ENTRY_FOOTER, self)
            if self.last_changed_date:
                emit(ENTRY_LOGINFO, self)
        print '
'

class FaqDir:

    entryclass = FaqEntry

    __okprog = re.compile(OKFILENAME)

    def __init__(self, dir=os.curdir):
        self.__dir = dir
        self.__files = None

    def __fill(self):
        if self.__files is not None:
            return
        self.__files = files = []
        okprog = self.__okprog
        for file in os.listdir(self.__dir):
            if self.__okprog.match(file):
                files.append(file)
        files.sort()

    def good(self, file):
        return self.__okprog.match(file)

    def parse(self, file):
        m = self.good(file)
        if not m:
            return None
        sec, num = m.group(1, 2)
        return int(sec), int(num)

    def list(self):
        # XXX Caller shouldn't modify result
        self.__fill()
        return self.__files

    def open(self, file):
        sec_num = self.parse(file)
        if not sec_num:
            raise InvalidFile(file)
        try:
            fp = open(file)
        except IOError, msg:
            raise NoSuchFile(file, msg)
        try:
            return self.entryclass(fp, file, sec_num)
        finally:
            fp.close()

    def show(self, file, edit=1):
        self.open(file).show(edit=edit)

    def new(self, section):
        if not SECTION_TITLES.has_key(section):
            raise NoSuchSection(section)
        maxnum = 0
        for file in self.list():
            sec, num = self.parse(file)
            if sec == section:
                maxnum = max(maxnum, num)
        sec_num = (section, maxnum+1)
        file = NEWFILENAME % sec_num
        return self.entryclass(None, file, sec_num)

class FaqWizard:

    def __init__(self):
        self.ui = UserInput()
        self.dir = FaqDir()

    def go(self):
        print 'Content-type: text/html'
        req = self.ui.req or 'home'
        mname = 'do_%s' % req
        try:
            meth = getattr(self, mname)
        except AttributeError:
            self.error("Bad request type %r." % (req,))
        else:
            try:
                meth()
            except InvalidFile, exc:
                self.error("Invalid entry file name %s" % exc.file)
            except NoSuchFile, exc:
                self.error("No entry with file name %s" % exc.file)
            except NoSuchSection, exc:
                self.error("No section number %s" % exc.section)
        self.epilogue()

    def error(self, message, **kw):
        self.prologue(T_ERROR)
        emit(message, kw)

    def prologue(self, title, entry=None, **kw):
        emit(PROLOGUE, entry, kwdict=kw, title=escape(title))

    def epilogue(self):
        emit(EPILOGUE)

    def do_home(self):
        self.prologue(T_HOME)
        emit(HOME)

    def do_debug(self):
        self.prologue("FAQ Wizard Debugging")
        form = cgi.FieldStorage()
        cgi.print_form(form)
        cgi.print_environ(os.environ)
        cgi.print_directory()
        cgi.print_arguments()

    def do_search(self):
        query = self.ui.query
        if not query:
            self.error("Empty query string!")
            return
        if self.ui.querytype == 'simple':
            query = re.escape(query)
            queries = [query]
        elif self.ui.querytype in ('anykeywords', 'allkeywords'):
            words = filter(None, re.split('\W+', query))
            if not words:
                self.error("No keywords specified!")
                return
            words = map(lambda w: r'\b%s\b' % w, words)
            if self.ui.querytype[:3] == 'any':
                queries = ['|'.join(words)]
            else:
                # Each of the individual queries must match
                queries = words
        else:
            # Default to regular expression
            queries = [query]
        self.prologue(T_SEARCH)
        progs = []
        for query in queries:
            if self.ui.casefold == 'no':
                p = re.compile(query)
            else:
                p = re.compile(query, re.IGNORECASE)
            progs.append(p)
        hits = []
        for file in self.dir.list():
            try:
                entry = self.dir.open(file)
            except FileError:
                constants
            for p in progs:
                if not p.search(entry.title) and not p.search(entry.body):
                    break
            else:
                hits.append(file)
        if not hits:
            emit(NO_HITS, self.ui, count=0)
        elif len(hits) <= MAXHITS:
            if len(hits) == 1:
                emit(ONE_HIT, count=1)
            else:
                emit(FEW_HITS, count=len(hits))
            self.format_all(hits, headers=0)
        else:
            emit(MANY_HITS, count=len(hits))
            self.format_index(hits)

    def do_all(self):
        self.prologue(T_ALL)
        files = self.dir.list()
        self.last_changed(files)
        self.format_index(files, localrefs=1)
        self.format_all(files)

    def do_compat(self):
        files = self.dir.list()
        emit(COMPAT)
        self.last_changed(files)
        self.format_index(files, localrefs=1)
        self.format_all(files, edit=0)
        sys.exit(0)                     # XXX Hack to suppress epilogue

    def last_changed(self, files):
        latest = 0
        for file in files:
            entry = self.dir.open(file)
            if entry:
                mtime = mtime = entry.getmtime()
                if mtime > latest:
                    latest = mtime
        print time.strftime(LAST_CHANGED, time.localtime(latest))
        emit(EXPLAIN_MARKS)

    def format_all(self, files, edit=1, headers=1):
        sec = 0
        for file in files:
            try:
                entry = self.dir.open(file)
            except NoSuchFile:
                continue
            if headers and entry.sec != sec:
                sec = entry.sec
                try:
                    title = SECTION_TITLES[sec]
                except KeyError:
                    title = "Untitled"
                emit("\n
\n
%(sec)s. %(title)s
\n",
                     sec=sec, title=title)
            entry.show(edit=edit)

    def do_index(self):
        self.prologue(T_INDEX)
        files = self.dir.list()
        self.last_changed(files)
        self.format_index(files, add=1)

    def format_index(self, files, add=0, localrefs=0):
        sec = 0
        for file in files:
            try:
                entry = self.dir.open(file)
            except NoSuchFile:
                continue
            if entry.sec != sec:
                if sec:
                    if add:
                        emit(INDEX_ADDSECTION, sec=sec)
                    emit(INDEX_ENDSECTION, sec=sec)
                sec = entry.sec
                try:
                    title = SECTION_TITLES[sec]
                except KeyError:
                    title = "Untitled"
                emit(INDEX_SECTION, sec=sec, title=title)
            if localrefs:
                emit(LOCAL_ENTRY, entry)
            else:
                emit(INDEX_ENTRY, entry)
            entry.emit_marks()
        if sec:
            if add:
                emit(INDEX_ADDSECTION, sec=sec)
            emit(INDEX_ENDSECTION, sec=sec)

    def do_recent(self):
        if not self.ui.days:
            days = 1
        else:
            days = float(self.ui.days)
        try:
            cutoff = now - days * 24 * 3600
        except OverflowError:
            cutoff = 0
        list = []
        for file in self.dir.list():
            entry = self.dir.open(file)
            if not entry:
                continue
            mtime = entry.getmtime()
            if mtime >= cutoff:
                list.append((mtime, file))
        list.sort()
        list.reverse()
        self.prologue(T_RECENT)
        if days <= 1:
            period = "%.2g hours" % (days*24)
        else:
            period = "%.6g days" % days
        if not list:
            emit(NO_RECENT, period=period)
        elif len(list) == 1:
            emit(ONE_RECENT, period=period)
        else:
            emit(SOME_RECENT, period=period, count=len(list))
        self.format_all(map(lambda (mtime, file): file, list), headers=0)
        emit(TAIL_RECENT)

    def do_roulette(self):
        import random
        files = self.dir.list()
        if not files:
            self.error("No entries.")
            return
        file = random.choice(files)
        self.prologue(T_ROULETTE)
        emit(ROULETTE)
        self.dir.show(file)

    def do_help(self):
        self.prologue(T_HELP)
        emit(HELP)

    def do_show(self):
        entry = self.dir.open(self.ui.file)
        self.prologue(T_SHOW)
        entry.show()

    def do_add(self):
        self.prologue(T_ADD)
        emit(ADD_HEAD)
        sections = SECTION_TITLES.items()
        sections.sort()
        for section, title in sections:
            emit(ADD_SECTION, section=section, title=title)
        emit(ADD_TAIL)

    def do_delete(self):
        self.prologue(T_DELETE)
        emit(DELETE)

    def do_log(self):
        entry = self.dir.open(self.ui.file)
        self.prologue(T_LOG, entry)
        emit(LOG, entry)
        self.rlog(interpolate(SH_RLOG, entry), entry)

    def rlog(self, command, entry=None):
        output = os.popen(command).read()
        sys.stdout.write('
')
        athead = 0
        lines = output.split('\n')
        while lines and not lines[-1]:
            del lines[-1]
        if lines:
            line = lines[-1]
            if line[:1] == '=' and len(line) >= 40 and \
               line == line[0]*len(line):
                del lines[-1]
        headrev = None
        for line in lines:
            if entry and athead and line[:9] == 'revision ':
                rev = line[9:].split()
                mami = revparse(rev)
                if not mami:
                    print line
                else:
                    emit(REVISIONLINK, entry, rev=rev, line=line)
                    if mami[1] > 1:
                        prev = "%d.%d" % (mami[0], mami[1]-1)
                        emit(DIFFLINK, entry, prev=prev, rev=rev)
                    if headrev:
                        emit(DIFFLINK, entry, prev=rev, rev=headrev)
                    else:
                        headrev = rev
                    print
                athead = 0
            else:
                athead = 0
                if line[:1] == '-' and len(line) >= 20 and \
                   line == len(line) * line[0]:
                    athead = 1
                    sys.stdout.write('
')
                else:
                    print line
        print '
'

    def do_revision(self):
        entry = self.dir.open(self.ui.file)
        rev = self.ui.rev
        mami = revparse(rev)
        if not mami:
            self.error("Invalid revision number: %r." % (rev,))
        self.prologue(T_REVISION, entry)
        self.shell(interpolate(SH_REVISION, entry, rev=rev))

    def do_diff(self):
        entry = self.dir.open(self.ui.file)
        prev = self.ui.prev
        rev = self.ui.rev
        mami = revparse(rev)
        if not mami:
            self.error("Invalid revision number: %r." % (rev,))
        if prev:
            if not revparse(prev):
                self.error("Invalid previous revision number: %r." % (prev,))
        else:
            prev = '%d.%d' % (mami[0], mami[1])
        self.prologue(T_DIFF, entry)
        self.shell(interpolate(SH_RDIFF, entry, rev=rev, prev=prev))

    def shell(self, command):
        output = os.popen(command).read()
        sys.stdout.write('
')
        print escape(output)
        print '
'

    def do_new(self):
        entry = self.dir.new(section=int(self.ui.section))
        entry.version = '*new*'
        self.prologue(T_EDIT)
        emit(EDITHEAD)
        emit(EDITFORM1, entry, editversion=entry.version)
        emit(EDITFORM2, entry, load_my_cookie())
        emit(EDITFORM3)
        entry.show(edit=0)

    def do_edit(self):
        entry = self.dir.open(self.ui.file)
        entry.load_version()
        self.prologue(T_EDIT)
        emit(EDITHEAD)
        emit(EDITFORM1, entry, editversion=entry.version)
        emit(EDITFORM2, entry, load_my_cookie())
        emit(EDITFORM3)
        entry.show(edit=0)

    def do_review(self):
        send_my_cookie(self.ui)
        if self.ui.editversion == '*new*':
            sec, num = self.dir.parse(self.ui.file)
            entry = self.dir.new(section=sec)
            entry.version = "*new*"
            if entry.file != self.ui.file:
                self.error("Commit version conflict!")
                emit(NEWCONFLICT, self.ui, sec=sec, num=num)
                return
        else:
            entry = self.dir.open(self.ui.file)
            entry.load_version()
        # Check that the FAQ entry number didn't change
        if self.ui.title.split()[:1] != entry.title.split()[:1]:
            self.error("Don't change the entry number please!")
            return
        # Check that the edited version is the current version
        if entry.version != self.ui.editversion:
            self.error("Commit version conflict!")
            emit(VERSIONCONFLICT, entry, self.ui)
            return
        commit_ok = ((not PASSWORD
                      or self.ui.password == PASSWORD)
                     and self.ui.author
                     and '@' in self.ui.email
                     and self.ui.log)
        if self.ui.commit:
            if not commit_ok:
                self.cantcommit()
            else:
                self.commit(entry)
            return
        self.prologue(T_REVIEW)
        emit(REVIEWHEAD)
        entry.body = self.ui.body
        entry.title = self.ui.title
        entry.show(edit=0)
        emit(EDITFORM1, self.ui, entry)
        if commit_ok:
            emit(COMMIT)
        else:
            emit(NOCOMMIT_HEAD)
            self.errordetail()
            emit(NOCOMMIT_TAIL)
        emit(EDITFORM2, self.ui, entry, load_my_cookie())
        emit(EDITFORM3)

    def cantcommit(self):
        self.prologue(T_CANTCOMMIT)
        print CANTCOMMIT_HEAD
        self.errordetail()
        print CANTCOMMIT_TAIL

    def errordetail(self):
        if PASSWORD and self.ui.password != PASSWORD:
            emit(NEED_PASSWD)
        if not self.ui.log:
            emit(NEED_LOG)
        if not self.ui.author:
            emit(NEED_AUTHOR)
        if not self.ui.email:
            emit(NEED_EMAIL)

    def commit(self, entry):
        file = entry.file
        # Normalize line endings in body
        if '\r' in self.ui.body:
            self.ui.body = re.sub('\r\n?', '\n', self.ui.body)
        # Normalize whitespace in title
        self.ui.title = ' '.join(self.ui.title.split())
        # Check that there were any changes
        if self.ui.body == entry.body and self.ui.title == entry.title:
            self.error("You didn't make any changes!")
            return

        # need to lock here because otherwise the file exists and is not writable (on NT)
        command = interpolate(SH_LOCK, file=file)
        p = os.popen(command)
        output = p.read()

        try:
            os.unlink(file)
        except os.error:
            pass
        try:
            f = open(file, 'w')
        except IOError, why:
            self.error(CANTWRITE, file=file, why=why)
            return
        date = time.ctime(now)
        emit(FILEHEADER, self.ui, os.environ, date=date, _file=f, _quote=0)
        f.write('\n')
        f.write(self.ui.body)
        f.write('\n')
        f.close()

        import tempfile
        tf = tempfile.NamedTemporaryFile()
        emit(LOGHEADER, self.ui, os.environ, date=date, _file=tf)
        tf.flush()
        tf.seek(0)

        command = interpolate(SH_CHECKIN, file=file, tfn=tf.name)
        log("\n\n" + command)
        p = os.popen(command)
        output = p.read()
        sts = p.close()
        log("output: " + output)
        log("done: " + str(sts))
        log("TempFile:\n" + tf.read() + "end")

        if not sts:
            self.prologue(T_COMMITTED)
            emit(COMMITTED)
        else:
            self.error(T_COMMITFAILED)
            emit(COMMITFAILED, sts=sts)
        print '
%s
' % escape(output)

        try:
            os.unlink(tf.name)
        except os.error:
            pass

        entry = self.dir.open(file)
        entry.show()

wiz = FaqWizard()
wiz.go()


text:
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.

#pragma once

#include "CoreMinimal.h"
#include "IDetailCustomization.h"

class IPropertyHandle;
class SWidget;

/**
 * Implements a details view customization for the UNdiMediaSource class.
 */
class FNdiMediaSourceCustomization
	: public IDetailCustomization
{
public:

	virtual void CustomizeDetails(IDetailLayoutBuilder& DetailBuilder) override;

public:

	/**
	 * Creates an instance of this class.
	 *
	 * @return The new instance.
	 */
	static TSharedRef<IDetailCustomization> MakeInstance()
	{
		return MakeShareable(new FNdiMediaSourceCustomization());
	}

private:

	enum class EProperty
	{
		SourceEndpoint,
		SourceName
	};

	/** Callback for generating the menu content of the SourceName combo box. */
	TSharedRef<SWidget> HandleSourceComboButtonMenuContent(EProperty Property) const;

private:

	/** Pointer to the SourceEndpoint property handle. */
	TSharedPtr<IPropertyHandle> SourceEndpointProperty;

	/** Pointer to the SourceName property handle. */
	TSharedPtr<IPropertyHandle> SourceNameProperty;
};