text:
<?php

require_once dirname(__FILE__) . '/../AbstractTest.php';

require_once 'PHP/PMD/Rule/UnusedPrivateField.php';

/**
 * Test case for the unused private field rule.
 *
 * @category   PHP
 * @package    PHP_PMD
 * @subpackage Rule
 * @author     Manuel Pichler <mapi@phpmd.org>
 * @copyright  2008-2012 Manuel Pichler. All rights reserved.
 * @license    http://www.opensource.org/licenses/bsd-license.php  BSD License
 * @version    Release: @package_version@
 * @link       http://phpmd.org
 *
 * @covers PHP_PMD_Rule_UnusedPrivateField
 * @group phpmd
 * @group phpmd::rule
 * @group unittest
 */
class PHP_PMD_Rule_UnusedPrivateFieldTest extends PHP_PMD_AbstractTest
{
    /**
     * testRuleAppliesToUnusedPrivateField
     *
     * @return void
     */
    public function testRuleAppliesToUnusedPrivateField()
    {
        $rule = new PHP_PMD_Rule_UnusedPrivateField();
        $rule->setReport($this->getReportMock(1));
        $rule->apply($this->getClass());
    }

    /**
     * testRuleAppliesToUnusedPrivateStaticField
     *
     * @return void
     */
    public function testRuleAppliesWhenFieldWithSameNameIsAccessedOnDifferentObject()
    {
        $rule = new PHP_PMD_Rule_UnusedPrivateField();
        $rule->setReport($this->getReportMock(1));
        $rule->apply($this->getClass());
    }

    /**
     * testRuleAppliesToUnusedPrivateStaticField
     *
     * @return void
     */
    public function testRuleAppliesToUnusedPrivateStaticField()
    {
        $rule = new PHP_PMD_Rule_UnusedPrivateField();
        $rule->setReport($this->getReportMock(1));
        $rule->apply($this->getClass());
    }

    /**
     * testRuleAppliesWhenStaticFieldWithSameNameIsAccessedOnDifferentClass
     *
     * @return void
     */
    public function testRuleAppliesWhenStaticFieldWithSameNameIsAccessedOnDifferentClass()
    {
        $rule = new PHP_PMD_Rule_UnusedPrivateField();
        $rule->setReport($this->getReportMock(1));
        $rule->apply($this->getClass());
    }

    /**
     * testRuleAppliesWhenStaticFieldWithSameNameIsAccessedOnParent
     *
     * @return void
     */
    public function testRuleAppliesWhenStaticFieldWithSameNameIsAccessedOnParent()
    {
        $rule = new PHP_PMD_Rule_UnusedPrivateField();
        $rule->setReport($this->getReportMock(1));
        $rule->apply($this->getClass());
    }

    /**
     * testRuleAppliesWhenLocalVariableIsUsedInStaticMemberPrefix
     *
     *
     * class Foo {
     *     private static $_bar = null;
     *
     *     public function baz() {
     *         self::${$_bar = '_bar'} = 42;
     *     }
     * }
     *
     *
     * @return void
     */
    public function testRuleAppliesWhenLocalVariableIsUsedInStaticMemberPrefix()
    {
        $rule = new PHP_PMD_Rule_UnusedPrivateField();
        $rule->setReport($this->getReportMock(1));
        $rule->apply($this->getClass());
    }

    /**
     * testRuleAppliesWhenLocalVariableIsUsedInStaticMemberPrefix
     *
     *
     * class Foo {
     *     private static $_bar = null;
     *
     *     public function baz() {
     *         self::${'_bar'} = 42;
     *     }
     * }
     *
     *
     * @return void
     */
    public function testRuleDoesNotResultInFatalErrorByCallingNonObject()
    {
        $rule = new PHP_PMD_Rule_UnusedPrivateField();
        $rule->setReport($this->getReportMock(1));
        $rule->apply($this->getClass());
    }

    /**
     * testRuleDoesNotApplyToUnusedPublicField
     *
     * @return void
     */
    public function testRuleDoesNotApplyToUnusedPublicField()
    {
        $rule = new PHP_PMD_Rule_UnusedPrivateField();
        $rule->setReport($this->getReportMock(0));
        $rule->apply($this->getClass());
    }

    /**
     * testRuleDoesNotApplyToUnusedProtectedField
     *
     * @return void
     */
    public function testRuleDoesNotApplyToUnusedProtectedField()
    {
        $rule = new PHP_PMD_Rule_UnusedPrivateField();
        $rule->setReport($this->getReportMock(0));
        $rule->apply($this->getClass());
    }

    /**
     * testRuleDoesNotApplyToThisAccessedPrivateField
     *
     * @return void
     */
    public function testRuleDoesNotApplyToThisAccessedPrivateField()
    {
        $rule = new PHP_PMD_Rule_UnusedPrivateField();
        $rule->setReport($this->getReportMock(0));
        $rule->apply($this->getClass());
    }

    /**
     * testRuleDoesNotApplyToSelfAccessedPrivateField
     *
     * @return void
     */
    public function testRuleDoesNotApplyToSelfAccessedPrivateField()
    {
        $rule = new PHP_PMD_Rule_UnusedPrivateField();
        $rule->setReport($this->getReportMock(0));
        $rule->apply($this->getClass());
    }

    /**
     * testRuleDoesNotApplyToStaticAccessedPrivateField
     *
     * @return void
     */
    public function testRuleDoesNotApplyToStaticAccessedPrivateField()
    {
        $rule = new PHP_PMD_Rule_UnusedPrivateField();
        $rule->setReport($this->getReportMock(0));
        $rule->apply($this->getClass());
    }

    /**
     * testRuleDoesNotApplyToClassNameAccessedPrivateField
     *
     * @return void
     */
    public function testRuleDoesNotApplyToClassNameAccessedPrivateField()
    {
        $rule = new PHP_PMD_Rule_UnusedPrivateField();
        $rule->setReport($this->getReportMock(0));
        $rule->apply($this->getClass());
    }

    /**
     * testRuleDoesNotApplyToPrivateFieldInChainedMethodCall
     *
     *
     * class Foo {
     *     private $bar = null;
     *     // ...
     *     public function baz() {
     *         $this->bar->foobar();
     *     }
     * }
     *
     *
     * @return void
     */
    public function testRuleDoesNotApplyToPrivateFieldInChainedMethodCall()
    {
        $rule = new PHP_PMD_Rule_UnusedPrivateField();
        $rule->setReport($this->getReportMock(0));
        $rule->apply($this->getClass());
    }

    /**
     * testRuleDoesNotApplyToPrivateArrayFieldAccess
     *
     *
     * class Foo {
     *     private $bar = array();
     *     // ...
     *     public function baz() {
     *         return $this->bar[42];
     *     }
     * }
     *
     *
     * @return void
     */
    public function testRuleDoesNotApplyToPrivateArrayFieldAccess()
    {
        $rule = new PHP_PMD_Rule_UnusedPrivateField();
        $rule->setReport($this->getReportMock(0));
        $rule->apply($this->getClass());
    }

    /**
     * testRuleDoesNotApplyToPrivateStringIndexFieldAccess
     *
     *
     * class Foo {
     *     private $bar = "Manuel";
     *     // ...
     *     public function baz() {
     *         return $this->bar{3};
     *     }
     * }
     *
     *
     * @return void
     */
    public function testRuleDoesNotApplyToPrivateStringIndexFieldAccess()
    {
        $rule = new PHP_PMD_Rule_UnusedPrivateField();
        $rule->setReport($this->getReportMock(0));
        $rule->apply($this->getClass());
    }
}


text:
//==============================================================================
CEvent::CEvent() {
}

//------------------------------------------------------------------------------
CEvent::~CEvent() {
	//Do nothing
}

