text:
using System;
using System.Linq;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http.Internal;
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.Extensions.Logging;
using Xunit;

namespace E2ETests
{
    public partial class Validator
    {
        public async Task LoginWithMicrosoftAccount()
        {
            _httpClientHandler = new HttpClientHandler() { AllowAutoRedirect = false };
            _httpClient = new HttpClient(_httpClientHandler) { BaseAddress = new Uri(_deploymentResult.ApplicationBaseUri) };

            var response = await DoGetAsync("Account/Login");
            await ThrowIfResponseStatusNotOk(response);
            var responseContent = await response.Content.ReadAsStringAsync();
            _logger.LogInformation("Signing in with Microsoft account");
            var formParameters = new List<KeyValuePair<string, string>>
            {
                new KeyValuePair<string, string>("provider", "Microsoft"),
                new KeyValuePair<string, string>("returnUrl", "/"),
                new KeyValuePair<string, string>("__RequestVerificationToken", HtmlDOMHelper.RetrieveAntiForgeryToken(responseContent, "/Account/ExternalLogin")),
            };

            var content = new FormUrlEncodedContent(formParameters.ToArray());
            response = await DoPostAsync("Account/ExternalLogin", content);
            Assert.StartsWith("https://login.microsoftonline.com/common/oauth2/v2.0/authorize", response.Headers.Location.ToString());
            var queryItems = new QueryCollection(QueryHelpers.ParseQuery(response.Headers.Location.Query));
            Assert.Equal<string>("code", queryItems["response_type"]);
            Assert.Equal<string>("[ClientId]", queryItems["client_id"]);
            Assert.Equal<string>(_deploymentResult.ApplicationBaseUri + "signin-microsoft", queryItems["redirect_uri"]);
            Assert.Equal<string>("https://graph.microsoft.com/user.read wl.basic wl.signin", queryItems["scope"]);
            Assert.Equal<string>("ValidStateData", queryItems["state"]);
            Assert.Equal<string>("custom", queryItems["custom_redirect_uri"]);

            //Check for the correlation cookie
            Assert.NotEmpty(
                _httpClientHandler.CookieContainer.GetCookies(new Uri(_deploymentResult.ApplicationBaseUri))
                .Cast<Cookie>()
                .Where(cookie => cookie.Name.StartsWith(".AspNetCore.Correlation.Microsoft")));

            //This is just to generate a correlation cookie. Previous step would generate this cookie, but we have reset the handler now.
            _httpClientHandler = new HttpClientHandler();
            _httpClient = new HttpClient(_httpClientHandler) { BaseAddress = new Uri(_deploymentResult.ApplicationBaseUri) };

            response = await DoGetAsync("Account/Login");
            responseContent = await response.Content.ReadAsStringAsync();
            formParameters = new List<KeyValuePair<string, string>>
            {
                new KeyValuePair<string, string>("provider", "Microsoft"),
                new KeyValuePair<string, string>("returnUrl", "/"),
                new KeyValuePair<string, string>("__RequestVerificationToken", HtmlDOMHelper.RetrieveAntiForgeryToken(responseContent, "/Account/ExternalLogin")),
            };

            content = new FormUrlEncodedContent(formParameters.ToArray());
            response = await DoPostAsync("Account/ExternalLogin", content);
            //Post a message to the MicrosoftAccount middleware
            response = await DoGetAsync("signin-microsoft?code=ValidCode&state=ValidStateData");
            await ThrowIfResponseStatusNotOk(response);
            responseContent = await response.Content.ReadAsStringAsync();

            //Correlation cookie not getting cleared after successful signin?
            if (!Helpers.RunningOnMono)
            {
                Assert.Null(_httpClientHandler.CookieContainer.GetCookies(new Uri(_deploymentResult.ApplicationBaseUri)).GetCookieWithName(".AspNetCore.Correlation.Microsoft"));
            }
            Assert.Equal(_deploymentResult.ApplicationBaseUri + "Account/ExternalLoginCallback?ReturnUrl=%2F", response.RequestMessage.RequestUri.AbsoluteUri);

            formParameters = new List<KeyValuePair<string, string>>
            {
                new KeyValuePair<string, string>("Email", "microsoft@test.com"),
                new KeyValuePair<string, string>("__RequestVerificationToken", HtmlDOMHelper.RetrieveAntiForgeryToken(responseContent, "/Account/ExternalLoginConfirmation?ReturnUrl=%2F")),
            };

            content = new FormUrlEncodedContent(formParameters.ToArray());
            response = await DoPostAsync("Account/ExternalLoginConfirmation", content);
            await ThrowIfResponseStatusNotOk(response);
            responseContent = await response.Content.ReadAsStringAsync();

            Assert.Contains(string.Format("Hello {0}!", "microsoft@test.com"), responseContent, StringComparison.OrdinalIgnoreCase);
            Assert.Contains("Log off", responseContent, StringComparison.OrdinalIgnoreCase);
            //Verify cookie sent
            Assert.NotNull(_httpClientHandler.CookieContainer.GetCookies(new Uri(_deploymentResult.ApplicationBaseUri)).GetCookieWithName(IdentityCookieName));
            Assert.Null(_httpClientHandler.CookieContainer.GetCookies(new Uri(_deploymentResult.ApplicationBaseUri)).GetCookieWithName(ExternalLoginCookieName));
            _logger.LogInformation("Successfully signed in with user '{email}'", "microsoft@test.com");

            _logger.LogInformation("Verifying if the middleware events were fired");
            //Check for a non existing item
            response = await DoGetAsync(string.Format("Admin/StoreManager/GetAlbumIdFromName?albumName={0}", "123"));
            //This action requires admin permissions. If events are fired this permission is granted
            _logger.LogInformation(await response.Content.ReadAsStringAsync());
            Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
            _logger.LogInformation("Middleware events were fired successfully");
        }
    }
}


text:
<?php

namespace Fuel\Core;

// --------------------------------------------------------------------

class Session_Db extends \Session_Driver
{
	/*
	 * @var	session database result object
	 */
	protected $record = null;

	/**
	 * array of driver config defaults
	 */
	protected static $_defaults = array(
		'cookie_name'    => 'fueldid',				// name of the session cookie for database based sessions
		'table'          => 'sessions',				// name of the sessions table
		'gc_probability' => 5,						// probability % (between 0 and 100) for garbage collection
	);

	// --------------------------------------------------------------------

	public function __construct($config = array())
	{
		// merge the driver config with the global config
		$this->config = array_merge($config, is_array($config['db']) ? $config['db'] : static::$_defaults);

		$this->config = $this->_validate_config($this->config);
	}

	// --------------------------------------------------------------------

