text:
package com.hellblazer.process.impl;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.UUID;

import javax.management.MBeanServerConnection;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;
import javax.security.auth.Subject;

import org.apache.commons.io.input.Tailer;
import org.apache.commons.io.input.TailerListener;

import com.hellblazer.process.CannotStopProcessException;
import com.hellblazer.process.JavaProcess;
import com.hellblazer.process.ManagedProcess;
import com.hellblazer.process.NoLocalJmxConnectionException;
import com.sun.tools.attach.AttachNotSupportedException;
import com.sun.tools.attach.VirtualMachine;

/**
 * @author Hal Hildebrand
 *
 */
public class JavaProcessImpl implements JavaProcess, Cloneable {
    private static final long        serialVersionUID = 1L;
    protected List<String>           arguments;
    protected File                   jarFile;
    protected String                 javaClass;
    protected File                   javaExecutable;
    protected transient JMXConnector jmxc;
    protected ManagedProcess         process;
    protected List<String>           vmOptions;

    public JavaProcessImpl(ManagedProcess process) {
        assert process != null;
        this.process = process;
    }

    /* (non-Javadoc)
     * @see com.hellblazer.process.JavaProcess#addArgument(java.lang.String)
     */
    @Override
    public void addArgument(String argument) {
        if (arguments == null) {
            arguments = new ArrayList<String>();
        }
        arguments.add(argument);
    }

    /* (non-Javadoc)
     * @see com.hellblazer.process.JavaProcess#addArguments(java.lang.String[])
     */
    @Override
    public void addArguments(String[] args) {
        if (arguments == null) {
            arguments = new ArrayList<String>();
        }
        for (String arg : args) {
            arguments.add(arg);
        }
    }

    @Override
    public void addCommand(String command) {
        throw new UnsupportedOperationException(
                                                "Cannot set the command of the process directly");
    }

    /* (non-Javadoc)
     * @see com.hellblazer.process.JavaProcess#addVmOption(java.lang.String)
     */
    @Override
    public void addVmOption(String vmOption) {
        if (vmOptions == null) {
            vmOptions = new ArrayList<String>();
        }
        vmOptions.add(vmOption);
    }

    /* (non-Javadoc)
     * @see com.hellblazer.process.JavaProcess#addVmOptions(java.lang.String[])
     */
    @Override
    public void addVmOptions(String[] vmOpts) {
        if (vmOptions == null) {
            vmOptions = new ArrayList<String>();
        }
        for (String opt : vmOpts) {
            vmOptions.add(opt);
        }
    }

    @Override
    public JavaProcess clone() {
        JavaProcessImpl clone;
        try {
            clone = (JavaProcessImpl) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException("Clone not supported", e);
        }
        clone.process = process.clone();
        if (arguments != null) {
            clone.arguments = new ArrayList<String>(arguments);
        }
        if (vmOptions != null) {
            clone.vmOptions = new ArrayList<String>(vmOptions);
        }
        clone.jarFile = jarFile;
        clone.javaClass = javaClass;
        return clone;
    }

    @Override
    public JavaProcess configureFrom(ManagedProcess p) {
        if (!(p instanceof JavaProcess)) {
            throw new UnsupportedOperationException(
                                                    "Can only configure from an instance of JavaProcess");
        }
        JavaProcess javaProcess = (JavaProcess) p;
        javaExecutable = javaProcess.getJavaExecutable();
        arguments = javaProcess.getArguments();
        vmOptions = javaProcess.getVmOptions();
        javaClass = javaProcess.getJavaClass();
        jarFile = javaProcess.getJarFile();
        process.setDirectory(javaProcess.getDirectory());
        process.setEnvironment(javaProcess.getEnvironment());
        return this;
    }

    @Override
    public void destroy() throws CannotStopProcessException, IOException {
        process.destroy();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final JavaProcessImpl other = (JavaProcessImpl) obj;
        if (process == null) {
            if (other.process != null) {
                return false;
            }
        } else if (!process.equals(other.process)) {
            return false;
        }
        return true;
    }

    /**
     * @return the List of arguments to the Java program
     */
    @Override
    public List<String> getArguments() {
        return new ArrayList<String>(arguments);
    }

    /**
     * @return the List which represents the command to execute this Java
     *         process
     */
    @Override
    public List<String> getCommand() {
        ArrayList<String> command = new ArrayList<String>();
        if (javaExecutable != null) {
            command.add(javaExecutable.getAbsolutePath());
        }
        if (vmOptions != null) {
            command.addAll(vmOptions);
        }
        command.addAll(getExecution());
        if (arguments != null) {
            command.addAll(arguments);
        }
        return command;
    }

    /**
     * @return the home directory of the process execution
     */
    @Override
    public File getDirectory() {
        return process.getDirectory();
    }

    @Override
    public Map<String, String> getEnvironment() {
        return process.getEnvironment();
    }

    @Override
    public Integer getExitValue() {
        return process.getExitValue();
    }

    /**
     * Answer the unique id of this java process
     */
    @Override
    public UUID getId() {
        return process.getId();
    }

    @Override
    public File getJarFile() {
        return jarFile;
    }

    @Override
    public String getJavaClass() {
        return javaClass;
    }

    /**
     * @return the File which points to the Java executable
     */
    @Override
    public File getJavaExecutable() {
        return javaExecutable;
    }

    /**
     * @throws ConnectException
     */
    @Override
    public JMXConnector getLocalJmxConnector(String connectorName) throws ConnectException,
                                              NoLocalJmxConnectionException {
        if (jmxc != null) {
            return jmxc;
        }

        if (!process.isActive()) {
            throw new ConnectException(
                                       "Cannot establish local JMX connection as process is not active: "
                                               + this);
        }

        String address;
        try {
            VirtualMachine vm = VirtualMachine.attach("" + process.getPid());
            Properties props = vm.getSystemProperties();
            address = props.getProperty(connectorName);

            if (address == null) {
                throw new ConnectException("Unable to find address for remote JMX connection with name = " + connectorName);
            }
        } catch (IOException e) {
            ConnectException cex = new ConnectException(
                                                        "Cannot obtain local JMX connector address of: "
                                                                + this);
            cex.initCause(e);
            throw cex;
        } catch (AttachNotSupportedException e) {
            throw new RuntimeException(e);
        }

        JMXServiceURL jmxUrl;
        try {
            jmxUrl = new JMXServiceURL(address);
        } catch (MalformedURLException e) {
            ConnectException cex = new ConnectException(
                                                        "Invalid local JMX URL for "
                                                                + this + " : "
                                                                + address);
            cex.initCause(e);
            throw cex;
        }

        try {
            jmxc = JMXConnectorFactory.connect(jmxUrl);
        } catch (java.rmi.ConnectException e) {
            if (e.getMessage().startsWith("Connection refused")) {
                throw new NoLocalJmxConnectionException(
                                                        "Local JMX connector address does not exist for: "
                                                                + this);
            }
            ConnectException cex = new ConnectException(
                                                        "Underlying RMI communications exception");
            cex.initCause(e);
            throw cex;
        } catch (IOException e) {
            ConnectException cex = new ConnectException(
                                                        "Cannot establish local JMX connection to: "
                                                                + this);
            cex.initCause(e);
            throw cex;
        }

        try {
            jmxc.connect();
        } catch (IOException e) {
            ConnectException cex = new ConnectException(
                                                        "Cannot establish local JMX connection to: "
                                                                + this);
            cex.initCause(e);
            throw cex;
        }

        return jmxc;
    }

    @Override
    public MBeanServerConnection getLocalMBeanServerConnection(String connectionName)
                                                                throws ConnectException,
                                                                NoLocalJmxConnectionException {
        JMXConnector connector = getLocalJmxConnector(connectionName);

        try {
            return connector.getMBeanServerConnection();
        } catch (IOException e) {
            ConnectException cex = new ConnectException(
                                                        "Cannot establish local JMX connection to: "
                                                                + this);
            cex.initCause(e);
            throw cex;
        }
    }

    @Override
    public MBeanServerConnection getLocalMBeanServerConnection(String connectionName, Subject delegationSubject)
                                                                                throws ConnectException,
                                                                                NoLocalJmxConnectionException {
        JMXConnector connector = getLocalJmxConnector(connectionName);

        try {
            return connector.getMBeanServerConnection(delegationSubject);
        } catch (IOException e) {
            ConnectException cex = new ConnectException(
                                                        "Cannot establish local JMX connection to: "
                                                                + this);
            cex.initCause(e);
            throw cex;
        }
    }

    @Override
    public Integer getPid() {
        return process.getPid();
    }

    @Override
    public InputStream getStdErr() {
        return process.getStdErr();
    }

    @Override
    public String getStdErrTail(int numLines) throws IOException {
        return process.getStdErrTail(numLines);
    }

    @Override
    public OutputStream getStdIn() {
        return process.getStdIn();
    }

    @Override
    public InputStream getStdOut() {
        return process.getStdOut();
    }

    @Override
    public String getStdOutTail(int numLines) throws IOException {
        return process.getStdOutTail(numLines);
    }

    /**
     * @return the List of arguments to the Java virtual machine
     */
    @Override
    public List<String> getVmOptions() {
        return new ArrayList<String>(vmOptions);
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + (process == null ? 0 : process.hashCode());
        return result;
    }

    /**
     * @return true if the Java process is active
     */
    @Override
    public boolean isActive() {
        return process.isActive();
    }

    @Override
    public boolean isSameConfiguration(ManagedProcess otherProcess) {
        if (!(otherProcess instanceof JavaProcess)) {
            return false;
        }

        JavaProcess other = (JavaProcess) otherProcess;
        if (arguments == null) {
            if (other.getArguments() != null) {
                return false;
            }
        } else if (!arguments.equals(other.getArguments())) {
            return false;
        }
        if (jarFile == null) {
            if (other.getJarFile() != null) {
                return false;
            }
        } else if (!jarFile.equals(other.getJarFile())) {
            return false;
        }
        if (javaClass == null) {
            if (other.getJavaClass() != null) {
                return false;
            }
        } else if (!javaClass.equals(other.getJavaClass())) {
            return false;
        }
        if (javaExecutable == null) {
            if (other.getJavaExecutable() != null) {
                return false;
            }
        } else if (!javaExecutable.equals(other.getJavaExecutable())) {
            return false;
        }
        if (vmOptions == null) {
            if (other.getVmOptions() != null) {
                return false;
            }
        } else if (!vmOptions.equals(other.getVmOptions())) {
            return false;
        }
        return true;
    }

    /* (non-Javadoc)
     * @see com.hellblazer.process.ManagedProcess#restart()
     */
    @Override
    public void restart() throws IOException {
        process.restart();
    }