//==============================================================================
void CEvent::OnEvent(SDL_Event* Event) {
	switch(Event->type) {
		case SDL_ACTIVEEVENT: {
			switch(Event->active.state) {
				case SDL_APPMOUSEFOCUS: {
					if ( Event->active.gain )	OnMouseFocus();
					else				OnMouseBlur();

					break;
				}
				case SDL_APPINPUTFOCUS: {
					if ( Event->active.gain )	OnInputFocus();
					else				OnInputBlur();

					break;
				}
				case SDL_APPACTIVE:	{
					if ( Event->active.gain )	OnRestore();
					else				OnMinimize();

					break;
				}
			}
			break;
		}

		case SDL_KEYDOWN: {
			OnKeyDown(Event->key.keysym.sym,Event->key.keysym.mod,Event->key.keysym.unicode);
			break;
		}

		case SDL_KEYUP: {
			OnKeyUp(Event->key.keysym.sym,Event->key.keysym.mod,Event->key.keysym.unicode);
			break;
		}

		case SDL_MOUSEMOTION: {
			OnMouseMove(Event->motion.x,Event->motion.y,Event->motion.xrel,Event->motion.yrel,(Event->motion.state&SDL_BUTTON(SDL_BUTTON_LEFT))!=0,(Event->motion.state&SDL_BUTTON(SDL_BUTTON_RIGHT))!=0,(Event->motion.state&SDL_BUTTON(SDL_BUTTON_MIDDLE))!=0);
			break;
		}

		case SDL_MOUSEBUTTONDOWN: {
			switch(Event->button.button) {
				case SDL_BUTTON_LEFT: {
					OnLButtonDown(Event->button.x,Event->button.y);
					break;
				}
				case SDL_BUTTON_RIGHT: {
					OnRButtonDown(Event->button.x,Event->button.y);
					break;
				}
				case SDL_BUTTON_MIDDLE: {
					OnMButtonDown(Event->button.x,Event->button.y);
					break;
				}
			}
			break;
		}

		case SDL_MOUSEBUTTONUP:	{
			switch(Event->button.button) {
				case SDL_BUTTON_LEFT: {
					OnLButtonUp(Event->button.x,Event->button.y);
					break;
				}
				case SDL_BUTTON_RIGHT: {
					OnRButtonUp(Event->button.x,Event->button.y);
					break;
				}
				case SDL_BUTTON_MIDDLE: {
					OnMButtonUp(Event->button.x,Event->button.y);
					break;
				}
			}
			break;
		}

		case SDL_JOYAXISMOTION: {
			OnJoyAxis(Event->jaxis.which,Event->jaxis.axis,Event->jaxis.value);
			break;
		}

		case SDL_JOYBALLMOTION: {
			OnJoyBall(Event->jball.which,Event->jball.ball,Event->jball.xrel,Event->jball.yrel);
			break;
		}

		case SDL_JOYHATMOTION: {
			OnJoyHat(Event->jhat.which,Event->jhat.hat,Event->jhat.value);
			break;
		}
		case SDL_JOYBUTTONDOWN: {
			OnJoyButtonDown(Event->jbutton.which,Event->jbutton.button);
			break;
		}

		case SDL_JOYBUTTONUP: {
			OnJoyButtonUp(Event->jbutton.which,Event->jbutton.button);
			break;
		}

		case SDL_QUIT: {
			OnExit();
			break;
		}

		case SDL_SYSWMEVENT: {
			//Ignore
			break;
		}

		case SDL_VIDEORESIZE: {
			OnResize(Event->resize.w,Event->resize.h);
			break;
		}

		case SDL_VIDEOEXPOSE: {
			OnExpose();
			break;
		}

		default: {
			OnUser(Event->user.type,Event->user.code,Event->user.data1,Event->user.data2);
			break;
		}
	}
}

//------------------------------------------------------------------------------
void CEvent::OnInputFocus() {
	//Pure virtual, do nothing
}

//------------------------------------------------------------------------------
void CEvent::OnInputBlur() {
	//Pure virtual, do nothing
}

//------------------------------------------------------------------------------
void CEvent::OnKeyDown(SDLKey sym, SDLMod mod, Uint16 unicode) {
	//Pure virtual, do nothing
}

//------------------------------------------------------------------------------
void CEvent::OnKeyUp(SDLKey sym, SDLMod mod, Uint16 unicode) {
	//Pure virtual, do nothing
}

//------------------------------------------------------------------------------
void CEvent::OnMouseFocus() {
	//Pure virtual, do nothing
}

//------------------------------------------------------------------------------
void CEvent::OnMouseBlur() {
	//Pure virtual, do nothing
}

//------------------------------------------------------------------------------
void CEvent::OnMouseMove(int mX, int mY, int relX, int relY, bool Left,bool Right,bool Middle) {
	//Pure virtual, do nothing
}

//------------------------------------------------------------------------------
void CEvent::OnMouseWheel(bool Up, bool Down) {
	//Pure virtual, do nothing
}

//------------------------------------------------------------------------------
void CEvent::OnLButtonDown(int mX, int mY) {
	//Pure virtual, do nothing
}

//------------------------------------------------------------------------------
void CEvent::OnLButtonUp(int mX, int mY) {
	//Pure virtual, do nothing
}

//------------------------------------------------------------------------------
void CEvent::OnRButtonDown(int mX, int mY) {
	//Pure virtual, do nothing
}

//------------------------------------------------------------------------------
void CEvent::OnRButtonUp(int mX, int mY) {
	//Pure virtual, do nothing
}

//------------------------------------------------------------------------------
void CEvent::OnMButtonDown(int mX, int mY) {
	//Pure virtual, do nothing
}

//------------------------------------------------------------------------------
void CEvent::OnMButtonUp(int mX, int mY) {
	//Pure virtual, do nothing
}

//------------------------------------------------------------------------------
void CEvent::OnJoyAxis(Uint8 which,Uint8 axis,Sint16 value) {
	//Pure virtual, do nothing
}

//------------------------------------------------------------------------------
void CEvent::OnJoyButtonDown(Uint8 which,Uint8 button) {
	//Pure virtual, do nothing
}

//------------------------------------------------------------------------------
void CEvent::OnJoyButtonUp(Uint8 which,Uint8 button) {
	//Pure virtual, do nothing
}

//------------------------------------------------------------------------------
void CEvent::OnJoyHat(Uint8 which,Uint8 hat,Uint8 value) {
	//Pure virtual, do nothing
}

//------------------------------------------------------------------------------
void CEvent::OnJoyBall(Uint8 which,Uint8 ball,Sint16 xrel,Sint16 yrel) {
	//Pure virtual, do nothing
}

//------------------------------------------------------------------------------
void CEvent::OnMinimize() {
	//Pure virtual, do nothing
}

//------------------------------------------------------------------------------
void CEvent::OnRestore() {
	//Pure virtual, do nothing
}

//------------------------------------------------------------------------------
void CEvent::OnResize(int w,int h) {
	//Pure virtual, do nothing
}

//------------------------------------------------------------------------------
void CEvent::OnExpose() {
	//Pure virtual, do nothing
}

//------------------------------------------------------------------------------
void CEvent::OnExit() {
	//Pure virtual, do nothing
}

//------------------------------------------------------------------------------
void CEvent::OnUser(Uint8 type, int code, void* data1, void* data2) {
	//Pure virtual, do nothing
}

//==============================================================================

redpajama_set_name: RedPajamaGithub


text:
import gocept.testing.assertion
import zeit.cms.testing
import zeit.campus.testing

class ZCOInfoboxDebate(zeit.cms.testing.BrowserTestCase,
                       gocept.testing.assertion.String):

    layer = zeit.campus.testing.LAYER

    def test_zco_infobox_has_debate_field(self):
        b = self.browser
        b.open('http://localhost/++skin++vivi/repository/campus')
        menu = b.getControl(name='add_menu')
        menu.displayValue = ['Infobox']
        b.open(menu.value[0])

        b.getControl('File name').value = 'info'
        b.getControl('Supertitle').value = 'spitz'
        b.getControl('Debate action URL').value = 'mailto:foo@example.com'
        b.getControl(name='form.actions.add').click()

        self.assertEndsWith('@@edit.html', b.url)
        self.assertEqual(
            'mailto:foo@example.com', b.getControl('Debate action URL').value)

        b.getLink('Checkin').click()
        self.assertEllipsis('...mailto:foo@example.com...', b.contents)


text:
class ChatRoomController < ApplicationController
  def show
    @chatroom = ChatRoom.default_chat_room
    @message = Message.new
  end
end


text:
<?php

namespace Framework\Tests\Controller;

use
	\Framework\Controller\Controller,
	\Framework\Request\Request,
	\Framework\View\View
;

class Controller_Test extends \PHPUnit_Framework_TestCase {

	/**
	 * @covers \Framework\Controller\Controller::__construct
	 * @covers \Framework\Controller\Controller::getRequest
	 * @covers \Framework\Controller\Controller::getView
	 */
	public function testConstruct() {
		$view = new View();
		$request = new Request();

		$controller = new Controller($request, $view);
	}

	/**
	 * @covers \Framework\Controller\Controller::getRequest
	 * @covers \Framework\Controller\Controller::getView
	 */
	public function testGetRequest() {
		$view = new View();
		$request = new Request();

		$controller = new Controller($request, $view);

		$this->assertEquals('Framework\Request\Request', get_class($controller->getRequest()));
		$this->assertEquals('Framework\View\View', get_class($controller->getView()));
	}

