text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Xml.Linq;

namespace AspNet.WebApi.HtmlMicrodataFormatter
{
    /// <summary>
    /// Formats arbitrary objects as html5 documents using microdata attributes
    /// to annotate properties and values.
    /// </summary>
    public class HtmlMicrodataFormatter : HtmlMediaTypeFormatter, IHtmlMicrodataSerializer
    {
        private readonly SerializerRegistry serializerRegistry = new SerializerRegistry();

        public readonly UriSerializer UriSerializer = new UriSerializer();
        public readonly LinkSerializer LinkSerializer = new LinkSerializer();
        public readonly DateTimeSerializer DateTimeSerializer = new DateTimeSerializer();
        public readonly TimeSpanSerializer TimeSpanSerializer = new TimeSpanSerializer();
        public readonly ToStringSerializer ToStringSerializer = new ToStringSerializer();
        public readonly ApiDocumentationSerializer ApiDocumentationSerializer = new ApiDocumentationSerializer();
        public readonly ApiDescriptionSerializer ApiDescriptionSerializer = new ApiDescriptionSerializer();
        public readonly TypeDocumentationSerializer TypeDocumentationSerializer = new TypeDocumentationSerializer();

        /// <summary>
        /// Default constructor. Registers pre-defined <see cref="IHtmlMicrodataSerializer"/>
        /// instances.
        /// </summary>
        public HtmlMicrodataFormatter()
        {
            serializerRegistry.Register(UriSerializer);
            serializerRegistry.Register(LinkSerializer);
            serializerRegistry.Register(DateTimeSerializer);
            serializerRegistry.Register(TimeSpanSerializer);
            serializerRegistry.Register(ToStringSerializer);
            serializerRegistry.Register(ApiDocumentationSerializer);
            serializerRegistry.Register(ApiDescriptionSerializer);
            serializerRegistry.Register(TypeDocumentationSerializer);

            PropNameProvider = new CamelCasePropNameProvider();
        }

        /// <summary>
        /// Adds a serializer instance that provides custom rendering
        /// for a given type or list of types.
        /// </summary>
        public void RegisterSerializer(IHtmlMicrodataSerializer serializer)
        {
            serializerRegistry.Register(serializer);
        }

        /// <summary>
        /// Removes a previously registered serializer instance.
        /// Pre-defined serializers may be removed if you wish
        /// to replace with your own implementation, as in
        /// <c>htmlMicrodataFormatter.RemoveSerializer(htmlMicrodataFormatter.LinkSerializer);</c>
        /// </summary>
        public void RemoveSerializer(IHtmlMicrodataSerializer serializer)
        {
            serializerRegistry.Remove(serializer);
        }

        /// <summary>
        /// Returns <c>true</c> for all types.
        /// </summary>
        public override bool CanWriteType(Type type)
        {
            return true;
        }

        public override IEnumerable<XObject> BuildBody(object value, HttpRequestMessage request)
        {
            var context = new SerializationContext(this, PropNameProvider, request, Title);
            return Serialize(null, value, context);
        }

        /// <summary>
        /// Controls how property names are converted to <c>itemprop</c> attribute values.
        /// Uses <see cref="CamelCasePropNameProvider"/> by default.
        /// </summary>
        public IPropNameProvider PropNameProvider { get; set; }

        /// <summary>
        /// Empty list. This <see cref="IHtmlMicrodataSerializer"/> is the root
        /// serializer and delegates all serialization to other instances found
        /// in <see cref="serializerRegistry"/>.
        /// </summary>
        public IEnumerable<Type> SupportedTypes { get { return Enumerable.Empty<Type>(); } }

        /// <summary>
        /// Finds a suitable <see cref="IHtmlMicrodataSerializer"/> in
        /// <see cref="serializerRegistry"/> and delegates to it.
        /// </summary>
        public IEnumerable<XObject> Serialize(string propertyName, object obj, SerializationContext context)
        {
            var type = obj == null ? typeof (string) : obj.GetType();
            var serializer = serializerRegistry.GetSerializer(type);

            return serializer.Serialize(propertyName, obj, context);
        }
    }
}


text:
package de.tbressler.waterrower.io.msg;

/**
 * @author Tobias Bressler
 * @version 1.0
 */
public abstract class InformationRequestMessage extends AbstractMessage {}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Minico\SilverBundle\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;

/**
 * Category
 *
 * @ORM\Table(name="category")
 * @ORM\Entity(repositoryClass="Minico\SilverBundle\Entity\CategoryRepository")
 */
class Category
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="name", type="string", length=100)
     */
    private $name;

    /**
     * @var Category[]|ArrayCollection
     * @ORM\OneToMany(targetEntity="Products", mappedBy="category", fetch="EXTRA_LAZY")
     */
    private $products;

    public function __construct()
    {
        $this->products = new ArrayCollection();
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set name
     *
     * @param string $name
     * @return Category
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * Get name
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    public function __toString()
    {
        return $this->name;
    }

    /**
     * @return mixed
     */
    public function getProducts()
    {
        return $this->products;
    }

    /**
     * @param mixed $products
     * @return Category
     */
    public function setProducts($products)
    {
        $this->products = $products;
        return $this;
    }

    /**
     * @param Products $product
     * @return $this
     */
    public function addProducts(Products $product)
    {
        $this->products[] = $product;
        return $this;
    }

    /**
     * @param Products $product
     * @return $this
     */
    public function removeProducts(Products $product)
    {
        $this->products->removeElement($product);
        return $this;
    }
}


text:
using UnityEngine;

namespace BitStrap
{
	/// <summary>
	/// Utility class to ease getting a reference to a component when you don't have a direct way to do it.
	/// E.g. getting a player component located on a different object (in the same hierarchy) than where a collision event happened.
	/// </summary>
	public sealed class ComponentReference : MonoBehaviour
	{
		/// <summary>
		/// The component referenced.
		/// </summary>
		public Component reference;

		/// <summary>
		/// Get the component reference given the gameobject where the ComponentReference is located.
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="obj"></param>
		/// <returns></returns>
		public static T Get<T>( GameObject obj ) where T : MonoBehaviour
		{
			var componentReference = obj.GetComponent<ComponentReference>();
			return Get( componentReference, obj ) as T;
		}

		/// <summary>
		/// Get the component reference given a component whose gameobject has the ComponentReference.
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="component"></param>
		/// <returns></returns>
		public static T Get<T>( Component component ) where T : MonoBehaviour
		{
			var componentReference = component.GetComponent<ComponentReference>();
			return Get( componentReference, component ) as T;
		}

		private static Component Get( ComponentReference componentReference, object obj )
		{
			return ( obj != null && componentReference != null ) ? componentReference.reference : null;
		}
	}
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HellBrick.Json.Utils
{
	public static partial class DictionaryExtensions
	{
		public static TValue GetOrDefault<TKey, TValue>( this IDictionary<TKey, TValue> dictionary, TKey key )
		{
			TValue value;
			dictionary.TryGetValue( key, out value );
			return value;
		}
	}
}


text:
<!--
    Licensed to the Apache Software Foundation (ASF) under one
    or more contributor license agreements.  See the NOTICE file
    distributed with this work for additional information
    regarding copyright ownership.  The ASF licenses this file
    to you under the Apache License, Version 2.0 (the
    "License"); you may not use this file except in compliance
    with the License.  You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing,
    software distributed under the License is distributed on an
    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    KIND, either express or implied.  See the License for the
    specific language governing permissions and limitations
    under the License.
-->

<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

    <parent>
        <groupId>org.apache.hcatalog</groupId>
        <artifactId>hcatalog</artifactId>
        <version>0.6.0-SNAPSHOT</version>
        <relativePath>../../pom.xml</relativePath>
    </parent>

    <modelVersion>4.0.0</modelVersion>
    <groupId>org.apache.hcatalog</groupId>
    <artifactId>webhcat</artifactId>
    <packaging>jar</packaging>
    <version>0.6.0-SNAPSHOT</version>
    <name>webhcat</name>
    <url>http://maven.apache.org</url>

    <dependencies>

        <!-- provided scope - made available as separate package
          not packaged or added as dependency
        -->

        <dependency>
            <groupId>org.apache.hcatalog</groupId>
            <artifactId>hcatalog-core</artifactId>
            <version>${hcatalog.version}</version>
            <scope>provided</scope>
        </dependency>

        <!-- compile scope - this is packaged -->
        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-json</artifactId>
            <version>${jersey.version}</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-servlet</artifactId>
            <version>${jersey.version}</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-exec</artifactId>
            <version>${commons-exec.version}</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.zookeeper</groupId>
            <artifactId>zookeeper</artifactId>
            <version>${zookeeper.version}</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-json</artifactId>
            <version>${jersey.version}</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-core-asl</artifactId>
            <version>${jackson.version}</version>
            <scope>compile</scope>
        </dependency>
         <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-mapper-asl</artifactId>
            <version>${jackson.version}</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.eclipse.jetty.aggregate</groupId>
            <artifactId>jetty-all-server</artifactId>
            <version>${jetty.webhcat.version}</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>com.sun.jersey.contribs</groupId>
            <artifactId>wadl-resourcedoc-doclet</artifactId>
            <version>${wadl-resourcedoc-doclet.version}</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>jul-to-slf4j</artifactId>
            <version>${slf4j.version}</version>
            <scope>compile</scope>
        </dependency>
    </dependencies>
</project>


text:
<html>
  <head>
    <meta http-equiv="Content-type" content="text/html; charset=utf-8">
  </head>

  <body>
    <div id="radar"/>
    <script data-main="scripts/main" src="lib/requirejs/require.js"></script>
  </body>
</html>


text:
static void *BitmapLoaderPixelFunc(void *destination,uint8_t r,uint8_t g,uint8_t b,uint8_t a,int x,int y);

static UnpackedBitmap *AllocAndLoadBitmapOrDie(const char *filename)
{
	size_t length;
	void *bytes=AllocAndLoadFileOrDie(filename,&length);

	PNGLoader loader;
	InitializePNGLoader(&loader,bytes,length);

	if(!LoadPNGHeader(&loader))
	{
		fprintf(stderr,"\"%s\" is not a valid PNG file.\n",filename);
		exit(1);
	}

	UnpackedBitmap *self=AllocBitmapOrDie(loader.width,loader.height);

	if(!LoadPNGImageData(&loader,self->pixels,sizeof(UnpackedPixel)*loader.width,BitmapLoaderPixelFunc))
	{
		fprintf(stderr,"Failed while loading PNG data from file \"%s\".\n",filename);
		exit(1);
	}

	free(bytes);

	return self;
}

static void *BitmapLoaderPixelFunc(void *destination,uint8_t r,uint8_t g,uint8_t b,uint8_t a,int x,int y)
{
	UnpackedPixel *pixel=destination;

	pixel->r=r;
	pixel->g=g;
	pixel->b=b;
	pixel->a=a;
	return pixel+1;
}

#endif


text:
TITLE    = 'AnimeFTW'
PREFIX   = '/video/animeftw'

ART      = 'art-default.png'
ICON     = 'icon-folder.png'

BASEURL  = 'https://www.animeftw.tv/api/v2?devkey=kAsq-suUj-qG4t-Nxhx&remember=true&'

###################################################################################################
def Start():

