text:
<?xml version="1.0" encoding="UTF-8"?>

<sect1 id="zend.view.scripts">
    <title>View Scripts</title>

    <para>
        Once your controller has assigned variables and called <methodname>render()</methodname>,
        <classname>Zend_View</classname> then includes the requested view script and executes
        it "inside" the scope of the <classname>Zend_View</classname> instance. Therefore,
        in your view scripts, references to $this actually point to the
        <classname>Zend_View</classname> instance itself.
    </para>

    <para>
        Variables assigned to the view from the controller are referred
        to as instance properties. For example, if the controller were
        to assign a variable 'something', you would refer to it as
        $this->something in the view script. (This allows you to keep
        track of which values were assigned to the script, and which are
        internal to the script itself.)
    </para>

    <para>
        By way of reminder, here is the example view script from the
        <classname>Zend_View</classname> introduction.
    </para>

    <programlisting language="php"><![CDATA[
<?php if ($this->books): ?>

            Author
            Title

        <?php foreach ($this->books as $key => $val): ?>

            <?php echo $this->escape($val['author']) ?>
            <?php echo $this->escape($val['title']) ?>

        <?php endforeach; ?>

<?php else: ?>

There are no books to display.

<?php endif;?>
]]></programlisting>

    <sect2 id="zend.view.scripts.escaping">
        <title>Escaping Output</title>

        <para>
            One of the most important tasks to perform in a view script
            is to make sure that output is escaped properly; among other
            things, this helps to avoid cross-site scripting attacks.
            Unless you are using a function, method, or helper that does
            escaping on its own, you should always escape variables when
            you output them.
        </para>

        <para>
            <classname>Zend_View</classname> comes with a method called escape() that does such
            escaping for you.
        </para>

        <programlisting language="php"><![CDATA[
// bad view-script practice:
echo $this->variable;

// good view-script practice:
echo $this->escape($this->variable);
]]></programlisting>

        <para>
            By default, the escape() method uses the <acronym>PHP</acronym> htmlspecialchars()
            function for escaping. However, depending on your environment,
            you may wish for escaping to occur in a different way. Use the
            setEscape() method at the controller level to tell <classname>Zend_View</classname>
            what escaping callback to use.
        </para>

        <programlisting language="php"><![CDATA[
// create a Zend_View instance
$view = new Zend_View();

// tell it to use htmlentities as the escaping callback
$view->setEscape('htmlentities');

// or tell it to use a static class method as the callback
$view->setEscape(array('SomeClass', 'methodName'));

// or even an instance method
$obj = new SomeClass();
$view->setEscape(array($obj, 'methodName'));

// and then render your view
echo $view->render(...);
]]></programlisting>

        <para>
            The callback function or method should take the value to be
            escaped as its first parameter, and all other parameters should
            be optional.
        </para>
    </sect2>

    <sect2 id="zend.view.scripts.templates">
        <title>Using Alternate Template Systems</title>

        <para>
            Although <acronym>PHP</acronym> is itself a powerful template system, many developers
            feel it is too powerful or complex for their template designers and
            will want to use an alternate template engine. <classname>Zend_View</classname> provides
            two mechanisms for doing so, the first through view scripts, the
            second by implementing <classname>Zend_View_Interface</classname>.
        </para>

        <sect3 id="zend.view.scripts.templates.scripts">
            <title>Template Systems Using View Scripts</title>

            <para>
                A view script may be used to instantiate and manipulate a
                separate template object, such as a PHPLIB-style template. The
                view script for that kind of activity might look something like
                this:
            </para>

            <programlisting language="php"><![CDATA[
include_once 'template.inc';
$tpl = new Template();

if ($this->books) {
    $tpl->setFile(array(
        "booklist" => "booklist.tpl",
        "eachbook" => "eachbook.tpl",
    ));

    foreach ($this->books as $key => $val) {
        $tpl->set_var('author', $this->escape($val['author']);
        $tpl->set_var('title', $this->escape($val['title']);
        $tpl->parse("books", "eachbook", true);
    }

    $tpl->pparse("output", "booklist");
} else {
    $tpl->setFile("nobooks", "nobooks.tpl")
    $tpl->pparse("output", "nobooks");
}
]]></programlisting>

            <para>
                These would be the related template files:
            </para>

            <programlisting language="html"><![CDATA[

        Author
        Title

    {books}

        {author}
        {title}

There are no books to display.

]]></programlisting>
        </sect3>

        <sect3 id="zend.view.scripts.templates.interface">
            <title>Template Systems Using Zend_View_Interface</title>

            <para>
                Some may find it easier to simply provide a
                <classname>Zend_View</classname>-compatible template engine.
                <classname>Zend_View_Interface</classname> defines the minimum interface needed for
                compatability:
            </para>

            <programlisting language="php"><![CDATA[
/**
 * Return the actual template engine object
 */
public function getEngine();

/**
 * Set the path to view scripts/templates
 */
public function setScriptPath($path);

/**
 * Set a base path to all view resources
 */
public function setBasePath($path, $prefix = 'Zend_View');

/**
 * Add an additional base path to view resources
 */
public function addBasePath($path, $prefix = 'Zend_View');

/**
 * Retrieve the current script paths
 */
public function getScriptPaths();

/**
 * Overloading methods for assigning template variables as object
 * properties
 */
public function __set($key, $value);
public function __isset($key);
public function __unset($key);

/**
 * Manual assignment of template variables, or ability to assign
 * multiple variables en masse.
 */
public function assign($spec, $value = null);

/**
 * Unset all assigned template variables
 */
public function clearVars();

/**
 * Render the template named $name
 */
public function render($name);
]]></programlisting>

            <para>
                Using this interface, it becomes relatively easy to wrap a
                third-party template engine as a <classname>Zend_View</classname>-compatible class.
                As an example, the following is one potential wrapper for Smarty:
            </para>

            <programlisting language="php"><![CDATA[
class Zend_View_Smarty implements Zend_View_Interface
{
    /**
     * Smarty object
     * @var Smarty
     */
    protected $_smarty;

    /**
     * Constructor
     *
     * @param string $tmplPath
     * @param array $extraParams
     * @return void
     */
    public function __construct($tmplPath = null, $extraParams = array())
    {
        $this->_smarty = new Smarty;

        if (null !== $tmplPath) {
            $this->setScriptPath($tmplPath);
        }

        foreach ($extraParams as $key => $value) {
            $this->_smarty->$key = $value;
        }
    }

    /**
     * Return the template engine object
     *
     * @return Smarty
     */
    public function getEngine()
    {
        return $this->_smarty;
    }

    /**
     * Set the path to the templates
     *
     * @param string $path The directory to set as the path.
     * @return void
     */
    public function setScriptPath($path)
    {
        if (is_readable($path)) {
            $this->_smarty->template_dir = $path;
            return;
        }

        throw new Exception('Invalid path provided');
    }

    /**
     * Retrieve the current template directory
     *
     * @return string
     */
    public function getScriptPaths()
    {
        return array($this->_smarty->template_dir);
    }

    /**
     * Alias for setScriptPath
     *
     * @param string $path
     * @param string $prefix Unused
     * @return void
     */
    public function setBasePath($path, $prefix = 'Zend_View')
    {
        return $this->setScriptPath($path);
    }

    /**
     * Alias for setScriptPath
     *
     * @param string $path
     * @param string $prefix Unused
     * @return void
     */
    public function addBasePath($path, $prefix = 'Zend_View')
    {
        return $this->setScriptPath($path);
    }

    /**
     * Assign a variable to the template
     *
     * @param string $key The variable name.
     * @param mixed $val The variable value.
     * @return void
     */
    public function __set($key, $val)
    {
        $this->_smarty->assign($key, $val);
    }

    /**
     * Allows testing with empty() and isset() to work
     *
     * @param string $key
     * @return boolean
     */
    public function __isset($key)
    {
        return (null !== $this->_smarty->get_template_vars($key));
    }

    /**
     * Allows unset() on object properties to work
     *
     * @param string $key
     * @return void
     */
    public function __unset($key)
    {
        $this->_smarty->clear_assign($key);
    }

    /**
     * Assign variables to the template
     *
     * Allows setting a specific key to the specified value, OR passing
     * an array of key => value pairs to set en masse.
     *
     * @see __set()
     * @param string|array $spec The assignment strategy to use (key or
     * array of key => value pairs)
     * @param mixed $value (Optional) If assigning a named variable,
     * use this as the value.
     * @return void
     */
    public function assign($spec, $value = null)
    {
        if (is_array($spec)) {
            $this->_smarty->assign($spec);
            return;
        }

        $this->_smarty->assign($spec, $value);
    }

    /**
     * Clear all assigned variables
     *
     * Clears all variables assigned to Zend_View either via
     * {@link assign()} or property overloading
     * ({@link __get()}/{@link __set()}).
     *
     * @return void
     */
    public function clearVars()
    {
        $this->_smarty->clear_all_assign();
    }

    /**
     * Processes a template and returns the output.
     *
     * @param string $name The template to process.
     * @return string The output.
     */
    public function render($name)
    {
        return $this->_smarty->fetch($name);
    }
}
]]></programlisting>

            <para>
                In this example, you would instantiate the
                <classname>Zend_View_Smarty</classname> class instead of
                <classname>Zend_View</classname>, and then use it in roughly the same
                fashion as <classname>Zend_View</classname>:
            </para>

            <programlisting language="php"><![CDATA[
//Example 1. In initView() of initializer.
$view = new Zend_View_Smarty('/path/to/templates');
$viewRenderer =
    Zend_Controller_Action_HelperBroker::getStaticHelper('ViewRenderer');
$viewRenderer->setView($view)
             ->setViewBasePathSpec($view->_smarty->template_dir)
             ->setViewScriptPathSpec(':controller/:action.:suffix')
             ->setViewScriptPathNoControllerSpec(':action.:suffix')
             ->setViewSuffix('tpl');

//Example 2. Usage in action controller remains the same...
class FooController extends Zend_Controller_Action
{
    public function barAction()
    {
        $this->view->book   = 'Zend PHP 5 Certification Study Guide';
        $this->view->author = 'Davey Shafik and Ben Ramsey'
    }
}

//Example 3. Initializing view in action controller
class FooController extends Zend_Controller_Action
{
    public function init()
    {
        $this->view   = new Zend_View_Smarty('/path/to/templates');
        $viewRenderer = $this->_helper->getHelper('viewRenderer');
        $viewRenderer->setView($this->view)
                     ->setViewBasePathSpec($view->_smarty->template_dir)
                     ->setViewScriptPathSpec(':controller/:action.:suffix')
                     ->setViewScriptPathNoControllerSpec(':action.:suffix')
                     ->setViewSuffix('tpl');
    }
]]></programlisting>
        </sect3>
    </sect2>
</sect1>


text:
package com.aerolitec.SMXL.ui.adapter;

import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.aerolitec.SMXL.R;
import com.aerolitec.SMXL.model.GarmentType;

import java.util.ArrayList;

/**
 * Created by stephaneL on 30/03/14.
 */
public class TypeGarmentAdapter extends ArrayAdapter<GarmentType> {

    private Context context;

    public TypeGarmentAdapter(Context context,int resource, ArrayList<GarmentType> garmentItems){
        super(context, resource , garmentItems);
        this.context = context;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null){
            LayoutInflater mInflater = (LayoutInflater)
                    context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
            convertView = mInflater.inflate(R.layout.item_garment_with_icon, null);
            holder = new ViewHolder();
            convertView.setTag(holder);
            holder.tvTypeGarment = (TextView) convertView.findViewById(R.id.textViewGarmentItemIcon);
            holder.ivIconGarment = (ImageView) convertView.findViewById(R.id.imageViewGarmentItemIcon);
            //holder.tvSex = (TextView) convertView.findViewById(R.id.tvSex);
        }
        else {
            holder = (ViewHolder) convertView.getTag();
        }

        GarmentType item = getItem(position);
        int tmp=context.getResources().getIdentifier(item.getType(), "string", context.getPackageName());
        holder.tvTypeGarment.setText(tmp);
        holder.ivIconGarment.setImageDrawable(context.getResources().getDrawable(item.getCategoryGarment().getIcon()));
        //holder.tvSex.setText(item.getSex());

        return convertView;
    }

    public static class ViewHolder {
        ImageView ivIconGarment;
        TextView tvTypeGarment;
        //TextView tvSex;
    }
}

redpajama_set_name: RedPajamaGithub


text:
CREATE TABLE Logs(
	Id int NOT NULL IDENTITY,
	LogDate datetime,
	MsgText varchar(300),
	CONSTRAINT PK_Logs_Id PRIMARY KEY (Id)
)

GO

-- 10M is too much for my laptop, i'm going with 1M
CREATE PROC usp_AddManyLogs
AS
DECLARE @counter int
SET @counter = 1;
WHILE(@counter < 1000000)
BEGIN
	DECLARE @Date datetime
	SET @Date =
	DATEADD(month, CONVERT(varbinary, newid()) % (50 * 12), getdate())
	INSERT INTO Logs (LogDate, MsgText)
	VALUES(@Date, 'LogText')
	SET @counter = @counter + 1;
END

GO

EXEC usp_AddManyLogs
-- 7 min and 20 sec to generate for 1M

CHECKPOINT; DBCC DROPCLEANBUFFERS; -- Empty the SQL Server cache

-- 01.Create a table in SQL Server with 10 000 000 log
-- 	entries (date + text). Search in the table by date range.
-- 	Check the speed (without caching).

SELECT l.LogDate
FROM Logs l
WHERE YEAR(l.LogDate) < 2012 AND YEAR(l.LogDate) > 2001
-- 2sec without cache

--02.Add an index to speed-up the search by date.
--	Test the search speed (after cleaning the cache).

CREATE INDEX IDX_Logs_LogDate ON Logs(LogDate)
DROP INDEX Logs.IDX_Logs_LogDate
--indexes created for 5sec.

SELECT l.LogDate
FROM Logs l
WHERE YEAR(l.LogDate) < 2012 AND YEAR(l.LogDate) > 2001
--1sec with cahe :D

--03.Add a full text index for the text column.
--	Try to search with and without the full-text index and compare the speed.

DROP INDEX Logs.IDX_Logs_LogDate
CREATE INDEX IDX_Logs_MsgText ON Logs(MsgText)
SELECT l.MsgText
FROM Logs l
WHERE YEAR(l.LogDate) < 2012 AND YEAR(l.LogDate) > 2001

-- create index - 8 sec

-- without cache - 2 sec
-- with cache - 1 sec


text:
title: "Pitch your script idea here"
    layout: default
    product: codescript
---

	            	Pitch your script idea @Codeville

	            		<emphasis class="bold">Hello!</emphasis>

	            		Thank you for pitching your idea. To publish your pitch you need to fill out a simple form. <emphasis class="bold">Thats it!</emphasis> All the formating and beautification will we taken care off.

	            		Fill out the fields below which represent different sections of the script. Once you submit the script to us, Codeville Team will publish it in few hours.

	            	<emphasis class="bold">Cheers!</emphasis>

                <form method="POST" action="https://vast-eyrie-2726.herokuapp.com/email" name="script-pitch" id="script-pitch" class="structured-form" enctype="multipart/form-data" validate>

                            Script Title

                            <input type="text" name="title" required data-validation-required-message="Please enter title of the script">

                                One liner that describes the script and should preferably be the script title.

                                Ex: Get live scores of a cricket match

                            Your Name

                            <input type="text" name="name" required data-validation-required-message="Please enter your display name">

                                This name will be displayed as Pitcher Name.

                                Ex: Arpit Bhayani

                            Website Link

                            <input type="text" name="link" required data-validation-required-message="Please enter your website address.">

                                Profile link: your web presence. Should be your website address or even your facebook profile link is cool!

                                Ex: http://facebook.com/itsmearpit

                            Email Address

                            <input type="email" name="email" required data-validation-required-message="Please enter your email address.">

                                Email address will be used for contact.

                			Script Description

                            <textarea name="intro" rows="5" required data-validation-required-message="Please enter script description here."></textarea>

                				In few lines describe what should the script perform. This short description will be used while publishing your pitch.

                		<input type="text" name="_gotcha" style="display:none" />
                    	<input type="hidden" name="_next" value="{{ site.url }}" />
                        <input type="hidden" name="type" value="PITCH" />

                        	<input type="submit" class="large_button" value="Submit"/>

                </form>


text:
<?xml version="1.0" encoding="UTF-8"?>

<recipeml version="0.5">
  <recipe>
    <head>
      <title>Basic Sourdough Starter</title>
      <categories>
        <cat>Bread</cat></categories>
      <yield>4</yield></head>
    <ingredients>
      <ing>
        <amt>
          <qty>1</qty>
          <unit>cup</unit></amt>
        <item>Water</item></ing>
      <ing>
        <amt>
          <qty>1</qty>
          <unit>tablespoon</unit></amt>
        <item>Sugar</item></ing>
      <ing>
        <amt>
          <qty>1</qty>
          <unit>cup</unit></amt>
        <item>Flour</item></ing>
      <ing>
        <amt>
          <qty>4</qty>
          <unit>tablespoons</unit></amt>
        <item>Commercial buttermilk</item></ing></ingredients>
    <directions>
      <step>    Sourdough starters can be purchased commercially or they can be started
  on your own. Your own might be more fun. One cup of water is mixed with 1
  tablespoon sugar, 1 cup flour, and 4 tablespoons commercial buttermilk. Mix
  all of this together and place it in a glass or stainless-steel bowl. Do
  not use aluminum. Cover this with a towel and allow to stand in a warm
  place for a few days, or until it has begun to ferment and has a wonderful
  sour smell. You might keep this on the top of the water heater or in your
  oven and leave the light on all the time. The starter should be the
  consistency of pancake batter and it can be covered and stored in the
  refrigerator. Use this as your starter in any of the recipes that follow.

    The old-timers claim that you can get a sourdough starter going by just
  mixing flour and water together and allowing it to sit in a warm place for
  several days. This may work, but it is not terribly reliable.

    HINT: ON STORING SOURDOUGH STARTER. When storing sourdough starter in the
  refrigerator, remember that it should be kept at around 42ø. If it is too
  cold, it will take a long time to come around again, to come back to life.
  Your refrigerator is probably colder than this, so perhaps you may want to
  store the starter in a very cool place.

  From <The Frugal Gourmet Cooks American>.  Downloaded from Glen's MM Recipe
  Archive, http://www.erols.com/hosey.

</step></directions></recipe></recipeml>


text:
package com.facebook.buck.js;

import com.facebook.buck.io.ProjectFilesystem;
import com.facebook.buck.shell.WorkerJobParams;
import com.facebook.buck.shell.WorkerShellStep;
import com.facebook.buck.shell.WorkerProcessPoolFactory;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;

import java.nio.file.Path;
import java.util.Optional;

public class ReactNativeBundleWorkerStep extends WorkerShellStep {

  public ReactNativeBundleWorkerStep(
      ProjectFilesystem filesystem,
      Path tmpDir,
      ImmutableList<String> jsPackagerCommand,
      Optional<String> additionalPackagerFlags,
      ReactNativePlatform platform,
      boolean isUnbundle,
      boolean isIndexedUnbundle,
      Path entryFile,
      boolean isDevMode,
      Path outputFile,
      Path resourcePath,
      Path sourceMapFile) {
    super(
        Optional.of(
            WorkerJobParams.of(
                filesystem.resolve(tmpDir),
                jsPackagerCommand,
                String.format(
                    "--platform %s%s",
                    platform.toString(),
                    additionalPackagerFlags.isPresent() ? " " + additionalPackagerFlags.get() : ""),
                ImmutableMap.of(),
                String.format(
                    "--command %s %s --entry-file %s --platform %s --dev %s --bundle-output %s " +
                        "--assets-dest %s --sourcemap-output %s",
                    isUnbundle ? "unbundle" : "bundle",
                    isIndexedUnbundle ? "--indexed-unbundle" : "",
                    entryFile.toString(),
                    platform.toString(),
                    isDevMode ? "true" : "false",
                    outputFile.toString(),
                    resourcePath.toString(),
                    sourceMapFile.toString()),
                1,
                Optional.empty(),
                Optional.empty())),
        Optional.empty(),
        Optional.empty(),
        new WorkerProcessPoolFactory(filesystem));
  }

  @Override
  public String getShortName() {
    return "react-native-bundle-worker";
  }
}


text:
require 'grpc'
require 'google/ads/google_ads/v12/services/ad_group_criterion_label_service_pb'

module Google
  module Ads
    module GoogleAds
      module V12
        module Services
          module AdGroupCriterionLabelService
            # Proto file describing the Ad Group Criterion Label service.
            #
            # Service to manage labels on ad group criteria.
            class Service

              include ::GRPC::GenericService

              self.marshal_class_method = :encode
              self.unmarshal_class_method = :decode
              self.service_name = 'google.ads.googleads.v12.services.AdGroupCriterionLabelService'

              # Creates and removes ad group criterion labels.
              # Operation statuses are returned.
              #
              # List of thrown errors:
              #   [AuthenticationError]()
              #   [AuthorizationError]()
              #   [DatabaseError]()
              #   [FieldError]()
              #   [HeaderError]()
              #   [InternalError]()
              #   [QuotaError]()
              #   [RequestError]()
              rpc :MutateAdGroupCriterionLabels, ::Google::Ads::GoogleAds::V12::Services::MutateAdGroupCriterionLabelsRequest, ::Google::Ads::GoogleAds::V12::Services::MutateAdGroupCriterionLabelsResponse
            end

            Stub = Service.rpc_stub_class
          end
        end
      end
    end
  end
end


text:
import CANNON from 'cannon';
import Ball from './objects/Ball';
import {Utils,} from './Utils';

const DEADZONE_DISTANCE = 5;

class Player {

  constructor(n, r, segments, color) {
    this.balls = [];
    this.position = new CANNON.Vec3();
    this.points = 0;
    this.scatter = 0;

    const d = 2*r;
    for (let i = 0; i < n; i++) {
      const ball = new Ball(r, segments, color);
      ball.position.set(d*Math.cos(Math.PI*(i/2))*Math.ceil(i/4), 0.1, 0.2 + d*Math.sin(Math.PI*(i/2))*Math.ceil(i/4));

      this.balls.push(ball);
    }
    this.update();
  }

  update() {
    let center = new CANNON.Vec3();
    for (const ball of this.balls) {
      center = center.vadd(ball.position);
    }
    center = center.scale(1/this.balls.length);
    this.position = center;

    // Remove balls too far from center, calculate max scatter
    let scatter = 0;
    for (const ball of this.balls) {
      const distance = this.position.distanceTo(ball.position);
      if (distance > DEADZONE_DISTANCE) {
        ball.markToBeRemoved();
      }
      if (distance > scatter) {
        scatter = distance;
      }
    }
    this.scatter = scatter;
  }

  addPoints(points) {
    this.points += points;
  }

  /**
   * Checks if given Object is in this.balls and removes it if found.
   * @param {Object} ball
   */
  removeBall(ball) {
    Utils.removeElementFromArray(ball, this.balls);
  }

}

export default Player;


text:
package com.knewton.titanik;

/**
 */
public interface TitanikEventConsumer {
    void consume(TitanikTransactionEvent titanikTransactionEvent);
}


text:
package org.basex.query.expr.path;

import static org.basex.query.QueryError.*;

import org.basex.query.*;
import org.basex.query.expr.*;
import org.basex.query.iter.*;
import org.basex.query.util.list.*;
import org.basex.query.value.*;
import org.basex.query.value.item.*;
import org.basex.query.value.node.*;
import org.basex.query.var.*;
import org.basex.util.*;
import org.basex.util.hash.*;

/**
 * Axis path expression.
 *
 * @author BaseX Team 2005-15, BSD License
 * @author Christian Gruen
 */
final class CachedPath extends AxisPath {
  /** Flag for result caching. */
  private boolean cache;

  /**
   * Constructor.
   * @param info input info
   * @param root root expression; can be a {@code null} reference
   * @param steps axis steps
   */
  CachedPath(final InputInfo info, final Expr root, final Expr... steps) {
    super(info, root, steps);
    // analyze if result set can be cached: no root node, no variables...
    cache = root != null && !hasFreeVars();
  }

  @Override
  public BasicNodeIter iter(final QueryContext qc) throws QueryException {
    final long cp = qc.pos, cs = qc.size;
    final Value cv = qc.value, r = root != null ? qc.value(root) : cv;
    try {
      final ANodeList list = new ANodeList().check();
      if(r != null) {
        final Iter ir = qc.iter(r);
        for(Item it; (it = ir.next()) != null;) {
          // ensure that root only returns nodes
          if(root != null && !(it instanceof ANode))
            throw PATHNODE_X_X_X.get(info, steps[0], it.type, it);
          qc.value = it;
          iter(0, list, qc);
        }
      } else {
        qc.value = null;
        iter(0, list, qc);
      }
      return list.iter();
    } finally {
      qc.value = cv;
      qc.size = cs;
      qc.pos = cp;
    }
  }

  /**
   * Recursive step iterator.
   * @param step current step
   * @param list node cache
   * @param qc query context
   * @throws QueryException query exception
   */
  private void iter(final int step, final ANodeList list, final QueryContext qc)
      throws QueryException {

    // cast is safe (steps will always return a {@link NodeIter} instance)
    final NodeIter ni = (NodeIter) qc.iter(steps[step]);
    final boolean more = step + 1 != steps.length;
    for(ANode node; (node = ni.next()) != null;) {
      if(more) {
        qc.value = node;
        iter(step + 1, list, qc);
      } else {
        qc.checkStop();
        list.add(node);
      }
    }
  }

  @Override
  public AxisPath copy(final QueryContext qc, final VarScope scp, final IntObjMap<Var> vs) {
    final Expr rt = root == null ? null : root.copy(qc, scp, vs);
    final CachedPath ap = copyType(new CachedPath(info, rt, Arr.copyAll(qc, scp, vs, steps)));
    ap.cache = cache;
    return ap;
  }
}


text: [UFRJ - COS482] Software Quality Assurance (SQA) course project at @ UFRJ - (G5 - Disciplinas)


text:
import React, { Component } from 'react'
import { Link, IndexLink } from 'react-router'
import Nav from './nav'

class Header extends Component {

  constructor(props) {
    super(props)
  }

  render() {
    return (

                <Link to="/" className="">FPM-ADMIN</Link>

                     Admin

Profile

Settings

Logout

              {/*<form className="right search col s6 hide-on-med-and-down">

                  <input id="search" type="search" placeholder="Search" autocomplete="off" />

                    search

              </form>*/}

    )
  }
}

export default Header


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<launchHistory>
<launchGroup id="org.eclipse.debug.ui.launchGroup.profilee">
<mruHistory/>
<favorites/>
</launchGroup>
<launchGroup id="org.eclipse.debug.ui.launchGroup.debug">
<mruHistory/>
<favorites/>
</launchGroup>
<launchGroup id="org.eclipse.debug.ui.launchGroup.profile">
<mruHistory/>
<favorites/>
</launchGroup>
<launchGroup id="org.eclipse.ui.externaltools.launchGroup">
<mruHistory>
<launch memento="<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<launchConfiguration local="true" path="build.xml (154)"/>
"/>
<launch memento="<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<launchConfiguration local="true" path="build.xml (153)"/>
"/>
<launch memento="<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<launchConfiguration local="true" path="build.xml (152)"/>
"/>
<launch memento="<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<launchConfiguration local="true" path="build.xml (151)"/>
"/>
<launch memento="<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<launchConfiguration local="true" path="build.xml (150)"/>
"/>
<launch memento="<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<launchConfiguration local="true" path="build.xml (149)"/>
"/>
<launch memento="<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<launchConfiguration local="true" path="build.xml (148)"/>
"/>
<launch memento="<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<launchConfiguration local="true" path="build.xml (147)"/>
"/>
<launch memento="<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<launchConfiguration local="true" path="build.xml (146)"/>
"/>
<launch memento="<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<launchConfiguration local="true" path="build.xml (145)"/>
"/>
</mruHistory>
<favorites/>
</launchGroup>
<launchGroup id="org.eclipse.debug.ui.launchGroup.run">
<mruHistory/>
<favorites/>
</launchGroup>
</launchHistory>


text:
import Parallax from './Parallax';

import Background from './Background';

export { Parallax, Background };


text:
package br.com.winget.cadele.fragments;

import java.util.ArrayList;
//import br.com.winget.cadele.R;
import br.com.winget.cadele.interfaces.InterLogin;
import br.com.winget.cadele.model.Usuario;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
//import android.widget.TextView;

public class ListProcurarFragment extends ListFragment{
	private ArrayList<Usuario> list = new ArrayList<Usuario>();
	private ArrayAdapter<Usuario> adapter;
	private InterLogin mCallback;
	//private String status;
	//private TextView tvStatus;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = super.onCreateView(inflater, container, savedInstanceState);
		return view;
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		try {
			mCallback = (InterLogin) activity;
		}
		catch (ClassCastException e) {
			throw new ClassCastException(activity.toString() + " must implement InterLogin");
		}
		adapter = new ArrayAdapter<Usuario>(getActivity(), android.R.layout.simple_list_item_1, list);
		setListAdapter(adapter);

	}

	public void addData(ArrayList<Usuario> users){
		list.clear();
		addItens(users);
	}

	private void addItens(ArrayList<Usuario> users) {
		for (Usuario user : users) {
				list.add(user);
		}
		adapter.notifyDataSetChanged();
	}

	@Override
	public void onListItemClick(ListView l, View v, int position, long id) {
		final Usuario amigo = (Usuario) l.getItemAtPosition(position);
		new Thread(new Runnable(){
            public void run() {
				/*status = */mCallback.adicionarAmigo(mCallback.getUsuarioLogado().getId(), amigo.getId());
				Activity act = (Activity) mCallback;
				act.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                    	//tvStatus = (TextView) getView().findViewById(R.id.tv_adicionado);
						//tvStatus.setText(status);
						adapter.remove(amigo);
						adapter.notifyDataSetChanged();
                    }
				});
			}
         }).start();
	}
}