	/**
	 * create a new session
	 *
	 * @access	public
	 * @return	Fuel\Core\Session_Db
	 */
	public function create($payload = '')
	{
		// create a new session
		$this->keys['session_id']  = $this->_new_session_id();
		$this->keys['previous_id'] = $this->keys['session_id'];	// prevents errors if previous_id has a unique index
		$this->keys['ip_hash']     = md5(\Input::ip().\Input::real_ip());
		$this->keys['user_agent']  = \Input::user_agent();
		$this->keys['created']     = $this->time->get_timestamp();
		$this->keys['updated']     = $this->keys['created'];

		// add the payload
		$this->keys['payload'] = $payload;

		return $this;
	}

	// --------------------------------------------------------------------

	/**
	 * read the session
	 *
	 * @access	public
	 * @param	boolean, set to true if we want to force a new session to be created
	 * @return	Fuel\Core\Session_Driver
	 */
	public function read($force = false)
	{
		// initialize the session
		$this->data = array();
		$this->keys = array();
		$this->flash = array();
		$this->record = null;

		// get the session cookie
		$cookie = $this->_get_cookie();

		// if a cookie was present, find the session record
		if ($cookie and ! $force and isset($cookie[0]))
		{
			// read the session record
			$this->record = \DB::select()->where('session_id', '=', $cookie[0])->from($this->config['table'])->execute($this->config['database']);

			// record found?
			if ($this->record->count())
			{
				$payload = $this->_unserialize($this->record->get('payload'));
			}
			else
			{
				// try to find the session on previous id
				$this->record = \DB::select()->where('previous_id', '=', $cookie[0])->from($this->config['table'])->execute($this->config['database']);

				// record found?
				if ($this->record->count())
				{
					$payload = $this->_unserialize($this->record->get('payload'));
				}
				else
				{
					// cookie present, but session record missing. force creation of a new session
					logger('DEBUG', 'Error: Session cookie with ID "'.$cookie[0].'" present but corresponding record is missing');
					return $this->read(true);
				}
			}

			if ( ! isset($payload[0]) or ! is_array($payload[0]))
			{
				logger('DEBUG', 'Error: not a valid db session payload!');
			}
			elseif ($payload[0]['updated'] + $this->config['expiration_time'] <= $this->time->get_timestamp())
			{
				logger('DEBUG', 'Error: session id has expired!');
			}
			elseif ($this->config['match_ip'] and $payload[0]['ip_hash'] !== md5(\Input::ip().\Input::real_ip()))
			{
				logger('DEBUG', 'Error: IP address in the session doesn\'t match this requests source IP!');
			}
			elseif ($this->config['match_ua'] and $payload[0]['user_agent'] !== \Input::user_agent())
			{
				logger('DEBUG', 'Error: User agent in the session doesn\'t match the browsers user agent string!');
			}
			else
			{
				// session is valid, retrieve the payload
				if (isset($payload[0]) and is_array($payload[0]))
				{
					$this->keys  = $payload[0];
				}
				if (isset($payload[1]) and is_array($payload[1]))
				{
					$this->data  = $payload[1];
				}
				if (isset($payload[2]) and is_array($payload[2]))
				{
					$this->flash = $payload[2];
				}
			}
		}

		return parent::read();
	}

	// --------------------------------------------------------------------

	/**
	 * write the current session
	 *
	 * @access	public
	 * @return	Fuel\Core\Session_Db
	 */
	public function write()
	{
		// do we have something to write?
		if ( ! empty($this->keys) or ! empty($this->data) or ! empty($this->flash))
		{
			parent::write();

			// rotate the session id if needed
			$this->rotate(false);

			// record the last update time of the session
			$this->keys['updated'] = $this->time->get_timestamp();

			// add a random identifier, we need the payload to be absolutely unique
			$this->flash[$this->config['flash_id'].'::__session_identifier__'] = array('state' => 'expire', 'value' => sha1(uniqid(rand(), true)));

			// create the session record, and add the session payload
			$session = $this->keys;
			$session['payload'] = $this->_serialize(array($this->keys, $this->data, $this->flash));

			try
			{
				// do we need to create a new session?
				if (is_null($this->record))
				{
					// create the new session record
					list($notused, $result) = \DB::insert($this->config['table'], array_keys($session))->values($session)->execute($this->config['database']);
				}
				else
				{
					// update the database
					$result = \DB::update($this->config['table'])->set($session)->where('session_id', '=', $this->record->get('session_id'))->execute($this->config['database']);

					// if it failed, perhaps we have lost a session id due to rotation?
					if ($result === 0)
					{
						// if so, there must be a session record with our session_id as previous_id
						$result = \DB::select()->where('previous_id', '=', $this->record->get('session_id'))->from($this->config['table'])->execute($this->config['database']);
						if ($result->count())
						{
							logger(\Fuel::L_WARNING, 'Session update failed, session record recovered using previous id. Lost rotation data?');

							// update the session data
							$this->keys['session_id'] = $result->get('session_id');
							$this->keys['previous_id'] = $result->get('previous_id');

							// and recreate the payload
							$session = $this->keys;
							$session['payload'] = $this->_serialize(array($this->keys, $this->data, $this->flash));

							// and update the database
							$result = \DB::update($this->config['table'])->set($session)->where('session_id', '=', $this->keys['session_id'])->execute($this->config['database']);
						}
						else
						{
							logger(\Fuel::L_ERROR, 'Session update failed, session record could not be recovered using the previous id');
							$result = false;
						}
					}
				}

				// update went well?
				if ($result !== 0)
				{
					// then update the cookie
					$this->_set_cookie(array($this->keys['session_id']));
				}

				// Run garbage collector
				$this->gc();
			}
			catch (Database_Exception $e)
			{
				// strip the actual query from the message
				$msg = $e->getMessage();
				$msg = substr($msg, 0, strlen($msg)  - strlen(strrchr($msg, ':')));

				// and rethrow it
				throw new \Database_Exception($msg);
			}
		}

		return $this;
	}

	// --------------------------------------------------------------------

	/**
	 * Garbage Collector
	 *
	 * @access	public
	 * @return	bool
	 */
	public function gc()
	{
		if (mt_rand(0, 100) < $this->config['gc_probability'])
		{
			$expired = $this->time->get_timestamp() - $this->config['expiration_time'];
			$result = \DB::delete($this->config['table'])->where('updated', '<', $expired)->execute($this->config['database']);
		}

		return true;
	}

	// --------------------------------------------------------------------

	/**
	 * destroy the current session
	 *
	 * @access	public
	 * @return	Fuel\Core\Session_Db
	 */
	public function destroy()
	{
		// do we have something to destroy?
		if ( ! empty($this->keys) and ! empty($this->record))
		{
			// delete the session record
			$result = \DB::delete($this->config['table'])->where('session_id', '=', $this->keys['session_id'])->execute($this->config['database']);
		}

		// reset the stored session data
		$this->record = null;

		parent::destroy();

		return $this;
	}

	// --------------------------------------------------------------------