    /* (non-Javadoc)
     * @see com.hellblazer.process.ManagedProcess#restart(int)
     */
    @Override
    public void restart(int waitForSeconds) throws IOException {
        process.restart(waitForSeconds);
    }

    @Override
    public void setArguments(List<String> arguments) {
        if (arguments == null) {
            arguments = new ArrayList<String>();
        }
        this.arguments = new ArrayList<String>(arguments);
    }

    @Override
    public void setArguments(String[] arguments) {
        if (arguments == null) {
            arguments = new String[] {};
        }
        ArrayList<String> args = new ArrayList<String>();
        for (String argument : arguments) {
            args.add(argument);
        }
        setArguments(args);
    }

    @Override
    public void setCommand(List<String> commands) {
        throw new UnsupportedOperationException(
                                                "Cannot set the command of the process directly");
    }

    @Override
    public void setCommand(String[] commands) {
        throw new UnsupportedOperationException(
                                                "Cannot set the command of the process directly");
    }

    @Override
    public void setDirectory(File directory) {
        process.setDirectory(directory);
    }

    @Override
    public void setDirectory(String directory) {
        process.setDirectory(directory);
    }

    @Override
    public void setEnvironment(Map<String, String> environment) {
        process.setEnvironment(environment);
    }

    @Override
    public void setJarFile(File jarFile) {
        if (jarFile != null) {
            javaClass = null; // exclusive or
        }
        this.jarFile = jarFile;
    }

    @Override
    public void setJarFile(String jarFile) {
        if (jarFile == null) {
            this.jarFile = null;
            return;
        }
        setJarFile(new File(jarFile));
    }

    @Override
    public void setJavaClass(String javaClass) {
        if (javaClass != null) {
            jarFile = null; // exclusive or
        }
        this.javaClass = javaClass;
    }

    @Override
    public void setJavaExecutable(File javaExecutable) {
        this.javaExecutable = javaExecutable;
    }

    @Override
    public void setJavaExecutable(String javaExecutable) {
        if (javaExecutable == null) {
            this.javaExecutable = null;
            return;
        }
        setJavaExecutable(new File(javaExecutable));
    }

    @Override
    public void setVmOptions(List<String> vmOptions) {
        if (vmOptions == null) {
            vmOptions = new ArrayList<String>();
        }
        this.vmOptions = new ArrayList<String>(vmOptions);
    }

    @Override
    public void setVmOptions(String[] vmOptions) {
        if (vmOptions == null) {
            vmOptions = new String[] {};
        }
        ArrayList<String> options = new ArrayList<String>();
        for (String option : vmOptions) {
            options.add(option);
        }
        setVmOptions(options);
    }

    /**
     * Start the Java process
     *
     * @throws IOException
     *             - if anything goes awry in starting up the process
     */
    @Override
    public synchronized void start() throws IOException {
        if (javaExecutable == null) {
            throw new IllegalStateException("Java executable must not be null");
        }
        if (vmOptions == null) {
            vmOptions = new ArrayList<String>();
        }
        if (arguments == null) {
            arguments = new ArrayList<String>();
        }
        process.setCommand(getCommand());
        process.start();
    }

    /**
     * Stop the execution of the Java process.
     *
     * @throws CannotStopProcessException
     */
    @Override
    public synchronized void stop() throws CannotStopProcessException {
        process.stop();
    }

    @Override
    public synchronized void stop(int waitForSeconds)
                                                     throws CannotStopProcessException {
        process.stop(waitForSeconds);
    }

    /* (non-Javadoc)
     * @see com.hellblazer.process.ManagedProcess#tailStdErr(org.apache.commons.io.input.TailerListener)
     */
    @Override
    public Tailer tailStdErr(TailerListener listener) {
        return process.tailStdErr(listener);
    }

    /* (non-Javadoc)
     * @see com.hellblazer.process.ManagedProcess#tailStdErr(org.apache.commons.io.input.TailerListener, long, boolean, boolean, int)
     */
    @Override
    public Tailer tailStdErr(TailerListener listener, long delayMillis,
                             boolean end, boolean reOpen, int bufSize) {
        return process.tailStdErr(listener, delayMillis, end, reOpen, bufSize);
    }

    /* (non-Javadoc)
     * @see com.hellblazer.process.ManagedProcess#tailStdOut(org.apache.commons.io.input.TailerListener)
     */
    @Override
    public Tailer tailStdOut(TailerListener listener) {
        return process.tailStdOut(listener);
    }

    /* (non-Javadoc)
     * @see com.hellblazer.process.ManagedProcess#tailStdOut(org.apache.commons.io.input.TailerListener, long, boolean, boolean, int)
     */
    @Override
    public Tailer tailStdOut(TailerListener listener, long delayMillis,
                             boolean end, boolean reOpen, int bufSize) {
        return tailStdOut(listener, delayMillis, end, reOpen, bufSize);
    }

    @Override
    public String toString() {
        StringBuffer buf = new StringBuffer();
        buf.append("JavaProcess");
        buf.append("{").append(getId()).append("} ");
        buf.append(" home dir: ");
        buf.append(getDirectory());
        buf.append(" pid: ");
        buf.append(getPid());
        return buf.toString();
    }

    @Override
    public int waitFor() throws InterruptedException {
        return process.waitFor();
    }

    /**
     * @return the List which represents the arguments to the VM invocation to
     *         run the Java program
     */
    protected List<String> getExecution() {
        assert !(jarFile != null && javaClass != null); // can't execute jar and java class simultaneously
        ArrayList<String> execution = new ArrayList<String>();
        if (jarFile != null) {
            execution.add("-jar");
            execution.add(jarFile.getAbsolutePath());
        } else {
            execution.add(javaClass);
        }
        return execution;
    }
}


text:
import _ from "lodash";
import Stream from "mithril/stream";
import {CurrentUser} from "./current_user";
import {NotificationFilters} from "./notification_filters";

export type Preferences = NotificationFilters | CurrentUser;
export type PreferenceVM = NotificationFilterVMs | CurrentUserVM;

export class PreferencesVM<T extends Preferences> {
  etag: Stream<string | undefined>;
  protected readonly _original: Stream<T>;
  readonly entity: Stream<T>;

  constructor(object?: T) {
    this.etag      = Stream();
    this._original = object ? Stream(object) : Stream();
    this.entity    = object ? Stream(object.clone() as T) : Stream();
  }

  reset() {
    this.entity(this._original().clone() as T);
  }

  sync(object: T, etag?: string) {
    this._original(object);
    this.entity(object.clone() as T);
    this.etag(etag);
  }

  isModified() {
    return !_.isEqual(this._original().toJSON(), this.entity().toJSON());
  }
}

export class NotificationFilterVMs extends PreferencesVM<NotificationFilters> {
  constructor(object?: NotificationFilters) {
    super(object || new NotificationFilters());
  }
}

export class CurrentUserVM extends PreferencesVM<CurrentUser> {
  constructor(object?: CurrentUser) {
    super(object || CurrentUser.default());
  }
}

redpajama_set_name: RedPajamaGithub


text:
adcode/placement.html
{{ section }}
{{ placement }}


text:
CoinWare server
===============

a small node.js server for highscore sharing in coinware.
It is totally insecure by design... Feel free to implement a better version.

Install
-------

In the *server* folder, type the following command:

	npm install

It will install all the required dependencies.

Launch server
-------------

In your CoinWare config.js file, activate the server-side routines by setting the serverSync variable to true.
Then, launch the server with the following command in the *server* folder:

	PORT=1234 node app

where 1234 is the port number you want your server to run on...


text:
<?xml version="1.0" encoding="UTF-8"?>
<article id="586">
	<title>An Evaluation of Index Medicus and MEDLARS in the Field of Ophthalmology	</title>
	<author>Virgo, Julie A.	</author>
	<text>
		   An evaluation of the performance of Index Medicus and MEDLARS in the field
		of ophthalmology is presented, using data generated by a separate study..
		MEDLARS performance figures gave a screened precision ratio of 54% and a recall
		ratio of 42%.. Over the same set of questions Index Medicus had a screened
		precision ratio of 53% and a recall ratio of 46%.. Results for Index Medicus
		alone over a large set of questions gave a 73% screened precision ratio and a
		47% recall ratio.. A random sample of MEDLARS and Index Medicus precision and
		recall failures showed that most of the Index Medicus recall failures resulted
		from manual searcher omission.. The major causes of Medlars precision failures
		were inadequate indexing terminalogy to express concepts and attempts at
		providing too exhaustive a search..
	</text>
</article>


text:
from base_grid import BaseGrid, BaseFace
from src.util.debug_util import assert_type_in_container

class SquareGrid(BaseGrid):
    """

    正四角形の面を持つグリッドの基底クラス

    """

    def __init__(self, vertices, square_faces, n_face, n_div, upper_direction,
                 is_face_assertion_enabled=True):
        """

        :type vertices: np.ndarray
        :param vertices: 頂点座標配列

        :type square_faces: list(SquareFaces) or tuple(SquareFaces)
        :param square_faces: SquareFacesの集合

        :type n_face: int or long
        :param n_face: 面の数

        :type n_div: int or long
        :param n_div: 面の分割数

        :type upper_direction: (float, float, float)
        :param upper_direction: グリッドの上方向を表す単位ベクトル

        :type is_face_assertion_enabled: bool
        :param is_face_assertion_enabled: メンバのアサーションチェックを有効にするかどうか

        """
        # assertion
        if is_face_assertion_enabled:
            assert_type_in_container(square_faces, SquareFace)

        super(SquareGrid, self).__init__(vertices, square_faces, n_face, n_div,
                                         upper_direction,
                                         is_face_assertion_enabled=False)

    def divide_face(self, n_div):
        """

        指定数で面を分割したSquareGridオブジェクトを返す

        :type n_div: int
        :param n_div: 分割する

        :rtype: SquareGrid
        :return: 面分割したSquareGridオブジェクト

        """

class SquareFace(BaseFace):
    """

    SquareGridが持つ面クラス

    """

    def __init__(self, face_id, top_face_id, left_face_id, right_face_id,
                 bottom_face_id, n_div=1, vidx_table=None):
        """

        :type face_id: int or long
        :param face_id: 面を一意に識別するためのID

        :type left_face_id: int or long
        :param left_face_id: 左辺に隣接するface_id

        :type right_face_id: int or long
        :param right_face_id: 右辺に隣接するface_id

        :type bottom_face_id: int or long
        :param bottom_face_id: 底辺に隣接するface_id

        :type n_div: int or long
        :param n_div: 面の分割数

        :type vidx_table: dict((int or long, int or long), int or long)
        :param vidx_table: 頂点座標(alpha, beta)と頂点インデックスのペア

        """

        super(SquareFace, self).__init__(face_id, n_div, vidx_table)