text:
//
//  NavigationBarScrollChangeBGViewController.m
//  CJUIKitDemo
//
//  Created by ciyouzen on 2017/5/16.
//  Copyright © 2017年 dvlproad. All rights reserved.
//

#import "NavigationBarScrollChangeBGViewController.h"

@interface NavigationBarScrollChangeBGViewController ()

@end

@implementation NavigationBarScrollChangeBGViewController

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

    [self navigationBarReset];
}

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

    [self navigationBarCustomSet];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    [self addTableScaleHeaderViewWithAttachNavigationBar:YES supportPullSmall:YES];

    self.automaticallyAdjustsScrollViewInsets = NO; //设成透明的时候,让顶部不会有一个statusBar的偏差
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [self navigationBarUpdateByScrollView:scrollView];
}

#pragma mark - 导航栏的设置
///导航栏的重置
- (void)navigationBarReset {
    [self.navigationController.navigationBar cj_resetBackgroundColor];

    [[UIBarButtonItem appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor]} forState:UIControlStateNormal];
    [[UIBarButtonItem appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor]} forState:UIControlStateHighlighted];
}

///导航栏在当前页面的自定义
- (void)navigationBarCustomSet {
    /* 改变导航栏 */
    [self.navigationController.navigationBar cj_hideUnderline:YES];//删除导航栏的下划线
    [self.navigationController.navigationBar cj_setBackgroundColor:[UIColor clearColor]];//改变导航栏背景色
    //[self.navigationController.navigationBar cj_setElementsAlpha:0];

    self.navigationItem.title = @"";

    [[UIBarButtonItem appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor clearColor]} forState:UIControlStateNormal];
    [[UIBarButtonItem appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor clearColor]} forState:UIControlStateHighlighted];

    //[self.navigationController.navigationBar setShadowImage:[UIImage new]];
}