	/**
	 * @covers \Framework\Controller\Controller::_preInit
	 * @covers \Framework\Controller\Controller::_init
	 * @covers \Framework\Controller\Controller::_postInit
	 * @covers \Framework\Controller\Controller::_preAction
	 * @covers \Framework\Controller\Controller::_postAction
	 * @covers \Framework\Controller\Controller::_preRender
	 * @covers \Framework\Controller\Controller::_postRender
	 * @covers \Framework\Controller\Controller::_preShutdown
	 * @covers \Framework\Controller\Controller::_shutdown
	 * @covers \Framework\Controller\Controller::_postShutdown
	 */
	public function testHooks() {
		$this->assertTrue(method_exists('Framework\Controller\Controller', '_preInit'));
		$this->assertTrue(method_exists('Framework\Controller\Controller', '_init'));
		$this->assertTrue(method_exists('Framework\Controller\Controller', '_postInit'));
		$this->assertTrue(method_exists('Framework\Controller\Controller', '_preAction'));
		$this->assertTrue(method_exists('Framework\Controller\Controller', '_postAction'));
		$this->assertTrue(method_exists('Framework\Controller\Controller', '_preRender'));
		$this->assertTrue(method_exists('Framework\Controller\Controller', '_postRender'));
		$this->assertTrue(method_exists('Framework\Controller\Controller', '_preShutdown'));
		$this->assertTrue(method_exists('Framework\Controller\Controller', '_shutdown'));
		$this->assertTrue(method_exists('Framework\Controller\Controller', '_postShutdown'));

		$view = new View();
		$request = new Request();

		$controller = new Controller($request, $view);

		// just need to make sure these eixsts
		$controller->_preInit();
		$controller->_init();
		$controller->_postInit();
		$controller->_preAction();
		$controller->_postAction();
		$controller->_preRender();
		$controller->_postRender();
		$controller->_preShutdown();
		$controller->_shutdown();
		$controller->_postShutdown();
	}

}


text:
package ninja.mpnguyen.chowders.nio.html;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;

import ninja.mpnguyen.chowders.nio.StringGet;

public abstract class GetHtml<T> extends StringGet<T> {
    public interface Parser<T> {
        T parse(Element e);
    }

    @Override
    public T handle(String html) {
        return getParser().parse(Jsoup.parse(html));
    }

    public abstract Parser<T> getParser();
}


text:
package io.quarkus.hibernate.reactive.panache.common.runtime;

import java.util.Map;
import java.util.Set;

import io.quarkus.runtime.annotations.Recorder;

@Recorder
public class PanacheHibernateRecorder {
    public void setNamedQueryMap(Map<String, Set<String>> namedQueryMap) {
        NamedQueryUtil.setNamedQueryMap(namedQueryMap);
    }
}


text:
using System;

namespace Piranha.Data
{
	/// <summary>
	/// Tools for seeding the database with default data.
	/// </summary>
	internal static class Seed
	{
		#region Members
		private const string ROLE_SYSADMIN = "Piranha SysAdmin";
		private const string ROLE_ADMIN = "Piranha Admin";
		#endregion

		/// <summary>
		/// Seed params.
		/// </summary>
		/// <param name="api">The current api</param>
		public static void Params(Api api) {
			var param = api.Params.GetSingle(where: p => p.Name == "site_title");
			if (param == null) {
				api.Params.Add(new Models.Param() {
					Name = "site_title",
					Value = "Piranha CMS"
				});
			}

			param = api.Params.GetSingle(where: p => p.Name == "site_description");
			if (param == null) {
				api.Params.Add(new Models.Param() {
					Name = "site_description",
					Value = "Welcome to Piranha CMS"
				});
			}

			param = api.Params.GetSingle(where: p => p.Name == "site_lastmodified");
			if (param == null) {
				api.Params.Add(new Models.Param() {
					Name = "site_lastmodified",
					Value = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
				});
			}

			param = api.Params.GetSingle(where: p => p.Name == "archive_pagesize");
			if (param == null) {
				api.Params.Add(new Models.Param() {
					Name = "archive_pagesize",
					Value = "10"
				});
			}

			param = api.Params.GetSingle(where: p => p.Name == "cache_expires");
			if (param == null) {
				api.Params.Add(new Models.Param() {
					Name = "cache_expires",
					Value = "0"
				});
			}

			param = api.Params.GetSingle(where: p => p.Name == "cache_maxage");
			if (param == null) {
				api.Params.Add(new Models.Param() {
					Name = "cache_maxage",
					Value = "0"
				});
			}

			param = api.Params.GetSingle(where: p => p.Name == "comment_moderate_authorized");
			if (param == null) {
				api.Params.Add(new Models.Param() {
					Name = "comment_moderate_authorized",
					Value = false.ToString()
				});
			}

			param = api.Params.GetSingle(where: p => p.Name == "comment_moderate_anonymous");
			if (param == null) {
				api.Params.Add(new Models.Param() {
					Name = "comment_moderate_anonymous",
					Value = false.ToString()
				});
			}

			param = api.Params.GetSingle(where: p => p.Name == "comment_notify_author");
			if (param == null) {
				api.Params.Add(new Models.Param() {
					Name = "comment_notify_author",
					Value = false.ToString()
				});
			}

			param = api.Params.GetSingle(where: p => p.Name == "comment_notify_moderators");
			if (param == null) {
				api.Params.Add(new Models.Param() {
					Name = "comment_notify_moderators",
					Value = false.ToString()
				});
			}

			param = api.Params.GetSingle(where: p => p.Name == "comment_moderators");
			if (param == null) {
				api.Params.Add(new Models.Param() {
					Name = "comment_moderators",
					Value = ""
				});
			}
			api.SaveChanges();
		}
	}
}


text: Works I've made using LaTeX. Mainly labs, papers and stuff.


text:
<?php

/**
 * Base class that represents a query for the 'sf_guard_group_permission' table.
 *
 *
 *
 * @method     sfGuardGroupPermissionQuery orderByGroupId($order = Criteria::ASC) Order by the group_id column
 * @method     sfGuardGroupPermissionQuery orderByPermissionId($order = Criteria::ASC) Order by the permission_id column
 *
 * @method     sfGuardGroupPermissionQuery groupByGroupId() Group by the group_id column
 * @method     sfGuardGroupPermissionQuery groupByPermissionId() Group by the permission_id column
 *
 * @method     sfGuardGroupPermissionQuery leftJoin($relation) Adds a LEFT JOIN clause to the query
 * @method     sfGuardGroupPermissionQuery rightJoin($relation) Adds a RIGHT JOIN clause to the query
 * @method     sfGuardGroupPermissionQuery innerJoin($relation) Adds a INNER JOIN clause to the query
 *
 * @method     sfGuardGroupPermissionQuery leftJoinsfGuardGroup($relationAlias = null) Adds a LEFT JOIN clause to the query using the sfGuardGroup relation
 * @method     sfGuardGroupPermissionQuery rightJoinsfGuardGroup($relationAlias = null) Adds a RIGHT JOIN clause to the query using the sfGuardGroup relation
 * @method     sfGuardGroupPermissionQuery innerJoinsfGuardGroup($relationAlias = null) Adds a INNER JOIN clause to the query using the sfGuardGroup relation
 *
 * @method     sfGuardGroupPermissionQuery leftJoinsfGuardPermission($relationAlias = null) Adds a LEFT JOIN clause to the query using the sfGuardPermission relation
 * @method     sfGuardGroupPermissionQuery rightJoinsfGuardPermission($relationAlias = null) Adds a RIGHT JOIN clause to the query using the sfGuardPermission relation
 * @method     sfGuardGroupPermissionQuery innerJoinsfGuardPermission($relationAlias = null) Adds a INNER JOIN clause to the query using the sfGuardPermission relation
 *
 * @method     sfGuardGroupPermission findOne(PropelPDO $con = null) Return the first sfGuardGroupPermission matching the query
 * @method     sfGuardGroupPermission findOneOrCreate(PropelPDO $con = null) Return the first sfGuardGroupPermission matching the query, or a new sfGuardGroupPermission object populated from the query conditions when no match is found
 *
 * @method     sfGuardGroupPermission findOneByGroupId(int $group_id) Return the first sfGuardGroupPermission filtered by the group_id column
 * @method     sfGuardGroupPermission findOneByPermissionId(int $permission_id) Return the first sfGuardGroupPermission filtered by the permission_id column
 *
 * @method     array findByGroupId(int $group_id) Return sfGuardGroupPermission objects filtered by the group_id column
 * @method     array findByPermissionId(int $permission_id) Return sfGuardGroupPermission objects filtered by the permission_id column
 *
 * @package    propel.generator.plugins.sfGuardPlugin.lib.model.om
 */