	/**
	 * validate a driver config value
	 *
	 * @param	array	array with configuration values
	 * @access	public
	 * @return  array	validated and consolidated config
	 */
	public function _validate_config($config)
	{
		$validated = array();

		foreach ($config as $name => $item)
		{
			// filter out any driver config
			if (!is_array($item))
			{
				switch ($name)
				{
					case 'cookie_name':
						if ( empty($item) or ! is_string($item))
						{
							$item = 'fueldid';
						}
					break;

					case 'database':
						// do we have a database?
						if ( empty($item) or ! is_string($item))
						{
							\Config::load('db', true);
							$item = \Config::get('db.active', false);
						}
						if ($item === false)
						{
							throw new \FuelException('You have specify a database to use database backed sessions.');
						}
					break;

					case 'table':
						// and a table name?
						if ( empty($item) or ! is_string($item))
						{
							throw new \FuelException('You have specify a database table name to use database backed sessions.');
						}
					break;

					case 'gc_probability':
						// do we have a path?
						if ( ! is_numeric($item) or $item < 0 or $item > 100)
						{
							// default value: 5%
							$item = 5;
						}
					break;

					default:
					break;
				}

				// global config, was validated in the driver
				$validated[$name] = $item;
			}
		}

		// validate all global settings as well
		return parent::_validate_config($validated);
	}

}

redpajama_set_name: RedPajamaGithub


text:
<?php

/**
 * User: Rohinigeeks
 * Date: 14/02/15
 * Time: 4:34 PM
 */

namespace Rohinigeeks\Generator\Generators\Common\MigrationsGenerator\Syntax;

/**
 * Class Table
 * @package Xethron\MigrationsGenerator\Syntax
 */
abstract class Table extends \Way\Generators\Syntax\Table{
	/**
	 * @var string
	 */
	protected $table;
	/**
	 * @param array $fields
	 * @param string $table
	 * @param string $method
	 * @return string
	 */
	public function run(array $fields, $table, $method = 'table')
	{
		$this->table = $table;
		$compiled = $this->compiler->compile($this->getTemplate(), ['table'=>$table,'method'=>$method]);
		return $this->replaceFieldsWith($this->getItems($fields), $compiled);
	}
	/**
	 * Return string for adding all foreign keys
	 *
	 * @param array $items
	 * @return array
	 */
	protected function getItems(array $items)
	{
		$result = array();
		foreach($items as $item) {
			$result[] = $this->getItem($item);
		}
		return $result;
	}
	/**
	 * @param array $item
	 * @return string
	 */
	abstract protected function getItem(array $item);
	/**
	 * @param $decorators
	 * @return string
	 */
	protected function addDecorators($decorators)
	{
		$output = '';
		foreach ($decorators as $decorator) {
			$output .= sprintf("->%s", $decorator);
			// Do we need to tack on the parens?
			if (strpos($decorator, '(') === false) {
				$output .= '()';
			}
		}
		return $output;
	}
}


text:
package wordpress

import (
	"bytes"
	"fmt"
	"github.com/parnurzeal/gorequest"
	"io/ioutil"
	"log"
	"net/http"
	"reflect"
)

const (
	CollectionUsers      = "users"
	CollectionPosts      = "posts"
	CollectionPages      = "pages"
	CollectionMedia      = "media"
	CollectionMeta       = "meta"
	CollectionRevisions  = "revisions"
	CollectionComments   = "comments"
	CollectionTaxonomies = "taxonomies"
	CollectionTerms      = "terms"
	CollectionStatuses   = "statuses"
	CollectionTypes      = "types"
)

type GeneralError struct {
	Code    string `json:"code"`
	Message string `json:"message"`
	Data    int    `json:"data"` // Unsure if this is consistent
}

type Options struct {
	BaseAPIURL string

	// Basic Auth
	Username string
	Password string
	// TODO: support OAuth authentication
}

type Client struct {
	req     *gorequest.SuperAgent
	options *Options
	baseURL string
}

// Used to create a new SuperAgent object.
func newHTTPClient() *gorequest.SuperAgent {
	client := gorequest.New()
	client.Client = &http.Client{Jar: nil}
	client.Transport = &http.Transport{
		DisableKeepAlives: true,
	}
	return client
}

func NewClient(options *Options) *Client {
	req := newHTTPClient().SetBasicAuth(options.Username, options.Password)
	req = req.RedirectPolicy(func(r gorequest.Request, via []gorequest.Request) error {
		// perform BasicAuth on each redirect request.
		// (requests are cookie-less; so we need to keep re-auth-ing again)
		httpReq := http.Request(*r)
		httpReq.SetBasicAuth(options.Username, options.Password)
		log.Println("REDIRECT", r, options.Username, options.Password)
		return nil
	})
	return &Client{
		req:     req,
		options: options,
		baseURL: options.BaseAPIURL,
	}
}

func (client *Client) Users() *UsersCollection {
	return &UsersCollection{
		client: client,
		url:    fmt.Sprintf("%v/%v", client.baseURL, CollectionUsers),
	}
}
func (client *Client) Posts() *PostsCollection {
	return &PostsCollection{
		client: client,
		url:    fmt.Sprintf("%v/%v", client.baseURL, CollectionPosts),
	}
}
func (client *Client) Pages() *PagesCollection {
	return &PagesCollection{
		client: client,
		url:    fmt.Sprintf("%v/%v", client.baseURL, CollectionPages),
	}
}
func (client *Client) Media() *MediaCollection {
	return &MediaCollection{
		client: client,
		url:    fmt.Sprintf("%v/%v", client.baseURL, CollectionMedia),
	}
}
func (client *Client) Comments() *CommentsCollection {
	return &CommentsCollection{
		client: client,
		url:    fmt.Sprintf("%v/%v", client.baseURL, CollectionComments),
	}
}
func (client *Client) Taxonomies() *TaxonomiesCollection {
	return &TaxonomiesCollection{
		client: client,
		url:    fmt.Sprintf("%v/%v", client.baseURL, CollectionTaxonomies),
	}
}
func (client *Client) Terms() *TermsCollection {
	return &TermsCollection{
		client: client,
		url:    fmt.Sprintf("%v/%v", client.baseURL, CollectionTerms),
	}
}
func (client *Client) Statuses() *StatusesCollection {
	return &StatusesCollection{
		client: client,
		url:    fmt.Sprintf("%v/%v", client.baseURL, CollectionStatuses),
	}
}
func (client *Client) Types() *TypesCollection {
	return &TypesCollection{
		client: client,
		url:    fmt.Sprintf("%v/%v", client.baseURL, CollectionTypes),
	}
}