///导航栏根据滚动视图的更新
- (void)navigationBarUpdateByScrollView:(UIScrollView *)scrollView {
    UIColor *navigationBarBackgroundColor = [UIColor colorWithRed:0/255.0 green:175/255.0 blue:240/255.0 alpha:1];
    CGFloat offsetY = scrollView.contentOffset.y + scrollView.contentInset.top; //注意加上top(top一般为0,但是在下拉图片放大的时候我们改变了contentInset)

    CGFloat navigationBarAlpha0OffsetY = 100;//设置滚动视图移动到(正值代表上移)多少时候,导航栏透明度为0

    CGFloat alpha = 0;
    if (offsetY > navigationBarAlpha0OffsetY) {
        alpha = MIN(1, 1 - ((navigationBarAlpha0OffsetY + 64 - offsetY) / 64));
    }

    /*
    CGFloat scaleHeadViewChangeHeightFromMaxToMin = self.scaleHeadView.originHeight - self.scaleHeadView.pullUpMinHeight; //scaleHeadView从初始大小缩小到最小大小所改变的大小
    CGFloat navigationBarAlpha1OffsetY = scaleHeadViewChangeHeightFromMaxToMin;//设置滚动视图移动到(正值代表上移)多少时候,导航栏透明度为1
    if (offsetY < navigationBarAlpha0OffsetY) {
        alpha = 0;
        //alpha = MIN(1, 1 - ((navigationBarAlpha0OffsetY + 64 - offsetY) / 64));
    } else if (offsetY > navigationBarAlpha1OffsetY) {
        alpha = 1;
    } else {
        alpha = (offsetY -navigationBarAlpha0OffsetY) /(navigationBarAlpha1OffsetY - navigationBarAlpha0OffsetY);
    }
    //*/
    //NSLog(@"offsetY = %.1f, alpha = %.3f", offsetY, alpha);

    UIColor *currentNavigationBarBackgroundColor = [navigationBarBackgroundColor colorWithAlphaComponent:alpha];
    [self.navigationController.navigationBar cj_setBackgroundColor:currentNavigationBarBackgroundColor];
    [self.navigationController.navigationBar cj_setElementsAlpha:alpha];
}

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

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end