abstract class BasesfGuardGroupPermissionQuery extends ModelCriteria
{

    /**
     * Initializes internal state of BasesfGuardGroupPermissionQuery object.
     *
     * @param     string $dbName The dabase name
     * @param     string $modelName The phpName of a model, e.g. 'Book'
     * @param     string $modelAlias The alias for the model in this query, e.g. 'b'
     */
    public function __construct($dbName = 'propel', $modelName = 'sfGuardGroupPermission', $modelAlias = null)
    {
        parent::__construct($dbName, $modelName, $modelAlias);
    }

    /**
     * Returns a new sfGuardGroupPermissionQuery object.
     *
     * @param     string $modelAlias The alias of a model in the query
     * @param     sfGuardGroupPermissionQuery|Criteria $criteria Optional Criteria to build the query from
     *
     * @return sfGuardGroupPermissionQuery
     */
    public static function create($modelAlias = null, $criteria = null)
    {
        if ($criteria instanceof sfGuardGroupPermissionQuery) {
            return $criteria;
        }
        $query = new sfGuardGroupPermissionQuery();
        if (null !== $modelAlias) {
            $query->setModelAlias($modelAlias);
        }
        if ($criteria instanceof Criteria) {
            $query->mergeWith($criteria);
        }

        return $query;
    }

    /**
     * Find object by primary key.
     * Propel uses the instance pool to skip the database if the object exists.
     * Go fast if the query is untouched.
     *
     *
     * $obj = $c->findPk(array(12, 34), $con);
     *
     *
     * @param array $key Primary key to use for the query
                         A Primary key composition: [$group_id, $permission_id]
     * @param     PropelPDO $con an optional connection object
     *
     * @return   sfGuardGroupPermission|sfGuardGroupPermission[]|mixed the result, formatted by the current formatter
     */
    public function findPk($key, $con = null)
    {
        if ($key === null) {
            return null;
        }
        if ((null !== ($obj = sfGuardGroupPermissionPeer::getInstanceFromPool(serialize(array((string) $key[0], (string) $key[1]))))) && !$this->formatter) {
            // the object is alredy in the instance pool
            return $obj;
        }
        if ($con === null) {
            $con = Propel::getConnection(sfGuardGroupPermissionPeer::DATABASE_NAME, Propel::CONNECTION_READ);
        }
        $this->basePreSelect($con);
        if ($this->formatter || $this->modelAlias || $this->with || $this->select
         || $this->selectColumns || $this->asColumns || $this->selectModifiers
         || $this->map || $this->having || $this->joins) {
            return $this->findPkComplex($key, $con);
        } else {
            return $this->findPkSimple($key, $con);
        }
    }

    /**
     * Find object by primary key using raw SQL to go fast.
     * Bypass doSelect() and the object formatter by using generated code.
     *
     * @param     mixed $key Primary key to use for the query
     * @param     PropelPDO $con A connection object
     *
     * @return   sfGuardGroupPermission A model object, or null if the key is not found
     * @throws   PropelException
     */
    protected function findPkSimple($key, $con)
    {
        $sql = 'SELECT `GROUP_ID`, `PERMISSION_ID` FROM `sf_guard_group_permission` WHERE `GROUP_ID` = :p0 AND `PERMISSION_ID` = :p1';
        try {
            $stmt = $con->prepare($sql);
			$stmt->bindValue(':p0', $key[0], PDO::PARAM_INT);
			$stmt->bindValue(':p1', $key[1], PDO::PARAM_INT);
            $stmt->execute();
        } catch (Exception $e) {
            Propel::log($e->getMessage(), Propel::LOG_ERR);
            throw new PropelException(sprintf('Unable to execute SELECT statement [%s]', $sql), $e);
        }
        $obj = null;
        if ($row = $stmt->fetch(PDO::FETCH_NUM)) {
            $obj = new sfGuardGroupPermission();
            $obj->hydrate($row);
            sfGuardGroupPermissionPeer::addInstanceToPool($obj, serialize(array((string) $key[0], (string) $key[1])));
        }
        $stmt->closeCursor();

        return $obj;
    }

    /**
     * Find object by primary key.
     *
     * @param     mixed $key Primary key to use for the query
     * @param     PropelPDO $con A connection object
     *
     * @return sfGuardGroupPermission|sfGuardGroupPermission[]|mixed the result, formatted by the current formatter
     */
    protected function findPkComplex($key, $con)
    {
        // As the query uses a PK condition, no limit(1) is necessary.
        $criteria = $this->isKeepQuery() ? clone $this : $this;
        $stmt = $criteria
            ->filterByPrimaryKey($key)
            ->doSelect($con);

        return $criteria->getFormatter()->init($criteria)->formatOne($stmt);
    }

    /**
     * Find objects by primary key
     *
     * $objs = $c->findPks(array(array(12, 56), array(832, 123), array(123, 456)), $con);
     *
     * @param     array $keys Primary keys to use for the query
     * @param     PropelPDO $con an optional connection object
     *
     * @return PropelObjectCollection|sfGuardGroupPermission[]|mixed the list of results, formatted by the current formatter
     */
    public function findPks($keys, $con = null)
    {
        if ($con === null) {
            $con = Propel::getConnection($this->getDbName(), Propel::CONNECTION_READ);
        }
        $this->basePreSelect($con);
        $criteria = $this->isKeepQuery() ? clone $this : $this;
        $stmt = $criteria
            ->filterByPrimaryKeys($keys)
            ->doSelect($con);

        return $criteria->getFormatter()->init($criteria)->format($stmt);
    }

    /**
     * Filter the query by primary key
     *
     * @param     mixed $key Primary key to use for the query
     *
     * @return sfGuardGroupPermissionQuery The current query, for fluid interface
     */
    public function filterByPrimaryKey($key)
    {
        $this->addUsingAlias(sfGuardGroupPermissionPeer::GROUP_ID, $key[0], Criteria::EQUAL);
        $this->addUsingAlias(sfGuardGroupPermissionPeer::PERMISSION_ID, $key[1], Criteria::EQUAL);

        return $this;
    }

    /**
     * Filter the query by a list of primary keys
     *
     * @param     array $keys The list of primary key to use for the query
     *
     * @return sfGuardGroupPermissionQuery The current query, for fluid interface
     */
    public function filterByPrimaryKeys($keys)
    {
        if (empty($keys)) {
            return $this->add(null, '1<>1', Criteria::CUSTOM);
        }
        foreach ($keys as $key) {
            $cton0 = $this->getNewCriterion(sfGuardGroupPermissionPeer::GROUP_ID, $key[0], Criteria::EQUAL);
            $cton1 = $this->getNewCriterion(sfGuardGroupPermissionPeer::PERMISSION_ID, $key[1], Criteria::EQUAL);
            $cton0->addAnd($cton1);
            $this->addOr($cton0);
        }

        return $this;
    }

    /**
     * Filter the query on the group_id column
     *
     * Example usage:
     *
     * $query->filterByGroupId(1234); // WHERE group_id = 1234
     * $query->filterByGroupId(array(12, 34)); // WHERE group_id IN (12, 34)
     * $query->filterByGroupId(array('min' => 12)); // WHERE group_id > 12
     *
     *
     * @see       filterBysfGuardGroup()
     *
     * @param     mixed $groupId The value to use as filter.
     *              Use scalar values for equality.
     *              Use array values for in_array() equivalent.
     *              Use associative array('min' => $minValue, 'max' => $maxValue) for intervals.
     * @param     string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL
     *
     * @return sfGuardGroupPermissionQuery The current query, for fluid interface
     */
    public function filterByGroupId($groupId = null, $comparison = null)
    {
        if (is_array($groupId) && null === $comparison) {
            $comparison = Criteria::IN;
        }

        return $this->addUsingAlias(sfGuardGroupPermissionPeer::GROUP_ID, $groupId, $comparison);
    }