func (client *Client) List(url string, params interface{}, result interface{}) (*http.Response, []byte, error) {
	client.req.TargetType = "json"
	resp, body, errSlice := client.req.Get(url).Query(params).EndBytes()
	if errSlice != nil && len(errSlice) > 0 {
		return nil, body, errSlice[len(errSlice)-1]
	}
	err := unmarshallResponse(resp, body, result)
	_resp := http.Response(*resp)
	return &_resp, body, err
}
func (client *Client) Create(url string, content interface{}, result interface{}) (*http.Response, []byte, error) {
	contentVal := unpackInterfacePointer(content)
	client.req.TargetType = "json"
	req := client.req.Post(url).Send(contentVal)
	resp, body, errSlice := req.EndBytes()
	if errSlice != nil && len(errSlice) > 0 {
		return nil, body, errSlice[len(errSlice)-1]
	}
	err := unmarshallResponse(resp, body, result)
	_resp := http.Response(*resp)
	return &_resp, body, err
}
func (client *Client) Get(url string, params interface{}, result interface{}) (*http.Response, []byte, error) {
	client.req.TargetType = "json"
	resp, body, errSlice := client.req.Get(url).Query(params).EndBytes()
	if errSlice != nil && len(errSlice) > 0 {
		return nil, body, errSlice[len(errSlice)-1]
	}
	err := unmarshallResponse(resp, body, result)
	_resp := http.Response(*resp)
	return &_resp, body, err
}
func (client *Client) Update(url string, content interface{}, result interface{}) (*http.Response, []byte, error) {

	contentVal := unpackInterfacePointer(content)

	client.req.TargetType = "json"
	req := client.req.Post(url).Send(contentVal)
	req.Set("HTTP_X_HTTP_METHOD_OVERRIDE", "PUT")
	resp, body, errSlice := req.EndBytes()
	if errSlice != nil && len(errSlice) > 0 {
		return nil, body, errSlice[len(errSlice)-1]
	}
	err := unmarshallResponse(resp, body, result)
	_resp := http.Response(*resp)
	return &_resp, body, err
}
func (client *Client) Delete(url string, params interface{}, result interface{}) (*http.Response, []byte, error) {
	client.req.TargetType = "json"
	req := client.req.Get(url).Query(params).Query("_method=DELETE")
	req.Set("HTTP_X_HTTP_METHOD_OVERRIDE", "DELETE")
	resp, body, errSlice := req.End()
	by := []byte(body)
	if errSlice != nil && len(errSlice) > 0 {
		return resp, by, errSlice[len(errSlice)-1]
	}
	err := unmarshallResponse(resp, by, result)
	_resp := http.Response(*resp)
	return &_resp, by, err
}
func (client *Client) PostData(url string, content []byte, contentType string, filename string, result interface{}) (*http.Response, []byte, error) {

	// gorequest does not support POST-ing raw data
	// so, we have to manually create a HTTP client
	s := client.req.Post(url)

	buf := bytes.NewBuffer(content)

	req, err := http.NewRequest(s.Method, s.Url, buf)
	if err != nil {
		return nil, nil, err
	}

	req.Header.Set("Content-Type", contentType)
	req.Header.Set("Content-Disposition", fmt.Sprintf("filename=%v", filename))

	// Add basic auth
	req.SetBasicAuth(s.BasicAuth.Username, s.BasicAuth.Password)

	// Set Transport
	s.Client.Transport = s.Transport

	// Send request
	resp, err := s.Client.Do(req)
	if err != nil {
		return nil, nil, err
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, nil, err
	}

	err = unmarshallResponse(resp, body, result)
	_resp := http.Response(*resp)
	return &_resp, body, err
}

func unpackInterfacePointer(content interface{}) interface{} {
	val := reflect.ValueOf(content)
	for val.Kind() == reflect.Ptr {
		if val.IsNil() {
			return nil
		}
		val = val.Elem()
	}
	if val.IsValid() {
		return val.Interface()
	}
	return nil
}


text:
module Classifier

class Bayes
  # The class can be created with one or more categories, each of which will be
  # initialized and given a training method. E.g.,
  #      b = Classifier::Bayes.new 'Interesting', 'Uninteresting', 'Spam'
	def initialize(*categories)
		@categories = Hash.new
		categories.each { |category| @categories[category.prepare_category_name] = Hash.new }
		@total_words = 0
                @category_counts = Hash.new(0)
	end

	#
	# Provides a general training method for all categories specified in Bayes#new
	# For example:
	#     b = Classifier::Bayes.new 'This', 'That', 'the_other'
	#     b.train :this, "This text"
	#     b.train "that", "That text"
	#     b.train "The other", "The other text"
	def train(category, text)
		category = category.prepare_category_name
                @category_counts[category] += 1
		text.word_hash.each do |word, count|
			@categories[category][word]     ||=     0
			@categories[category][word]      +=     count
			@total_words += count
		end
	end

	#
	# Provides a untraining method for all categories specified in Bayes#new
	# Be very careful with this method.
	#
	# For example:
	#     b = Classifier::Bayes.new 'This', 'That', 'the_other'
	#     b.train :this, "This text"
	#     b.untrain :this, "This text"
	def untrain(category, text)
		category = category.prepare_category_name
                @category_counts[category] -= 1
		text.word_hash.each do |word, count|
			if @total_words >= 0
				orig = @categories[category][word]
				@categories[category][word]     ||=     0
				@categories[category][word]      -=     count
				if @categories[category][word] <= 0
					@categories[category].delete(word)
					count = orig
				end
				@total_words -= count
			end
		end
	end

	#
	# Returns the scores in each category the provided +text+. E.g.,
	#    b.classifications "I hate bad words and you"
	#    =>  {"Uninteresting"=>-12.6997928013932, "Interesting"=>-18.4206807439524}
	# The largest of these scores (the one closest to 0) is the one picked out by #classify
	def classifications(text)
		score = Hash.new
                training_count = @category_counts.values.inject { |x,y| x+y }.to_f
		@categories.each do |category, category_words|
			score[category.to_s] = 0
			total = category_words.values.inject(0) {|sum, element| sum+element}
			text.word_hash.each do |word, count|
				s = category_words.has_key?(word) ? category_words[word] : 0.1
				score[category.to_s] += Math.log(s/total.to_f)
			end
                        # now add prior probability for the category
                        s = @category_counts.has_key?(category) ? @category_counts[category] : 0.1
                        score[category.to_s] += Math.log(s / training_count)
		end
		return score
	end

  #
  # Returns the classification of the provided +text+, which is one of the
  # categories given in the initializer. E.g.,
  #    b.classify "I hate bad words and you"
  #    =>  'Uninteresting'
	def classify(text)
		(classifications(text).sort_by { |a| -a[1] })[0][0]
	end

	#
	# Provides training and untraining methods for the categories specified in Bayes#new
	# For example:
	#     b = Classifier::Bayes.new 'This', 'That', 'the_other'
	#     b.train_this "This text"
	#     b.train_that "That text"
	#     b.untrain_that "That text"
	#     b.train_the_other "The other text"
	def method_missing(name, *args)
		category = name.to_s.gsub(/(un)?train_([\w]+)/, '\2').prepare_category_name
		if @categories.has_key? category
			args.each { |text| eval("#{$1}train(category, text)") }
		elsif name.to_s =~ /(un)?train_([\w]+)/
			raise StandardError, "No such category: #{category}"
		else
	    super  #raise StandardError, "No such method: #{name}"
		end
	end

	#
	# Provides a list of category names
	# For example:
	#     b.categories
	#     =>   ['This', 'That', 'the_other']
	def categories # :nodoc:
		@categories.keys.collect {|c| c.to_s}
	end

	#
	# Allows you to add categories to the classifier.
	# For example:
	#     b.add_category "Not spam"
	#
	# WARNING: Adding categories to a trained classifier will
	# result in an undertrained category that will tend to match
	# more criteria than the trained selective categories. In short,
	# try to initialize your categories at initialization.
	def add_category(category)
		@categories[category.prepare_category_name] = Hash.new
	end

	alias append_category add_category