text:
class CreatePayableActions < ActiveRecord::Migration
  def self.up
    create_table :payable_actions do |t|
			t.string 	:type
			t.string  :state
			t.integer :user_id
			t.string  :trackback_code_name
			t.string  :trackback_id
			t.string  :order_number
			t.float   :order_amount, :scale => 10, :precision => 2
			t.float   :payout, :scale => 10, :precision => 2

      t.timestamps
    end
  end

  def self.down
    drop_table :payable_actions
  end
end


text:
module CommonSetup
  def self.included(target)
    target.class_eval do
      include Aruba::Api
    end

    target.let(:gem_root) { File.expand_path('../..', File.dirname(__FILE__)) }

    target.let(:ensure_load_paths_valid) do
      <<-RUBY
        %w(lib spec).each do |include_folder|
          $LOAD_PATH.unshift(File.join('#{gem_root}', include_folder))
        end
      RUBY
    end

    target.let(:screenshot_path) { 'tmp' }
    target.let(:screenshot_for_pruning_path) { "#{screenshot_path}/old_screenshot.html" }

    target.let(:setup_test_app) do
      <<-RUBY
        require 'support/test_app'
        Capybara.save_and_open_page_path = '#{screenshot_path}'
        Capybara.app = TestApp
        Capybara::Screenshot.append_timestamp = false
        #{@additional_setup_steps}
      RUBY
    end

    target.before do
      if ENV['BUNDLE_GEMFILE'] && ENV['BUNDLE_GEMFILE'].match(/^\.|^[^\/\.]/)
        ENV['BUNDLE_GEMFILE'] = File.join(gem_root, ENV['BUNDLE_GEMFILE'])
      end
    end

    def run_simple_with_retry(*args)
      run_simple(*args)
    rescue ChildProcess::TimeoutError => e
      puts "run_simple(#{args.join(', ')}) failed. Will retry once. `#{e.message}`"
      run_simple(*args)
    end

    def configure_prune_strategy(strategy)
       @additional_setup_steps = "Capybara::Screenshot.prune_strategy = :keep_last_run"
    end

    def create_screenshot_for_pruning
      write_file screenshot_for_pruning_path, '<html></html>'
    end

    def assert_screenshot_pruned
      if defined? :be_an_existing_file
        expect(screenshot_for_pruning_path).not_to be_an_existing_file
      else
        puts "Here I just be"
        expect(screenshot_for_pruning_path).not_to be_existing_file
      end
    end

    def assert_screenshot_not_pruned
      expect(screenshot_for_pruning_path).to be_an_existing_file
    end
  end