    /**
     * Filter the query on the permission_id column
     *
     * Example usage:
     *
     * $query->filterByPermissionId(1234); // WHERE permission_id = 1234
     * $query->filterByPermissionId(array(12, 34)); // WHERE permission_id IN (12, 34)
     * $query->filterByPermissionId(array('min' => 12)); // WHERE permission_id > 12
     *
     *
     * @see       filterBysfGuardPermission()
     *
     * @param     mixed $permissionId The value to use as filter.
     *              Use scalar values for equality.
     *              Use array values for in_array() equivalent.
     *              Use associative array('min' => $minValue, 'max' => $maxValue) for intervals.
     * @param     string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL
     *
     * @return sfGuardGroupPermissionQuery The current query, for fluid interface
     */
    public function filterByPermissionId($permissionId = null, $comparison = null)
    {
        if (is_array($permissionId) && null === $comparison) {
            $comparison = Criteria::IN;
        }

        return $this->addUsingAlias(sfGuardGroupPermissionPeer::PERMISSION_ID, $permissionId, $comparison);
    }

    /**
     * Filter the query by a related sfGuardGroup object
     *
     * @param   sfGuardGroup|PropelObjectCollection $sfGuardGroup The related object(s) to use as filter
     * @param     string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL
     *
     * @return   sfGuardGroupPermissionQuery The current query, for fluid interface
     * @throws   PropelException - if the provided filter is invalid.
     */
    public function filterBysfGuardGroup($sfGuardGroup, $comparison = null)
    {
        if ($sfGuardGroup instanceof sfGuardGroup) {
            return $this
                ->addUsingAlias(sfGuardGroupPermissionPeer::GROUP_ID, $sfGuardGroup->getId(), $comparison);
        } elseif ($sfGuardGroup instanceof PropelObjectCollection) {
            if (null === $comparison) {
                $comparison = Criteria::IN;
            }

            return $this
                ->addUsingAlias(sfGuardGroupPermissionPeer::GROUP_ID, $sfGuardGroup->toKeyValue('PrimaryKey', 'Id'), $comparison);
        } else {
            throw new PropelException('filterBysfGuardGroup() only accepts arguments of type sfGuardGroup or PropelCollection');
        }
    }

    /**
     * Adds a JOIN clause to the query using the sfGuardGroup relation
     *
     * @param     string $relationAlias optional alias for the relation
     * @param     string $joinType Accepted values are null, 'left join', 'right join', 'inner join'
     *
     * @return sfGuardGroupPermissionQuery The current query, for fluid interface
     */
    public function joinsfGuardGroup($relationAlias = null, $joinType = Criteria::INNER_JOIN)
    {
        $tableMap = $this->getTableMap();
        $relationMap = $tableMap->getRelation('sfGuardGroup');

        // create a ModelJoin object for this join
        $join = new ModelJoin();
        $join->setJoinType($joinType);
        $join->setRelationMap($relationMap, $this->useAliasInSQL ? $this->getModelAlias() : null, $relationAlias);
        if ($previousJoin = $this->getPreviousJoin()) {
            $join->setPreviousJoin($previousJoin);
        }

        // add the ModelJoin to the current object
        if ($relationAlias) {
            $this->addAlias($relationAlias, $relationMap->getRightTable()->getName());
            $this->addJoinObject($join, $relationAlias);
        } else {
            $this->addJoinObject($join, 'sfGuardGroup');
        }

        return $this;
    }

    /**
     * Use the sfGuardGroup relation sfGuardGroup object
     *
     * @see       useQuery()
     *
     * @param     string $relationAlias optional alias for the relation,
     *                                   to be used as main alias in the secondary query
     * @param     string $joinType Accepted values are null, 'left join', 'right join', 'inner join'
     *
     * @return   sfGuardGroupQuery A secondary query class using the current class as primary query
     */
    public function usesfGuardGroupQuery($relationAlias = null, $joinType = Criteria::INNER_JOIN)
    {
        return $this
            ->joinsfGuardGroup($relationAlias, $joinType)
            ->useQuery($relationAlias ? $relationAlias : 'sfGuardGroup', 'sfGuardGroupQuery');
    }

    /**
     * Filter the query by a related sfGuardPermission object
     *
     * @param   sfGuardPermission|PropelObjectCollection $sfGuardPermission The related object(s) to use as filter
     * @param     string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL
     *
     * @return   sfGuardGroupPermissionQuery The current query, for fluid interface
     * @throws   PropelException - if the provided filter is invalid.
     */
    public function filterBysfGuardPermission($sfGuardPermission, $comparison = null)
    {
        if ($sfGuardPermission instanceof sfGuardPermission) {
            return $this
                ->addUsingAlias(sfGuardGroupPermissionPeer::PERMISSION_ID, $sfGuardPermission->getId(), $comparison);
        } elseif ($sfGuardPermission instanceof PropelObjectCollection) {
            if (null === $comparison) {
                $comparison = Criteria::IN;
            }

            return $this
                ->addUsingAlias(sfGuardGroupPermissionPeer::PERMISSION_ID, $sfGuardPermission->toKeyValue('PrimaryKey', 'Id'), $comparison);
        } else {
            throw new PropelException('filterBysfGuardPermission() only accepts arguments of type sfGuardPermission or PropelCollection');
        }
    }

    /**
     * Adds a JOIN clause to the query using the sfGuardPermission relation
     *
     * @param     string $relationAlias optional alias for the relation
     * @param     string $joinType Accepted values are null, 'left join', 'right join', 'inner join'
     *
     * @return sfGuardGroupPermissionQuery The current query, for fluid interface
     */
    public function joinsfGuardPermission($relationAlias = null, $joinType = Criteria::INNER_JOIN)
    {
        $tableMap = $this->getTableMap();
        $relationMap = $tableMap->getRelation('sfGuardPermission');

        // create a ModelJoin object for this join
        $join = new ModelJoin();
        $join->setJoinType($joinType);
        $join->setRelationMap($relationMap, $this->useAliasInSQL ? $this->getModelAlias() : null, $relationAlias);
        if ($previousJoin = $this->getPreviousJoin()) {
            $join->setPreviousJoin($previousJoin);
        }

        // add the ModelJoin to the current object
        if ($relationAlias) {
            $this->addAlias($relationAlias, $relationMap->getRightTable()->getName());
            $this->addJoinObject($join, $relationAlias);
        } else {
            $this->addJoinObject($join, 'sfGuardPermission');
        }

        return $this;
    }

    /**
     * Use the sfGuardPermission relation sfGuardPermission object
     *
     * @see       useQuery()
     *
     * @param     string $relationAlias optional alias for the relation,
     *                                   to be used as main alias in the secondary query
     * @param     string $joinType Accepted values are null, 'left join', 'right join', 'inner join'
     *
     * @return   sfGuardPermissionQuery A secondary query class using the current class as primary query
     */
    public function usesfGuardPermissionQuery($relationAlias = null, $joinType = Criteria::INNER_JOIN)
    {
        return $this
            ->joinsfGuardPermission($relationAlias, $joinType)
            ->useQuery($relationAlias ? $relationAlias : 'sfGuardPermission', 'sfGuardPermissionQuery');
    }

    /**
     * Exclude object from result
     *
     * @param   sfGuardGroupPermission $sfGuardGroupPermission Object to remove from the list of results
     *
     * @return sfGuardGroupPermissionQuery The current query, for fluid interface
     */
    public function prune($sfGuardGroupPermission = null)
    {
        if ($sfGuardGroupPermission) {
            $this->addCond('pruneCond0', $this->getAliasedColName(sfGuardGroupPermissionPeer::GROUP_ID), $sfGuardGroupPermission->getGroupId(), Criteria::NOT_EQUAL);
            $this->addCond('pruneCond1', $this->getAliasedColName(sfGuardGroupPermissionPeer::PERMISSION_ID), $sfGuardGroupPermission->getPermissionId(), Criteria::NOT_EQUAL);
            $this->combine(array('pruneCond0', 'pruneCond1'), Criteria::LOGICAL_OR);
        }

        return $this;
    }

} // BasesfGuardGroupPermissionQuery


text:
// OpenGL ES 2.0 code

#include "GLDemo.h"

#include "Texture.h"

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

static const char gVertexShader[] =
"attribute vec4 vPosition;\n"
"attribute vec4 vUV;\n"
"varying vec2 v_texCoord;\n"
"void main() {\n"
"  gl_Position = vPosition;\n"
"  v_texCoord = vUV.st;\n"
"}\n";

static const char gFragmentShader[] =
"precision mediump float;\n"
"uniform sampler2D sampler2d;\n"
"varying vec2 v_texCoord;\n"
"void main() {\n"
"  gl_FragColor = texture2D(sampler2d, v_texCoord);\n"
"}\n";