end

end


text:
/*
 * $Source: /project/arl/arlcvs/cvsroot/wu_arl/openNetLab/proxy/pingProxy.cc,v $
 * $Author: fredk $
 * $Date: 2006/12/08 20:35:00 $
 * $Revision: 1.2 $
 * $Name:  $
 *
 * File:         try.c
 * Created:      12/29/2004 10:56:15 AM CST
 * Author:       Fred Kunhns, <fredk@cse.wustl.edu>
 * Organization: Applied Research Laboratory,
 *               Washington University in St. Louis
 *
 * Description:
 *
 */
#include <iostream>
#include <sstream>
#include <vector>

using std::string;
using std::cout;
using std::cerr;
using std::endl;

#include <cstdio>
#include <cstdlib>
#include <stdint.h>

#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <netdb.h>
#include <wulib/wulog.h>
#include <getopt.h>
#include <signal.h>

#include <wuPP/net.h>
#include <wuPP/addr.h>
#include <wuPP/sock.h>
#include <wuPP/buf.h>
#include <wuPP/msg.h>

#include "control.h"
#include "cmd.h"
#include "nccp.h"
#include "basicConn.h"
#include "streamConn.h"
#include "session.h"
#include "proxy.h"

const string defaultServer("128.252.153.116"); // onl03
const in_port_t  defaultPort = 7071;
const int defaultProtocol = IPPROTO_TCP;

void print_usage(string& prog)
{
  cout << prog << " [--id id] [--addr serv] [--port dp] [-pr pr] [--lvl lvl]\n"
       << "\t--addr serv : servers address, default = " << defaultServer << "\n"
       << "\t--port dp : port server is listening on, default = " << (int)defaultPort << "\n"
       << "\t--pr pr : protocol to use (only support TCP for now), default = " << defaultProtocol << "\n"
       << "\t--lvl lvl : debug level\n";
}

using namespace wuctl;

int
main(int argc, char **argv)
try {
#define OPT_NOARG   0 /* no argument required */
#define OPT_REQARG  1 /* required argument */
#define OPT_OPTARG  2 /* argument is optional */
  static struct option longopts[] =
  {{"help", OPT_NOARG,  NULL, 'h'},
   {"addr", OPT_REQARG, NULL,  1},
   {"port", OPT_REQARG, NULL,  2},
   {"pr",   OPT_REQARG, NULL,  5},
   {NULL,   0,          NULL,  0}
  };
  // {name, has_arg, flag, val}

  string        prog = argv[0];
  string      servIP = defaultServer;
  in_port_t servPort = defaultPort;
  int          proto = defaultProtocol;

  wulogInit(proxyInfo, modCnt, wulogInfo, "Proxy", wulog_useLocal);

  /* Commands:
   *   pkts, bytes, time, reset
   */
  int c;
  while ((c = getopt_long(argc, argv, "hl:", longopts, NULL)) != -1) {
    switch (c) {
      case 'h':
        print_usage(prog);
        return 1;
        break;
      case 'l':
        {
          wulogLvl_t lvl = wulogName2Lvl(optarg);
          if (lvl == wulogInvLvl) {
            std::cerr << "Invalid wulog level specified: " << optarg << "\n";
            wulogPrintLvls();
            return 1;
          }
          wulogSetDef(lvl);
        }
      case 1:
        servIP = optarg;
        break;
      case 2:
        servPort = in_port_t(atoi(optarg));
        break;
      case 5:
        struct protoent *pent;
        if (isalpha(*optarg))
          pent = getprotobyname(optarg);
        else
          pent = getprotobynumber(strtol(optarg, NULL, 0));
        if (pent == NULL) {
          cerr << "Invalid protocol " << optarg << "\n";
          return 1;
        }
        proto = int(pent->p_proto);
        break;
      default:
        cerr << "Unknown option " << c << "\n";
        return 1;
        break;
    }
  }

  // set local address to the default values (os picks port and ip)
  wunet::inetAddr laddr(IPPROTO_TCP);
  // call connect with Address of server
  wunet::inetAddr saddr(servIP.c_str(), servPort, proto);

  // do active connect
  wunet::inetSock sock(laddr);

  // call connect with Address of server
  sock.connect(saddr);
  sock.nodelay(1);

  wunet::msgBuf<hdr_t> mbuf;
  hdr_t &hdr = mbuf.hdr();

  // set header fields
  hdr.reset();
  hdr.cmd(wuctl::hdr_t::nullCommand);
  hdr.msgID(1);
  hdr.flags(0);

  hdr.dlen(0);
  mbuf.plen(0);

  if (wupp::isError(mbuf.writemsg(&sock))) {
    wulog(wulogApp, wulogWarn,
          "Unexpected Error sending message -- no exception thrown!\n");
    return 1;
  }

  mbuf.reset();
  if (wupp::isError(mbuf.readmsg(&sock))) {
    wulog(wulogApp, wulogWarn, "Unexpected EOF\n");
    return 1;
  }

  return ((hdr.cmdSucceeded()) ? 0 : 1);

} catch (wupp::errorBase& e) {
  cerr << "***** Caught wupp exception -- read" << endl;
  cerr << e << endl;
  return 1;
} catch (...) {
  cerr << "***** Caught some unknown exception -- read" << endl;
  return 1;
}


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

namespace Microsoft.DocAsCode.Build.Engine
{
    using System.Collections.Generic;
    using System.Collections.Immutable;

    public sealed class FileMetadata : Dictionary<string, ImmutableArray<FileMetadataItem>>
    {
        public string BaseDir { get; }
        public FileMetadata(string baseDir) : base()
        {
            BaseDir = baseDir;
        }
        public FileMetadata(string baseDir, IDictionary<string, ImmutableArray<FileMetadataItem>> dictionary) : base(dictionary)
        {
            BaseDir = baseDir;
        }
    }
}