end


text:
class Classroom < ActiveRecord::Base
	belongs_to :instructor, class_name: "User"
	belongs_to :apprentice, class_name: "User"
	has_one :detail
	validates :cuisine, presence: true

	def rating_for(user)
		if user == instructor
			instructor_goodness
		else
			apprentice_goodness
		end
	end

	def soon?
		if (this.starttime - Time.now)/60 < 20
			return true
		else
			return false
		end
	end

	def done?
		if self.endtime < Time.now
			return true
		else
			return false
		end
	end

	def emails
		holder = []
		holder << self.instructor.email
		holder << self.apprentice.email
		return holder
	end

	def next_open_rooms

	end

	def self.all_rooms(current_user)
		open_classroom_for_instructors = Classroom.where(instructor_id: nil).where.not(apprentice_id: current_user.id)
		open_classroom_for_students = Classroom.where(apprentice_id: nil).where.not(instructor_id: current_user.id)
		classrooms = (open_classroom_for_students + open_classroom_for_instructors)
    classrooms.sort_by(&:starttime).map do |kitchen|
      kitchen.as_json.merge(user_type: kitchen.instructor_id == nil ? "Teacher" : "Student")
    end
	end
end


text:
<link rel="stylesheet" type="text/css" href= "stylesheets/week1_technical.css">

What is the difference between Margin, Border and Padding? Here is an explanation:

Margin is the distance an element has to be from an adjacent element. So, if the margin of an element on the top is 50 pixels, There must be 50 px of space above the element before another element should be able to reside. *It is important to remember that if that element above has a margin of 70 px, there will 70 px of space between the top and bottom element. The greater of the two corresponding margins is the one that manifests.

Padding, on the other hand, is the distance between the border of an element and the content within it. So if there is an image with a padding of 10px from the top within a div, the image will be 10px from the top border of that element.

A schematic was taken from stackoverflow.com:


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Collections.Generic;
using Cake.Core.IO;

namespace Cake.Core.Tooling
{
    /// <summary>
    /// Implementation of the tool locator.
    /// </summary>
    public sealed class ToolLocator : IToolLocator
    {
        private readonly ICakeEnvironment _environment;
        private readonly IToolRepository _repository;
        private readonly IToolResolutionStrategy _strategy;

        /// <summary>
        /// Initializes a new instance of the <see cref="ToolLocator"/> class.
        /// </summary>
        /// <param name="environment">The environment.</param>
        /// <param name="repository">The tool repository.</param>
        /// <param name="strategy">The tool resolution strategy.</param>
        public ToolLocator(ICakeEnvironment environment, IToolRepository repository, IToolResolutionStrategy strategy)
        {
            _environment = environment ?? throw new ArgumentNullException(nameof(environment));
            _repository = repository ?? throw new ArgumentNullException(nameof(repository));
            _strategy = strategy ?? throw new ArgumentNullException(nameof(strategy));
        }

        /// <inheritdoc/>
        public void RegisterFile(FilePath path)
        {
            if (path == null)
            {
                throw new ArgumentNullException(nameof(path));
            }

            _repository.Register(path.MakeAbsolute(_environment));
        }

        /// <inheritdoc/>
        public FilePath Resolve(string tool)
        {
            if (tool == null)
            {
                throw new ArgumentNullException(nameof(tool));
            }
            if (string.IsNullOrWhiteSpace(tool))
            {
                throw new ArgumentException("Tool name cannot be empty.", nameof(tool));
            }

            return _strategy.Resolve(_repository, tool);
        }