text:
import React from 'react'
import { Advertisement } from 'shengnian-ui-react'

const AdvertisementExampleRectangle = () => (
  <Advertisement unit='medium rectangle' test='Medium Rectangle' />
)

export default AdvertisementExampleRectangle


text:
	soundBlogTag = new Sound(Blog_Tag);
//interface
	soundInterfaceClick = new Sound(itfc_click,.8);
	soundInterfaceBuyItem = new Sound(itfc_buy_item);
	soundInterfaceCancelItem = new Sound(itfc_item_cancel);
//pistol
	soundWpnPistolShot01 = new Sound(wpn_pistol_shot_01,.3);
	soundWpnPistolShot02 = new Sound(wpn_pistol_shot_02,.3);
	soundWpnPistolShot03 = new Sound(wpn_pistol_shot_03,.3);
//shotgun
	soundWpnShotgunFire01 = new Sound(wpn_shotgun_fire_01,.45);
	soundWpnShotgunFire02 = new Sound(wpn_shotgun_fire_02,.45);
	soundWpnShotgunLoad01 = new Sound(wpn_shotgun_load_01,.45);
	soundWpnShotgunLoad02 = new Sound(wpn_shotgun_load_02,.45);

//-------------------------
//
// Declare and initialize our variables
//
//----------

	var myContext, myShotgunContext;
	var randomizePitch = false;
	var randomizeSound = false;
	var pistolIsPlaying = false;
	var shotgunIsPlaying = false;
	var touchIsOngoing = false;

	var randomPitchCheckbox = document.getElementById("randomizePitch");
	var randomSoundCheckbox = document.getElementById("randomizeSound");

	var thePlayButton = document.getElementById("audioPlayer_play");
	var theStopButton = document.getElementById("audioPlayer_stop");
	var thePistol = document.getElementById("pistol");
	var theShotgun = document.getElementById("shotgun");

//-------------------------
//
// Declare our listeners
//
//----------

//
// has the randomPitch checkbox been clicked?
//
	randomPitchCheckbox.addEventListener('click',
			function(){
				randomizePitch = randomPitchCheckbox.checked;
			}
		, false);

//
// has the randomSound checkbox been clicked?
//
	randomSoundCheckbox.addEventListener('click',
			function(){
				randomizeSound = randomSoundCheckbox.checked;
			}
		, false);

//
// listen for the user to click on the stop button
//
	thePlayButton.addEventListener('click',
			function(){
				myContext = playTheSound(soundBlogTag);

				// check the playbackState in order to set the play button
				// back to its original state when the sound finishes playing
				var myPlayback = setInterval(function() {
					if (myContext.playbackState == 3) {
						killTheSound(myContext);
					}
				},100);
			}
		, false);

//
// listen for the user to click on the stop button
//
	theStopButton.addEventListener('click',
			function(e){
				killTheSound(myContext);
			}
		, false);

//
// listen for the user to click or touch on the pistol icon
//
	thePistol.addEventListener('mousedown',
			function(e){
				e.preventDefault();
				fireThePistol();
			}
		, false);

	thePistol.addEventListener('touchstart',
			function(e){
				e.preventDefault();
				touchIsOngoing = true;
				firePistolTouchEvent();
			}
		, false);

	thePistol.addEventListener('touchend',
			function(e){
				touchIsOngoing = false;
				e.preventDefault();
			}
		, false);

	window.addEventListener('shake', shakeEventDidOccur, false);

	//define a custom method to fire when shake occurs.
	function shakeEventDidOccur () {
		fireTheShotgun();
	}

//
// listen for the user to click on the pistol icon
//
	theShotgun.addEventListener('click',
			function(e){
				e.preventDefault();
				fireTheShotgun();
			}
		, false);

//
// listen for key presses
//
	window.addEventListener("keydown",onKeyDown);

	function onKeyDown(e) {
		switch (e.keyCode) {
			// spacebar
			case 32:
				fireThePistol();
				break;
			// q
			case 81:
				fireTheShotgun();
				break;
			// x
			case 88:
				// toggle the randomPitch checkbox
				if (randomizePitch) {
					randomPitchCheckbox.checked = false;
					randomizePitch = false;
				}
				else {
					randomPitchCheckbox.checked = true;
					randomizePitch = true;
				}
				break;
			// z
			case 90:
				// toggle the randomSound checkbox
				if (randomizeSound) {
					randomSoundCheckbox.checked = false;
					randomizeSound = false;
				}
				else {
					randomSoundCheckbox.checked = true;
					randomizeSound = true;
				}
				break;
		}
	}

//
// setup listeners for the list items
//
	// get an array of list items
	var li = document.getElementsByClassName("listItem");
	myImg = new Array();

	// loop through all the list items and set listeners for click and hover events
	// play sounds based on the events and change the colors, too.
	for (var i=0; i<li.length; i++) {
		// initialize the clicked attribute
		li[i].clicked = false;

		li[i].addEventListener('click',
			function(){
				if (!this.clicked) {
					// play the sound
					soundInterfaceBuyItem.play();

					// set the different background color to indicate click
					this.setAttribute("style", "background-color:#ccc;");
					// set the clicked variable
					this.clicked = true;

					// get the child image (checkmark) and make it visible
					myImg = this.lastChild;
					myImg.removeAttribute("hidden");
				}
				else {
					// play the sound
					soundInterfaceCancelItem.play();

					// remove the background color we had set
					// (hope we didn't set anything else!)
					this.removeAttribute("style");
					// reset the clicked variable
					this.clicked = false;

					// get the child image (checkmark) and make it hidden
					myImg = this.lastChild;
					myImg.setAttribute("hidden","hidden");
				}
			}
		, false);
		li[i].addEventListener('mouseover',
			function(){
				// play the sound
				soundInterfaceClick.play();
			}
		, false);
	}


text: alter table SYS_FILE alter column FILE_SIZE type bigint^


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

namespace Ocelog.Test
{
    public class ExceptionHandlingTests
    {
        [Fact]
        public void should_throw_logging_exceptions_into_calling_code_by_default()
        {
            var exception = new Exception();
            var logger = new Logger(logEvents => logEvents
                .Subscribe(log => { throw exception; })
                );

            Assert.Throws<Exception>(() => logger.Info(new { }));
        }

        [Fact]
        public void should_allow_logging_exceptions_to_be_directed_into_another_logger()
        {
            var output = new List<LogEvent>();
            var exception = new Exception();
            var logger = new Logger(logEvents => logEvents
                .HandleLoggingErrors(exceptionLogsEvents => exceptionLogsEvents
                    .Subscribe(log => output.Add(log)))
                .Subscribe(log => { throw exception; })
                );

            logger.Info(new { });

            Assert.Collection(output,
                log => Assert.Equal(exception, log.Content));
            Assert.Collection(output,
                log => Assert.Equal(LogLevel.Error, log.Level));
        }

        [Fact]
        public void should_allow_ignoring_exceptions()
        {
            var exception = new Exception();
            var logger = new Logger(logEvents => logEvents
                .IgnoreLoggingErrors()
                .Subscribe(log => { throw exception; })
                );

            logger.Info(new { });
        }
    }
}


text:
<?php

/* CensoBundle:AguasServidas:edit.html.twig */
class __TwigTemplate_e7a564cf80c22db8a7c2bce9d5e659a3b3350872ab3d81122f42294f3736a4f6 extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        $this->parent = $this->env->loadTemplate("::base.html.twig");

        $this->blocks = array(
            'body' => array($this, 'block_body'),
        );
    }

    protected function doGetParent(array $context)
    {
        return "::base.html.twig";
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        $this->parent->display($context, array_merge($this->blocks, $blocks));
    }

    // line 3
    public function block_body($context, array $blocks = array())
    {
        // line 4
        echo "
AguasServidas edit

    ";
        // line 6
        echo         $this->env->getExtension('form')->renderer->renderBlock((isset($context["edit_form"]) ? $context["edit_form"] : $this->getContext($context, "edit_form")), 'form');
        echo "

        env->getExtension('routing')->getPath("aguasservidas");
        echo "\">
            Back to the list

";
        // line 14
        echo         $this->env->getExtension('form')->renderer->renderBlock((isset($context["delete_form"]) ? $context["delete_form"] : $this->getContext($context, "delete_form")), 'form');
        echo "

";
    }

    public function getTemplateName()
    {
        return "CensoBundle:AguasServidas:edit.html.twig";
    }

    public function isTraitable()
    {
        return false;
    }

    public function getDebugInfo()
    {
        return array (  49 => 14,  42 => 10,  35 => 6,  31 => 4,  28 => 3,);
    }
}


text:
//*******************************************************************************************//
//                                                                                //
// Download Free Evaluation Version From: https://bytescout.com/download/web-installer       //
//                                                                                //
// Also available as Web API! Get Your Free API Key: https://app.pdf.co/signup               //
//                                                                                //
// Copyright © 2017-2020 ByteScout, Inc. All rights reserved.                                //
// https://www.bytescout.com                                                                 //
// https://pdf.co                                                                            //
//                                                                                //
//*******************************************************************************************//

// x64 IMPORTANT NOTE: set CPU to x86 to build in x86 mode.

using System.Diagnostics;
using BytescoutSWFToVideo;

namespace SetAudioTrack
{
	class Program
	{
		static void Main(string[] args)
		{
			// Create an instance of SWFToVideo ActiveX object
			SWFToVideo converter = new SWFToVideo();

			// Set debug log
			//converter.SetLogFile("log.txt");

			// Register SWFToVideo
			converter.RegistrationName = "demo";
			converter.RegistrationKey = "demo";

			// set input SWF file
			converter.InputSWFFileName = "SlideShowWithEffects.swf";
			// set output AVI video filename
			converter.OutputVideoFileName = "result.avi";

			// Set background music
			converter.ExternalAudioTrackFromFileName = "bgmusic.mp3";
			// Set output audio codec
			converter.CurrentAudioCodecName = "ADPCM";

			// Set output movie dimensions
			converter.OutputWidth = 640;
			converter.OutputHeight = 480;

			// Run conversion
			converter.RunAndWait();

			// release resources
			System.Runtime.InteropServices.Marshal.ReleaseComObject(converter);
			converter = null;

			// Open the result movie in default media player
			Process.Start("result.avi");
		}
	}
}


text:
package tech.hobbs.hlfdocmgmntsystem.dao.activity.impl;

import java.util.List;

import org.springframework.stereotype.Repository;

import tech.hobbs.hlfdocmgmntsystem.dao.activity.ActivityVideoDao;
import tech.hobbs.hlfdocmgmntsystem.model.activity.Activity;
import tech.hobbs.hlfdocmgmntsystem.model.activity.ActivityVideo;
import tech.hobbs.hlfdocmgmntsystem.model.student.Student;