GLuint loadShader(GLenum shaderType, const char* pSource) {
    GLuint shader = glCreateShader(shaderType);
    if (shader) {
        glShaderSource(shader, 1, &pSource, NULL);
        glCompileShader(shader);
        GLint compiled = 0;
        glGetShaderiv(shader, GL_COMPILE_STATUS, &compiled);
        if (!compiled) {
            GLint infoLen = 0;
            glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &infoLen);
            if (infoLen) {
                char* buf = (char*) malloc(infoLen);
                if (buf) {
                    glGetShaderInfoLog(shader, infoLen, NULL, buf);
                    free(buf);
                }
                glDeleteShader(shader);
                shader = 0;
            }
        }
    }
    return shader;
}

GLuint createProgram(const char* pVertexSource, const char* pFragmentSource) {
    GLuint vertexShader = loadShader(GL_VERTEX_SHADER, pVertexSource);
    if (!vertexShader) {
        return 0;
    }

    GLuint pixelShader = loadShader(GL_FRAGMENT_SHADER, pFragmentSource);
    if (!pixelShader) {
        return 0;
    }

    GLuint program = glCreateProgram();
    if (program) {
        glAttachShader(program, vertexShader);
        glAttachShader(program, pixelShader);
        glLinkProgram(program);
        GLint linkStatus = GL_FALSE;
        glGetProgramiv(program, GL_LINK_STATUS, &linkStatus);
        if (linkStatus != GL_TRUE) {
            GLint bufLength = 0;
            glGetProgramiv(program, GL_INFO_LOG_LENGTH, &bufLength);
            if (bufLength) {
                char* buf = (char*) malloc(bufLength);
                if (buf) {
                    glGetProgramInfoLog(program, bufLength, NULL, buf);
                    free(buf);
                }
            }
            glDeleteProgram(program);
            program = 0;
        }
    }
    return program;
}

GLuint gProgram;
GLuint gvPositionHandle;
GLuint gvUVHandle;

bool setupGraphics(int w, int h, std::string bundlePath) {

    gProgram = createProgram(gVertexShader, gFragmentShader);
    if (!gProgram) {
        return false;
    }
    gvPositionHandle = glGetAttribLocation(gProgram, "vPosition");
    gvUVHandle = glGetAttribLocation(gProgram, "vUV");

    glViewport(0, 0, w, h);

    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    glClearColor(0.0f, 0.0f, 0.0f, 1.0f);

    std::string fullTexturePath = bundlePath + "/Candy_Person1.png";
    std::string pngStreamString;
    std::ifstream sourceFile( fullTexturePath.c_str() );

    //Source file loaded
    if( !sourceFile )
    {
        return false;
    }

    //Get PNG file contents
    pngStreamString.assign( ( std::istreambuf_iterator< char >( sourceFile ) ), std::istreambuf_iterator< char >() );

    // Convert it into a data stream
    std::istringstream pngDataStream( pngStreamString );

    GLuint texture = LoadFromStream(pngDataStream);

    glBindTexture(GL_TEXTURE_2D, texture);

    return true;
}

const GLfloat gSquareVertices[] = { -0.5f, -0.5f, 0.0f, 0.0f,
                                    0.5f, -0.5f, 1.0f, 0.0f,
                                    0.5f, 0.5f, 1.0f, 1.0f,
                                    -0.5f, -0.5f, 0.0f, 0.0f,
                                    0.5f, 0.5f, 1.0f, 1.0f,
                                    -0.5f, 0.5f, 0.0f, 1.0f };

void renderFrame() {

    glClear( GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);

    glUseProgram(gProgram);

    int stride = 4*sizeof(GLfloat);

    glVertexAttribPointer(gvPositionHandle, 2, GL_FLOAT, GL_FALSE, stride, &gSquareVertices[0]);
    glVertexAttribPointer(gvUVHandle, 2, GL_FLOAT, GL_FALSE, stride, &gSquareVertices[2]);

    glEnableVertexAttribArray(gvPositionHandle);
    glEnableVertexAttribArray(gvUVHandle);

    glDrawArrays(GL_TRIANGLES, 0, 6);

}


text:
import _ from 'lodash';
import { DataEntity } from '@terascope/job-components';
import { OperationConfig } from '../../interfaces';

export default abstract class OperationBase {
    protected source: string;
    protected target: string;
    protected removeSource: boolean;

    constructor(config: OperationConfig) {
        this.source = '';
        this.target = '';
        this.removeSource =  false;
        this.validate(config);
    }

    protected validate(config: OperationConfig) {
        // we don't need to check target or source for selector ops
        if (this.constructor.name === 'Selector' || this.constructor.name === 'RequiredExtractions') return;
        const { target_field: targetField, source_field: sField, remove_source } = config;
        const tField = targetField || sField;
        if (remove_source && typeof remove_source !== 'boolean') throw new Error('remove_source if specified must be of type boolean');
        if (!tField || typeof tField !== 'string' || tField.length === 0) {
            throw new Error(`could not find target_field for ${this.constructor.name} validation or it is improperly formatted, config: ${JSON.stringify(config)}`);
        }
        if (!sField || typeof sField !== 'string' || sField.length === 0) {
            throw new Error(`could not find source_field for ${this.constructor.name} validation or it is improperly formatted, config: ${JSON.stringify(config)}`);
        }
        if (remove_source) this.removeSource = remove_source;
        this.source = sField;
        this.target = tField;
    }

    protected fieldPath(str: string): string {
        return str.lastIndexOf('.') === -1 ? str : str.slice(0, str.lastIndexOf('.'));
    }

    protected decode(doc: DataEntity, decodeFn: Function) {
        try {
            const data = _.get(doc, this.source);
            if (typeof data !== 'string') {
                _.unset(doc, this.source);
            } else {
                _.set(doc, this.target, decodeFn(data));
            }
        } catch (err) {
            _.unset(doc, this.source);
        }

        if (this.removeSource) _.unset(doc, this.source);
        return doc;
    }

    abstract run(data: DataEntity): null | DataEntity;
}


text:
module AlchemyNodes
  class ApplicationController < ActionController::Base
  end
end


text:
CVE-2022-35986

### Impact
If `RaggedBincount` is given an empty input tensor `splits`, it results in a segfault that can be used to trigger a denial of service attack.
```python
import tensorflow as tf
binary_output = True
splits = tf.random.uniform(shape=[0], minval=-10000, maxval=10000, dtype=tf.int64, seed=-7430)
values = tf.random.uniform(shape=[], minval=-10000, maxval=10000, dtype=tf.int32, seed=-10000)
size = tf.random.uniform(shape=[], minval=-10000, maxval=10000, dtype=tf.int32, seed=-10000)
weights = tf.random.uniform(shape=[], minval=-10000, maxval=10000, dtype=tf.float32, seed=-10000)
tf.raw_ops.RaggedBincount(splits=splits, values=values, size=size, weights=weights, binary_output=binary_output)
```