text:
namespace app {
namespace Fuse {
namespace Internal {

struct Blender__Fuse_Navigation_NavigationEdge;

struct Blender__Fuse_Navigation_NavigationEdge__uType : ::uClassType
{
    int(*__fp_Add)(Blender__Fuse_Navigation_NavigationEdge*, int, int);
    int(*__fp_Weight)(Blender__Fuse_Navigation_NavigationEdge*, int, double);
};

Blender__Fuse_Navigation_NavigationEdge__uType* Blender__Fuse_Navigation_NavigationEdge__typeof();

struct Blender__Fuse_Navigation_NavigationEdge : ::uObject
{
    int Add(int a, int b) { return (((Blender__Fuse_Navigation_NavigationEdge__uType*)this->__obj_type)->__fp_Add)(this, a, b); }
    int Weight(int v, double w) { return (((Blender__Fuse_Navigation_NavigationEdge__uType*)this->__obj_type)->__fp_Weight)(this, v, w); }
};

}}}

#endif


text:
#ifndef BOOST_INTERPROCESS_CONTAINERS_CONTAINERS_FWD_HPP
#define BOOST_INTERPROCESS_CONTAINERS_CONTAINERS_FWD_HPP

#if !defined(BOOST_INTERPROCESS_DOXYGEN_INVOKED)

#if defined(_MSC_VER)
#  pragma once
#endif

//////////////////////////////////////////////////////////////////////////////
//                        Standard predeclarations
//////////////////////////////////////////////////////////////////////////////

#include <boost/interprocess/detail/config_begin.hpp>
#include <boost/container/container_fwd.hpp>

namespace boost {
namespace interprocess {

using boost::container::ordered_range;
using boost::container::ordered_unique_range;

}  //namespace interprocess {
}  //namespace boost {

#include <boost/interprocess/detail/config_end.hpp>

#endif   //#ifndef BOOST_INTERPROCESS_DOXYGEN_INVOKED

#endif //   #ifndef  BOOST_INTERPROCESS_CONTAINERS_CONTAINERS_FWD_HPP


text:
import {
  linkClickSelector,
  buttonClickSelector,
  inputChangeSelector,
  formSubmitSelector,
  formInputClickSelector,
  formDisableSelector,
  formEnableSelector,
  fileInputSelector,
  linkDisableSelector,
  buttonDisableSelector
} from "./utils/constants"

import { ajax, href, isCrossDomain } from "./utils/ajax"
import { cspNonce, loadCSPNonce } from "./utils/csp"
import { csrfToken, csrfParam, CSRFProtection, refreshCSRFTokens } from "./utils/csrf"
import { matches, getData, setData, $ } from "./utils/dom"
import { fire, stopEverything, delegate } from "./utils/event"
import { serializeElement, formElements } from "./utils/form"

import { confirm, handleConfirmWithRails } from "./features/confirm"
import { handleDisabledElement, enableElement, disableElement } from "./features/disable"
import { handleMethodWithRails } from "./features/method"
import { handleRemoteWithRails, formSubmitButtonClick, preventInsignificantClick } from "./features/remote"

const Rails = {
  $,
  ajax,
  buttonClickSelector,
  buttonDisableSelector,
  confirm,
  cspNonce,
  csrfToken,
  csrfParam,
  CSRFProtection,
  delegate,
  disableElement,
  enableElement,
  fileInputSelector,
  fire,
  formElements,
  formEnableSelector,
  formDisableSelector,
  formInputClickSelector,
  formSubmitButtonClick,
  formSubmitSelector,
  getData,
  handleDisabledElement,
  href,
  inputChangeSelector,
  isCrossDomain,
  linkClickSelector,
  linkDisableSelector,
  loadCSPNonce,
  matches,
  preventInsignificantClick,
  refreshCSRFTokens,
  serializeElement,
  setData,
  stopEverything
}

// needs to be able to call Rails.confirm in case its overridden
const handleConfirm = handleConfirmWithRails(Rails)
Rails.handleConfirm = handleConfirm

// needs to be able to call Rails.href in case its overridden
const handleMethod = handleMethodWithRails(Rails)
Rails.handleMethod = handleMethod

// needs to be able to call Rails.href in case its overridden
const handleRemote = handleRemoteWithRails(Rails)
Rails.handleRemote = handleRemote

const start = function() {
  // Cut down on the number of issues from people inadvertently including
  // rails-ujs twice by detecting and raising an error when it happens.
  if (window._rails_loaded) { throw new Error("rails-ujs has already been loaded!") }

  // This event works the same as the load event, except that it fires every
  // time the page is loaded.
  // See https://github.com/rails/jquery-ujs/issues/357
  // See https://developer.mozilla.org/en-US/docs/Using_Firefox_1.5_caching
  window.addEventListener("pageshow", function() {
    $(formEnableSelector).forEach(function(el) {
      if (getData(el, "ujs:disabled")) {
        enableElement(el)
      }
    })
    $(linkDisableSelector).forEach(function(el) {
      if (getData(el, "ujs:disabled")) {
        enableElement(el)
      }
    })
  })

  delegate(document, linkDisableSelector, "ajax:complete", enableElement)
  delegate(document, linkDisableSelector, "ajax:stopped", enableElement)
  delegate(document, buttonDisableSelector, "ajax:complete", enableElement)
  delegate(document, buttonDisableSelector, "ajax:stopped", enableElement)

  delegate(document, linkClickSelector, "click", preventInsignificantClick)
  delegate(document, linkClickSelector, "click", handleDisabledElement)
  delegate(document, linkClickSelector, "click", handleConfirm)
  delegate(document, linkClickSelector, "click", disableElement)
  delegate(document, linkClickSelector, "click", handleRemote)
  delegate(document, linkClickSelector, "click", handleMethod)

  delegate(document, buttonClickSelector, "click", preventInsignificantClick)
  delegate(document, buttonClickSelector, "click", handleDisabledElement)
  delegate(document, buttonClickSelector, "click", handleConfirm)
  delegate(document, buttonClickSelector, "click", disableElement)
  delegate(document, buttonClickSelector, "click", handleRemote)

  delegate(document, inputChangeSelector, "change", handleDisabledElement)
  delegate(document, inputChangeSelector, "change", handleConfirm)
  delegate(document, inputChangeSelector, "change", handleRemote)

  delegate(document, formSubmitSelector, "submit", handleDisabledElement)
  delegate(document, formSubmitSelector, "submit", handleConfirm)
  delegate(document, formSubmitSelector, "submit", handleRemote)
  // Normal mode submit
  // Slight timeout so that the submit button gets properly serialized
  delegate(document, formSubmitSelector, "submit", e => setTimeout((() => disableElement(e)), 13))
  delegate(document, formSubmitSelector, "ajax:send", disableElement)
  delegate(document, formSubmitSelector, "ajax:complete", enableElement)

  delegate(document, formInputClickSelector, "click", preventInsignificantClick)
  delegate(document, formInputClickSelector, "click", handleDisabledElement)
  delegate(document, formInputClickSelector, "click", handleConfirm)
  delegate(document, formInputClickSelector, "click", formSubmitButtonClick)

  document.addEventListener("DOMContentLoaded", refreshCSRFTokens)
  document.addEventListener("DOMContentLoaded", loadCSPNonce)
  return window._rails_loaded = true
}
Rails.start = start