@Repository
public class ActivityVideoDaoImpl implements ActivityVideoDao {

	@Override
	public List<ActivityVideo> findAll() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void saveOrUpdate(ActivityVideo model) {
		// TODO Auto-generated method stub

	}

	@Override
	public void delete(ActivityVideo model) {
		// TODO Auto-generated method stub

	}

	@Override
	public ActivityVideo findByActivityName(Activity activity) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public ActivityVideo findByUploader(Student student) {
		// TODO Auto-generated method stub
		return null;
	}

}


text:
require 'chefspec'
require 'spec_helper'
require 'fauxhai'

describe 'python::virtualenv' do
  let :chef_run do
    ChefSpec::SoloRunner.new(file_cache_path: '/var/chef/cache').converge(described_recipe)
  end

  before do
    stub_command("/usr/bin/python -c 'import setuptools'").and_return(true)
    stub_command("/usr/bin/python get-pip-py").and_return(true)
    stub_command("/usr/local/bin/python2.7 get-pip-py").and_return(true)
  end

  it 'includes python::pip' do
    chef_run.converge(described_recipe)
    expect(chef_run).to include_recipe('python::pip')
  end

  it 'installs virtualenv' do
    chef_run.converge(described_recipe)
    expect(chef_run).to upgrade_python_pip('virtualenv')
  end

end


text:
package org.sablecc.util;

/**
 * This enumeration encapsulates strictness levels.
 */
public enum Strictness {
    /**
     * Ignore unused constructs.
     */
    LENIENT,

    /**
     * Detect unused constructs.
     */
    STRICT;
}


text:
class Entry(object):
    def __init__(self, B_used, file_type, start_addr, end_addr, reserved_a, tape_pos, reserved_b, file_name):
        self.file_type = file_type
        self.start_addr = start_addr
        self.end_addr = end_addr # unreliable.
        self.reserved_a = reserved_a
        self.tape_pos = tape_pos
        self.reserved_b = reserved_b
        self.file_name = file_name
    #def __str__(self):
    #    return(self.file_name)
    #def __repr__(self):
    #    return("Entry(**%r)" % self.__dict__)
class Loader(object):
    def __init__(self):
        pass
#    def parse(self, stream, file_name):
#        pass
#    def load_header(self, file_name):
#        pass
#    def load_data(self, file_name):
#        pass


text:
FROM airhacks/wildfly
MAINTAINER Mroczny Banan, mrocznybanan.eu
COPY ./target/flyway.war ${DEPLOYMENT_DIR}


text:
<keycloak-saml-adapter>
    <SP entityID="http://localhost:8082/employee-sig-front/"
        sslPolicy="EXTERNAL"
        logoutPage="/logout.jsp"
        nameIDPolicyFormat="urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified"
        forceAuthentication="false">
        <Keys>
            <Key signing="true" >
                <KeyStore resource="/WEB-INF/keystore.jks" password="store123">
                    <PrivateKey alias="http://localhost:8080/employee-sig/" password="test123"/>
                    <Certificate alias="http://localhost:8080/employee-sig/"/>
                </KeyStore>
            </Key>
        </Keys>
        <PrincipalNameMapping policy="FROM_NAME_ID"/>
        <RoleMapping>
            <Attribute name="Role"/>
        </RoleMapping>
        <IDP entityID="idp">
            <SingleSignOnService signRequest="true"
                                 validateResponseSignature="true"
                                 requestBinding="REDIRECT"
                                 bindingUrl="http://localhost:8081/auth/realms/demo/protocol/saml"
                    />

            <SingleLogoutService
                    validateRequestSignature="true"
                    validateResponseSignature="true"
                    signRequest="true"
                    signResponse="true"
                    requestBinding="REDIRECT"
                    responseBinding="REDIRECT"
                    redirectBindingUrl="http://localhost:8081/auth/realms/demo/protocol/saml"
                    />
            <Keys>
                <Key signing="true">
                    <KeyStore resource="/WEB-INF/keystore.jks" password="store123">
                        <Certificate alias="demo"/>
                    </KeyStore>
                </Key>
            </Keys>
        </IDP>
     </SP>
</keycloak-saml-adapter>


text:
package com.twu.biblioteca.entities;

import java.util.HashMap;

/**
 * Created by alvarohernandez on 6/13/17.
 */
public abstract class LibraryElement {

    protected int id;
    protected String currentOwner;
    public abstract HashMap<String,String> getDetails();

    public abstract String getCurrentOwner();

    abstract void setCurrentOwner(String currentOwner);

    abstract String getTextIdentifier();

    public String getAsSimpleListElement() {
        StringBuilder elementString = new StringBuilder();
        elementString.append(id).append(". ").append(getTextIdentifier());
        if(currentOwner != null){
            elementString.append(" - CheckedOutBy: ").append(currentOwner);
        }
        elementString.append("\n");
        return  elementString.toString();
    }

}


text:
<?php

namespace Symfony\Component\Form\Tests\Extension\Core\Type;

use Symfony\Component\Form\Extension\Core\View\ChoiceView;
use Symfony\Component\Form\FormError;
use Symfony\Component\Intl\Util\IntlTestHelper;

class DateTypeTest extends TypeTestCase
{
    protected function setUp()
    {
        parent::setUp();

        // we test against "de_AT", so we need the full implementation
        IntlTestHelper::requireFullIntl($this);

        \Locale::setDefault('de_AT');
    }

    /**
     * @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException
     */
    public function testInvalidWidgetOption()
    {
        $this->factory->create('date', null, array(
            'widget' => 'fake_widget',
        ));
    }

    /**
     * @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException
     */
    public function testInvalidInputOption()
    {
        $this->factory->create('date', null, array(
            'input' => 'fake_input',
        ));
    }

    public function testSubmitFromSingleTextDateTimeWithDefaultFormat()
    {
        $form = $this->factory->create('date', null, array(
            'model_timezone' => 'UTC',
            'view_timezone' => 'UTC',
            'widget' => 'single_text',
            'input' => 'datetime',
        ));

        $form->submit('2010-06-02');

        $this->assertDateTimeEquals(new \DateTime('2010-06-02 UTC'), $form->getData());
        $this->assertEquals('2010-06-02', $form->getViewData());
    }

    public function testSubmitFromSingleTextDateTime()
    {
        $form = $this->factory->create('date', null, array(
            'format' => \IntlDateFormatter::MEDIUM,
            'model_timezone' => 'UTC',
            'view_timezone' => 'UTC',
            'widget' => 'single_text',
            'input' => 'datetime',
        ));

        $form->submit('2.6.2010');

        $this->assertDateTimeEquals(new \DateTime('2010-06-02 UTC'), $form->getData());
        $this->assertEquals('02.06.2010', $form->getViewData());
    }

    public function testSubmitFromSingleTextString()
    {
        $form = $this->factory->create('date', null, array(
            'format' => \IntlDateFormatter::MEDIUM,
            'model_timezone' => 'UTC',
            'view_timezone' => 'UTC',
            'widget' => 'single_text',
            'input' => 'string',
        ));

        $form->submit('2.6.2010');

        $this->assertEquals('2010-06-02', $form->getData());
        $this->assertEquals('02.06.2010', $form->getViewData());
    }

    public function testSubmitFromSingleTextTimestamp()
    {
        $form = $this->factory->create('date', null, array(
            'format' => \IntlDateFormatter::MEDIUM,
            'model_timezone' => 'UTC',
            'view_timezone' => 'UTC',
            'widget' => 'single_text',
            'input' => 'timestamp',
        ));

        $form->submit('2.6.2010');

        $dateTime = new \DateTime('2010-06-02 UTC');

        $this->assertEquals($dateTime->format('U'), $form->getData());
        $this->assertEquals('02.06.2010', $form->getViewData());
    }

    public function testSubmitFromSingleTextRaw()
    {
        $form = $this->factory->create('date', null, array(
            'format' => \IntlDateFormatter::MEDIUM,
            'model_timezone' => 'UTC',
            'view_timezone' => 'UTC',
            'widget' => 'single_text',
            'input' => 'array',
        ));

        $form->submit('2.6.2010');

        $output = array(
            'day' => '2',
            'month' => '6',
            'year' => '2010',
        );

        $this->assertEquals($output, $form->getData());
        $this->assertEquals('02.06.2010', $form->getViewData());
    }

    public function testSubmitFromText()
    {
        $form = $this->factory->create('date', null, array(
            'model_timezone' => 'UTC',
            'view_timezone' => 'UTC',
            'widget' => 'text',
        ));

        $text = array(
            'day' => '2',
            'month' => '6',
            'year' => '2010',
        );

        $form->submit($text);

        $dateTime = new \DateTime('2010-06-02 UTC');

        $this->assertDateTimeEquals($dateTime, $form->getData());
        $this->assertEquals($text, $form->getViewData());
    }

    public function testSubmitFromChoice()
    {
        $form = $this->factory->create('date', null, array(
            'model_timezone' => 'UTC',
            'view_timezone' => 'UTC',
            'widget' => 'choice',
        ));

        $text = array(
            'day' => '2',
            'month' => '6',
            'year' => '2010',
        );

        $form->submit($text);

        $dateTime = new \DateTime('2010-06-02 UTC');

        $this->assertDateTimeEquals($dateTime, $form->getData());
        $this->assertEquals($text, $form->getViewData());
    }

    public function testSubmitFromChoiceEmpty()
    {
        $form = $this->factory->create('date', null, array(
            'model_timezone' => 'UTC',
            'view_timezone' => 'UTC',
            'widget' => 'choice',
            'required' => false,
        ));

        $text = array(
            'day' => '',
            'month' => '',
            'year' => '',
        );

        $form->submit($text);

        $this->assertNull($form->getData());
        $this->assertEquals($text, $form->getViewData());
    }

    public function testSubmitFromInputDateTimeDifferentPattern()
    {
        $form = $this->factory->create('date', null, array(
            'model_timezone' => 'UTC',
            'view_timezone' => 'UTC',
            'format' => 'MM*yyyy*dd',
            'widget' => 'single_text',
            'input' => 'datetime',
        ));

        $form->submit('06*2010*02');

        $this->assertDateTimeEquals(new \DateTime('2010-06-02 UTC'), $form->getData());
        $this->assertEquals('06*2010*02', $form->getViewData());
    }

    public function testSubmitFromInputStringDifferentPattern()
    {
        $form = $this->factory->create('date', null, array(
            'model_timezone' => 'UTC',
            'view_timezone' => 'UTC',
            'format' => 'MM*yyyy*dd',
            'widget' => 'single_text',
            'input' => 'string',
        ));

        $form->submit('06*2010*02');

        $this->assertEquals('2010-06-02', $form->getData());
        $this->assertEquals('06*2010*02', $form->getViewData());
    }