        /// <inheritdoc/>
        public FilePath Resolve(IEnumerable<string> toolExeNames)
        {
            if (toolExeNames == null)
            {
                throw new ArgumentNullException(nameof(toolExeNames));
            }

            return _strategy.Resolve(_repository, toolExeNames);
        }
    }
}


text:
fn main() {
    let A: ();
    //~^ ERROR should have a snake case name
}


text:
import json
import yaml

from bson.objectid import ObjectId
from dateutil.parser import parse
from django.http import HttpResponse
from lxml.etree import tostring

from django.core.urlresolvers import resolve, get_script_prefix

from tastypie.exceptions import BadRequest, ImmediateHttpResponse
from tastypie.serializers import Serializer
from tastypie.authentication import SessionAuthentication, ApiKeyAuthentication
from tastypie.utils.mime import build_content_type
from tastypie_mongoengine.resources import MongoEngineResource

from crits.core.data_tools import format_file, create_zip
from crits.core.handlers import remove_quotes, generate_regex
from crits.core.user_tools import user_sources

# The following leverages code from the Tastypie library.
class CRITsApiKeyAuthentication(ApiKeyAuthentication):
    """
    API Key Authentication Class.
    """

    def is_authenticated(self, request, **kwargs):
        """
        Determine if the user can properly authenticate with the
        username and API key they provided.

        :param request: Django request object (Required)
        :type request: :class:`django.http.HttpRequest`
        :returns: True, :class:`tastypie.http.HttpUnauthorized`
        """

        try:
            username, api_key = self.extract_credentials(request)
        except ValueError:
            return self._unauthorized()

        if not username or not api_key:
            return self._unauthorized()

        try:
            from crits.core.user import CRITsUser
            user = CRITsUser.objects(username=username).first()
        except:
            return self._unauthorized()

        if not user:
            return self._unauthorized()

        if not user.is_active:
            return self._unauthorized()

        key_auth_check = self.get_key(user, api_key)
        if key_auth_check:
            request.user = user
            return True
        else:
            return self._unauthorized()

    def get_key(self, user, api_key):
        """
        Attempts to find the API key for the user. Uses ``ApiKey`` by default
        but can be overridden.

        :param user: The user trying to authenticate.
        :type user: str
        :param api_key: The key the user is trying to authenticate with.
        :type api_key: str
        :returns: True, False
        """

        if user:
            if user.validate_api_key(api_key):
                return True
        return False

class CRITsSessionAuthentication(SessionAuthentication):
    """
    API Authentication leveraging an existing Django browser session.
    """

    def get_identifier(self, request):
        """
        Returns the username as the identifier.

        :param request: Django request object (Required)
        :type request: :class:`django.http.HttpRequest`
        :returns: str
        """

        return request.user.username

class CRITsSerializer(Serializer):
    """
    Custom serializer for CRITs.
    """

    formats = ['json', 'xml', 'yaml', 'file']
    content_types = {
        'json': 'application/json',
        'xml': 'application/xml',
        'yaml': 'text/yaml',
        'file': 'application/octet-stream',
    }

    def _format_data(self, filedata, file_format=None):
        """
        Format filedata based on request.

        :param filedata: The filedata to format.
        :type filedata: str
        :param file_format: The format the file should be in:
                            "base64", "zlib", "raw", "invert".
        :type file_format: str
        :returns: list of [<formatted data>, <file extension>]
        """

        if file_format not in ('base64', 'zlib', 'raw', 'invert'):
            file_format = 'raw'
        return format_file(filedata, file_format)[0]

    def to_file(self, data, options=None):
        """
        Respond with filedata instead of metadata.

        :param data: The data to be worked on.
        :type data: dict for multiple objects,
                    :class:`tastypie.bundle.Bundle` for a single object.
        :param options: Options to alter how this serializer works.
        :type options: dict
        :returns: :class:`django.http.HttpResponse`,
                  :class:`tastypie.exceptions.BadRequest`
        """

        get_file = options.get('file', None)
        file_format = options.get('file_format', 'raw')
        response = None
        zipfile = None

        if get_file:
            files = []
            if hasattr(data, 'obj'):
                if hasattr(data.obj, 'filedata'):
                    filename = data.obj.md5
                    filedata = data.obj.filedata.read()
                    if filedata:
                        filedata = self._format_data(filedata, file_format)
                        files.append([filename, filedata])
                elif hasattr(data.obj, 'screenshot'):
                    filename = "%s.png" % data.obj.md5
                    filedata = data.obj.screenshot.read()
                    if filedata:
                        files.append([filename, filedata])
            elif 'objects' in data:
                try:
                    objs = data['objects']
                    for obj_ in objs:
                        if hasattr(obj_.obj, 'filedata'):
                            filename = obj_.obj.md5
                            filedata = obj_.obj.filedata.read()
                            if filedata:
                                filedata = self._format_data(filedata,
                                                             file_format)
                                files.append([filename, filedata])
                        elif hasattr(obj_.obj, 'screenshot'):
                            filename = "%s.png" % data.obj.md5
                            filedata = data.obj.screenshot.read()
                            if filedata:
                                files.append([filename, filedata])
                except:
                    pass
            try:
                if len(files):
                    zipfile = create_zip(files)
                    response =  HttpResponse(zipfile,
                                                mimetype='application/octet-stream; charset=utf-8')
                    response['Content-Disposition'] = 'attachment; filename="results.zip"'
                else:
                    response = BadRequest("No files found!")
            except Exception, e:
                response = BadRequest(str(e))
        return response

    def to_json(self, data, options=None):
        """
        Respond with JSON formatted data. This is the default.

        :param data: The data to be worked on.
        :type data: dict for multiple objects,
                    :class:`tastypie.bundle.Bundle` for a single object.
        :param options: Options to alter how this serializer works.
        :type options: dict
        :returns: str
        """

        options = options or {}
        username = options.get('username', None)

        # if this is a singular object, just return our internal to_json()
        # which handles the Embedded MongoEngine classes.
        if hasattr(data, 'obj'):
            if data.obj._has_method('sanitize'):
                data.obj.sanitize(username=username, rels=True)
            return data.obj.to_json()

        data = self._convert_mongoengine(data, options)
        return json.dumps(data, sort_keys=True)

    def to_xml(self, data, options=None):
        """
        Respond with XML formatted data.

        :param data: The data to be worked on.
        :type data: dict for multiple objects,
                    :class:`tastypie.bundle.Bundle` for a single object.
        :param options: Options to alter how this serializer works.
        :type options: dict
        :returns: str
        """

        options = options or {}

        if hasattr(data, 'obj'):
            data = {'objects': [data]}

        data = self._convert_mongoengine(data, options)
        return tostring(self.to_etree(data, options), xml_declaration=True,
                        encoding='utf-8')

    def to_yaml(self, data, options=None):
        """
        Respond with YAML formatted data.

        :param data: The data to be worked on.
        :type data: dict for multiple objects,
                    :class:`tastypie.bundle.Bundle` for a single object.
        :param options: Options to alter how this serializer works.
        :type options: dict
        :returns: str
        """

        options = options or {}
        username = options.get('username', None)

        # if this is a singular object, just return our internal to_yaml()
        # which handles the Embedded MongoEngine classes.
        if hasattr(data, 'obj'):
            if data.obj._has_method('sanitize'):
                data.obj.sanitize(username=username, rels=True)
            return data.obj.to_yaml()

        data = self._convert_mongoengine(data, options)
        return yaml.dump(data)

    def _convert_mongoengine(self, data, options=None):
        """
        Convert the MongoEngine class to a serializable object.
        This also sanitizes the content.

        :param data: The data to be worked on.
        :type data: dict for multiple objects,
                    :class:`tastypie.bundle.Bundle` for a single object.
        :param options: Options to alter how this serializer works.
        :type options: dict
        :returns: dict
        """

        # if this is a list of multiple objects, use our internal to_json()
        # for each one before processing normally.
        username = options.get('username', None)
        if 'objects' in data:
            objs = data['objects']
            data['objects'] = []
            for obj_ in objs:
                if obj_.obj._has_method('sanitize'):
                    obj_.obj.sanitize(username=username, rels=True)
                data['objects'].append(json.loads(obj_.obj.to_json()))
        data = self.to_simple(data, options)
        return data