### Patches
We have patched the issue in GitHub commit [7a4591fd4f065f4fa903593bc39b2f79530a74b8](https://github.com/tensorflow/tensorflow/commit/7a4591fd4f065f4fa903593bc39b2f79530a74b8).

The fix will be included in TensorFlow 2.10.0. We will also cherrypick this commit on TensorFlow 2.9.1, TensorFlow 2.8.1, and TensorFlow 2.7.2, as these are also affected and still in supported range.

### For more information
Please consult [our security guide](https://github.com/tensorflow/tensorflow/blob/master/SECURITY.md) for more information regarding the security model and how to contact us with issues and questions.

### Attribution
This vulnerability has been reported by Di Jin, Secure Systems Labs, Brown University


text:
package org.wso2.carbon.apimgt.rest.api.analytics;

import io.swagger.annotations.ApiParam;

import org.wso2.carbon.apimgt.rest.api.analytics.dto.SubscriptionCountListDTO;
import org.wso2.carbon.apimgt.rest.api.analytics.dto.SubscriptionInfoListDTO;
import org.wso2.carbon.apimgt.rest.api.analytics.factories.SubscriptionApiServiceFactory;

import org.wso2.msf4j.Microservice;
import org.wso2.msf4j.Request;
import org.wso2.msf4j.formparam.FileInfo;
import org.wso2.msf4j.formparam.FormDataParam;
import org.osgi.service.component.annotations.Component;

import java.io.InputStream;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.HEAD;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;

@Component(
    name = "org.wso2.carbon.apimgt.rest.api.analytics.SubscriptionApi",
    service = Microservice.class,
    immediate = true
)
@Path("/api/am/analytics/v1.[\\d]+/subscription")
@Consumes({ "application/json" })
@Produces({ "application/json" })
@ApplicationPath("/subscription")
@io.swagger.annotations.Api(description = "the subscription API")
public class SubscriptionApi implements Microservice  {
   private final SubscriptionApiService delegate = SubscriptionApiServiceFactory.getSubscriptionApi();

    @GET
    @Path("/count-over-time")
    @Consumes({ "application/json" })
    @Produces({ "application/json" })
    @io.swagger.annotations.ApiOperation(value = "Retrieve APIs created over time details ", notes = "Get application created over time details from summarized data. ", response = SubscriptionCountListDTO.class, authorizations = {
        @io.swagger.annotations.Authorization(value = "OAuth2Security", scopes = {
            @io.swagger.annotations.AuthorizationScope(scope = "apim:subscription_graph", description = "View Graphs Releated to subscriptions")
        })
    }, tags={  })
    @io.swagger.annotations.ApiResponses(value = {
        @io.swagger.annotations.ApiResponse(code = 200, message = "OK. Requested subscription count created over time information is returned ", response = SubscriptionCountListDTO.class),

        @io.swagger.annotations.ApiResponse(code = 400, message = "Bad Request. Request paramters attribute does not meet requiremnts. ", response = SubscriptionCountListDTO.class),

        @io.swagger.annotations.ApiResponse(code = 406, message = "Not Acceptable. The requested media type is not supported ", response = SubscriptionCountListDTO.class) })
    public Response subscriptionCountOverTimeGet(@ApiParam(value = "Defines the starting timestamp of the interval ",required=true) @QueryParam("startTime") String startTime
,@ApiParam(value = "Defines the ending timestamp of the interval ",required=true) @QueryParam("endTime") String endTime
,@ApiParam(value = "application/api creator name. In case of any creator is not provided all the details will be provided ") @QueryParam("createdBy") String createdBy
, @Context Request request)
    throws NotFoundException {
        return delegate.subscriptionCountOverTimeGet(startTime,endTime,createdBy, request);
    }
    @GET
    @Path("/list")
    @Consumes({ "application/json" })
    @Produces({ "application/json" })
    @io.swagger.annotations.ApiOperation(value = "Retrieve Subscription details ", notes = "Get Subscription details from summarized data. ", response = SubscriptionInfoListDTO.class, authorizations = {
        @io.swagger.annotations.Authorization(value = "OAuth2Security", scopes = {
            @io.swagger.annotations.AuthorizationScope(scope = "apim:subscription_graph", description = "View Graphs Releated to subscriptions")
        })
    }, tags={  })
    @io.swagger.annotations.ApiResponses(value = {
        @io.swagger.annotations.ApiResponse(code = 200, message = "OK. Requested Subscription Information is returned for the given time period ", response = SubscriptionInfoListDTO.class),

        @io.swagger.annotations.ApiResponse(code = 400, message = "Bad Request. Request paramters attribute does not meet requiremnts. ", response = SubscriptionInfoListDTO.class),

        @io.swagger.annotations.ApiResponse(code = 406, message = "Not Acceptable. The requested media type is not supported ", response = SubscriptionInfoListDTO.class) })
    public Response subscriptionListGet(@ApiParam(value = "Defines the starting timestamp of the interval ",required=true) @QueryParam("startTime") String startTime
,@ApiParam(value = "Defines the ending timestamp of the interval ",required=true) @QueryParam("endTime") String endTime
,@ApiParam(value = "application/api creator name. In case of any creator is not provided all the details will be provided ") @QueryParam("createdBy") String createdBy
, @Context Request request)
    throws NotFoundException {
        return delegate.subscriptionListGet(startTime,endTime,createdBy, request);
    }
}


text:
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
-- |
-- Module      :  Core.hs
--
-- Maintainer  :  adam.smyczek@gmail.com
-- Stability   :  experimental
-- Portability :  portable
--
-- The core module implements the base types and functions of the bindings.
--
-----------------------------------------------------------------------------

module ReviewBoard.Core (

    -- * RB action monad
    RBAction,
    runRBAction,
    runRequest,
    defaultResponseHandler,

    -- * RB state
    RBState(..),
    setErrorHandler,

    -- * Form fields
    RBRequestType(..),
    RBRequestMethod(..),
    Form(..),
    FormVar(..),
    textField,
    checkBox,
    fileUpload,

    -- * Response types
    RBResponse(..),
    responseToEither,

    -- * Common functions
    logout,

    ) where

import ReviewBoard.Response
import Control.Monad.Error
import Control.Monad.State
import Data.Maybe
import Text.JSON
import Network.Curl
import qualified Data.Map as M

-- ---------------------------------------------------------------------------
-- Review board action monad

-- | The action monad, a state with error handler.
--
-- 'RBAction' represents one ReviewBoard session that handles multiple API calls.
-- The RBAction runner 'runRBAction' performs a login to the ReviewBoard server
-- and initializes the session.  All session related parameters are stored in
-- the 'RBState' of the action.
--
-- Errors are handled in two ways:
--
-- * Network related errors are immediately thrown using ErrorT throwError.
--
-- * ReviewBoard response errors are handled using the error handler defined
-- in 'RBState' (default handler is print).
--
newtype RBAction a = RBAction
    { exec :: ErrorT String (StateT RBState IO) a }
    deriving (Functor, Monad, MonadIO, MonadState RBState, MonadError String)

-- | Run for 'RBAction', performs a login using provided URL, user
-- and password parameters and executes the action. When login fails
-- 'runRBAction' returns immediately with an error.
--
runRBAction :: String -> String -> String -> RBAction a -> IO (Either String a, RBState)
runRBAction url u p a = runStateT (runErrorT (exec init)) $ initState url u
    where init = login u p >> a

-- ---------------------------------------------------------------------------
-- State type and handler functions

-- | RB action state contains session related information.
--
data RBState = RBState
    { rbUrl        :: String          -- ^ ReviewBoard server URL
    , rbUser       :: String          -- ^ Logged in user
    , rbSessionId  :: Maybe String    -- ^ Session id cookie retrieve from a successful login
    , rbErrHandler :: String -> IO () -- ^ Error handler, for example error or print
    }

-- | Default state initialization including server URL and user.
--
initState :: String -> String -> RBState
initState url user = RBState
    { rbUrl        = url
    , rbUser       = user
    , rbSessionId  = Nothing
    , rbErrHandler = print }

-- | Session id setter
--
setSessionId :: Maybe String -> RBAction ()
setSessionId sid = get >>= \s -> put s { rbSessionId = sid }

-- | Set error handler used for ReviewBoard error responses.
--
setErrorHandler :: (String -> IO ()) -> RBAction ()
setErrorHandler eh = get >>= \s -> put s { rbErrHandler = eh }

-- ---------------------------------------------------------------------------
-- Request types

-- | Type of the request
--
data RBRequestType
    = API               -- ^ Default Json API request
    | HTTP              -- ^ HTTP request currently used to publish a review request
    deriving Show

-- | HTTP request method
--
data RBRequestMethod
    = GET               -- ^ GET
    | POST              -- ^ and POST
    deriving Show

-- | Typed form variable
--
data FormVar = FormVar
    { fvName :: String          -- ^ variable name
    , fvValue :: FormVarValue   -- ^ and content type
    } deriving Show

-- | Form content value types
--
data FormVarValue
    = TextField String              -- ^ A text field with String value
    | FileUpload FilePath String    -- ^ File upload referencing the file path and file name
    | CheckBox Bool                 -- ^ Boolean field, a check box
    deriving Show

-- | Form type
--
data Form = Form
    { requestType   :: RBRequestType    -- ^ the request type API or HTTP
    , requestMethod :: RBRequestMethod  -- ^ http method, GET or POST
    , apiURLString  :: URLString        -- ^ API sub-url e.g. 'repositories'
    , formVars      :: [FormVar] }      -- ^ Form fields

-- | Create text field variable
--
textField :: String -> String -> FormVar
textField n v = FormVar n $ TextField v

-- | Create checkbox variable
--
checkBox :: String -> Bool -> FormVar
checkBox n v = FormVar n $ CheckBox v

-- | Create file upload variable
--
fileUpload :: String -> FilePath -> String -> FormVar
fileUpload n p t = FormVar n $ FileUpload p t

-- ---------------------------------------------------------------------------
-- Response types

-- | Response type return by every API function
--
data RBResponse
    = RBok  JSValue -- ^ Successful response returns the JSON response object
    | RBerr String  -- ^ Response error
    deriving Eq

instance Show RBResponse where
   show (RBok r)    = "Ok: " ++ encode r
   show (RBerr e)   = "Error: " ++ e

-- | Convenient response to either converter
--
responseToEither :: RBResponse -> Either String JSValue
responseToEither (RBok r)   = Right r
responseToEither (RBerr s)  = Left s

-- ---------------------------------------------------------------------------
-- Request and response handling

-- | The request runner, generates request from provided 'Form' parameters,
-- executes the requests and handles the response using the handler function.
--
runRequest :: Form -> (Form -> CurlResponse -> RBAction a) -> RBAction a
runRequest form respHandler = do
    sid <- liftM rbSessionId get
    rt  <- requestType form
    rm  <- requestMethod form

    -- Execute request
    r <- liftIO $ initialize >>= \ h -> do
            setopt  h (CurlVerbose False)
            setopt  h rt
            setopts h rm
            setopt  h (CurlHttpPost (map toHttpPost $ formVars form))
            when (isJust sid) $ setopt h (CurlCookie . fromJust $ sid) >> return ()
            perform_with_response h

    -- Check response status
    case respCurlCode r of
        CurlOK -> respHandler form r
        c      -> throwError $ respStatusLine r ++ " (Code: " ++ show c ++ ")"
    where
        -- Request type to curl option
        requestType (Form API _ url _) = mkApiURL url >>= return . CurlURL
        requestType (Form HTTP _ url _) = mkHttpURL url >>= return . CurlURL

        -- Request method to curl options
        requestMethod (Form _ POST url _) = return method_POST
        requestMethod (Form _ GET  url _) = return method_GET

        -- HttpPost content
        toHttpPost (FormVar name (TextField value))       = multiformString name value
        toHttpPost (FormVar name (CheckBox bool))         = multiformString name (show bool)
        toHttpPost (FormVar name (FileUpload path ctype)) = HttpPost
            { postName      = name
            , content       = ContentFile path
            , contentType   = Just ctype
            , extraHeaders  = []
            , showName      = Nothing }

-- | Default response handler returns the RBResponse type
--
defaultResponseHandler :: Form -> CurlResponse -> RBAction RBResponse
defaultResponseHandler (Form API  _ _ _) resp = decodeResp resp >>= mkApiResponse
defaultResponseHandler (Form HTTP _ _ _) resp = mkHttpResponse resp

-- | Login action updates session id cookie from successful login response
--
login :: String -> String -> RBAction RBResponse
login user password = do
    let form = Form API POST "accounts/login/" [textField "username" user, textField "password" password]
    runRequest form withCookie
    where
        withCookie _ resp = (maybe noCookieErr (respond resp)) . getCookie . respHeaders $ resp
        respond resp sc   = setSessionId (Just sc) >> decodeResp resp >>= mkApiResponse
        noCookieErr       = throwError "No session cookie received!"
        getCookie hs      = (M.lookup "Set-Cookie" . M.fromList $ hs) :: Maybe String

-- | Logout and remove session cookie
--
logout :: RBAction RBResponse
logout = do
    let form = Form API POST "accounts/logout/" []
    runRequest form withCookie
    where
        withCookie _ resp = setSessionId Nothing >> decodeResp resp >>= mkApiResponse

-- | Decode response body
--
decodeResp = (either throwError return) . resultToEither . decode . respBody

-- | Create response for an API request
--
mkApiResponse :: JSValue -> RBAction RBResponse
mkApiResponse v = do
    erh <- liftM rbErrHandler get
    stat <- (return $ stat v) `catchError` (\_ -> return "")
    apiResp stat >>= handle erh
    where
        apiResp "ok"   = return $ RBok v
        apiResp "fail" = do
            err <- (return $ (msg . err)  v) `catchError` (\_ -> return "No error message received")
            return $ RBerr (err ++ " (" ++ encode v ++ ")")
        apiResp _      = return $ RBerr "Invalid response, not status received"

        -- Run handler on response
        handle :: (String -> IO ()) -> RBResponse -> RBAction RBResponse
        handle _ o@(RBok r) = return o
        handle eh o@(RBerr e) = liftIO (eh e) >> return o

-- | Create response for an HTTP request
-- The successful response returns a JSObject of the from:
-- { head : [
--              { name = "header name"
--                value = "header value" }
--          ],
--   body : "body content" }
--
mkHttpResponse :: CurlResponse -> RBAction RBResponse
mkHttpResponse r = return $ RBok . JSObject . toJSObject $
      [ ("head", mkHead (respHeaders r))
      , ("body", mkBody (respBody r)) ]
    where
        mkHead = JSArray . map (\(n, v) -> JSObject . toJSObject $
            [ ("name", JSString . toJSString . show $ n)
            , ("value", JSString . toJSString $ v)])
        mkBody = JSString . toJSString

-- ---------------------------------------------------------------------------
-- Util functions

-- | Create ReviewBoard specific URI for a Web API call URL.
--
mkApiURL :: String -> RBAction URLString
mkApiURL apiUrl = mkURL ("/api/json/" ++ apiUrl)

-- | Create ReviewBoard specific URI for direct HTTP request.
--
mkHttpURL = mkURL

-- | General URI maker.
--
mkURL :: String -> RBAction URLString
mkURL url = liftM ((++url) . rbUrl) get


text:
class CreateProjects < ActiveRecord::Migration
  def change
    create_table :projects do |t|
      t.belongs_to :owner, class_name: "User"
      t.string :name
      t.string :description
      t.date :due_date
      t.integer :status, default: 0
      t.timestamps null: false
    end
  end
end


text:
require 'rubygems'
require 'json'
require 'thor'
require 'thor/group'
require 'fileutils'
require 'active_support/inflector'
require 'active_support/core_ext/hash/indifferent_access'
require 'action_view'
require 'foreman_api/base'
require 'net/http'
require 'uri'
require 'pp'
require 'htmlentities'

module ForemanApi
  module Generator

    class Base < Thor::Group
      include Thor::Actions
      include ActionView::Helpers::SanitizeHelper

      attr_reader :doc, :resource, :resource_key

      def initialize(doc, *args)
        super
        @doc = doc.first
        @coder = HTMLEntities.new
      end

      def self.source_root
        File.expand_path("../template", __FILE__)
      end

      def self.start(foreman_url)
        foreman_url = foreman_url.sub(/\.json\Z/,"")
        foreman_url << "/v#{ForemanApi::Base::API_VERSION}.json"
        response = Net::HTTP.get_response(URI.parse(foreman_url))
        unless response.code == "200"
          raise "Could not load data from #{foreman_url}"
        end
        body = response.body
        File.open(ForemanApi.doc_file, "w") { |f| f.write(body) }
        doc = JSON.load(body).with_indifferent_access
        destination = File.expand_path("../../../..", __FILE__)
        super([doc[:docs]], :destination_root => destination)
      end

      def generate
        doc[:resources].each do |key, resource|
          @resource_key, @resource = key, resource
          template("resource.rb.tt", "lib/foreman_api/resources/#{resource_name}.rb")
        end
      end

      protected

      def camelizer(string)
        string = string.sub(/^[a-z\d]*/) { $&.capitalize }
        string.gsub(/(?:_|(\/))([a-z\d]*)/i) { "#{$2.capitalize}" }
      end

      # Resource related helper methods:

      def resource_name
        resource[:name].gsub(/\s/, "_").downcase.singularize
      end

      def validation(method)
        stringify = lambda do |object|
          case object
            when Hash
              clone = object.dup
              object.keys.each { |key| clone[key.to_s] = stringify[clone.delete(key)] }
              clone
            when Array
              object.map { |value| stringify[value] }
            else
              object
          end
        end
        ForemanApi::Base.construct_validation_hash(stringify[method])
      end

      def format_param_description(descr, prefix = ' ')
        unless descr.empty?
          prefix + strip_tags(@coder.decode(descr)).gsub(/\n/,' ').capitalize
        end
      end

      def all_params(method)
        all_params = method[:params].dup
        method[:apis].each do |api|
          ForemanApi::Base.params_in_path(api[:api_url]).each do |path_param|
            unless all_params.any? { |param| param['name'] == path_param }
              all_params << {'name' => path_param, 'expected_type' => 'object', 'description' => %[part of +#{api[:api_url]}+ path] }
            end
          end
        end
        return all_params
      end

      def prioritize_id(param)
        return "00" if param.upcase == 'ID'
        return "00#{param}" if param =~ /_id/i
        param
      end

    end
  end
end