    public function testSubmitFromInputTimestampDifferentPattern()
    {
        $form = $this->factory->create('date', null, array(
            'model_timezone' => 'UTC',
            'view_timezone' => 'UTC',
            'format' => 'MM*yyyy*dd',
            'widget' => 'single_text',
            'input' => 'timestamp',
        ));

        $form->submit('06*2010*02');

        $dateTime = new \DateTime('2010-06-02 UTC');

        $this->assertEquals($dateTime->format('U'), $form->getData());
        $this->assertEquals('06*2010*02', $form->getViewData());
    }

    public function testSubmitFromInputRawDifferentPattern()
    {
        $form = $this->factory->create('date', null, array(
            'model_timezone' => 'UTC',
            'view_timezone' => 'UTC',
            'format' => 'MM*yyyy*dd',
            'widget' => 'single_text',
            'input' => 'array',
        ));

        $form->submit('06*2010*02');

        $output = array(
            'day' => '2',
            'month' => '6',
            'year' => '2010',
        );

        $this->assertEquals($output, $form->getData());
        $this->assertEquals('06*2010*02', $form->getViewData());
    }

    /**
     * @dataProvider provideDateFormats
     */
    public function testDatePatternWithFormatOption($format, $pattern)
    {
        $form = $this->factory->create('date', null, array(
            'format' => $format,
        ));

        $view = $form->createView();

        $this->assertEquals($pattern, $view->vars['date_pattern']);
    }

    public function provideDateFormats()
    {
        return array(
            array('dMy', '{{ day }}{{ month }}{{ year }}'),
            array('d-M-yyyy', '{{ day }}-{{ month }}-{{ year }}'),
            array('M d y', '{{ month }} {{ day }} {{ year }}'),
        );
    }

    /**
     * This test is to check that the strings '0', '1', '2', '3' are not accepted
     * as valid IntlDateFormatter constants for FULL, LONG, MEDIUM or SHORT respectively.
     *
     * @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException
     */
    public function testThrowExceptionIfFormatIsNoPattern()
    {
        $this->factory->create('date', null, array(
            'format' => '0',
            'widget' => 'single_text',
            'input' => 'string',
        ));
    }

    /**
     * @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException
     */
    public function testThrowExceptionIfFormatDoesNotContainYearMonthAndDay()
    {
        $this->factory->create('date', null, array(
            'months' => array(6, 7),
            'format' => 'yy',
        ));
    }

    /**
     * @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException
     */
    public function testThrowExceptionIfFormatIsNoConstant()
    {
        $this->factory->create('date', null, array(
            'format' => 105,
        ));
    }

    /**
     * @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException
     */
    public function testThrowExceptionIfFormatIsInvalid()
    {
        $this->factory->create('date', null, array(
            'format' => array(),
        ));
    }

    /**
     * @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException
     */
    public function testThrowExceptionIfYearsIsInvalid()
    {
        $this->factory->create('date', null, array(
            'years' => 'bad value',
        ));
    }

    /**
     * @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException
     */
    public function testThrowExceptionIfMonthsIsInvalid()
    {
        $this->factory->create('date', null, array(
            'months' => 'bad value',
        ));
    }

    /**
     * @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException
     */
    public function testThrowExceptionIfDaysIsInvalid()
    {
        $this->factory->create('date', null, array(
            'days' => 'bad value',
        ));
    }

    public function testSetDataWithDifferentTimezones()
    {
        $form = $this->factory->create('date', null, array(
            'format' => \IntlDateFormatter::MEDIUM,
            'model_timezone' => 'America/New_York',
            'view_timezone' => 'Pacific/Tahiti',
            'input' => 'string',
            'widget' => 'single_text',
        ));

        $form->setData('2010-06-02');

        $this->assertEquals('01.06.2010', $form->getViewData());
    }

    public function testSetDataWithDifferentTimezonesDateTime()
    {
        $form = $this->factory->create('date', null, array(
            'format' => \IntlDateFormatter::MEDIUM,
            'model_timezone' => 'America/New_York',
            'view_timezone' => 'Pacific/Tahiti',
            'input' => 'datetime',
            'widget' => 'single_text',
        ));

        $dateTime = new \DateTime('2010-06-02 America/New_York');

        $form->setData($dateTime);

        $this->assertDateTimeEquals($dateTime, $form->getData());
        $this->assertEquals('01.06.2010', $form->getViewData());
    }

    public function testYearsOption()
    {
        $form = $this->factory->create('date', null, array(
            'years' => array(2010, 2011),
        ));

        $view = $form->createView();

        $this->assertEquals(array(
            new ChoiceView('2010', '2010', '2010'),
            new ChoiceView('2011', '2011', '2011'),
        ), $view['year']->vars['choices']);
    }

    public function testMonthsOption()
    {
        $form = $this->factory->create('date', null, array(
            'months' => array(6, 7),
        ));

        $view = $form->createView();

        $this->assertEquals(array(
            new ChoiceView('6', '6', '06'),
            new ChoiceView('7', '7', '07'),
        ), $view['month']->vars['choices']);
    }

    public function testMonthsOptionShortFormat()
    {
        $form = $this->factory->create('date', null, array(
            'months' => array(1, 4),
            'format' => 'dd.MMM.yy',
        ));

        $view = $form->createView();

        $this->assertEquals(array(
            new ChoiceView('1', '1', 'Jän'),
            new ChoiceView('4', '4', 'Apr.'),
        ), $view['month']->vars['choices']);
    }

    public function testMonthsOptionLongFormat()
    {
        $form = $this->factory->create('date', null, array(
            'months' => array(1, 4),
            'format' => 'dd.MMMM.yy',
        ));

        $view = $form->createView();

        $this->assertEquals(array(
            new ChoiceView('1', '1', 'Jänner'),
            new ChoiceView('4', '4', 'April'),
        ), $view['month']->vars['choices']);
    }

    public function testMonthsOptionLongFormatWithDifferentTimezone()
    {
        $form = $this->factory->create('date', null, array(
            'months' => array(1, 4),
            'format' => 'dd.MMMM.yy',
        ));

        $view = $form->createView();

        $this->assertEquals(array(
            new ChoiceView('1', '1', 'Jänner'),
            new ChoiceView('4', '4', 'April'),
        ), $view['month']->vars['choices']);
    }

    public function testIsDayWithinRangeReturnsTrueIfWithin()
    {
        $form = $this->factory->create('date', null, array(
            'days' => array(6, 7),
        ));

        $view = $form->createView();

        $this->assertEquals(array(
            new ChoiceView('6', '6', '06'),
            new ChoiceView('7', '7', '07'),
        ), $view['day']->vars['choices']);
    }

    public function testIsPartiallyFilledReturnsFalseIfSingleText()
    {
        $this->markTestIncomplete('Needs to be reimplemented using validators');

        $form = $this->factory->create('date', null, array(
            'model_timezone' => 'UTC',
            'view_timezone' => 'UTC',
            'widget' => 'single_text',
        ));

        $form->submit('7.6.2010');

        $this->assertFalse($form->isPartiallyFilled());
    }

    public function testIsPartiallyFilledReturnsFalseIfChoiceAndCompletelyEmpty()
    {
        $this->markTestIncomplete('Needs to be reimplemented using validators');

        $form = $this->factory->create('date', null, array(
            'model_timezone' => 'UTC',
            'view_timezone' => 'UTC',
            'widget' => 'choice',
        ));

        $form->submit(array(
            'day' => '',
            'month' => '',
            'year' => '',
        ));

        $this->assertFalse($form->isPartiallyFilled());
    }

    public function testIsPartiallyFilledReturnsFalseIfChoiceAndCompletelyFilled()
    {
        $this->markTestIncomplete('Needs to be reimplemented using validators');

        $form = $this->factory->create('date', null, array(
            'model_timezone' => 'UTC',
            'view_timezone' => 'UTC',
            'widget' => 'choice',
        ));

        $form->submit(array(
            'day' => '2',
            'month' => '6',
            'year' => '2010',
        ));

        $this->assertFalse($form->isPartiallyFilled());
    }

    public function testIsPartiallyFilledReturnsTrueIfChoiceAndDayEmpty()
    {
        $this->markTestIncomplete('Needs to be reimplemented using validators');

        $form = $this->factory->create('date', null, array(
            'model_timezone' => 'UTC',
            'view_timezone' => 'UTC',
            'widget' => 'choice',
        ));

        $form->submit(array(
            'day' => '',
            'month' => '6',
            'year' => '2010',
        ));

        $this->assertTrue($form->isPartiallyFilled());
    }

    public function testPassDatePatternToView()
    {
        $form = $this->factory->create('date');
        $view = $form->createView();

        $this->assertSame('{{ day }}{{ month }}{{ year }}', $view->vars['date_pattern']);
    }

    public function testPassDatePatternToViewDifferentFormat()
    {
        $form = $this->factory->create('date', null, array(
            'format' => \IntlDateFormatter::LONG,
        ));

        $view = $form->createView();

        $this->assertSame('{{ day }}{{ month }}{{ year }}', $view->vars['date_pattern']);
    }

    public function testPassDatePatternToViewDifferentPattern()
    {
        $form = $this->factory->create('date', null, array(
            'format' => 'MMyyyydd',
        ));

        $view = $form->createView();

        $this->assertSame('{{ month }}{{ year }}{{ day }}', $view->vars['date_pattern']);
    }

    public function testPassDatePatternToViewDifferentPatternWithSeparators()
    {
        $form = $this->factory->create('date', null, array(
            'format' => 'MM*yyyy*dd',
        ));

        $view = $form->createView();

        $this->assertSame('{{ month }}*{{ year }}*{{ day }}', $view->vars['date_pattern']);
    }

    public function testDontPassDatePatternIfText()
    {
        $form = $this->factory->create('date', null, array(
            'widget' => 'single_text',
        ));
        $view = $form->createView();

        $this->assertFalse(isset($view->vars['date_pattern']));
    }

    public function testPassWidgetToView()
    {
        $form = $this->factory->create('date', null, array(
            'widget' => 'single_text',
        ));
        $view = $form->createView();

        $this->assertSame('single_text', $view->vars['widget']);
    }

    // Bug fix
    public function testInitializeWithDateTime()
    {
        // Throws an exception if "data_class" option is not explicitly set
        // to null in the type
        $this->factory->create('date', new \DateTime());
    }