class CRITsAPIResource(MongoEngineResource):
    """
    Standard CRITs API Resource.
    """

    class Meta:
        default_format = "application/json"

    def crits_response(self, content, status=200):
        """
        An amazing hack so we can return our own custom JSON response. Instead
        of having the ability to craft and return an HttpResponse, Tastypie
        requires us to raise this custom exception in order to do so.

        The content should be a dict with keys of:

            - return_code: 0 (success), 1 (failure), etc. for custom returns.
            - type: The CRITs TLO type (Sample, Email, etc.)
            - id: The ObjectId (as a string) of the TLO. (optional if not
                  available)
            - message: A custom message you wish to return.

        If you wish to extend your content to contain more k/v pairs you can do
        so as long as they are JSON serializable.

        :param content: The information we wish to return in the response.
        :type content: dict (must be json serializable)
        :param status: If we wish to return anything other than a 200.
        :type status: int
        :raises: :class:`tastypie.exceptions.ImmediateHttpResponse`
        """

        raise ImmediateHttpResponse(HttpResponse(json.dumps(content),
                                                 mimetype="application/json",
                                                 status=status))

    def create_response(self, request, data, response_class=HttpResponse,
                        **response_kwargs):
        """
        Override the default create_response so we can pass the GET
        parameters into options. This allows us to use GET parameters
        to adjust how our serializers respond.

        :param request: Django request object (Required)
        :type request: :class:`django.http.HttpRequest`
        :param data: The data to be worked on.
        :type data: dict for multiple objects,
                    :class:`tastypie.bundle.Bundle` for a single object.
        :param response_class: The class to utilize for the response.
        :type response_class: :class:`django.http.HttpResponse` (Default)
        :returns: :class:`django.http.HttpResponse` (Default)
        """

        desired_format = self.determine_format(request)
        options = request.GET.copy()
        options['username'] = request.user.username
        serialized = self.serialize(request, data, desired_format,
                                    options=options)
        return response_class(content=serialized,
                            content_type=build_content_type(desired_format),
                            **response_kwargs)

    def determine_format(self, request):
        """
        Used to determine the desired format.

        :param request: Django request object (Required)
        :type request: :class:`django.http.HttpRequest`
        :returns: str
        """

        return determine_format(request, self._meta.serializer,
                                default_format=self._meta.default_format)

    def deserialize(self, request, data, format=None):
        """
        Custom deserializer which is only used to collect filedata uploads
        and pass the binary along with the rest of the POST like
        tastyie would normally do.

        :param request: Django request object (Required)
        :type request: :class:`django.http.HttpRequest`
        :param data: The data to pass along.
        :type data: dict
        :param format: The format of the request.
        :type format: str
        :returns: data in requested format.
        """

        # Get format from request. Assume json if nothing provided
        if not format:
            format = request.META.get('CONTENT_TYPE', 'application/json')
        if format == 'application/x-www-form-urlencoded':
            if 'filedata' in request.POST:
                raise BadRequest("Filedata only supported in multipart forms.")
            else:
                return request.POST
        # If a file was uploaded, add it to data and pass it along
        if format.startswith('multipart'):
            data = request.POST.copy()
            if 'filedata' in request.FILES:
                if hasattr(request.FILES['filedata'], 'read'):
                    data.update(request.FILES)
                else:
                    raise BadRequest("Expected filehandle, got string.")
            return data
        return super(CRITsAPIResource, self).deserialize(request, data, format)

    def get_object_list(self, request, klass, sources=True):
        """
        Handle GET requests. This does all sorts of work to ensure the
        results are sanitized and that source restriction is adhered to.
        Adds the ability to limit results and the content of the results
        through GET parameters.

        :param request: Django request object (Required)
        :type request: :class:`django.http.HttpRequest`
        :param klass: The CRITs top-level object to get.
        :type klass: class which inherits from
                     :class:`crits.core.crits_mongoengine.CritsBaseAttributes`
        :param sources: If we should limit by source.
        :type sources: boolean
        :returns: :class:`crits.core.crits_mongoengine.CritsQuerySet`
        """

        querydict = {}
        get_params = request.GET.copy()
        regex = request.GET.get('regex', False)
        only = request.GET.get('only', None)
        exclude = request.GET.get('exclude', None)
        source_list = user_sources(request.user.username)
        no_sources = True
        # Chop off trailing slash and split on remaining slashes.
        # If last part of path is not the resource name, assume it is an
        # object ID.
        path = request.path[:-1].split('/')
        if path[-1] != self.Meta.resource_name:
            # If this is a valid object ID, convert it. Otherwise, use
            # the string. The corresponding query will return 0.
            if ObjectId.is_valid(path[-1]):
                querydict['_id'] = ObjectId(path[-1])
            else:
                querydict['_id'] = path[-1]

        for k,v in get_params.iteritems():
            v = v.strip()
            try:
                v_int = int(v)
            except:
                # If can't be converted to an int use the string.
                v_int = v
            if k == "c-_id":
                try:
                    querydict['_id'] = ObjectId(v)
                except:
                    pass
            if k.startswith("c-"):
                field = k[2:]
                # Attempt to discover query operators. We use django-style operators
                # (same as MongoEngine). These also override regex.
                try:
                    op_index = field.index("__")
                    op = "$%s" % field[op_index+2:]
                    field = field[:op_index]
                except ValueError:
                    op_index = None
                if op_index is not None:
                    if op in ('$gt', '$gte', '$lt', '$lte', '$ne', '$in', '$nin', '$exists'):
                        val = v
                        if field in ('created', 'modified'):
                            try:
                                val = parse(val, fuzzy=True)
                            except:
                                pass
                        if op in ('$in', '$nin'):
                            if field == 'source.name':
                                val = []
                                for i in v.split(','):
                                    s = remove_quotes(i)
                                    if s in source_list:
                                        no_sources = False
                                        val.append(s)
                            else:
                                val = [remove_quotes(i) for i in v.split(',')]
                        if op == '$exists':
                            if val in ('true', 'True', '1'):
                                val = 1
                            elif val in ('false', 'False', '0'):
                                val = 0
                        if field in ('size', 'schema_version'):
                            if isinstance(val, list):
                                v_f = []
                                for i in val:
                                    try:
                                        v_f.append(int(i))
                                    except:
                                        pass
                                val = v_f
                            else:
                                try:
                                    val = int(val)
                                except:
                                    val = None
                        if val or val == 0:
                            querydict[field] = {op: val}
                elif field in ('size', 'schema_version'):
                    querydict[field] = v_int
                elif field in ('created', 'modified'):
                    try:
                        querydict[field] = parse(v, fuzzy=True)
                    except:
                        querydict[field] = v
                elif field == 'source.name':
                    v = remove_quotes(v)
                    if v in source_list:
                        no_sources = False
                        querydict[field] = v
                elif regex:
                    querydict[field] = generate_regex(v)
                else:
                    querydict[field] = remove_quotes(v)
        if no_sources and sources:
            querydict['source.name'] = {'$in': source_list}
        if only or exclude:
            required = [k for k,f in klass._fields.iteritems() if f.required]
        if only:
            fields = only.split(',')
            if exclude:
                excludes = exclude.split(',')
                fields = [x for x in fields if x not in excludes]
            for r in required:
                if r not in fields:
                    fields.append(r)
            results = klass.objects(__raw__=querydict).only(*fields)
        elif exclude:
            fields = exclude.split(',')
            for r in required:
                if r not in fields:
                    fields.append(r)
            results = klass.objects(__raw__=querydict).exclude(*fields)
        else:
            results = klass.objects(__raw__=querydict)
        return results

    def obj_get_list(self, bundle, **kwargs):
        """
        Placeholder for overriding the default tastypie function in the future.
        """

        return super(CRITsAPIResource, self).obj_get_list(bundle=bundle, **kwargs)

    def obj_get(self, bundle, **kwargs):
        """
        Placeholder for overriding the default tastypie function in the future.
        """

        return super(CRITsAPIResource, self).obj_get(bundle=bundle, **kwargs)

    def obj_create(self, bundle, **kwargs):
        """
        Create an object in CRITs. Should be overridden by each
        individual top-level resource.

        :returns: NotImplementedError if the resource doesn't override.
        """

        raise NotImplementedError('You cannot currently create this objects through the API.')

    def obj_update(self, bundle, **kwargs):
        """
        Update an object in CRITs. Should be overridden by each
        individual top-level resource.

        :returns: NotImplementedError if the resource doesn't override.
        """

        import crits.actors.handlers as ah
        import crits.core.handlers as coreh
        import crits.objects.handlers as objh
        import crits.relationships.handlers as relh
        import crits.services.handlers as servh
        import crits.signatures.handlers as sigh
        import crits.indicators.handlers as indh

        actions = {
            'Common': {
                'add_object': objh.add_object,
                'add_releasability': coreh.add_releasability,
                'forge_relationship': relh.forge_relationship,
                'run_service': servh.run_service,
                'status_update' : coreh.status_update,
                'ticket_add' : coreh.ticket_add,
                'ticket_update' : coreh.ticket_update,
                'ticket_remove' : coreh.ticket_remove,
                'source_add_update': coreh.source_add_update,
                'source_remove': coreh.source_remove,
                'action_add' : coreh.action_add,
                'action_update' : coreh.action_update,
                'action_remove' : coreh.action_remove,
                'description_update' : coreh.description_update,
            },
            'Actor': {
                'update_actor_tags': ah.update_actor_tags,
                'attribute_actor_identifier': ah.attribute_actor_identifier,
                'set_identifier_confidence': ah.set_identifier_confidence,
                'remove_attribution': ah.remove_attribution,
                'set_actor_name': ah.set_actor_name,
                'update_actor_aliases': ah.update_actor_aliases,
            },
            'Backdoor': {},
            'Campaign': {},
            'Certificate': {},
            'Domain': {},
            'Email': {},
            'Event': {},
            'Exploit': {},
            'Indicator': {
                'set_indicator_attack_type' : indh.set_indicator_attack_type,
                'set_indicator_threat_type' : indh.set_indicator_threat_type,
                'activity_add' : indh.activity_add,
                'activity_update' : indh.activity_update,
                'activity_remove' : indh.activity_remove,
                'ci_update' : indh.ci_update
                          },
            'IP': {},
            'PCAP': {},
            'RawData': {},
            'Sample': {},
            'Signature': {
                'update_dependency': sigh.update_dependency,
                'update_min_version': sigh.update_min_version,
                'update_max_version': sigh.update_max_version,
                'update_signature_data': sigh.update_signature_data,
                'update_signature_type': sigh.update_signature_type,
                'update_title': sigh.update_title
            },
            'Target': {},
        }

        prefix = get_script_prefix()
        uri = bundle.request.path
        if prefix and uri.startswith(prefix):
            uri = uri[len(prefix)-1:]
        view, args, kwargs = resolve(uri)

        type_ = kwargs['resource_name'].title()
        if type_ == "Raw_data":
            type_ = "RawData"
        if type_[-1] == 's':
            type_ = type_[:-1]
        if type_ in ("Pcap", "Ip"):
            type_ = type_.upper()
        id_ = kwargs['pk']

        content = {'return_code': 0,
                   'type': type_,
                   'message': '',
                   'id': id_}

        # Make sure we have an appropriate action.
        action = bundle.data.get("action", None)
        atype = actions.get(type_, None)
        if atype is None:
            content['return_code'] = 1
            content['message'] = "'%s' is not a valid resource." % type_
            self.crits_response(content)
        action_type = atype.get(action, None)
        if action_type is None:
            atype = actions.get('Common')
            action_type = atype.get(action, None)
        if action_type:
            data = bundle.data
            # Requests don't need to have an id_ as we will derive it from
            # the request URL. Override id_ if the request provided one.
            data['id_'] = id_
            # Override type (if provided)
            data['type_'] = type_
            # Override user (if provided) with the one who made the request.
            data['user'] = bundle.request.user.username
            try:
                results = action_type(**data)
                if not results.get('success', False):
                    content['return_code'] = 1
                    # TODO: Some messages contain HTML and other such content
                    # that we shouldn't be returning here.
                    message = results.get('message', None)
                    content['message'] = message
                else:
                    content['message'] = "success!"
            except Exception, e:
                content['return_code'] = 1
                content['message'] = str(e)
        else:
            content['return_code'] = 1
            content['message'] = "'%s' is not a valid action." % action
        self.crits_response(content)

    def obj_delete_list(self, bundle, **kwargs):
        """
        Delete list of objects in CRITs. Should be overridden by each
        individual top-level resource.

        :returns: NotImplementedError if the resource doesn't override.
        """

        raise NotImplementedError('You cannot currently delete objects through the API.')

    def obj_delete(self, bundle, **kwargs):
        """
        Delete an object in CRITs. Should be overridden by each
        individual top-level resource.

        :returns: NotImplementedError if the resource doesn't override.
        """

        raise NotImplementedError('You cannot currently delete this object through the API.')

    def resource_name_from_type(self, crits_type):
        """
        Take a CRITs type and convert it to the appropriate API resource name.

        :param crits_type: The CRITs type.
        :type crits_type: str
        :returns: str
        """

        if crits_type == "RawData":
            return "raw_data"
        else:
            return "%ss" % crits_type.lower()