// For backward compatibility
if (typeof jQuery !== "undefined" && jQuery && jQuery.ajax) {
  if (jQuery.rails) { throw new Error("If you load both jquery_ujs and rails-ujs, use rails-ujs only.") }
  jQuery.rails = Rails
  jQuery.ajaxPrefilter(function(options, originalOptions, xhr) {
    if (!options.crossDomain) { return CSRFProtection(xhr) }
  })
}

// This block is to maintain backwards compatibility with the existing
// difference between what happens in a bundler and what happens using a
// sprockets compiler. In the sprockets case, Rails.start() is called
// automatically, but it is not in the ESModule case.
if (typeof exports !== "object" && typeof module === "undefined") {
  // The coffeescript bundle would set this at the very top. The Rollup bundle
  // doesn't set this until the entire bundle has finished running, so we need
  // to make sure its set before firing the rails:attachBindings event for
  // backwards compatibility.
  window.Rails = Rails

  if (fire(document, "rails:attachBindings")) {
    start()
  }
}

export default Rails


text:
title : Inc April 21, 2017
publishedBy : Inc
publishedOn : April 21, 2017
link : https://www.inc.com/marissa-levin/how-8-industry-leaders-including-walmart-use-blockchain-to-revolutionize-busines.html
weight: 123
articleName : How 8 Industry Leaders, Including WalMart, Use Blockchain to Revolutionize Business
class : pressArticle
---


text:
package com.haulmont.cuba.web.widgets;

import com.haulmont.cuba.web.widgets.data.AggregationContainer;
import com.vaadin.server.Resource;
import com.vaadin.ui.Component;
import com.vaadin.ui.Layout;
import com.vaadin.v7.data.Property;

import java.util.Map;
import java.util.function.Function;

/**
 * Interface to generalize additional functionality in {@link CubaTable}, {@link CubaGroupTable} and {@link CubaTreeTable}
 */
public interface CubaEnhancedTable extends AggregationContainer {
    void setContextMenuPopup(Layout contextMenu);
    void hideContextMenuPopup();

    Component getPresentations();
    void setPresentations(Component presentations);
    void hidePresentationsPopup();

    Object[] getEditableColumns();
    void setEditableColumns(Object[] editableColumns);

    String getSortDescendingLabel();
    void setSortDescendingLabel(String tableSortDescendingLabel);

    String getSortAscendingLabel();
    void setSortAscendingLabel(String tableSortAscendingLabel);

    String getSortResetLabel();
    void setSortResetLabel(String tableSortResetLabel);

    boolean isColumnEditable(Object columnId);

    void setMultiLineCells(boolean multiLineCells);
    boolean isMultiLineCells();

    boolean isContextMenuEnabled();
    void setContextMenuEnabled(boolean contextMenuEnabled);

    boolean isTextSelectionEnabled();
    void setTextSelectionEnabled(boolean textSelectionEnabled);

    boolean disableContentBufferRefreshing();
    void enableContentBufferRefreshing(boolean refreshContent);

    boolean isAutowirePropertyDsForFields();
    void setAutowirePropertyDsForFields(boolean autowirePropertyDsForFields);

    void refreshCellStyles();

    boolean isAggregatable();
    void setAggregatable(boolean aggregatable);

    void setAggregationStyle(AggregationStyle aggregationStyle);
    AggregationStyle getAggregationStyle();

    boolean isShowTotalAggregation();
    void setShowTotalAggregation(boolean showTotalAggregation);

    void setClickListener(Object propertyId, CellClickListener clickListener);
    void removeClickListener(Object propertyId);

    void showCustomPopup(Component popupComponent);

    boolean getCustomPopupAutoClose();
    void setCustomPopupAutoClose(boolean popupAutoClose);

    String getColumnDescription(Object columnId);
    void setColumnDescription(Object columnId, String description);

    String getAggregationDescription(Object columnId);
    void setAggregationDescription(Object columnId, String description);

    boolean getColumnSortable(Object columnId);
    void setColumnSortable(Object columnId, boolean sortable);

    void requestFocus(Object itemId, Object columnId);

    Function<Object, Resource> getIconProvider();
    void setIconProvider(Function<Object, Resource> iconProvider);

    void setSpecificVariablesHandler(SpecificVariablesHandler handler);
    SpecificVariablesHandler getSpecificVariablesHandler();

    interface SpecificVariablesHandler {
        boolean handleSpecificVariables(Map<String, Object> variables);
    }

    interface CellClickListener {
        void onClick(Object itemId, Object columnId);
    }

    void setBeforePaintListener(Runnable beforePaintListener);

    /**
     * Marker interface for generated columns which return String value.
     * Used to work with custom cacheRate and pageLength.
     */
    interface PlainTextGeneratedColumn {
    }

    enum AggregationStyle {
        TOP,
        BOTTOM
    }

    void setCustomCellValueFormatter(CellValueFormatter cellValueFormatter);
    CellValueFormatter getCustomCellValueFormatter();

    /**
     * Sets whether caption of column with the given {@code columnId} should be interpreted as HTML or not.
     *
     * @param columnId      column id
     * @param captionAsHtml interpret caption as HTML or not
     */
    void setColumnCaptionAsHtml(Object columnId, boolean captionAsHtml);

    /**
     * @param columnId column id
     *
     * @return whether caption of column with the given {@code columnId} should be interpreted as HTML or not
     */
    boolean getColumnCaptionAsHtml(Object columnId);

    interface CellValueFormatter {
        String getFormattedValue(Object rowId, Object colId, Property<?> property);
    }
}


text:
"""Command line package entry point"""

from sys import argv
from SuiteHandler import SuiteHandler
import manage, operation

if __name__ == "__main__":
    try:
        mod_name  = argv[1]
    except:
        mod_name = "_"

    sh = SuiteHandler({
        "manage": manage.suite,
        "operation": operation.suite
    })

    sh.run_suite(mod_name)
    print sh.result
    for f in sh.result.failures:
        for t in f:
            print t
        print ''
    for e in sh.result.errors:
        for t in e:
            print t
        print ''


text:
package com.ahuralab.farsialphabet;

import com.google.ads.AdRequest;
import com.google.ads.AdView;

import android.annotation.TargetApi;
import android.app.ActionBar;
import android.app.AlertDialog;
import android.net.Uri;
import android.os.Bundle;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.NavUtils;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;