    public function testSingleTextWidgetShouldUseTheRightInputType()
    {
        $form = $this->factory->create('date', null, array(
            'widget' => 'single_text',
        ));

        $view = $form->createView();
        $this->assertEquals('date', $view->vars['type']);
    }

    public function testPassDefaultPlaceholderToViewIfNotRequired()
    {
        $form = $this->factory->create('date', null, array(
            'required' => false,
        ));

        $view = $form->createView();
        $this->assertSame('', $view['year']->vars['placeholder']);
        $this->assertSame('', $view['month']->vars['placeholder']);
        $this->assertSame('', $view['day']->vars['placeholder']);
    }

    public function testPassNoPlaceholderToViewIfRequired()
    {
        $form = $this->factory->create('date', null, array(
            'required' => true,
        ));

        $view = $form->createView();
        $this->assertNull($view['year']->vars['placeholder']);
        $this->assertNull($view['month']->vars['placeholder']);
        $this->assertNull($view['day']->vars['placeholder']);
    }

    public function testPassPlaceholderAsString()
    {
        $form = $this->factory->create('date', null, array(
            'placeholder' => 'Empty',
        ));

        $view = $form->createView();
        $this->assertSame('Empty', $view['year']->vars['placeholder']);
        $this->assertSame('Empty', $view['month']->vars['placeholder']);
        $this->assertSame('Empty', $view['day']->vars['placeholder']);
    }

    public function testPassEmptyValueBC()
    {
        $form = $this->factory->create('date', null, array(
            'empty_value' => 'Empty',
        ));

        $view = $form->createView();
        $this->assertSame('Empty', $view['year']->vars['placeholder']);
        $this->assertSame('Empty', $view['month']->vars['placeholder']);
        $this->assertSame('Empty', $view['day']->vars['placeholder']);
        $this->assertSame('Empty', $view['year']->vars['empty_value']);
        $this->assertSame('Empty', $view['month']->vars['empty_value']);
        $this->assertSame('Empty', $view['day']->vars['empty_value']);
    }

    public function testPassPlaceholderAsArray()
    {
        $form = $this->factory->create('date', null, array(
            'placeholder' => array(
                'year' => 'Empty year',
                'month' => 'Empty month',
                'day' => 'Empty day',
            ),
        ));

        $view = $form->createView();
        $this->assertSame('Empty year', $view['year']->vars['placeholder']);
        $this->assertSame('Empty month', $view['month']->vars['placeholder']);
        $this->assertSame('Empty day', $view['day']->vars['placeholder']);
    }

    public function testPassPlaceholderAsPartialArrayAddEmptyIfNotRequired()
    {
        $form = $this->factory->create('date', null, array(
            'required' => false,
            'placeholder' => array(
                'year' => 'Empty year',
                'day' => 'Empty day',
            ),
        ));

        $view = $form->createView();
        $this->assertSame('Empty year', $view['year']->vars['placeholder']);
        $this->assertSame('', $view['month']->vars['placeholder']);
        $this->assertSame('Empty day', $view['day']->vars['placeholder']);
    }

    public function testPassPlaceholderAsPartialArrayAddNullIfRequired()
    {
        $form = $this->factory->create('date', null, array(
            'required' => true,
            'placeholder' => array(
                'year' => 'Empty year',
                'day' => 'Empty day',
            ),
        ));

        $view = $form->createView();
        $this->assertSame('Empty year', $view['year']->vars['placeholder']);
        $this->assertNull($view['month']->vars['placeholder']);
        $this->assertSame('Empty day', $view['day']->vars['placeholder']);
    }

    public function testPassHtml5TypeIfSingleTextAndHtml5Format()
    {
        $form = $this->factory->create('date', null, array(
            'widget' => 'single_text',
        ));

        $view = $form->createView();
        $this->assertSame('date', $view->vars['type']);
    }

    public function testDontPassHtml5TypeIfHtml5NotAllowed()
    {
        $form = $this->factory->create('date', null, array(
            'widget' => 'single_text',
            'html5' => false,
        ));

        $view = $form->createView();
        $this->assertFalse(isset($view->vars['type']));
    }

    public function testDontPassHtml5TypeIfNotHtml5Format()
    {
        $form = $this->factory->create('date', null, array(
            'widget' => 'single_text',
            'format' => \IntlDateFormatter::MEDIUM,
        ));

        $view = $form->createView();
        $this->assertFalse(isset($view->vars['type']));
    }

    public function testDontPassHtml5TypeIfNotSingleText()
    {
        $form = $this->factory->create('date', null, array(
            'widget' => 'text',
        ));

        $view = $form->createView();
        $this->assertFalse(isset($view->vars['type']));
    }

    public function provideCompoundWidgets()
    {
        return array(
            array('text'),
            array('choice'),
        );
    }

    /**
     * @dataProvider provideCompoundWidgets
     */
    public function testYearErrorsBubbleUp($widget)
    {
        $error = new FormError('Invalid!');
        $form = $this->factory->create('date', null, array(
            'widget' => $widget,
        ));
        $form['year']->addError($error);

        $this->assertSame(array(), iterator_to_array($form['year']->getErrors()));
        $this->assertSame(array($error), iterator_to_array($form->getErrors()));
    }

    /**
     * @dataProvider provideCompoundWidgets
     */
    public function testMonthErrorsBubbleUp($widget)
    {
        $error = new FormError('Invalid!');
        $form = $this->factory->create('date', null, array(
            'widget' => $widget,
        ));
        $form['month']->addError($error);

        $this->assertSame(array(), iterator_to_array($form['month']->getErrors()));
        $this->assertSame(array($error), iterator_to_array($form->getErrors()));
    }

    /**
     * @dataProvider provideCompoundWidgets
     */
    public function testDayErrorsBubbleUp($widget)
    {
        $error = new FormError('Invalid!');
        $form = $this->factory->create('date', null, array(
            'widget' => $widget,
        ));
        $form['day']->addError($error);

        $this->assertSame(array(), iterator_to_array($form['day']->getErrors()));
        $this->assertSame(array($error), iterator_to_array($form->getErrors()));
    }

    public function testYearsFor32BitsMachines()
    {
        if (4 !== PHP_INT_SIZE) {
            $this->markTestSkipped(
                'PHP must be compiled in 32 bit mode to run this test');
        }

        $form = $this->factory->create('date', null, array(
            'years' => range(1900, 2040),
        ));

        $view = $form->createView();

        $listChoices = array();
        foreach (range(1902, 2037) as $y) {
            $listChoices[] = new ChoiceView($y, $y, $y);
        }

        $this->assertEquals($listChoices, $view['year']->vars['choices']);
    }
}


text:
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models

class Migration(SchemaMigration):

    def forwards(self, orm):

        # Deleting field 'Post.tweeter_id'
        db.delete_column('posts_post', 'tweeter_id')

        # Deleting field 'Post.tweeter_profile_image'
        db.delete_column('posts_post', 'tweeter_profile_image')

        # Deleting field 'Post.tweeter_name'
        db.delete_column('posts_post', 'tweeter_name')

    def backwards(self, orm):

        # Adding field 'Post.tweeter_id'
        db.add_column('posts_post', 'tweeter_id', self.gf('django.db.models.fields.BigIntegerField')(null=True, blank=True), keep_default=False)

        # Adding field 'Post.tweeter_profile_image'
        db.add_column('posts_post', 'tweeter_profile_image', self.gf('django.db.models.fields.URLField')(max_length=200, null=True, blank=True), keep_default=False)

        # Adding field 'Post.tweeter_name'
        db.add_column('posts_post', 'tweeter_name', self.gf('django.db.models.fields.CharField')(max_length=100, null=True, blank=True), keep_default=False)

    models = {
        'auth.group': {
            'Meta': {'object_name': 'Group'},
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
            'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
        },
        'auth.permission': {
            'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
            'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
        },
        'auth.user': {
            'Meta': {'object_name': 'User'},
            'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
            'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
            'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
            'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
            'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
            'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
            'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
            'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
            'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
        },
        'beers.beer': {
            'Meta': {'object_name': 'Beer'},
            'brewery': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['beers.Brewery']"}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
            'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '50', 'db_index': 'True'}),
            'type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['beers.BeerType']", 'null': 'True', 'blank': 'True'})
        },
        'beers.beertype': {
            'Meta': {'object_name': 'BeerType'},
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
            'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '50', 'db_index': 'True'})
        },
        'beers.brewery': {
            'Meta': {'object_name': 'Brewery'},
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
            'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '50', 'db_index': 'True'})
        },
        'contenttypes.contenttype': {
            'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
            'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
        },
        'posts.post': {
            'Meta': {'ordering': "['-pub_date']", 'object_name': 'Post'},
            'author': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'null': 'True', 'blank': 'True'}),
            'beer': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['beers.Beer']", 'null': 'True', 'blank': 'True'}),
            'content': ('django.db.models.fields.TextField', [], {}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'live': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
            'pub_date': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
            'tweet_id': ('django.db.models.fields.BigIntegerField', [], {'null': 'True', 'blank': 'True'})
        }
    }

    complete_apps = ['posts']


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ICameraService.cs" company="Catel development team">
//   Copyright (c) 2008 - 2015 Catel development team. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

#pragma warning disable 3021 // 'type' does not need a CLSCompliant attribute because the assembly does not have a CLSCompliant attribute

namespace Catel.Services
{
    using System;
    using System.Collections.Generic;

#if XAMARIN
    using System.Drawing;
#elif NETFX_CORE
    using global::Windows.Foundation;
#else
    using System.Windows;
#endif

    /// <summary>
    /// Defines the operating mode of the camera flash.
    /// </summary>
    [Flags]
    public enum FlashMode
    {
        /// <summary>
        /// The camera flash is enabled.
        /// </summary>
        On = 1,

        /// <summary>
        /// The camera flash is disabled.
        /// </summary>
        Off = 2,

        /// <summary>
        /// The camera flash is in auto mode.
        /// </summary>
        Auto = 4,

        /// <summary>
        /// The camera flash is in red-eye reduction mode.
        /// </summary>
        RedEyeReduction = 8
    }

    /// <summary>
    /// Specifies the general location of the camera on the device.
    /// </summary>
    [Flags]
    public enum CameraType
    {
        /// <summary>
        /// The camera is located on the back of the device.
        /// </summary>
        Primary = 1,

        /// <summary>
        /// The camera is located on the front of the device.
        /// </summary>
        FrontFacing = 2
    }

    /// <summary>
    /// Interface for retrieving the camera information.
    /// </summary>
    [CLSCompliant(false)]
    public interface ICameraService
    {
        #region Properties
        /// <summary>
        /// Gets the available resolutions.
        /// </summary>
        /// <value>The available resolutions.</value>
        IEnumerable<Size> AvailableResolutions { get; }