def determine_format(request, serializer, default_format='application/json'):
    """
    This overrides the default tastyie determine_format.
    This is done because we want to default to "application/json"
    even though most browsers will send along "application/xml" in the
    Accept header if no "format" is provided.

    :param request: Django request object (Required)
    :type request: :class:`django.http.HttpRequest`
    :param serializer: The serializer being used.
    :type serializer: :class:`crits.core.api.CRITsSerializer`
    :param default_format: The format to respond in.
    :type default_format: str
    :returns: str
    """

    # First, check if they forced the format.
    if request.GET.get('format'):
        if request.GET['format'] in serializer.formats:
            return serializer.get_mime_for_format(request.GET['format'])

    if request.GET.get('file'):
        default_format = 'application/octet-stream'

    # No valid 'Accept' header/formats. Sane default.
    return default_format


text:
from setuptools import setup
import os
import sys

# Publish the library to PyPI.
if "publish" in sys.argv[-1]:
    os.system("python setup.py sdist upload")
    sys.exit()

# Push a new tag to GitHub.
if "tag" in sys.argv:
    os.system("git tag -a {0} -m 'version {0}'".format(version))
    os.system("git push --tags")
    sys.exit()

setup(
    name="batchserial",
    version='0.1',
    author="Timothy D. Morton",
    author_email="tim.morton@gmail.com",
    url="https://github.com/timothydmorton/batch-serial",
    license="MIT",
    description="Script to submit list of serial commands as batch job",
    long_description=open("README.md").read(),
    scripts=['batch-serial'],
    classifiers=[
        # "Development Status :: 5 - Production/Stable",
        "Intended Audience :: Science/Research",
        "License :: OSI Approved :: MIT License",
        "Programming Language :: Python",
    ],
)


text:
namespace KinectVisionLib {
    namespace Core {

        using namespace std;

        class ImageBase
        {
        public:
            ImageBase(int width, int height)
            {
                this->width = width;
                this->height = height;
            }
            int GetWidth() const { return width; }
            int GetHeight() const { return height; }
            Rect GetRect() const { return Rect(0, 0, width, height); }
            Size GetSize() const { return Size(width, height); }
            Point GetCenter() const { return Point(width / 2, height / 2); }

            virtual void RenderAsRGBA(uint8* buffer) const = 0;

            virtual const wstring ReadPixelValue(int x, int y, int width, int height) const = 0;

        protected:
            bool IsValid(Point point) const {
                return Rect(0, 0, width, height).Contains(point);
            }

        private:
            int width;
            int height;
        };
    }
}