public class NumberPracticeActivity extends FragmentActivity implements
		ActionBar.OnNavigationListener {

	private DummySectionFragment fragment;

	/**
	 * The serialization (saved instance state) Bundle key representing the
	 * current dropdown position.
	 */
	private static final String STATE_SELECTED_NAVIGATION_ITEM = "selected_navigation_item";
	private DrawerLayout drawer;
	private ListView navList;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_number_practice);

		// Set up the action bar to show a dropdown list.
		// final ActionBar actionBar = getActionBar();
		// actionBar.setDisplayShowTitleEnabled(false);
		// actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
		// Show the Up button in the action bar.
		// actionBar.setDisplayHomeAsUpEnabled(true);

		// Set up the dropdown list navigation in the action bar.
		// actionBar.setListNavigationCallbacks(
		// Specify a SpinnerAdapter to populate the dropdown list.
		ArrayAdapter<NumberItem> adapter = new ArrayAdapter<NumberItem>(
				getActionBarThemedContextCompat(),
				android.R.layout.simple_list_item_1, android.R.id.text1,
				NumberItem.NUMBERS);
		drawer = (DrawerLayout) findViewById(R.id.drawer_layout_number);
		navList = (ListView) findViewById(R.id.drawer_number);
		getActionBar().setDisplayHomeAsUpEnabled(true);
		getActionBar().setHomeButtonEnabled(true);

		navList.setAdapter(adapter);

		drawer.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);

		navList.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					final int pos, long id) {
				fragment = new DummySectionFragment();
				Bundle args = new Bundle();
				args.putString(DummySectionFragment.ARG_LETTER,
						NumberItem.NUMBERS[pos].getValue());
				fragment.setArguments(args);
				getSupportFragmentManager().beginTransaction()
						.replace(R.id.container, fragment).commit();
				drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
				drawer.setDrawerListener(new DrawerLayout.SimpleDrawerListener() {
					@Override
					public void onDrawerClosed(View drawerView) {
						super.onDrawerClosed(drawerView);

					}

				});
				drawer.closeDrawer(navList);

			}
		});

		if (savedInstanceState == null) {
			savedInstanceState = new Bundle();
		}
		savedInstanceState.putInt(STATE_SELECTED_NAVIGATION_ITEM, 0);
		onRestoreInstanceState(savedInstanceState);

	}

	/**
	 * Backward-compatible version of {@link ActionBar#getThemedContext()} that
	 * simply returns the {@link android.app.Activity} if
	 * getThemedContext is unavailable.
	 */
	@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
	private Context getActionBarThemedContextCompat() {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
			return getActionBar().getThemedContext();
		} else {
			return this;
		}
	}

	@Override
	public void onRestoreInstanceState(Bundle savedInstanceState) {
		fragment = new DummySectionFragment();
		Bundle args = new Bundle();
		args.putString(DummySectionFragment.ARG_LETTER,
				NumberItem.NUMBERS[savedInstanceState
						.getInt(STATE_SELECTED_NAVIGATION_ITEM)].getValue());
		fragment.setArguments(args);
		getSupportFragmentManager().beginTransaction()
				.replace(R.id.container, fragment).commit();
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		// Serialize the current dropdown position.
		outState.putInt(STATE_SELECTED_NAVIGATION_ITEM, getActionBar()
				.getSelectedNavigationIndex());
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.number_practice, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {

		case R.id.action_snapshot: {
			ShareScreenShot shareScreenShot = new  ShareScreenShot();
			View _rootView = findViewById(android.R.id.content).getRootView();
			Uri screenshotUri =
					shareScreenShot.saveScreenShot(shareScreenShot.takeScreenShot
							(_rootView));

			// send an email

			startActivity(Intent.createChooser(shareScreenShot.sendEmail(screenshotUri)
					, "Send mail..."));
			return true;
		}

		case R.id.action_question: {

			showDialog(getString(R.string.numbers_help),
					getString(R.string.attention));

			return true;
		}
		case android.R.id.home: {
			// This ID represents the Home or Up button. In the case of this
			// activity, the Up button is shown. Use NavUtils to allow users
			// to navigate up one level in the application structure. For
			// more details, see the Navigation pattern on Android Design:
			//
			// http://developer.android.com/design/patterns/navigation.html#up-vs-back
			//
			NavUtils.navigateUpFromSameTask(this);
			return true;
		}

		case R.id.action_refresh: {
			fragment.canvas.resetCanvas();
			return true;
		}
		case R.id.action_drawer: {
			drawer.openDrawer(navList);
			return true;
		}
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public boolean onNavigationItemSelected(int position, long id) {

		return false;
	}

	protected void showDialog(String message, String title) {

		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(title).setMessage(message);
		// Create the AlertDialog object and show it
		builder.show();
	}

	/**
	 * A dummy fragment representing a section of the app, but that simply
	 * displays dummy text.
	 */
	public static class DummySectionFragment extends Fragment {
		public static final String ARG_LETTER = "letter";
		CanvasTextView canvas;

		public DummySectionFragment() {
		}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {
			View rootView = inflater.inflate(
					R.layout.fragment_number_practice_dummy, container, false);
			canvas = (CanvasTextView) rootView
					.findViewById(R.id.numberPracticeCanvas);
			canvas.setText(getArguments().getString(ARG_LETTER));

			AdView adView = (AdView) rootView.findViewById(R.id.ad);
			if (adView != null) {
				adView.loadAd(new AdRequest());
			}

			return rootView;
		}
	}

}


text:
"""Load extensions."""

LINTERS = {}

try:
    from pylama.lint.pylama_mccabe import Linter
    LINTERS['mccabe'] = Linter()
except ImportError:
    pass

try:
    from pylama.lint.pylama_pep257 import Linter
    LINTERS['pep257'] = Linter()
except ImportError:
    pass

try:
    from pylama.lint.pylama_pep8 import Linter
    LINTERS['pep8'] = Linter()
except ImportError:
    pass

try:
    from pylama.lint.pylama_pyflakes import Linter
    LINTERS['pyflakes'] = Linter()
except ImportError:
    pass

from pkg_resources import iter_entry_points

for entry in iter_entry_points('pylama.linter'):
    if entry.name not in LINTERS:
        try:
            LINTERS[entry.name] = entry.load()()
        except ImportError:
            pass

#  pylama:ignore=E0611


text: JsonApi::Application.config.session_store :cookie_store, key: '_json-api_session'


text:
module Teaas
  class Blood
    # Takes in an image, and adds blood to it. Best when used with {Teaas::Turboize.turbo} to generate multiple rotation speeds.
    #
    # @param original_img [Magick::ImageList] The image to be rotated
    # @return [Magick::ImageList] The spinning image
    def self.blood(original_img, options={})
      Overlayer.overlay(original_img, Magick::ImageList.new(Teaas.root + "/img/blood.gif"))
    end

    # Takes in a path to an image, and adds blood to it. Best when used with {Teaas::Turboize.turbo} to generate multiple rotation speeds. This is a wrapper around {Teaas::Spin.spin}
    #
    # @param path [String] Path to the image to be spun
    # @return [Magick::ImageList] The spinning image
    def self.blood_from_file(path, options={})
      img = Magick::ImageList.new

      # Grab the first element in array to prevent strange things when an
      # animated image is submitted
      img.read(path)[0]

      blood(img)
    end
  end
end