        /// <summary>
        /// Gets or sets the flash mode. Unsupported flash modes silently default to <see cref="Catel.Services.FlashMode.Off"/>.
        /// </summary>
        /// <value>The flash mode.</value>
        FlashMode FlashMode { get; set; }

        /// <summary>
        /// Gets the type of the camera.
        /// </summary>
        /// <value>The type of the camera.</value>
        CameraType CameraType { get; }

        /// <summary>
        /// Gets a value indicating whether the camera can programmatically auto focus on a specific point in the viewfinder.
        /// </summary>
        /// <value>
        /// 	<c>true</c> if the camera can programmatically auto focus on a specific point in the viewfinder; otherwise, <c>false</c>.
        /// </value>
        bool IsFocusAtPointSupported { get; }

        /// <summary>
        /// Gets a value indicating whether the camera can be auto-focused programmatically.
        /// </summary>
        /// <value>
        /// 	<c>true</c> if the camera can be auto-focused programmatically; otherwise, <c>false</c>.
        /// </value>
        bool IsFocusSupported { get;}

        /// <summary>
        /// Gets the number of degrees that the viewfind brush needs to be rotated clockwise to align with the camera sensor.
        /// </summary>
        /// <value>The number of degrees that the viewfinder brush needs to be rotated clockwise to align with the camera sensor.</value>
        double Orientation { get; }

        /// <summary>
        /// Gets the preview resolution of the images.
        /// </summary>
        /// <value>The preview resolution.</value>
        [CLSCompliant(false)]
        Size PreviewResolution { get; }

        /// <summary>
        /// Gets or sets the resolution of the actual images.
        /// </summary>
        /// <value>The resolution.</value>
        [CLSCompliant(false)]
        Size Resolution { get; set; }

        ///// <summary>
        ///// Gets the YCbCr pixel layout of the camera preview buffer.
        ///// </summary>
        ///// <value>The YCbCr pixel layout of the camera.</value>
        //YCbCrPixelLayout YCbCrPixelLayout { get; }
        // TODO: Support YCbCr pixel layout
        #endregion

        #region Events
        /// <summary>
        /// Occurs when the camera has been initialized.
        /// </summary>
        event EventHandler<CameraOperationCompletedEventArgs> Initialized;

        /// <summary>
        /// Occurs when the focus operation is completed.
        /// </summary>
        event EventHandler<CameraOperationCompletedEventArgs> AutoFocusCompleted;

        /// <summary>
        /// Occurs when the capture sequence has started.
        /// </summary>
        event EventHandler CaptureStarted;

        /// <summary>
        /// Occurs when a thumbnail image is available.
        /// </summary>
        event EventHandler<ContentReadyEventArgs> CaptureThumbnailAvailable;

        /// <summary>
        /// Occurs when an image is available.
        /// </summary>
        event EventHandler<ContentReadyEventArgs> CaptureImageAvailable;

        /// <summary>
        /// Occurs when the capture sequence is complete.
        /// </summary>
        event EventHandler<CameraOperationCompletedEventArgs> CaptureCompleted;
        #endregion

        #region Methods
        /// <summary>
        /// Starts the camera service so it's retrieving data.
        /// </summary>
        void Start();

        /// <summary>
        /// Starts the camera service for a specific camera type so it's retrieving data.
        /// </summary>
        /// <param name="cameraType">Type of the camera.</param>
        void Start(CameraType cameraType);

        /// <summary>
        /// Stops the camera service so it's no longer retrieving data.
        /// </summary>
        void Stop();

        /// <summary>
        /// Starts a camera auto focus operation.
        /// </summary>
        void Focus();

        /// <summary>
        /// Starts a camera auto focus operation on a specific point in the viewfinder, for those devices that support it.
        /// </summary>
        /// <param name="x">The horizontal location in the viewfinder; a value between 0 (left) and 1.0 (right).</param>
        /// <param name="y">The vertical location in the viewfinder; a value between 0 (top) and 1.0 (bottom).</param>
        void FocusAtPoint(double x, double y);

        /// <summary>
        /// Cancels the current camera auto focus operation.
        /// </summary>
        void CancelFocus();

        /// <summary>
        /// Initiates a full-resolution capture of the current image displayed in the viewfinder
        /// </summary>
        void CaptureImage();

        /// <summary>
        /// Determines whether a particular camera type is supported on the device.
        /// </summary>
        /// <param name="type">The type.</param>
        /// <returns>
        /// 	<c>true</c> if the specified camera type is supported; otherwise, <c>false</c>.
        /// </returns>
        bool IsCameraTypeSupported(CameraType type);

        /// <summary>
        /// Determines whether a particular flash mode is supported on the device.
        /// </summary>
        /// <param name="mode">The mode.</param>
        /// <returns>
        /// 	<c>true</c> if the specified flash mode is supported; otherwise, <c>false</c>.
        /// </returns>
        bool IsFlashModeSupported(FlashMode mode);

        /// <summary>
        /// Copies the current viewfinder ARGB frame into a buffer for further manipulation.
        /// </summary>
        /// <param name="pixelData">The ARGB pixel data.</param>
        void GetPreviewBufferArgb32(int[] pixelData);

        /// <summary>
        /// Copies the luminance data for the current viewfinder frame into a buffer for further manipulation.
        /// </summary>
        /// <param name="pixelData">The YCrCb pixel data.</param>
        void GetPreviewBufferY(byte[] pixelData);

        /// <summary>
        /// Copies the current viewfinder frame into a buffer for further manipulation.
        /// </summary>
        /// <param name="pixelData">The pixel data.</param>
        void GetPreviewBufferYCbCr(byte[] pixelData);
        #endregion
    }
}


text:
<?php

namespace Notamedia\ConsoleJedi\Iblock\Command;

use Notamedia\ConsoleJedi\Application\Application;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Filesystem\Filesystem;
use Bitrix\Main\SiteTable;
use Bitrix\Iblock\TypeTable;
use Bitrix\Iblock\IblockTable;

/**
 * Trait checks and sets import/export parameters information block
 */
trait MigrationCommandTrait
{
    /**
     * Errors check parameters
     *
     * @var array
     */
    protected $errors = [];

    /**
     * Information block sites
     *
     * @var array
     */
    protected $sites = [];

    /**
     * Information block type
     *
     * @var string
     */
    protected $type = '';

    /**
     * Information blocks
     *
     * @var array
     */
    protected $iblocks = [];

    /**
     * Directory with file(s)
     *
     * @var string
     */
    protected $dir;

    /**
     * Extension file(s)
     *
     * @var string
     */
    protected $extension = '.xml';

    /**
     * Check argument directory and set $this->dir
     *
     * @param InputInterface $input
     */
    protected function setDir(InputInterface $input)
    {
        $app = new Application();
        $filesystem = new Filesystem();
        $dir = $input->getArgument('dir');

        if (!$dir) {
            $dir = $app->getRoot();
        } elseif (!$filesystem->isAbsolutePath($dir)) {
            $dir = $app->getRoot() . DIRECTORY_SEPARATOR . $dir;
        }
        $dir = rtrim($dir, DIRECTORY_SEPARATOR);

        if (!$filesystem->exists($dir)) {
            $this->errors[] = "Directory $dir not found";
        }

        $this->dir = $dir;
    }

    /**
     * Check arguments type and code, set $this->iblocks
     *
     * @param InputInterface $input
     */
    protected function setIblocks(InputInterface $input)
    {
        $iblocks = IblockTable::query()
            ->setFilter([
                'IBLOCK_TYPE_ID' => $input->getArgument('type'),
                'CODE' => $input->getArgument('code')
            ])
            ->setSelect(['ID', 'CODE'])
            ->exec();

        if ($iblocks->getSelectedRowsCount() <= 0) {
            $this->errors[] = 'Iblock(s) not found';
        }

        $this->iblocks = $iblocks->fetchAll();
    }

    /**
     * Check argument type and set $this->type
     *
     * @param InputInterface $input
     */
    protected function setType(InputInterface $input)
    {
        $type = TypeTable::query()
            ->setFilter([
                'ID' => $input->getArgument('type'),
            ])
            ->setSelect(['ID'])
            ->exec();

        if ($type->getSelectedRowsCount() <= 0) {
            $this->errors[] = 'Type not found';
        }

        $this->type = $type->fetch()['ID'];
    }

    /**
     * Check argument sites and set $this->sites
     *
     * @param InputInterface $input
     */
    protected function setSites(InputInterface $input)
    {
        $sites = SiteTable::query()
            ->setFilter([
                'LID' => $input->getArgument('sites'),
            ])
            ->setSelect(['LID'])
            ->exec();

        if ($sites->getSelectedRowsCount() <= 0) {
            $this->errors[] = 'Sites not found';
        }

        $this->sites = $sites->fetchAll();
    }
}


text:
<?xml version='1.0' encoding='UTF-8'?>
<resources>
  <string name="openpgp_list_preference_none">Brez</string>
  <string name="openpgp_install_openkeychain_via">Namesti OpenKeychain prek %s</string>
</resources>


text:
// Copyright (c) DotSpatial Team. All rights reserved.
// Licensed under the MIT license. See License.txt file in the project root for full license information.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using GeoAPI.Geometries;
using NetTopologySuite.Algorithm;

namespace DotSpatial.Data
{
    /// <summary>
    /// This class is strictly the vector access code. This does not handle
    /// the attributes, which must be handled independently.
    /// </summary>
    public class PolygonShapefileFeatureSource : ShapefileFeatureSource
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="PolygonShapefileFeatureSource"/> class from the specified file.
        /// </summary>
        /// <param name="fileName">The fileName to work with.</param>
        public PolygonShapefileFeatureSource(string fileName)
            : base(fileName)
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="PolygonShapefileFeatureSource"/> class from the specified file and builds spatial index if requested.
        /// </summary>
        /// <param name="fileName">The fileName to work with.</param>
        /// <param name="useSpatialIndexing">Indicates whether the spatial index should be build.</param>
        /// <param name="trackDeletedRows">Indicates whether deleted records should be tracked.</param>
        public PolygonShapefileFeatureSource(string fileName, bool useSpatialIndexing, bool trackDeletedRows)
            : base(fileName, useSpatialIndexing, trackDeletedRows)
        {
        }

        /// <inheritdoc />
        public override FeatureType FeatureType => FeatureType.Polygon;

        /// <inheritdoc />
        public override ShapeType ShapeType => ShapeType.Polygon;

        /// <inheritdoc />
        public override ShapeType ShapeTypeM => ShapeType.PolygonM;

        /// <inheritdoc />
        public override ShapeType ShapeTypeZ => ShapeType.PolygonZ;