	HTTP.Headers['User-Agent'] = 'plex-animeftw'

	# set default title for the plugin
	ObjectContainer.title1 = TITLE
	ObjectContainer.art = R(ART)

	TVShowObject.thumb = R(ICON)
	TVShowObject.art = R(ICON)

	DirectoryObject.thumb = R(ICON)
	DirectoryObject.art = R(ART)
	EpisodeObject.thumb = R(ICON)
	EpisodeObject.art = R(ART)
	VideoClipObject.thumb = R(ICON)
	VideoClipObject.art = R(ART)

###################################################################################################
def ValidatePrefs():

	# ensure that username / password are not empty
	username = Prefs['username']
	password = Prefs['password']

	Log.Info("validating the username and password")

	if not (username and password):
		Log.Error("failed username / password empty test")
		return ObjectContainer(
			header = "Error",
			message = L("EmptySettingsError")
		)
		'''
		return MessageContainer(
			"Error",
			L("EmptySettingsError")
		)
		'''

	else:
		# send request to validate credentials
		json_url = BASEURL + "username=" + username + "&password=" + password
		tokenRequest = JSON.ObjectFromURL(json_url)

		if (tokenRequest["status"] != "200"):
			Log.Error("failed authentication test at the server")
			return ObjectContainer(
				header = "Error",
				message = L("AuthenticationError")
			)
			'''
			return MessageContainer(
				"Error",
				L("AuthenticationError")
			)
			'''

###################################################################################################
@handler(PREFIX, TITLE)
def MainMenu():

	oc = ObjectContainer()

	try:
		# get a token from the server based on the username/password
		token = GetApiToken()

		# Create an object container for the menu and add the menu items
		oc.add(DirectoryObject(key=Callback(SeriesMenu, token=token), title=L("BrowseTitle")))

	except Exception, e:
		Log.Error(e)
		oc.header = "Error"
		oc.message = L("AuthenticationError")

	return oc

###################################################################################################
@route(PREFIX + '/series')
def SeriesMenu(token):

	# Create list of shows available to be viewed
	oc = ObjectContainer()
	oc.title1 = L("BrowseTitle")

	# send request to validate credentials
	json_url = BASEURL + "token=" + token + "&action=display-series"
	seriesList = JSON.ObjectFromURL(json_url)

	# TODO: this should be replaced with date from json response
	seriesArt = "https://d206m0dw9i4jjv.cloudfront.net/video-images/eyes_1_screen.jpeg"

	for series in seriesList["results"].values():

		Log(series)

		# Create tv show and add to container
		oc.add(TVShowObject(
			key=Callback(EpisodeMenu, token=token, seriesId=series["id"], seriesTitle=series["fullSeriesName"], seriesArt=seriesArt),
			rating_key="animeftw-" + series["id"],
			title=series["fullSeriesName"],
			summary=series["description"],
			thumb=series["image"],
			art=series["image"]
		))

	return oc

###################################################################################################
@route(PREFIX + '/episodes')
def EpisodeMenu(token, seriesId, seriesTitle, seriesArt = ""):

	Log("token: " + token + "; id: " + seriesId + "; seriesTitle: " + seriesTitle + "; seriesArt: " + seriesArt)

	# Create list of shows available to be viewed
	oc = ObjectContainer()
	oc.title1 = seriesTitle

	# send request to validate credentials
	json_url = BASEURL + "token=" + token + "&action=display-episodes&id=" + seriesId
	episodeList = JSON.ObjectFromURL(json_url)

	episodes = sorted(episodeList["results"].values(), key=lambda x: int(x["epnumber"]))
	Log(episodes)

	for episode in episodes:
		# create a video clip object for each episode and add to container
		oc.add(CreateVideoClipObject(episode))

	return oc

###################################################################################################
def CreateVideoClipObject(episode, include_container=False):

	url = episode["video"]
	title = episode["epname"]
	summary = ""
	image = episode["image"]
	resolution = episode["vidwidth"]
	episode_number = int(episode["epnumber"])

	# determine the container type
	container_type = Container.MP4
	if episode["videotype"] == "mkv":
		container_type = Container.MKV
	if episode["videotype"] == "divx":
		container_type = Container.AVI

	videoclip_obj = EpisodeObject(
		key=Callback(CreateVideoClipObject, episode=episode, include_container=True),
		rating_key=url,
		title=title,
		summary=summary,
		thumb=image,
		art=image,
		index=episode_number,
		items = [
			MediaObject(
				parts = [
					PartObject(key=url)
				],
				container = container_type,
				video_resolution = resolution
			)
		]
	)

	if include_container:
		return ObjectContainer(objects=[videoclip_obj])
	else:
		return videoclip_obj

###################################################################################################
def GetApiToken():

	# ensure that username / password are not empty
	username = Prefs['username']
	password = Prefs['password']

	Log.Debug("validating the username and password")

	if not (username and password):
		Log.Error("failed username / password empty test")
		raise Ex.MediaNotAuthorized

	# send request to validate credentials
	json_url = BASEURL + "username=" + username + "&password=" + password
	tokenRequest = JSON.ObjectFromURL(json_url)

	if (tokenRequest["status"] != "200"):
		Log.Error("failed credential test")
		raise Ex.MediaNotAuthorized

	Log.Debug("token was acquired: " + tokenRequest["message"])
	return tokenRequest["message"]


text:
using namespace std;

class Contacts {
  map<string, unsigned> ctcs;

public:
  // Adds a contact to the "list"
  void add(const string& name) {
    // updates the count of all prefixes of the string
    for (int i = 1; i <= name.size(); ++i) {
      string p = name.substr(0, i);
      if (ctcs.find(p) == ctcs.end()) {
        ctcs[p] = 1;
      } else {
        ctcs[p] += 1;
      }
    }
  }
  // counts the contacts where partial is a prefix
  unsigned find(const string& partial) {
    return ctcs.find(partial) != ctcs.end() ? ctcs[partial] : 0;
  }
};

int main() {
  Contacts agenda;

  int queries;
  cin >> queries;

  for (int q = 0; q < queries; q += 1) {
    string command, argument;
    cin >> command;
    cin >> argument;
    if (command == "add") {
      agenda.add(argument);
    } else if (command == "find") {
      cout << agenda.find(argument) << endl;
    }
  }

  return 0;
}


text:
import {IEffect} from '../../Blocks/IEffect';
import {PostEffect} from '../../Blocks/Effects/PostEffect';

export class AudioNodeConnectionManager {

    static Debug: boolean = false;

    constructor() {

        this.ExtendToneConnectionMethods();
    }

    ExtendToneConnectionMethods() {

        // Extend AudioNode.connect to include PostEffects
        (<any>AudioNode).prototype._toneConnect = AudioNode.prototype.connect;
        AudioNode.prototype.connect = function (destination: any, outNum, inNum) {
            if (destination instanceof PostEffect) {
                destination = (<IEffect>destination).Effect;
            }
            this._toneConnect(destination, outNum, inNum);
        };
    }
}


text:
import { StepDefinitions } from 'cucumber';

module.exports = function then() {
    let step: StepDefinitions = this;
    // step.Then(/^I open the (url|site) "([^"]*)?"$/, openWebsite);
};


text:
sudo apt-get install -y git
sudo apt-get install -y haskell-platform
sudo apt-get install -y ghc-haddock

git clone https://gitr.sys.kth.se/ingo/forsyde-shallow.git /tmp
cd /tmp/forsyde-shallow

./Setup.hs configure
./Setup.hs build
./Setup.hs haddock


text:
package armcognitiveservices

import (
	"context"
	"errors"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore/arm"
	armruntime "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/runtime"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore/cloud"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime"
	"net/http"
	"net/url"
	"strings"
)

// DeploymentsClient contains the methods for the Deployments group.
// Don't use this type directly, use NewDeploymentsClient() instead.
type DeploymentsClient struct {
	host           string
	subscriptionID string
	pl             runtime.Pipeline
}

// NewDeploymentsClient creates a new instance of DeploymentsClient with the specified values.
// subscriptionID - The ID of the target subscription.
// credential - used to authorize requests. Usually a credential from azidentity.
// options - pass nil to accept the default values.
func NewDeploymentsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*DeploymentsClient, error) {
	if options == nil {
		options = &arm.ClientOptions{}
	}
	ep := cloud.AzurePublic.Services[cloud.ResourceManager].Endpoint
	if c, ok := options.Cloud.Services[cloud.ResourceManager]; ok {
		ep = c.Endpoint
	}
	pl, err := armruntime.NewPipeline(moduleName, moduleVersion, credential, runtime.PipelineOptions{}, options)
	if err != nil {
		return nil, err
	}
	client := &DeploymentsClient{
		subscriptionID: subscriptionID,
		host:           ep,
		pl:             pl,
	}
	return client, nil
}

// BeginCreateOrUpdate - Update the state of specified deployments associated with the Cognitive Services account.
// If the operation fails it returns an *azcore.ResponseError type.
// Generated from API version 2022-10-01
// resourceGroupName - The name of the resource group. The name is case insensitive.
// accountName - The name of Cognitive Services account.
// deploymentName - The name of the deployment associated with the Cognitive Services Account
// deployment - The deployment properties.
// options - DeploymentsClientBeginCreateOrUpdateOptions contains the optional parameters for the DeploymentsClient.BeginCreateOrUpdate
// method.
func (client *DeploymentsClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, accountName string, deploymentName string, deployment Deployment, options *DeploymentsClientBeginCreateOrUpdateOptions) (*runtime.Poller[DeploymentsClientCreateOrUpdateResponse], error) {
	if options == nil || options.ResumeToken == "" {
		resp, err := client.createOrUpdate(ctx, resourceGroupName, accountName, deploymentName, deployment, options)
		if err != nil {
			return nil, err
		}
		return runtime.NewPoller[DeploymentsClientCreateOrUpdateResponse](resp, client.pl, nil)
	} else {
		return runtime.NewPollerFromResumeToken[DeploymentsClientCreateOrUpdateResponse](options.ResumeToken, client.pl, nil)
	}
}