        /// <inheritdoc />
        public override IShapeSource CreateShapeSource()
        {
            return new PolygonShapefileShapeSource(Filename, Quadtree, null);
        }

        /// <inheritdoc />
        public override void UpdateExtents()
        {
            UpdateExtents(new PolygonShapefileShapeSource(Filename));
        }

        /// <inheritdoc/>
        public override IFeatureSet Select(string filterExpression, Envelope envelope, ref int startIndex, int maxCount)
        {
            return Select(new PolygonShapefileShapeSource(Filename, Quadtree, null), filterExpression, envelope, ref startIndex, maxCount);
        }

        /// <inheritdoc/>
        public override void SearchAndModifyAttributes(Envelope envelope, int chunkSize, FeatureSourceRowEditEvent rowCallback)
        {
            SearchAndModifyAttributes(new PolygonShapefileShapeSource(Filename, Quadtree, null), envelope, chunkSize, rowCallback);
        }

        /// <inheritdoc/>
        protected override void AppendGeometry(ShapefileHeader header, IGeometry feature, int numFeatures)
        {
            FileInfo fi = new FileInfo(Filename);
            int offset = Convert.ToInt32(fi.Length / 2);

            FileStream shpStream = new FileStream(Filename, FileMode.Append, FileAccess.Write, FileShare.None, 10000);
            FileStream shxStream = new FileStream(header.ShxFilename, FileMode.Append, FileAccess.Write, FileShare.None, 100);

            List<int> parts = new List<int>();

            List<Coordinate> points = new List<Coordinate>();
            int contentLength = 22;
            for (int iPart = 0; iPart < feature.NumGeometries; iPart++)
            {
                parts.Add(points.Count);
                IPolygon pg = feature.GetGeometryN(iPart) as IPolygon;
                if (pg == null) continue;
                var bl = pg.Shell;
                IEnumerable<Coordinate> coords = bl.Coordinates;

                if (CGAlgorithms.IsCCW(bl.Coordinates))
                {
                    // Exterior rings need to be clockwise
                    coords = coords.Reverse();
                }

                points.AddRange(coords);
                foreach (ILineString hole in pg.Holes)
                {
                    parts.Add(points.Count);
                    IEnumerable<Coordinate> holeCoords = hole.Coordinates;
                    if (!CGAlgorithms.IsCCW(hole.Coordinates))
                    {
                        // Interior rings need to be counter-clockwise
                        holeCoords = holeCoords.Reverse();
                    }

                    points.AddRange(holeCoords);
                }
            }

            contentLength += 2 * parts.Count;
            if (header.ShapeType == ShapeType.Polygon)
            {
                contentLength += points.Count * 8;
            }
            else if (header.ShapeType == ShapeType.PolygonM)
            {
                contentLength += 8; // mmin mmax
                contentLength += points.Count * 12; // x, y, m
            }
            else if (header.ShapeType == ShapeType.PolygonZ)
            {
                contentLength += 16; // mmin, mmax, zmin, zmax
                contentLength += points.Count * 16; // x, y, m, z
            }

            ////                                              Index File
            //                                                 ---------------------------------------------------------
            //                                                 Position     Value               Type        Number      Byte Order
            //                                                 ---------------------------------------------------------
            shxStream.WriteBe(offset);                         // Byte 0     Offset             Integer     1           Big
            shxStream.WriteBe(contentLength);                  // Byte 4    Content Length      Integer     1           Big
            shxStream.Flush();
            shxStream.Close();
            ////                                                 X Y Poly Lines
            //                                                 ---------------------------------------------------------
            //                                                 Position     Value               Type        Number      Byte Order
            //                                                 ---------------------------------------------------------
            shpStream.WriteBe(numFeatures);                    // Byte 0       Record Number       Integer     1           Big
            shpStream.WriteBe(contentLength);                  // Byte 4       Content Length      Integer     1           Big
            shpStream.WriteLe((int)header.ShapeType);          // Byte 8       Shape Type 3        Integer     1           Little
            if (header.ShapeType == ShapeType.NullShape)
            {
                return;
            }

            shpStream.WriteLe(feature.EnvelopeInternal.MinX);  // Byte 12      Xmin                Double      1           Little
            shpStream.WriteLe(feature.EnvelopeInternal.MinY);  // Byte 20      Ymin                Double      1           Little
            shpStream.WriteLe(feature.EnvelopeInternal.MaxX);  // Byte 28      Xmax                Double      1           Little
            shpStream.WriteLe(feature.EnvelopeInternal.MaxY);  // Byte 36      Ymax                Double      1           Little
            shpStream.WriteLe(parts.Count);                    // Byte 44      NumParts            Integer     1           Little
            shpStream.WriteLe(points.Count);                   // Byte 48      NumPoints           Integer     1           Little

            foreach (int iPart in parts)
            {
                shpStream.WriteLe(iPart);                      // Byte 52      Parts               Integer     NumParts    Little
            }

            double[] xyVals = new double[points.Count * 2];
            for (var i = 0; i < points.Count; i++)
            {
                xyVals[i * 2] = points[i].X;
                xyVals[i * 2 + 1] = points[i].Y;
            }

            shpStream.WriteLe(xyVals, 0, 2 * points.Count);

            if (header.ShapeType == ShapeType.PolygonZ)
            {
                shpStream.WriteLe(feature.EnvelopeInternal.Minimum.Z);
                shpStream.WriteLe(feature.EnvelopeInternal.Maximum.Z);
                double[] zVals = new double[points.Count];
                for (int ipoint = 0; ipoint < points.Count; ipoint++)
                {
                    zVals[ipoint] = points[ipoint].Z;
                }

                shpStream.WriteLe(zVals, 0, points.Count);
            }

            if (header.ShapeType == ShapeType.PolygonM || header.ShapeType == ShapeType.PolygonZ)
            {
                if (feature.EnvelopeInternal == null)
                {
                    shpStream.WriteLe(0.0);
                    shpStream.WriteLe(0.0);
                }
                else
                {
                    shpStream.WriteLe(feature.EnvelopeInternal.Minimum.M);
                    shpStream.WriteLe(feature.EnvelopeInternal.Maximum.M);
                }

                double[] mVals = new double[points.Count];
                for (int ipoint = 0; ipoint < points.Count; ipoint++)
                {
                    mVals[ipoint] = points[ipoint].M;
                }

                shpStream.WriteLe(mVals, 0, points.Count);
            }

            shpStream.Flush();
            shpStream.Close();
            offset += contentLength;
            Shapefile.WriteFileLength(Filename, offset + 4); // Add 4 for the record header
            Shapefile.WriteFileLength(header.ShxFilename, 50 + numFeatures * 4);
        }
    }
}


text:
using System;

namespace Adaptive.Arp.Api
{
     /**
        Enumeration INetworkReachabilityCallbackWarning
     */
     public enum INetworkReachabilityCallbackWarning {

          IncorrectScheme,
          NotSecure,
          NotTrusted,
          Redirected,
          NotRegisteredService,
          Unknown

     }
}


text:
#include <stdlib.h>
#include <string.h>

#include "cli.h"

#include "fio.h"
#include "fio_cli.h"
#include "http.h"
#include "redis_engine.h"

static void redis_cleanup(void *e_) {
  redis_engine_destroy(e_);
  FIO_LOG_DEBUG("Cleaned up redis engine object.");
  FIO_PUBSUB_DEFAULT = FIO_PUBSUB_CLUSTER;
}

void initialize_cli(int argc, char const *argv[]) {
  /*     ****  Command line arguments ****     */
  fio_cli_start(
      argc, argv, 0, 0, NULL, FIO_CLI_PRINT_HEADER("Address binding:"),
      FIO_CLI_INT("-port -p port number to listen to. defaults port 3000"),
      FIO_CLI_STRING("-bind -b address to listen to. defaults any available."),
      FIO_CLI_PRINT_HEADER("Concurrency:"),
      FIO_CLI_INT("-workers -w number of processes to use."),
      FIO_CLI_INT("-threads -t number of threads per process."),
      FIO_CLI_PRINT_HEADER("HTTP Server:"),
      FIO_CLI_STRING("-public -www public folder, for static file service."),
      FIO_CLI_INT(
          "-keep-alive -k HTTP keep-alive timeout (0..255). default: ~5s"),
      FIO_CLI_INT("-max-body -maxbd HTTP upload limit. default: ~50Mb"),
      FIO_CLI_BOOL("-log -v request verbosity (logging)."),
      FIO_CLI_PRINT_HEADER("WebSocket Server:"),
      FIO_CLI_INT("-ping websocket ping interval (0..255). default: ~40s"),
      FIO_CLI_INT("-max-msg -maxms incoming websocket message size limit. "
                  "default: ~250Kb"),
      FIO_CLI_PRINT_HEADER("Redis support:"),
      FIO_CLI_STRING("-redis -r an optional Redis URL server address."),
      FIO_CLI_PRINT("\t\ti.e.: redis://user:password@localhost:6379/"));

  /* Test and set any default options */
  if (!fio_cli_get("-b")) {
    char *tmp = getenv("ADDRESS");
    if (tmp) {
      fio_cli_set("-b", tmp);
      fio_cli_set("-bind", tmp);
    }
  }
  if (!fio_cli_get("-p")) {
    /* Test environment as well and make sure address is missing */
    char *tmp = getenv("PORT");
    if (!tmp && !fio_cli_get("-b"))
      tmp = "3000";
    /* Set default (unlike cmd line arguments, aliases are manually set) */
    fio_cli_set("-p", tmp);
    fio_cli_set("-port", tmp);
  }
  if (!fio_cli_get("-public")) {
    char *tmp = getenv("HTTP_PUBLIC_FOLDER");
    if (tmp) {
      fio_cli_set("-public", tmp);
      fio_cli_set("-www", tmp);
    }
  }

  if (!fio_cli_get("-redis")) {
    char *tmp = getenv("REDIS_URL");
    if (tmp) {
      fio_cli_set("-redis", tmp);
      fio_cli_set("-r", tmp);
    }
  }

  if (fio_cli_get("-redis") && strlen(fio_cli_get("-redis"))) {
    FIO_LOG_INFO("* Initializing Redis connection to %s\n",
                 fio_cli_get("-redis"));
    http_url_s info =
        http_url_parse(fio_cli_get("-redis"), strlen(fio_cli_get("-redis")));
    fio_pubsub_engine_s *e =
        redis_engine_create(.address = info.host, .port = info.port,
                            .auth = info.password);
    if (e) {
      fio_state_callback_add(FIO_CALL_ON_FINISH, redis_cleanup, e);
      FIO_PUBSUB_DEFAULT = e;
    } else {
      FIO_LOG_ERROR("Failed to create redis engine object.");
    }
  }
}

void free_cli(void) { fio_cli_end(); }