// CreateOrUpdate - Update the state of specified deployments associated with the Cognitive Services account.
// If the operation fails it returns an *azcore.ResponseError type.
// Generated from API version 2022-10-01
func (client *DeploymentsClient) createOrUpdate(ctx context.Context, resourceGroupName string, accountName string, deploymentName string, deployment Deployment, options *DeploymentsClientBeginCreateOrUpdateOptions) (*http.Response, error) {
	req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, accountName, deploymentName, deployment, options)
	if err != nil {
		return nil, err
	}
	resp, err := client.pl.Do(req)
	if err != nil {
		return nil, err
	}
	if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusCreated) {
		return nil, runtime.NewResponseError(resp)
	}
	return resp, nil
}

// createOrUpdateCreateRequest creates the CreateOrUpdate request.
func (client *DeploymentsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, accountName string, deploymentName string, deployment Deployment, options *DeploymentsClientBeginCreateOrUpdateOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/deployments/{deploymentName}"
	if resourceGroupName == "" {
		return nil, errors.New("parameter resourceGroupName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
	if accountName == "" {
		return nil, errors.New("parameter accountName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName))
	if client.subscriptionID == "" {
		return nil, errors.New("parameter client.subscriptionID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
	if deploymentName == "" {
		return nil, errors.New("parameter deploymentName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{deploymentName}", url.PathEscape(deploymentName))
	req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.host, urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2022-10-01")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, runtime.MarshalAsJSON(req, deployment)
}

// BeginDelete - Deletes the specified deployment associated with the Cognitive Services account.
// If the operation fails it returns an *azcore.ResponseError type.
// Generated from API version 2022-10-01
// resourceGroupName - The name of the resource group. The name is case insensitive.
// accountName - The name of Cognitive Services account.
// deploymentName - The name of the deployment associated with the Cognitive Services Account
// options - DeploymentsClientBeginDeleteOptions contains the optional parameters for the DeploymentsClient.BeginDelete method.
func (client *DeploymentsClient) BeginDelete(ctx context.Context, resourceGroupName string, accountName string, deploymentName string, options *DeploymentsClientBeginDeleteOptions) (*runtime.Poller[DeploymentsClientDeleteResponse], error) {
	if options == nil || options.ResumeToken == "" {
		resp, err := client.deleteOperation(ctx, resourceGroupName, accountName, deploymentName, options)
		if err != nil {
			return nil, err
		}
		return runtime.NewPoller[DeploymentsClientDeleteResponse](resp, client.pl, nil)
	} else {
		return runtime.NewPollerFromResumeToken[DeploymentsClientDeleteResponse](options.ResumeToken, client.pl, nil)
	}
}

// Delete - Deletes the specified deployment associated with the Cognitive Services account.
// If the operation fails it returns an *azcore.ResponseError type.
// Generated from API version 2022-10-01
func (client *DeploymentsClient) deleteOperation(ctx context.Context, resourceGroupName string, accountName string, deploymentName string, options *DeploymentsClientBeginDeleteOptions) (*http.Response, error) {
	req, err := client.deleteCreateRequest(ctx, resourceGroupName, accountName, deploymentName, options)
	if err != nil {
		return nil, err
	}
	resp, err := client.pl.Do(req)
	if err != nil {
		return nil, err
	}
	if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusAccepted, http.StatusNoContent) {
		return nil, runtime.NewResponseError(resp)
	}
	return resp, nil
}

// deleteCreateRequest creates the Delete request.
func (client *DeploymentsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, accountName string, deploymentName string, options *DeploymentsClientBeginDeleteOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/deployments/{deploymentName}"
	if resourceGroupName == "" {
		return nil, errors.New("parameter resourceGroupName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
	if accountName == "" {
		return nil, errors.New("parameter accountName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName))
	if client.subscriptionID == "" {
		return nil, errors.New("parameter client.subscriptionID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
	if deploymentName == "" {
		return nil, errors.New("parameter deploymentName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{deploymentName}", url.PathEscape(deploymentName))
	req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.host, urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2022-10-01")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

// Get - Gets the specified deployments associated with the Cognitive Services account.
// If the operation fails it returns an *azcore.ResponseError type.
// Generated from API version 2022-10-01
// resourceGroupName - The name of the resource group. The name is case insensitive.
// accountName - The name of Cognitive Services account.
// deploymentName - The name of the deployment associated with the Cognitive Services Account
// options - DeploymentsClientGetOptions contains the optional parameters for the DeploymentsClient.Get method.
func (client *DeploymentsClient) Get(ctx context.Context, resourceGroupName string, accountName string, deploymentName string, options *DeploymentsClientGetOptions) (DeploymentsClientGetResponse, error) {
	req, err := client.getCreateRequest(ctx, resourceGroupName, accountName, deploymentName, options)
	if err != nil {
		return DeploymentsClientGetResponse{}, err
	}
	resp, err := client.pl.Do(req)
	if err != nil {
		return DeploymentsClientGetResponse{}, err
	}
	if !runtime.HasStatusCode(resp, http.StatusOK) {
		return DeploymentsClientGetResponse{}, runtime.NewResponseError(resp)
	}
	return client.getHandleResponse(resp)
}

// getCreateRequest creates the Get request.
func (client *DeploymentsClient) getCreateRequest(ctx context.Context, resourceGroupName string, accountName string, deploymentName string, options *DeploymentsClientGetOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/deployments/{deploymentName}"
	if resourceGroupName == "" {
		return nil, errors.New("parameter resourceGroupName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
	if accountName == "" {
		return nil, errors.New("parameter accountName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName))
	if client.subscriptionID == "" {
		return nil, errors.New("parameter client.subscriptionID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
	if deploymentName == "" {
		return nil, errors.New("parameter deploymentName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{deploymentName}", url.PathEscape(deploymentName))
	req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.host, urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2022-10-01")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

// getHandleResponse handles the Get response.
func (client *DeploymentsClient) getHandleResponse(resp *http.Response) (DeploymentsClientGetResponse, error) {
	result := DeploymentsClientGetResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.Deployment); err != nil {
		return DeploymentsClientGetResponse{}, err
	}
	return result, nil
}

// NewListPager - Gets the deployments associated with the Cognitive Services account.
// Generated from API version 2022-10-01
// resourceGroupName - The name of the resource group. The name is case insensitive.
// accountName - The name of Cognitive Services account.
// options - DeploymentsClientListOptions contains the optional parameters for the DeploymentsClient.List method.
func (client *DeploymentsClient) NewListPager(resourceGroupName string, accountName string, options *DeploymentsClientListOptions) *runtime.Pager[DeploymentsClientListResponse] {
	return runtime.NewPager(runtime.PagingHandler[DeploymentsClientListResponse]{
		More: func(page DeploymentsClientListResponse) bool {
			return page.NextLink != nil && len(*page.NextLink) > 0
		},
		Fetcher: func(ctx context.Context, page *DeploymentsClientListResponse) (DeploymentsClientListResponse, error) {
			var req *policy.Request
			var err error
			if page == nil {
				req, err = client.listCreateRequest(ctx, resourceGroupName, accountName, options)
			} else {
				req, err = runtime.NewRequest(ctx, http.MethodGet, *page.NextLink)
			}
			if err != nil {
				return DeploymentsClientListResponse{}, err
			}
			resp, err := client.pl.Do(req)
			if err != nil {
				return DeploymentsClientListResponse{}, err
			}
			if !runtime.HasStatusCode(resp, http.StatusOK) {
				return DeploymentsClientListResponse{}, runtime.NewResponseError(resp)
			}
			return client.listHandleResponse(resp)
		},
	})
}

// listCreateRequest creates the List request.
func (client *DeploymentsClient) listCreateRequest(ctx context.Context, resourceGroupName string, accountName string, options *DeploymentsClientListOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/deployments"
	if resourceGroupName == "" {
		return nil, errors.New("parameter resourceGroupName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
	if accountName == "" {
		return nil, errors.New("parameter accountName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName))
	if client.subscriptionID == "" {
		return nil, errors.New("parameter client.subscriptionID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
	req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.host, urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2022-10-01")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

// listHandleResponse handles the List response.
func (client *DeploymentsClient) listHandleResponse(resp *http.Response) (DeploymentsClientListResponse, error) {
	result := DeploymentsClientListResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.DeploymentListResult); err != nil {
		return DeploymentsClientListResponse{}, err
	}
	return result, nil
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>TopicControl (HornetQ JMS Client 2.4.0.Final API)</title>
<meta name="date" content="2013-12-16">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.hornetq.api.jms.management

Interface TopicControl

<map id="APIVIZ" name="APIVIZ">
<area shape="rect" id="node1" href="TopicControl.html" title="«interface» TopicControl" alt="" coords="23,84,115,124"/>
<area shape="rect" id="node2" href="DestinationControl.html" title="«interface» DestinationControl" alt="" coords="5,5,133,45"/>
</map>

All Superinterfaces:

DestinationControl

public interface TopicControl
extends DestinationControl

A TopicControl is used to manage a JMS Topic.

Author:

Jeff Mesnil

Method Summary

Methods

Modifier and Type
Method and Description

void
addJNDI(String jndi)

Add the JNDI binding to this destination

int
countMessagesForSubscription(String clientID,
                            String subscriptionName,
                            String filter)

Counts the number of messages in the subscription specified by the specified client ID and subscription name.

void
dropAllSubscriptions()

Drops all subscriptions.

void
dropDurableSubscription(String clientID,
                       String subscriptionName)

Drops the subscription specified by the specified client ID and subscription name.

int
getDurableMessageCount()

Returns the number of messages for all durable subscribers for this topic.

int
getDurableSubscriptionCount()

Returns the number of durable subscribers for this topic.

String[]
getJNDIBindings()

Returns the JNDI bindings associated  to this connection factory.

int
getNonDurableMessageCount()

Returns the number of messages for all non-durable subscribers for this topic.

int
getNonDurableSubscriptionCount()

Returns the number of non-durable subscribers for this topic.

int
getSubscriptionCount()

Returns the number of (durable and non-durable) subscribers for this topic.

Object[]
listAllSubscriptions()

Lists all the subscriptions for this topic (both durable and non-durable).

String
listAllSubscriptionsAsJSON()

Lists all the subscriptions for this topic (both durable and non-durable) using JSON serialization.

Object[]
listDurableSubscriptions()

Lists all the durable subscriptions for this topic.

String
listDurableSubscriptionsAsJSON()

Lists all the durable subscriptions  using JSON serialization.

Map<String,Object>[]
listMessagesForSubscription(String queueName)

Lists all the messages in this queue matching the specified queue representing the subscription.

String
listMessagesForSubscriptionAsJSON(String queueName)

Lists all the messages in this queue matching the specified queue representing the subscription using JSON serialization.

Object[]
listNonDurableSubscriptions()

Lists all the non-durable subscriptions for this topic.

String
listNonDurableSubscriptionsAsJSON()

Lists all the non-durable subscriptions  using JSON serialization.

Methods inherited from interface org.hornetq.api.jms.management.DestinationControl

getAddress, getDeliveringCount, getMessageCount, getMessagesAdded, getName, isTemporary, removeMessages

Method Detail

getSubscriptionCount

int getSubscriptionCount()

Returns the number of (durable and non-durable) subscribers for this topic.

getDurableSubscriptionCount

int getDurableSubscriptionCount()

Returns the number of durable subscribers for this topic.

getNonDurableSubscriptionCount

int getNonDurableSubscriptionCount()

Returns the number of non-durable subscribers for this topic.

getDurableMessageCount

int getDurableMessageCount()

Returns the number of messages for all durable subscribers for this topic.

getNonDurableMessageCount

int getNonDurableMessageCount()

Returns the number of messages for all non-durable subscribers for this topic.

getJNDIBindings

String[] getJNDIBindings()

Returns the JNDI bindings associated  to this connection factory.

addJNDI

void addJNDI(String jndi)
             throws Exception

Add the JNDI binding to this destination

Throws:

Exception

listAllSubscriptions

Object[] listAllSubscriptions()
                              throws Exception

Lists all the subscriptions for this topic (both durable and non-durable).

Throws:

Exception

listAllSubscriptionsAsJSON

String listAllSubscriptionsAsJSON()
                                  throws Exception

Lists all the subscriptions for this topic (both durable and non-durable) using JSON serialization.

 Java objects can be recreated from JSON serialization using SubscriptionInfo.from(String).

Throws:

Exception

listDurableSubscriptions

Object[] listDurableSubscriptions()
                                  throws Exception

Lists all the durable subscriptions for this topic.

Throws:

Exception

listDurableSubscriptionsAsJSON

String listDurableSubscriptionsAsJSON()
                                      throws Exception

Lists all the durable subscriptions  using JSON serialization.

 Java objects can be recreated from JSON serialization using SubscriptionInfo.from(String).

Throws:

Exception

listNonDurableSubscriptions

Object[] listNonDurableSubscriptions()
                                     throws Exception

Lists all the non-durable subscriptions for this topic.

Throws:

Exception

listNonDurableSubscriptionsAsJSON

String listNonDurableSubscriptionsAsJSON()
                                         throws Exception

Lists all the non-durable subscriptions  using JSON serialization.

 Java objects can be recreated from JSON serialization using SubscriptionInfo.from(String).

Throws:

Exception

listMessagesForSubscription

Map<String,Object>[] listMessagesForSubscription(String queueName)
                                                 throws Exception

Lists all the messages in this queue matching the specified queue representing the subscription.

 1 Map represents 1 message, keys are the message's properties and headers, values are the corresponding values.

Throws:

Exception

listMessagesForSubscriptionAsJSON

String listMessagesForSubscriptionAsJSON(String queueName)
                                         throws Exception

Lists all the messages in this queue matching the specified queue representing the subscription using JSON serialization.

Throws:

Exception

countMessagesForSubscription

int countMessagesForSubscription(String clientID,
                               String subscriptionName,
                               String filter)
                                 throws Exception

Counts the number of messages in the subscription specified by the specified client ID and subscription name. Only messages matching the filter will be counted.

 Using null or an empty filter will count all messages from this queue.

Throws:

Exception

dropDurableSubscription

void dropDurableSubscription(String clientID,
                           String subscriptionName)
                             throws Exception

Drops the subscription specified by the specified client ID and subscription name.

Throws:

Exception

dropAllSubscriptions

void dropAllSubscriptions()
                          throws Exception

Drops all subscriptions.

Throws:

Exception

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Copyright © 2013 JBoss, a division of Red Hat. All Rights Reserved.


text:
SELECT
engine.name AS name,
engine.engine_id AS id,
'engine' AS "type details"

FROM engine AS engine
LEFT OUTER JOIN car AS car
ON engine.engine_id = car.engine_id
WHERE car.engine_id is NULL

UNION

SELECT
box.name AS name,
box.gear_box_id AS id,
'gear box' AS "type details"

FROM gear_box AS box
LEFT OUTER JOIN car AS car
ON  box.gear_box_id = car.box_id
WHERE car.box_id is NULL

UNION

SELECT
transm.name AS name,
transm.transmission_id AS id,
'transmission' AS "type details"

FROM transmission AS transm
LEFT OUTER JOIN car AS car
ON  transm.transmission_id = car.transm_id
WHERE car.transm_id is NULL


text:
({
	'bold': 'Krepko',
	'copy': 'Prekopiraj',
	'cut': 'Izreži',
	'delete': 'Izbriši',
	'indent': 'Zamik',
	'insertHorizontalRule': 'Vodoravno ravnilo',
	'insertOrderedList': 'Oštevilčen seznam',
	'insertUnorderedList': 'Naštevni seznam',
	'italic': 'Ležeče',
	'justifyCenter': 'Poravnaj na sredino',
	'justifyFull': 'Obojestranska poravnava',
	'justifyLeft': 'Poravnaj levo',
	'justifyRight': 'Poravnaj desno',
	'outdent': 'Viseč odstavek',
	'paste': 'Prilepi',
	'redo': 'Znova uveljavi',
	'removeFormat': 'Odstrani obliko zapisa',
	'selectAll': 'Izberi vse',
	'strikethrough': 'Prečrtano',
	'subscript': 'Podpisano',
	'superscript': 'Nadpisano',
	'underline': 'Podčrtano',
	'undo': 'Razveljavi',
	'unlink': 'Odstrani povezavo',
	'createLink': 'Ustvari povezavo',
	'toggleDir': 'Preklopi na usmeritev',
	'insertImage': 'Vstavi sliko',
	'insertTable': 'Vstavi/uredi tabelo',
	'toggleTableBorder': 'Preklopi na rob tabele',
	'deleteTable': 'Izbriši tabelo',
	'tableProp': 'Lastnost tabele',
	'htmlToggle': 'Izvorna koda HTML',
	'foreColor': 'Barva ospredja',
	'hiliteColor': 'Barva ozadja',
	'plainFormatBlock': 'Slog odstavka',
	'formatBlock': 'Slog odstavka',
	'fontSize': 'Velikost pisave',
	'fontName': 'Ime pisave',
	'tabIndent': 'Zamik tabulatorja',
	"fullScreen": "Preklopi na celozaslonski način",
	"viewSource": "Prikaži izvorno kodo HTML",
	"print": "Natisni",
	"newPage": "Nova stran",
	/* Error messages */
	'systemShortcut': 'Dejanje "${0}" lahko v vašem brskalniku uporabite samo z bližnjico na tipkovnici. Uporabite ${1}.'
})


text:
#pragma once

#include <string>
#include <chrono>
#include <stdexcept>
#include <mutex>

#include "../time/ElapsedTime.hpp"

#include "LogHandler.hpp"

namespace openlib {

/**
 * @brief Logging Utility
 *
 * Log::init(...) must be called before any instance of Log is created,
 * otherwise logging will be disable for those instances of Log.
 *
 * It is recommended to create one log object per module or class, that way
 * each module can have their own log level or sub tag as needed.
 */
class Log {
public:

  static const std::string TAG_NONE;    /**< Human readable tag for LogLevel::NONE */
  static const std::string TAG_FATAL;   /**< Human readable tag for LogLevel::FATAL */
  static const std::string TAG_ERROR;   /**< Human readable tag for LogLevel::ERROR */
  static const std::string TAG_WARN;    /**< Human readable tag for LogLevel::WARN */
  static const std::string TAG_INFO;    /**< Human readable tag for LogLevel::INFO */
  static const std::string TAG_VERBOSE; /**< Human readable tag for LogLevel::VERBOSE */
  static const std::string TAG_DEBUG;   /**< Human readable tag for LogLevel::DEBUG */
  static const std::string TAG_ALL;     /**< Human readable tag for LogLevel::ALL */

  /**
   * @brief Init the logging infrastructure
   * @param tag a human readable tag to be used for all instances of Log
   */
  static void init(const std::string& logTag);

  /**
   * @brief Init the logging infrastructure
   * @param tag a human readable tag to be used for all instances of Log
   * @param levelFilter log levels below this are ignored
   */
  static void init(const std::string& logTag, LogLevel levelFilter);

  /**
   * @brief Init the logging infrastructure
   * @param tag a human readable tag to be used for all instances of Log
   * @param logHandler a custom handler to output the logs
   */
  static void init(const std::string& logTag, const LogHandler *logHandler);

  /**
   * @brief Init the logging infrastructure
   * @param tag a human readable tag to be used for all instances of Log
   * @param levelFilter log levels below this are ignored
   * @param logHandler a custom handler to output the logs
   */
  static void init(const std::string& logTag, LogLevel levelFilter, const LogHandler *logHandler);

  /**
   * @brief Format a message using printf style variable argument lists
   * @param message printf style format string
   * @param ... arguments needed by message
   * @return a formatted message
   */
  static std::string format(const char* message, ...);

  /**
   * @brief get a human readable string for a given log level
   * @param level log level
   * @return a human readable string
   */
  static const std::string& levelStr(LogLevel level);

  /**
   * @brief Construct a log object using the default settings
   */
  Log();

  /**
   * @brief Construct a log object, overriding the default log level
   * @param levelFilter log levels below this are ignored
   */
  explicit Log(LogLevel levelFilter);

  /**
   * @brief Construct a log object, using a custom sub tag
   * @param subTag log messages will have an aditional sub tag
   */
  explicit Log(const std::string& subTag);

  /**
   * @brief Construct a log object, overriding the default log level and using a custom sub tag
   * @param levelFilter log levels below this are ignored
   * @param subTag log messages will have an aditional sub tag
   */
  explicit Log(LogLevel levelFilter, const std::string& subTag);

  /**
   * @brief Destructor
   */
  virtual ~Log() = default;

  /**
   * @brief get the current log level
   * @return current log level
   */
  virtual LogLevel level();

  /**
   * @brief set the log level
   * @param logLevel new log level
   */
  virtual void level(LogLevel logLevel);

  /**
   * @brief Log a fatal message
   * @param message to be logged
   */
  virtual void f(const std::string& message) const;

  /**
   * @brief Log a fatal message
   * @param message to be logged
   */
  virtual void fatal(const std::string& message) const;

  /**
   * @brief Log an error message
   * @param message to be logged
   */
  virtual void e(const std::string& message) const;

  /**
   * @brief Log an error message
   * @param message to be logged
   */
  virtual void error(const std::string& message) const;

  /**
   * @brief Log a warn message
   * @param message to be logged
   */
  virtual void w(const std::string& message) const;

  /**
   * @brief Log a warn message
   * @param message to be logged
   */
  virtual void warn(const std::string& message) const;

  /**
   * @brief Log an info message
   * @param message to be logged
   */
  virtual void i(const std::string& message) const;

  /**
   * @brief Log an info message
   * @param message to be logged
   */
  virtual void info(const std::string& message) const;

  /**
   * @brief Log a verbose message
   * @param message to be logged
   */
  virtual void v(const std::string& message) const;

  /**
   * @brief Log a verbose message
   * @param message to be logged
   */
  virtual void verbose(const std::string& message) const;

  /**
   * @brief Log a debug message
   * @param message to be logged
   */
  virtual void d(const std::string& message) const;

  /**
   * @brief Log a debug message
   * @param message to be logged
   */
  virtual void debug(const std::string& message) const;

  /**
   * @brief isLogging
   * Is this log object logging messages of this level?
   */
  virtual bool isLogging(LogLevel logLevel);

private:
  static const LogHandler *logHandler;
  static const ElapsedTime timestamp;

  static std::string globalTag;
  static LogLevel globalLevelFilter;
  static char globalFormatBuffer[];
  static std::mutex globalFormatBufferMutex;

  std::string logTag;
  LogLevel levelFilter;

  virtual void logMessage(LogLevel level, const std::string& message) const;
};

}


text:
import denodeify = require('denodeify');
import mockFs = require('mock-fs');
import ts = require('typescript');
import fs = require('fs');

import {InsertChange, NodeHost, RemoveChange} from './change';
import {insertAfterLastOccurrence, addDeclarationToModule} from './ast-utils';
import {findNodes} from './node';
import {it} from './spec-utils';

const readFile = <any>denodeify(fs.readFile);

describe('ast-utils: findNodes', () => {
  const sourceFile = 'tmp/tmp.ts';

  beforeEach(() => {
    let mockDrive = {
      'tmp': {
        'tmp.ts': `import * as myTest from 'tests' \n` +
        'hello.'
      }
    };
    mockFs(mockDrive);
  });

  afterEach(() => {
    mockFs.restore();
  });

  it('finds no imports', () => {
    let editedFile = new RemoveChange(sourceFile, 0, `import * as myTest from 'tests' \n`);
    return editedFile
      .apply(NodeHost)
      .then(() => {
        let rootNode = getRootNode(sourceFile);
        let nodes = findNodes(rootNode, ts.SyntaxKind.ImportDeclaration);
        expect(nodes).toEqual([]);
      });
  });
  it('finds one import', () => {
    let rootNode = getRootNode(sourceFile);
    let nodes = findNodes(rootNode, ts.SyntaxKind.ImportDeclaration);
    expect(nodes.length).toEqual(1);
  });
  it('finds two imports from inline declarations', () => {
    // remove new line and add an inline import
    let editedFile = new RemoveChange(sourceFile, 32, '\n');
    return editedFile
      .apply(NodeHost)
      .then(() => {
        let insert = new InsertChange(sourceFile, 32, `import {Routes} from '@angular/routes'`);
        return insert.apply(NodeHost);
      })
      .then(() => {
        let rootNode = getRootNode(sourceFile);
        let nodes = findNodes(rootNode, ts.SyntaxKind.ImportDeclaration);
        expect(nodes.length).toEqual(2);
      });
  });
  it('finds two imports from new line separated declarations', () => {
    let editedFile = new InsertChange(sourceFile, 33, `import {Routes} from '@angular/routes'`);
    return editedFile
      .apply(NodeHost)
      .then(() => {
        let rootNode = getRootNode(sourceFile);
        let nodes = findNodes(rootNode, ts.SyntaxKind.ImportDeclaration);
        expect(nodes.length).toEqual(2);
      });
  });
});

describe('ast-utils: insertAfterLastOccurrence', () => {
  const sourceFile = 'tmp/tmp.ts';
  beforeEach(() => {
    let mockDrive = {
      'tmp': {
        'tmp.ts': ''
      }
    };
    mockFs(mockDrive);
  });

  afterEach(() => {
    mockFs.restore();
  });

  it('inserts at beginning of file', () => {
    let imports = getNodesOfKind(ts.SyntaxKind.ImportDeclaration, sourceFile);
    return insertAfterLastOccurrence(imports, `\nimport { Router } from '@angular/router';`,
                                     sourceFile, 0)
      .apply(NodeHost)
      .then(() => {
        return readFile(sourceFile, 'utf8');
      }).then((content) => {
        let expected = '\nimport { Router } from \'@angular/router\';';
        expect(content).toEqual(expected);
      });
  });
  it('throws an error if first occurence with no fallback position', () => {
    let imports = getNodesOfKind(ts.SyntaxKind.ImportDeclaration, sourceFile);
    expect(() => insertAfterLastOccurrence(imports, `import { Router } from '@angular/router';`,
                                           sourceFile)).toThrowError();
  });
  it('inserts after last import', () => {
    let content = `import { foo, bar } from 'fizz';`;
    let editedFile = new InsertChange(sourceFile, 0, content);
    return editedFile
      .apply(NodeHost)
      .then(() => {
        let imports = getNodesOfKind(ts.SyntaxKind.ImportDeclaration, sourceFile);
        return insertAfterLastOccurrence(imports, ', baz', sourceFile,
          0, ts.SyntaxKind.Identifier)
          .apply(NodeHost);
      })
      .then(() => {
        return readFile(sourceFile, 'utf8');
      })
      .then(newContent => expect(newContent).toEqual(`import { foo, bar, baz } from 'fizz';`));
  });
  it('inserts after last import declaration', () => {
    let content = `import * from 'foo' \n import { bar } from 'baz'`;
    let editedFile = new InsertChange(sourceFile, 0, content);
    return editedFile
      .apply(NodeHost)
      .then(() => {
        let imports = getNodesOfKind(ts.SyntaxKind.ImportDeclaration, sourceFile);
        return insertAfterLastOccurrence(imports, `\nimport Router from '@angular/router'`,
          sourceFile)
          .apply(NodeHost);
      })
      .then(() => {
        return readFile(sourceFile, 'utf8');
      })
      .then(newContent => {
        let expected = `import * from 'foo' \n import { bar } from 'baz'` +
          `\nimport Router from '@angular/router'`;
        expect(newContent).toEqual(expected);
      });
  });
  it('inserts correctly if no imports', () => {
    let content = `import {} from 'foo'`;
    let editedFile = new InsertChange(sourceFile, 0, content);
    return editedFile
      .apply(NodeHost)
      .then(() => {
        let imports = getNodesOfKind(ts.SyntaxKind.ImportDeclaration, sourceFile);
        return insertAfterLastOccurrence(imports, ', bar', sourceFile, undefined,
          ts.SyntaxKind.Identifier)
          .apply(NodeHost);
      })
      .catch(() => {
        return readFile(sourceFile, 'utf8');
      })
      .then(newContent => {
        expect(newContent).toEqual(content);
        // use a fallback position for safety
        let imports = getNodesOfKind(ts.SyntaxKind.ImportDeclaration, sourceFile);
        let pos = findNodes(imports.sort((a, b) => a.pos - b.pos).pop(),
          ts.SyntaxKind.CloseBraceToken).pop().pos;
        return insertAfterLastOccurrence(imports, ' bar ',
          sourceFile, pos, ts.SyntaxKind.Identifier)
          .apply(NodeHost);
      })
      .then(() => {
        return readFile(sourceFile, 'utf8');
      })
      .then(newContent => {
        expect(newContent).toEqual(`import { bar } from 'foo'`);
      });
  });
});

describe('addDeclarationToModule', () => {
  beforeEach(() => {
    mockFs({
      '1.ts': `
import {NgModule} from '@angular/core';

@NgModule({
  declarations: []
})
class Module {}`,
      '2.ts': `
import {NgModule} from '@angular/core';

@NgModule({
  declarations: [
    Other
  ]
})
class Module {}`,
      '3.ts': `
import {NgModule} from '@angular/core';

@NgModule({
})
class Module {}`,
      '4.ts': `
import {NgModule} from '@angular/core';

@NgModule({
  field1: [],
  field2: {}
})
class Module {}`
    });
  });
  afterEach(() => mockFs.restore());

  it('works with empty array', () => {
    return addDeclarationToModule('1.ts', 'MyClass', 'MyImportPath')
      .then(change => change.apply(NodeHost))
      .then(() => readFile('1.ts', 'utf-8'))
      .then(content => {
        expect(content).toEqual(
          '\n' +
          'import {NgModule} from \'@angular/core\';\n' +
          'import { MyClass } from \'MyImportPath\';\n' +
          '\n' +
          '@NgModule({\n' +
          '  declarations: [MyClass]\n' +
          '})\n' +
          'class Module {}'
        );
      });
  });

  it('does not append duplicate declarations', () => {
    return addDeclarationToModule('2.ts', 'MyClass', 'MyImportPath')
      .then(change => change.apply(NodeHost))
      .then(() => addDeclarationToModule('2.ts', 'MyClass', 'MyImportPath'))
      .then(change => change.apply(NodeHost))
      .then(() => readFile('2.ts', 'utf-8'))
      .then(content => {
        expect(content).toEqual(
          '\n' +
          'import {NgModule} from \'@angular/core\';\n' +
          'import { MyClass } from \'MyImportPath\';\n' +
          '\n' +
          '@NgModule({\n' +
          '  declarations: [\n' +
          '    Other,\n' +
          '    MyClass\n' +
          '  ]\n' +
          '})\n' +
          'class Module {}'
        );
      });
  });

  it('works with array with declarations', () => {
    return addDeclarationToModule('2.ts', 'MyClass', 'MyImportPath')
      .then(change => change.apply(NodeHost))
      .then(() => readFile('2.ts', 'utf-8'))
      .then(content => {
        expect(content).toEqual(
          '\n' +
          'import {NgModule} from \'@angular/core\';\n' +
          'import { MyClass } from \'MyImportPath\';\n' +
          '\n' +
          '@NgModule({\n' +
          '  declarations: [\n' +
          '    Other,\n' +
          '    MyClass\n' +
          '  ]\n' +
          '})\n' +
          'class Module {}'
        );
      });
  });

  it('works without any declarations', () => {
    return addDeclarationToModule('3.ts', 'MyClass', 'MyImportPath')
      .then(change => change.apply(NodeHost))
      .then(() => readFile('3.ts', 'utf-8'))
      .then(content => {
        expect(content).toEqual(
          '\n' +
          'import {NgModule} from \'@angular/core\';\n' +
          'import { MyClass } from \'MyImportPath\';\n' +
          '\n' +
          '@NgModule({\n' +
          '  declarations: [MyClass]\n' +
          '})\n' +
          'class Module {}'
        );
      });
  });

  it('works without a declaration field', () => {
    return addDeclarationToModule('4.ts', 'MyClass', 'MyImportPath')
      .then(change => change.apply(NodeHost))
      .then(() => readFile('4.ts', 'utf-8'))
      .then(content => {
        expect(content).toEqual(
          '\n' +
          'import {NgModule} from \'@angular/core\';\n' +
          'import { MyClass } from \'MyImportPath\';\n' +
          '\n' +
          '@NgModule({\n' +
          '  field1: [],\n' +
          '  field2: {},\n' +
          '  declarations: [MyClass]\n' +
          '})\n' +
          'class Module {}'
        );
      });
  });
});

/**
 * Gets node of kind kind from sourceFile
 */
function getNodesOfKind(kind: ts.SyntaxKind, sourceFile: string) {
  return findNodes(getRootNode(sourceFile), kind);
}

function getRootNode(sourceFile: string) {
  return ts.createSourceFile(sourceFile, fs.readFileSync(sourceFile).toString(),
    ts.ScriptTarget.Latest, true);
}


text:
import collections
import os
import re
import numpy

from . import spectra_reader

ENVI_TO_NUMPY_DTYPE = {'1':  numpy.uint8,
                       '2':  numpy.int16,
                       '3':  numpy.int32,
                       '4':  numpy.float32,
                       '5':  numpy.float64,
                       '6':  numpy.complex64,
                       '9':  numpy.complex128,
                       '12': numpy.uint16,
                       '13': numpy.uint32,
                       '14': numpy.int64,
                       '15': numpy.uint64}

class ENVIFormat(spectra_reader.SpectraReader):
    """
    Reader for ENVI spectral library.
    """

    def read_hdr_file(self, rawfilename):
        """
        Read information from ENVI header file to a dictionary.
        """

        # Get the filename without path or extension
        filename = os.path.basename(rawfilename)
        filesplit = os.path.splitext(filename)
        filebase = filesplit[0]
        dirname = os.path.dirname(rawfilename)

        # See if we can find the header file to use
        if os.path.isfile(os.path.join(dirname, filebase + '.hdr')):
            hdrfilename = os.path.join(dirname, filebase + '.hdr')
        elif os.path.isfile(os.path.join(dirname, filename + '.hdr')):
            hdrfilename = os.path.join(dirname, filename + '.hdr')
        else:
            raise IOError('Could not find coresponding header file')

        hdrfile = open(hdrfilename, 'r')
        output = collections.OrderedDict()
        inblock = False

        # Read line, split it on equals, strip whitespace from resulting strings
        # and add key/value pair to output
        for currentline in hdrfile:
            # ENVI headers accept blocks bracketed by curly braces - check for these
            if not inblock:
                # Split line on first equals sign
                if re.search('=', currentline) is not None:
                    linesplit = re.split('=', currentline, 1)
                    # Convert all values to lower case
                    key = linesplit[0].strip().lower()
                    value = linesplit[1].strip()

                    # If value starts with an open brace, it's the start of a block
                    # - strip the brace off and read the rest of the block
                    if re.match('{', value) is not None:
                        inblock = True
                        value = re.sub('^{', '', value, 1)

                        # If value ends with a close brace it's the end
                        # of the block as well - strip the brace off
                        if re.search('}$', value):
                            inblock = False
                            value = re.sub('}$', '', value, 1)
                    value = value.strip()
                    output[key] = value
            else:
                # If we're in a block, just read the line, strip whitespace
                # (and any closing brace ending the block) and add the whole thing
                value = currentline.strip()
                if re.search('}$', value):
                    inblock = False
                    value = re.sub('}$', '', value, 1)
                    value = value.strip()
                output[key] = output[key] + value

        hdrfile.close()

        return output

    def get_spectra(self, filename, spectra_number=1):
        """
        Extracts spectra from ENVI file. To get a list of all spectra within
        a file use 'print_spectra_names'.

        Requires:

        * filename
        * spectra_number - multiple spectra are often present in the same file. Use to specify required spectra.

        Returns:

        * Spectra object with values, radiance, pixel and line

        """
        in_header = self.read_hdr_file(filename)

        # Get samples lines and data type
        lines = int(in_header['lines'])
        samples = int(in_header['samples'])
        data_type = in_header['data type']
        byte_order = int(in_header['byte order'])

        # Get wavelengths as NumPy array.
        wavelengths = in_header['wavelength'].split(',')
        wavelengths = [float(w) for w in wavelengths]
        wavelengths = numpy.array(wavelengths)

        # Read to numpy array
        data = numpy.fromfile(filename,
                              dtype=ENVI_TO_NUMPY_DTYPE[data_type])
        if byte_order == 0:
            data = data.reshape((lines, samples))
        else:
            data = data.byteswap()
            data = data.reshape((lines, samples))

        reflectance = data[spectra_number-1,:]

        self.spectra.file_name = filename
        self.spectra.wavelengths = wavelengths
        self.spectra.values = reflectance
        if in_header['wavelength units'].lower() == 'micrometers':
            self.spectra.wavelength_units = 'um'
        else:
            self.spectra.wavelength_units = 'nm'
        self.spectra.value_units = 'reflectance'
        try:
            scale_factor = float(in_header['reflectance scale factor'])
            self.spectra.value_scaling = scale_factor
        except KeyError:
            self.spectra.value_scaling = 1

        return self.spectra

    def print_spectra_names(self, filename):
        """
        Prints the names of spectra within a spectral library and the
        coresponding number, which can be used in 'get_spectra'
        """
        in_header = self.read_hdr_file(filename)

        spectra_names = in_header['spectra names']

        for i, name in enumerate(spectra_names.split(',')):
            print("{:0>3}: {}".format(i+1, name.strip()))


text:
using base::StringPrintf;

namespace extensions {

// A target maximum size (in number of entries) for the mapping tables.  If the
// cache would grow larger than this, the size should be reduced.
static const size_t kMaximumCacheSize = 1000;

DatabaseStringTable::DatabaseStringTable(const std::string& table)
    : table_(table) {}

DatabaseStringTable::~DatabaseStringTable() {}

bool DatabaseStringTable::Initialize(sql::Database* connection) {
  if (!connection->DoesTableExist(table_.c_str())) {
    return connection->Execute(StringPrintf(
        "CREATE TABLE %s (id INTEGER PRIMARY KEY, value TEXT NOT NULL); "
        "CREATE UNIQUE INDEX %s_index ON %s(value)",
        table_.c_str(),
        table_.c_str(),
        table_.c_str()).c_str());
  } else {
    return true;
  }
}

bool DatabaseStringTable::StringToInt(sql::Database* connection,
                                      const std::string& value,
                                      int64_t* id) {
  std::map<std::string, int64_t>::const_iterator lookup =
      value_to_id_.find(value);
  if (lookup != value_to_id_.end()) {
    *id = lookup->second;
    return true;
  }

  // We will be adding data to the cache below--check the cache size now and
  // reduce it if needed.
  PruneCache();

  // Operate on the assumption that the cache does a good job on
  // frequently-used strings--if there is a cache miss, first act on the
  // assumption that the string is not in the database either.
  sql::Statement update(connection->GetUniqueStatement(
      StringPrintf("INSERT OR IGNORE INTO %s(value) VALUES (?)", table_.c_str())
          .c_str()));
  update.BindString(0, value);
  if (!update.Run())
    return false;

  if (connection->GetLastChangeCount() == 1) {
    *id = connection->GetLastInsertRowId();
    id_to_value_[*id] = value;
    value_to_id_[value] = *id;
    return true;
  }

  // The specified string may have already existed in the database, in which
  // case the insert above will have been ignored.  If this happens, do a
  // lookup to find the old value.
  sql::Statement query(connection->GetUniqueStatement(
      StringPrintf("SELECT id FROM %s WHERE value = ?", table_.c_str())
          .c_str()));
  query.BindString(0, value);
  if (!query.Step())
    return false;
  *id = query.ColumnInt64(0);
  id_to_value_[*id] = value;
  value_to_id_[value] = *id;
  return true;
}

bool DatabaseStringTable::IntToString(sql::Database* connection,
                                      int64_t id,
                                      std::string* value) {
  std::map<int64_t, std::string>::const_iterator lookup = id_to_value_.find(id);
  if (lookup != id_to_value_.end()) {
    *value = lookup->second;
    return true;
  }

  // We will be adding data to the cache below--check the cache size now and
  // reduce it if needed.
  PruneCache();

  sql::Statement query(connection->GetUniqueStatement(
      StringPrintf("SELECT value FROM %s WHERE id = ?", table_.c_str())
          .c_str()));
  query.BindInt64(0, id);
  if (!query.Step())
    return false;

  *value = query.ColumnString(0);
  id_to_value_[id] = *value;
  value_to_id_[*value] = id;
  return true;
}

void DatabaseStringTable::ClearCache() {
  id_to_value_.clear();
  value_to_id_.clear();
}

void DatabaseStringTable::PruneCache() {
  if (id_to_value_.size() <= kMaximumCacheSize &&
      value_to_id_.size() <= kMaximumCacheSize)
    return;

  // TODO(mvrable): Perhaps implement a more intelligent caching policy.  For
  // now, to limit memory usage we simply clear the entire cache when it would
  // become too large.  Data will be brought back in from the database as
  // needed.
  ClearCache();
}

}  // namespace extensions


text:
/*
 * Modified by the GTK+ Team and others 1997-2000.  See the AUTHORS
 * file for a list of people on the GTK+ Team.  See the ChangeLog
 * files for a list of changes.  These files are distributed with
 * GTK+ at ftp://ftp.gtk.org/pub/gtk/.
 */

#ifndef __GTK_TEXT_LAYOUT_H__
#define __GTK_TEXT_LAYOUT_H__

/* This is a "semi-private" header; it is intended for
 * use by the text widget, and the text canvas item,
 * but that's all. We may have to install it so the
 * canvas item can use it, but users are not supposed
 * to use it.
 */
#ifndef GTK_TEXT_USE_INTERNAL_UNSUPPORTED_API
#error "You are not supposed to be including this file; the equivalent public API is in gtktextview.h"
#endif

#include <gtk/gtk.h>

G_BEGIN_DECLS

/* forward declarations that have to be here to avoid including
 * gtktextbtree.h
 */
typedef struct _GtkTextLine     GtkTextLine;
typedef struct _GtkTextLineData GtkTextLineData;

#define GTK_TYPE_TEXT_LAYOUT             (gtk_text_layout_get_type ())
#define GTK_TEXT_LAYOUT(obj)             (G_TYPE_CHECK_INSTANCE_CAST ((obj), GTK_TYPE_TEXT_LAYOUT, GtkTextLayout))
#define GTK_TEXT_LAYOUT_CLASS(klass)     (G_TYPE_CHECK_CLASS_CAST ((klass), GTK_TYPE_TEXT_LAYOUT, GtkTextLayoutClass))
#define GTK_IS_TEXT_LAYOUT(obj)          (G_TYPE_CHECK_INSTANCE_TYPE ((obj), GTK_TYPE_TEXT_LAYOUT))
#define GTK_IS_TEXT_LAYOUT_CLASS(klass)  (G_TYPE_CHECK_CLASS_TYPE ((klass), GTK_TYPE_TEXT_LAYOUT))
#define GTK_TEXT_LAYOUT_GET_CLASS(obj)   (G_TYPE_INSTANCE_GET_CLASS ((obj), GTK_TYPE_TEXT_LAYOUT, GtkTextLayoutClass))

typedef struct _GtkTextLayout         GtkTextLayout;
typedef struct _GtkTextLayoutClass    GtkTextLayoutClass;
typedef struct _GtkTextLineDisplay    GtkTextLineDisplay;
typedef struct _GtkTextAttrAppearance GtkTextAttrAppearance;

struct _GtkTextLayout
{
  GObject parent_instance;

  /* width of the display area on-screen,
   * i.e. pixels we should wrap to fit inside. */
  gint screen_width;

  /* width/height of the total logical area being layed out */
  gint width;
  gint height;

  /* Pixel offsets from the left and from the top to be used when we
   * draw; these allow us to create left/top margins. We don't need
   * anything special for bottom/right margins, because those don't
   * affect drawing.
   */
  /* gint left_edge; */
  /* gint top_edge; */

  GtkTextBuffer *buffer;

  /* Default style used if no tags override it */
  GtkTextAttributes *default_style;

  /* Pango contexts used for creating layouts */
  PangoContext *ltr_context;
  PangoContext *rtl_context;

  /* A cache of one style; this is used to ensure
   * we don't constantly regenerate the style
   * over long runs with the same style. */
  GtkTextAttributes *one_style_cache;

  /* A cache of one line display. Getting the same line
   * many times in a row is the most common case.
   */
  GtkTextLineDisplay *one_display_cache;

  /* Whether we are allowed to wrap right now */
  gint wrap_loop_count;

  /* Whether to show the insertion cursor */
  guint cursor_visible : 1;

  /* For what GtkTextDirection to draw cursor GTK_TEXT_DIR_NONE -
   * means draw both cursors.
   */
  guint cursor_direction : 2;

  /* The keyboard direction is used to default the alignment when
     there are no strong characters.
  */
  guint keyboard_direction : 2;

  /* The preedit string and attributes, if any */

  gchar *preedit_string;
  PangoAttrList *preedit_attrs;
  gint preedit_len;
  gint preedit_cursor;

  guint overwrite_mode : 1;
};

struct _GtkTextLayoutClass
{
  GObjectClass parent_class;

  /* Some portion of the layout was invalidated
   */
  void  (*invalidated)  (GtkTextLayout *layout);

  /* A range of the layout changed appearance and possibly height
   */
  void  (*changed)              (GtkTextLayout     *layout,
                                 gint               y,
                                 gint               old_height,
                                 gint               new_height);
  GtkTextLineData* (*wrap)      (GtkTextLayout     *layout,
                                 GtkTextLine       *line,
                                 GtkTextLineData   *line_data); /* may be NULL */
  void  (*get_log_attrs)        (GtkTextLayout     *layout,
                                 GtkTextLine       *line,
                                 PangoLogAttr     **attrs,
                                 gint              *n_attrs);
  void  (*invalidate)           (GtkTextLayout     *layout,
                                 const GtkTextIter *start,
                                 const GtkTextIter *end);
  void  (*free_line_data)       (GtkTextLayout     *layout,
                                 GtkTextLine       *line,
                                 GtkTextLineData   *line_data);

  void (*allocate_child)        (GtkTextLayout     *layout,
                                 GtkWidget         *child,
                                 gint               x,
                                 gint               y);

  void (*invalidate_cursors)    (GtkTextLayout     *layout,
                                 const GtkTextIter *start,
                                 const GtkTextIter *end);

  /* Padding for future expansion */
  void (*_gtk_reserved1) (void);
  void (*_gtk_reserved2) (void);
  void (*_gtk_reserved3) (void);
};

struct _GtkTextAttrAppearance
{
  PangoAttribute attr;
  GtkTextAppearance appearance;
};

struct _GtkTextLineDisplay
{
  PangoLayout *layout;
  GArray *cursors;      /* indexes of cursors in the PangoLayout */

  GtkTextDirection direction;

  gint width;                   /* Width of layout */
  gint total_width;             /* width - margins, if no width set on layout, if width set on layout, -1 */
  gint height;
  /* Amount layout is shifted from left edge - this is the left margin
   * plus any other factors, such as alignment or indentation.
   */
  gint x_offset;
  gint left_margin;
  gint right_margin;
  gint top_margin;
  gint bottom_margin;
  gint insert_index;		/* Byte index of insert cursor within para or -1 */

  GtkTextLine *line;

  GdkColor *pg_bg_color;

  GdkRectangle block_cursor;
  guint cursors_invalid : 1;
  guint has_block_cursor : 1;
  guint cursor_at_line_end : 1;
  guint size_only : 1;

  GdkRGBA *pg_bg_rgba;
};

#ifdef GTK_COMPILATION
extern G_GNUC_INTERNAL PangoAttrType gtk_text_attr_appearance_type;
#endif

GType         gtk_text_layout_get_type    (void) G_GNUC_CONST;

GtkTextLayout*     gtk_text_layout_new                   (void);
void               gtk_text_layout_set_buffer            (GtkTextLayout     *layout,
							  GtkTextBuffer     *buffer);
GtkTextBuffer     *gtk_text_layout_get_buffer            (GtkTextLayout     *layout);
void               gtk_text_layout_set_default_style     (GtkTextLayout     *layout,
							  GtkTextAttributes *values);
void               gtk_text_layout_set_contexts          (GtkTextLayout     *layout,
							  PangoContext      *ltr_context,
							  PangoContext      *rtl_context);
void               gtk_text_layout_set_cursor_direction  (GtkTextLayout     *layout,
                                                          GtkTextDirection   direction);
void		   gtk_text_layout_set_overwrite_mode	 (GtkTextLayout     *layout,
							  gboolean           overwrite);
void               gtk_text_layout_set_keyboard_direction (GtkTextLayout     *layout,
							   GtkTextDirection keyboard_dir);
void               gtk_text_layout_default_style_changed (GtkTextLayout     *layout);

void gtk_text_layout_set_screen_width       (GtkTextLayout     *layout,
                                             gint               width);
void gtk_text_layout_set_preedit_string     (GtkTextLayout     *layout,
 					     const gchar       *preedit_string,
 					     PangoAttrList     *preedit_attrs,
 					     gint               cursor_pos);

void     gtk_text_layout_set_cursor_visible (GtkTextLayout     *layout,
                                             gboolean           cursor_visible);
gboolean gtk_text_layout_get_cursor_visible (GtkTextLayout     *layout);

/* Getting the size or the lines potentially results in a call to
 * recompute, which is pretty massively expensive. Thus it should
 * basically only be done in an idle handler.
 *
 * Long-term, we would really like to be able to do these without
 * a full recompute so they may get cheaper over time.
 */
void    gtk_text_layout_get_size  (GtkTextLayout  *layout,
                                   gint           *width,
                                   gint           *height);
GSList* gtk_text_layout_get_lines (GtkTextLayout  *layout,
                                   /* [top_y, bottom_y) */
                                   gint            top_y,
                                   gint            bottom_y,
                                   gint           *first_line_y);

void gtk_text_layout_wrap_loop_start (GtkTextLayout *layout);
void gtk_text_layout_wrap_loop_end   (GtkTextLayout *layout);

GtkTextLineDisplay* gtk_text_layout_get_line_display  (GtkTextLayout      *layout,
                                                       GtkTextLine        *line,
                                                       gboolean            size_only);
void                gtk_text_layout_free_line_display (GtkTextLayout      *layout,
                                                       GtkTextLineDisplay *display);

void gtk_text_layout_get_line_at_y     (GtkTextLayout     *layout,
                                        GtkTextIter       *target_iter,
                                        gint               y,
                                        gint              *line_top);
void gtk_text_layout_get_iter_at_pixel (GtkTextLayout     *layout,
                                        GtkTextIter       *iter,
                                        gint               x,
                                        gint               y);
void gtk_text_layout_get_iter_at_position (GtkTextLayout     *layout,
					   GtkTextIter       *iter,
					   gint              *trailing,
					   gint               x,
					   gint               y);
void gtk_text_layout_invalidate        (GtkTextLayout     *layout,
                                        const GtkTextIter *start,
                                        const GtkTextIter *end);
void gtk_text_layout_invalidate_cursors(GtkTextLayout     *layout,
                                        const GtkTextIter *start,
                                        const GtkTextIter *end);
void gtk_text_layout_free_line_data    (GtkTextLayout     *layout,
                                        GtkTextLine       *line,
                                        GtkTextLineData   *line_data);

gboolean gtk_text_layout_is_valid        (GtkTextLayout *layout);
void     gtk_text_layout_validate_yrange (GtkTextLayout *layout,
                                          GtkTextIter   *anchor_line,
                                          gint           y0_,
                                          gint           y1_);
void     gtk_text_layout_validate        (GtkTextLayout *layout,
                                          gint           max_pixels);

/* This function should return the passed-in line data,
 * OR remove the existing line data from the line, and
 * return a NEW line data after adding it to the line.
 * That is, invariant after calling the callback is that
 * there should be exactly one line data for this view
 * stored on the btree line.
 */
GtkTextLineData* gtk_text_layout_wrap  (GtkTextLayout   *layout,
                                        GtkTextLine     *line,
                                        GtkTextLineData *line_data); /* may be NULL */
void     gtk_text_layout_changed              (GtkTextLayout     *layout,
                                               gint               y,
                                               gint               old_height,
                                               gint               new_height);
void     gtk_text_layout_cursors_changed      (GtkTextLayout     *layout,
                                               gint               y,
                                               gint               old_height,
                                               gint               new_height);
void     gtk_text_layout_get_iter_location    (GtkTextLayout     *layout,
                                               const GtkTextIter *iter,
                                               GdkRectangle      *rect);
void     gtk_text_layout_get_line_yrange      (GtkTextLayout     *layout,
                                               const GtkTextIter *iter,
                                               gint              *y,
                                               gint              *height);
void     _gtk_text_layout_get_line_xrange     (GtkTextLayout     *layout,
                                               const GtkTextIter *iter,
                                               gint              *x,
                                               gint              *width);
void     gtk_text_layout_get_cursor_locations (GtkTextLayout     *layout,
                                               GtkTextIter       *iter,
                                               GdkRectangle      *strong_pos,
                                               GdkRectangle      *weak_pos);
gboolean _gtk_text_layout_get_block_cursor    (GtkTextLayout     *layout,
					       GdkRectangle      *pos);
gboolean gtk_text_layout_clamp_iter_to_vrange (GtkTextLayout     *layout,
                                               GtkTextIter       *iter,
                                               gint               top,
                                               gint               bottom);

gboolean gtk_text_layout_move_iter_to_line_end      (GtkTextLayout *layout,
                                                     GtkTextIter   *iter,
                                                     gint           direction);
gboolean gtk_text_layout_move_iter_to_previous_line (GtkTextLayout *layout,
                                                     GtkTextIter   *iter);
gboolean gtk_text_layout_move_iter_to_next_line     (GtkTextLayout *layout,
                                                     GtkTextIter   *iter);
void     gtk_text_layout_move_iter_to_x             (GtkTextLayout *layout,
                                                     GtkTextIter   *iter,
                                                     gint           x);
gboolean gtk_text_layout_move_iter_visually         (GtkTextLayout *layout,
                                                     GtkTextIter   *iter,
                                                     gint           count);

gboolean gtk_text_layout_iter_starts_line           (GtkTextLayout       *layout,
                                                     const GtkTextIter   *iter);

void     gtk_text_layout_get_iter_at_line           (GtkTextLayout *layout,
                                                     GtkTextIter    *iter,
                                                     GtkTextLine    *line,
                                                     gint            byte_offset);

/* Don't use these. Use gtk_text_view_add_child_at_anchor().
 * These functions are defined in gtktextchild.c, but here
 * since they are semi-public and require GtkTextLayout to
 * be declared.
 */
void gtk_text_child_anchor_register_child   (GtkTextChildAnchor *anchor,
                                             GtkWidget          *child,
                                             GtkTextLayout      *layout);
void gtk_text_child_anchor_unregister_child (GtkTextChildAnchor *anchor,
                                             GtkWidget          *child);

void gtk_text_child_anchor_queue_resize     (GtkTextChildAnchor *anchor,
                                             GtkTextLayout      *layout);

void gtk_text_anchored_child_set_layout     (GtkWidget          *child,
                                             GtkTextLayout      *layout);

void gtk_text_layout_spew (GtkTextLayout *layout);

G_END_DECLS

#endif  /* __GTK_TEXT_LAYOUT_H__ */


text:
<?php
require_once('../model/OptionModel.php');
require_once('../model/RoomLocationModel.php');
class ReportController
{
	function __construct()
	{
		if(!isset($_SESSION))
		{
			session_start();
		}
	}
	public function activate($id = NULL)
	{
		if(!$_SESSION['isLoggedIn'])//maybe change this to be user name...
		{
			require_once('../view/LoginView.php');
			return;
		}

		$RoomLocation = new RoomLocationModel();
		$Option = new OptionModel();

		$OptionList = $Option->getList();
		$RoomList = $RoomLocation->getList();

		require_once('../view/ReportView.php');
	}
}
?>


text:
#ifndef BOOST_ARCHIVE_BASIC_BINARY_OARCHIVE_HPP
#define BOOST_ARCHIVE_BASIC_BINARY_OARCHIVE_HPP

// MS compatible compilers support #pragma once
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
# pragma once
#endif

/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8
// basic_binary_oarchive.hpp

// (C) Copyright 2002 Robert Ramey - http://www.rrsd.com .
// Use, modification and distribution is subject to the Boost Software
// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

//  See http://www.boost.org for updates, documentation, and revision history.

// archives stored as native binary - this should be the fastest way
// to archive the state of a group of obects.  It makes no attempt to
// convert to any canonical form.

// IN GENERAL, ARCHIVES CREATED WITH THIS CLASS WILL NOT BE READABLE
// ON PLATFORM APART FROM THE ONE THEY ARE CREATE ON

#include <cassert>
#include <boost/integer.hpp>
#include <boost/integer_traits.hpp>

#include <boost/config.hpp>
#include <boost/serialization/pfto.hpp>

#include <boost/detail/workaround.hpp>
#include <boost/archive/detail/common_oarchive.hpp>
#include <boost/serialization/string.hpp>
#include <boost/serialization/collection_size_type.hpp>

#include <boost/archive/detail/abi_prefix.hpp> // must be the last header

#ifdef BOOST_MSVC
#  pragma warning(push)
#  pragma warning(disable : 4511 4512)
#endif

namespace boost {
namespace archive {

//////////////////////////////////////////////////////////////////////
// class basic_binary_oarchive - write serialized objects to a binary output stream
// note: this archive has no pretensions to portability.  Archive format
// may vary across machine architectures and compilers.  About the only
// guarentee is that an archive created with this code will be readable
// by a program built with the same tools for the same machne.  This class
// does have the virtue of buiding the smalles archive in the minimum amount
// of time.  So under some circumstances it may be he right choice.
template<class Archive>
class basic_binary_oarchive :
    public archive::detail::common_oarchive<Archive>
{
protected:
#if BOOST_WORKAROUND(BOOST_MSVC, <= 1300)
public:
#elif defined(BOOST_MSVC)
    // for some inexplicable reason insertion of "class" generates compile erro
    // on msvc 7.1
    friend detail::interface_oarchive<Archive>;
#else
    friend class detail::interface_oarchive<Archive>;
#endif
    // any datatype not specifed below will be handled by base class
    typedef detail::common_oarchive<Archive> detail_common_oarchive;
    template<class T>
    void save_override(const T & t, BOOST_PFTO int version){
      this->detail_common_oarchive::save_override(t, static_cast<int>(version));
    }

    // binary files don't include the optional information
    void save_override(const class_id_optional_type & /* t */, int){}

    void save_override(const version_type & t, int){
        // upto 255 versions
        // note:t.t resolves borland ambguity
        assert(t.t <= boost::integer_traits<unsigned char>::const_max);
        const unsigned char x = static_cast<const unsigned char>(t.t);
        * this->This() << x;
    }
    void save_override(const class_id_type & t, int){
        // upto 32K classes
        assert(t.t <= boost::integer_traits<boost::int_least16_t>::const_max);
        const boost::int_least16_t x = static_cast<const boost::int_least16_t>(t.t);
        * this->This() << x;
    }
    void save_override(const class_id_reference_type & t, int){
        // upto 32K classes
        assert(t.t <= boost::integer_traits<boost::int_least16_t>::const_max);
        const boost::int_least16_t x = t.t;
        * this->This() << x;
    }
    void save_override(const object_id_type & t, int){
        // upto 2G objects
        assert(t.t <= boost::integer_traits<boost::uint_least32_t>::const_max);
        const boost::uint_least32_t x = t.t;
        * this->This() << x;
    }
    void save_override(const object_reference_type & t, int){
        // upto 2G objects
        assert(t.t <= boost::integer_traits<boost::uint_least32_t>::const_max);
        const boost::uint_least32_t x = t.t;
        * this->This() << x;
    }
    void save_override(const tracking_type & t, int){
        const char x = t.t;
        * this->This() << x;
    }

    // explicitly convert to char * to avoid compile ambiguities
    void save_override(const class_name_type & t, int){
        const std::string s(t);
        * this->This() << s;
    }

    void save_override(const serialization::collection_size_type & t, int){
    // for backward compatibility, 64 bit integer or variable length integer would be preferred
        std::size_t x = t.t;
        * this->This() << x;
   }

    BOOST_ARCHIVE_OR_WARCHIVE_DECL(void)
    init();

    basic_binary_oarchive(unsigned int flags) :
        detail::common_oarchive<Archive>(flags)
    {}
};

} // namespace archive
} // namespace boost

#ifdef BOOST_MSVC
#pragma warning(pop)
#endif

#include <boost/archive/detail/abi_suffix.hpp> // pops abi_suffix.hpp pragmas

#endif // BOOST_ARCHIVE_BASIC_BINARY_OARCHIVE_HPP


text:
from __future__ import unicode_literals

from django.db import models, migrations
import django.contrib.gis.db.models.fields

class Migration(migrations.Migration):

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='Neighborhood',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('state', models.CharField(max_length=2, db_index=True)),
                ('city', models.CharField(max_length=90)),
                ('name', models.CharField(max_length=90)),
                ('geog', django.contrib.gis.db.models.fields.MultiPolygonField(srid=4326, geography=True)),
                ('region_id', models.FloatField(null=True, blank=True)),
            ],
            options={
                'ordering': ['name'],
            },
        ),
        migrations.CreateModel(
            name='NeighborhoodSource',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('name', models.CharField(max_length=255)),
                ('slug', models.SlugField()),
                ('priority', models.PositiveSmallIntegerField()),
            ],
        ),
        migrations.AddField(
            model_name='neighborhood',
            name='source',
            field=models.ForeignKey(blank=True, to='neighborhoods.NeighborhoodSource', null=True),
        ),
        migrations.AlterUniqueTogether(
            name='neighborhood',
            unique_together=set([('source', 'state', 'city', 'name', 'region_id')]),
        ),
    ]


text:
package be.waines.maven.incremental.distributed.server.impl;

import java.io.File;

import javax.inject.Singleton;

import org.codehaus.jackson.jaxrs.JacksonJsonProvider;
import org.glassfish.hk2.utilities.binding.AbstractBinder;
import org.glassfish.jersey.server.ResourceConfig;

import be.waines.maven.incremental.distributed.BuildIdBodyReaderAndWriter;
import be.waines.maven.incremental.distributed.ChecksumBodyReaderAndWriter;
import be.waines.maven.incremental.distributed.server.resources.BuildRestService;

public class BuildServerConfig extends ResourceConfig {

	public static final String REPOSITORY_ROOT_DIR = "repositoryRootDir";
	private final File repositoryRootDir;

	public BuildServerConfig(File repositoryRootDir) {
		this.repositoryRootDir = repositoryRootDir;
		register(new AbstractBinder() {
			protected void configure() {
				bind(BuildServerConfig.this.repositoryRootDir).named(REPOSITORY_ROOT_DIR).to(File.class);
				bind(InProgressRepositories.class).to(InProgressRepositories.class).in(Singleton.class);
				bind(SharedBuildRepository.class).to(SharedBuildRepository.class).in(Singleton.class);
			};
		});
		registerClasses(BuildRestService.class);

		register(BuildIdBodyReaderAndWriter.class);
		register(ChecksumBodyReaderAndWriter.class);
		//registerClasses(SerializationMessageBodyReaderAndWriter.class);
		register(JacksonJsonProvider.class);
	}

}