text:
"""
Converting the colour table on the Wikipedia CPK article to JSON format
=======================================================================

The Wikipedia article on `CPK colouring`_ contains a nice table for the colours
for each element in various colouring schemes. This script aims to convert that
table into a JSON file that can be used for Pov-Ray visualization.

The table, with only the main row entries, are read from the standard input.
The JSON file are going to be written to the standard output. In the JSON file,
the root element is a dictionary with the colouring scheme as the key,
currently the keys are ``CPK``, ``Koltun``, ``Jmol``, and ``Rasmol``. For each
colouring scheme, the entry is a dictionary with the element symbol as the key
and the colour in the Pov-Ray RGB vector format as value in string.

.. _CPK colouring:,http://en.wikipedia.org/wiki/CPK_coloring>

"""

from __future__ import print_function

import json
import itertools
import re
import sys

def break_into_rows(lines):

    """Breaks the list of lines into sections for each element"""

    row_brk = re.compile(r'^ *\|- *$')
    if_brk = lambda l: row_brk.match(l) is not None

    return [
        list(g) for k, g in itertools.groupby(lines, if_brk) if not k
    ]

def get_elem_symb(line):

    """Gets the element symbol on a line

    If the symbol is for an isotope, ``None`` is going to be returned.

    """

    symb_re = re.compile(
        r'(?P<iso><sup>\d*</sup>)? *(?P<symb>[A-Z][a-z]?)'
        )
    search_res = symb_re.search(line)

    if search_res.group('iso') is not None:
        return None
    else:
        return search_res.group('symb')

def get_pov_rgb(line):

    """Converts a line from Wikipedia into a string for pov-ray rgb colour

    A ``None`` will be returned if the colour cannot be found on the given
    line.
    """

    c_re = re.compile(
        r'colorbox\|#(?P<r>.{2})(?P<g>.{2})(?P<b>.{2})\}\} *$'
        )
    color_max = 255.0

    search_res = c_re.search(line)
    if search_res is None:
        return None
    raw_intensities = (
        search_res.group(i)
        for i in ['r', 'g', 'b']
        )

    intensities = (
        int(i, 16) / color_max
        for i in raw_intensities
    )

    return 'rgb <%4.2f, %4.2f, %4.2f>' % tuple(intensities)

def to_dicts(rows, n_schemes):

    """Convert the lines into dictionaries of colours

    A list of ``n_schemes`` dictionaries are going to be returned for the
    ``n_schemes`` colouring schemes.

    :param rows: A list of rows in the table, as nested list of lines
    :param n_schemes: The number of colouring schemes on each row

    """

    ret_val = [dict() for i in xrange(0, n_schemes)]

    for row_i in rows:

        symb = get_elem_symb(row_i[1])
        if symb is None:
            continue

        for i, l in enumerate(row_i[3:3 + n_schemes]):
            colour = get_pov_rgb(l)
            if colour is not None:
                ret_val[i][symb] = colour

    return ret_val

def main():

    """The main driver function"""

    rows = break_into_rows([i for i in sys.stdin])
    dicts = to_dicts(rows, 4)

    res = {
        'CPK': dicts[0],
        'Koltun': dicts[1],
        'Jmol': dicts[2],
        'Rasmol': dicts[3]
    }

    print(json.dumps(res, indent=4))

    return 0

if __name__ == '__main__':
    main()


text:
<?xml version="1.0" encoding="UTF-8"?>
<gmd:MD_Metadata xsi:schemaLocation="http://www.isotc211.org/2005/gmd ../schemas/iso19139fra/gmd/gmd.xsd" xmlns:fo="http://www.w3.org/1999/XSL/Format" xmlns:map="urn:brgm:mapping" xmlns:gmd="http://www.isotc211.org/2005/gmd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:gml="http://www.opengis.net/gml" xmlns:gts="http://www.isotc211.org/2005/gts" xmlns:gmx="http://www.isotc211.org/2005/gmx" xmlns:gfc="http://www.isotc211.org/2005/gfc" xmlns:gco="http://www.isotc211.org/2005/gco">
	<geosoft xmlns="http://www.geosoft.com/schema/geo">
		<dataset version="1">
			<title>test_polydata_3d_grd_cone</title>
			<file_format>geosoft_3dv</file_format>
			<data_created_by>TestingSystem\Tester</data_created_by>
			<data_creation_date>2003-01-01</data_creation_date>
			<metadata_created_by>TestingSystem\Tester</metadata_created_by>
			<metadata_creation_date>2003-01-01</metadata_creation_date>
			<georeference>
				<dataextents>
					<extent3d minx="662215" miny="23833215" minz="388.524887085" maxx="663610" maxy="23834410" maxz="958.874450684"/>
				</dataextents>
				<projection type="TRANSVERSE_MERCATOR" name="NAD83 / UTM zone 24N" projection="UTM zone 24N" ellipsoid="GRS 1980" datum="NAD83" datumtrf="NAD83 to WGS 84 (1)" datumtrf_description="[NAD83] (4m) North America - Canada and USA (CONUS, Alaska mainland)" radius="6378137" eccentricity="0.0818191910428">
					<shift x="0" y="0" z="0"/>
					<parameters scale="0.9996" false_east="500000" false_north="0" lat_origin="0" lon_origin="-39"/>
					<units name="m" unit_scale="1"/>
				</projection>
			</georeference>
		</dataset>
	</geosoft>
	<gmd:identificationInfo>
		<gmd:MD_DataIdentification>
			<gmd:citation>
				<gmd:CI_Citation>
					<gmd:title>
						<gco:CharacterString>test_polydata_3d_grd_cone</gco:CharacterString>
					</gmd:title>
					<gmd:date>
						<gmd:CI_Date>
							<gmd:date>
								<gco:Date>2003-1-1</gco:Date>
							</gmd:date>
						</gmd:CI_Date>
					</gmd:date>
				</gmd:CI_Citation>
			</gmd:citation>
			<gmd:resourceFormat>
				<gmd:MD_Format>
					<gmd:name>
						<gco:CharacterString>geosoft_3dv</gco:CharacterString>
					</gmd:name>
				</gmd:MD_Format>
			</gmd:resourceFormat>
			<gmd:pointOfContact>
				<gmd:CI_ResponsibleParty>
					<gmd:individualName>
						<gco:CharacterString>TestingSystem\Tester</gco:CharacterString>
					</gmd:individualName>
				</gmd:CI_ResponsibleParty>
			</gmd:pointOfContact>
			<gmd:extent>
				<gmd:EX_Extent>
					<gmd:geographicElement>
						<gmd:EX_GeographicBoundingBox>
							<gmd:westBoundLongitude>
								<gco:Decimal>139.214176483</gco:Decimal>
							</gmd:westBoundLongitude>
							<gmd:eastBoundLongitude>
								<gco:Decimal>139.229625865</gco:Decimal>
							</gmd:eastBoundLongitude>
							<gmd:southBoundLatitude>
								<gco:Decimal>-34.6754607141</gco:Decimal>
							</gmd:southBoundLatitude>
							<gmd:northBoundLatitude>
								<gco:Decimal>-34.6644674449</gco:Decimal>
							</gmd:northBoundLatitude>
						</gmd:EX_GeographicBoundingBox>
					</gmd:geographicElement>
				</gmd:EX_Extent>
			</gmd:extent>
		</gmd:MD_DataIdentification>
	</gmd:identificationInfo>
	<gmd:contact>
		<gmd:CI_ResponsibleParty>
			<gmd:individualName>
				<gco:CharacterString>TestingSystem\Tester</gco:CharacterString>
			</gmd:individualName>
		</gmd:CI_ResponsibleParty>
	</gmd:contact>
	<gmd:dataQualityInfo>
		<gmd:DQ_DataQuality/>
	</gmd:dataQualityInfo>
	<gmd:dateStamp>
		<gco:Date>2003-1-1</gco:Date>
	</gmd:dateStamp>
	<gmd:referenceSystemInfo>
		<gmd:MD_ReferenceSystem>
			<gmd:referenceSystemIdentifier>
				<gmd:RS_Identifier>
					<gmd:codeSpace>
						<gco:CharacterString>ESRI</gco:CharacterString>
					</gmd:codeSpace>
					<gmd:code>
						<gco:CharacterString>PROJCS["UTM_zone_24N",GEOGCS["GCS_North_American_1983",DATUM["D_North_American_1983",SPHEROID["GRS_1980",6378137,298.257222101]],PRIMEM["Greenwich",0],UNIT["Degree",0.0174532925199432955]],PROJECTION["Transverse_Mercator"],PARAMETER["False_Easting",500000],PARAMETER["False_Northing",0],PARAMETER["Central_Meridian",-39],PARAMETER["Scale_Factor",0.9996],PARAMETER["Latitude_Of_Origin",0],UNIT["Meter",1]]</gco:CharacterString>
					</gmd:code>
					<gmd:version>
						<gco:CharacterString>1</gco:CharacterString>
					</gmd:version>
				</gmd:RS_Identifier>
			</gmd:referenceSystemIdentifier>
		</gmd:MD_ReferenceSystem>
	</gmd:referenceSystemInfo>
</gmd:MD_Metadata>

redpajama_set_name: RedPajamaGithub


text:
/**
 * Created by jack on 15/7/24.
 */

class GameOver extends egret.DisplayObjectContainer
{
    private _btnShare:egret.Bitmap;
    private _btnRetry:egret.Bitmap;
    private _bg:egret.Bitmap;
    private _overBg:egret.Bitmap;
    private _textScore:egret.TextField;

    private _score = 0;

    constructor()
    {
        super();
        if (this.stage) {
            this.init();
        } else {
            this.addEventListener(egret.Event.ADDED_TO_STAGE, this.onAddToStage, this);
        }
    }

    private onAddToStage(event:egret.Event)
    {
        this.removeEventListener(egret.Event.ADDED_TO_STAGE, this.onAddToStage, this);
        this.init();
    }

    private init()
    {
        this._bg = new egret.Bitmap();
        this._bg.texture = RES.getRes('bg_png');
        this._bg.width = this.stage.stageWidth;
        this._bg.height = this.stage.stageHeight;
        this.addChild(this._bg);

        this._overBg = new egret.Bitmap();
        this._overBg.texture = RES.getRes('over_png');
        this._overBg.x = (this.stage.stageWidth - this._overBg.width) / 2;
        this._overBg.y = (this.stage.stageHeight - this._overBg.height) / 2;
        this.addChild(this._overBg);

        this._textScore = new egret.TextField();
        this._textScore = new egret.TextField();
        this._textScore.textColor = 0xffdb5d;
        this._textScore.size = 40;
        this._textScore.text = "我吃掉了 " + this._score.toString() + " 個果蔬";
        this._textScore.x = (this.stage.stageWidth - this._textScore.width) / 2;
        this._textScore.y = (this.stage.stageHeight - this._textScore.height) / 2 - 60;
        this.addChild(this._textScore);

        this._btnRetry = new egret.Bitmap();
        this._btnRetry.texture = RES.getRes('ui_json.retry');
        this._btnRetry.x = (this.stage.stageWidth - this._btnRetry.width) / 2 - 100;
        this._btnRetry.y = (this.stage.stageHeight - this._btnRetry.height) / 2 + 80;
        this._btnRetry.touchEnabled = true;
        this._btnRetry.addEventListener(egret.TouchEvent.TOUCH_TAP, this.retry, this);
        this.addChild(this._btnRetry);

        this._btnShare = new egret.Bitmap();
        this._btnShare.texture = RES.getRes('ui_json.share');
        this._btnShare.x = (this.stage.stageWidth - this._btnShare.width) / 2 + 100;
        this._btnShare.y = (this.stage.stageHeight - this._btnShare.height) / 2 + 80;
        this.addChild(this._btnShare);
    }

    public retry()
    {
        this.dispatchEvent(new egret.Event("GameStart"));
    }

    public set score(value)
    {
        this._score = value;
    }
}


text:
var http = require('http');
var pid = process.pid

function sigusr1() {
    console.log('[' + pid + ']', 'Got SIGUSR1')
    /* Stop accepting connection on this server, we will eventually
       exit when there is no more work to do */
    server.watcher.stop()
}

function helloWorld(req, res) {
    console.log('[' + pid + ']', req.url, req.socket.fd)
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello World I am ' + pid + '\n');
}

var server = http.createServer(helloWorld)

process.on('SIGUSR1', sigusr1)

server.listenFD(3)

console.log('[' + pid + ']', 'Started')


text:
using Engine.Model.Common.Dto;
using Engine.Model.Common.Entities;
using System;
using System.Linq;
using System.Security;

namespace Engine.Model.Server.Entities
{
  [Serializable]
  public class ServerChat : Chat<User, ServerRoom, ServerVoiceRoom>
  {
    [SecurityCritical]
    public ServerChat()
    {
      AddRoom(new ServerRoom(UserId.Empty, MainRoomName));
    }

    #region users
    /// <summary>
    /// Returns all users from room as dtos.
    /// </summary>
    /// <param name="roomName">Room name.</param>
    [SecuritySafeCritical]
    public UserDto[] GetRoomUserDtos(string roomName)
    {
      var room = GetRoom(roomName);
      return room.Users
        .Select(CreateDto)
        .ToArray();
    }

    [SecuritySafeCritical]
    private UserDto CreateDto(UserId userId)
    {
      var user = GetUser(userId);
      var certificate = ServerModel.Server.GetCertificate(userId);
      return new UserDto(user, certificate.RawData);
    }
    #endregion
  }
}


text:
$("#makeGreen").click(function() {
  $("#makeGreen").css({"color": "lightGreen"});
});

// Create an image carousel using bxslider (http://bxslider.com/)

$(document).ready(function(){
  $('.bxslider').bxSlider();
});

// Make the second h2 disappear when hovering over it, and come back into view when stop hovering

$("#hoverDisappear").hover(function() {
  $("#hoverDisappear").fadeOut(1000);
  $("#hoverDisappear").fadeIn(1000);
});

// Make the paragraph font size larger everytime it's "touched" by the mouse (ie hovered over)

$("#biggerOnClick").hover(function() {
  var fontSize = parseInt($("#biggerOnClick").css("font-size"));
  fontSize = fontSize + 1 + "px";
  $("#biggerOnClick").css({ "font-size": fontSize});
});

// Make several actions possible for this paragraph

// Change text alignment when click on the paragraph
$("#multipleActions").click(function() {
  $("#multipleActions").css({"text-align": "center"});
});

// Change text colour when hover over the paragraph
$("#multipleActions").hover(
  // when hover in
  function() {
  $("#multipleActions").css({"color": "purple"});
  // when hover out
  }, function() {
  $("#multipleActions").css({"color": "black"});
  }
);

// When click on the button, animate the text in the following div

$("#clickBtn").click(function() {
  $("#animated").animate({
    height: "+=150px",
    width: "+=150px",
  });
});


text:
import pytest

from tests.providers.google.cloud.utils.gcp_authenticator import GCP_AI_KEY
from tests.test_utils.gcp_system_helpers import CLOUD_DAG_FOLDER, GoogleSystemTest, provide_gcp_context

@pytest.mark.backend("mysql", "postgres")
@pytest.mark.credential_file(GCP_AI_KEY)
class CloudNaturalLanguageExampleDagsTest(GoogleSystemTest):
    def setUp(self):
        super().setUp()

    @provide_gcp_context(GCP_AI_KEY)
    def test_run_example_dag(self):
        self.run_dag('example_gcp_natural_language', CLOUD_DAG_FOLDER)

    def tearDown(self):
        super().tearDown()


text:
package com.parallelsymmetry.cirrus;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Path2D;
import java.awt.geom.Rectangle2D;
import java.awt.geom.RoundRectangle2D;

import javax.swing.JComponent;

final class CheckBoxMenuItemPainter extends AbstractRegionPainter {
	//package private integers representing the available states that
	//this painter will paint. These are used when creating a new instance
	//of CheckBoxMenuItemPainter to determine which region/state is being painted
	//by that instance.
	static final int BACKGROUND_DISABLED = 1;

	static final int BACKGROUND_ENABLED = 2;

	static final int BACKGROUND_MOUSEOVER = 3;

	static final int BACKGROUND_SELECTED_MOUSEOVER = 4;

	static final int CHECKICON_DISABLED_SELECTED = 5;

	static final int CHECKICON_ENABLED_SELECTED = 6;

	static final int CHECKICON_SELECTED_MOUSEOVER = 7;

	private int state; //refers to one of the static final ints above

	private PaintContext ctx;

	//the following 4 variables are reused during the painting code of the layers
	private Path2D path = new Path2D.Float();

	private Rectangle2D rect = new Rectangle2D.Float( 0, 0, 0, 0 );

	private RoundRectangle2D roundRect = new RoundRectangle2D.Float( 0, 0, 0, 0, 0, 0 );

	private Ellipse2D ellipse = new Ellipse2D.Float( 0, 0, 0, 0 );

	//All Colors used for painting are stored here. Ideally, only those colors being used
	//by a particular instance of CheckBoxMenuItemPainter would be created. For the moment at least,
	//however, all are created for each instance.
	private Color color1 = decodeColor( "cirrusSelection", 0.0f, 0.0f, 0.0f, 0 );

	private Color color2 = decodeColor( "cirrusSecondary", 0.0f, -0.08983666f, -0.17647058f, 0 );

	private Color color3 = decodeColor( "cirrusSecondary", 0.055555582f, -0.096827686f, -0.45882353f, 0 );

	private Color color4 = decodeColor( "cirrusSecondary", 0.0f, -0.110526316f, 0.25490195f, 0 );

	//Array of current component colors, updated in each paint call
	private Object[] componentColors;

	public CheckBoxMenuItemPainter( PaintContext ctx, int state ) {
		super();
		this.state = state;
		this.ctx = ctx;
	}

	@Override
	protected void doPaint( Graphics2D g, JComponent c, int width, int height, Object[] extendedCacheKeys ) {
		//populate componentColors array with colors calculated in getExtendedCacheKeys call
		componentColors = extendedCacheKeys;
		//generate this entire method. Each state/bg/fg/border combo that has
		//been painted gets its own KEY and paint method.
		switch( state ) {
			case BACKGROUND_MOUSEOVER:
				paintBackgroundMouseOver( g );
				break;
			case BACKGROUND_SELECTED_MOUSEOVER:
				paintBackgroundSelectedAndMouseOver( g );
				break;
			case CHECKICON_DISABLED_SELECTED:
				paintcheckIconDisabledAndSelected( g );
				break;
			case CHECKICON_ENABLED_SELECTED:
				paintcheckIconEnabledAndSelected( g );
				break;
			case CHECKICON_SELECTED_MOUSEOVER:
				paintcheckIconSelectedAndMouseOver( g );
				break;

		}
	}

	@Override
	protected final PaintContext getPaintContext() {
		return ctx;
	}

	private void paintBackgroundMouseOver( Graphics2D g ) {
		rect = decodeRect1();
		g.setPaint( color1 );
		g.fill( rect );

	}

	private void paintBackgroundSelectedAndMouseOver( Graphics2D g ) {
		rect = decodeRect1();
		g.setPaint( color1 );
		g.fill( rect );

	}

	private void paintcheckIconDisabledAndSelected( Graphics2D g ) {
		path = decodePath1();
		g.setPaint( color2 );
		g.fill( path );

	}

	private void paintcheckIconEnabledAndSelected( Graphics2D g ) {
		path = decodePath1();
		g.setPaint( color3 );
		g.fill( path );

	}

	private void paintcheckIconSelectedAndMouseOver( Graphics2D g ) {
		path = decodePath1();
		g.setPaint( color4 );
		g.fill( path );

	}

	private Rectangle2D decodeRect1() {
		rect.setRect( decodeX( 1.0f ), //x
		decodeY( 1.0f ), //y
		decodeX( 2.0f ) - decodeX( 1.0f ), //width
		decodeY( 2.0f ) - decodeY( 1.0f ) ); //height
		return rect;
	}

	private Path2D decodePath1() {
		path.reset();
		path.moveTo( decodeX( 0.0f ), decodeY( 1.5f ) );
		path.lineTo( decodeX( 0.4292683f ), decodeY( 1.5f ) );
		path.lineTo( decodeX( 0.7121951f ), decodeY( 2.4780488f ) );
		path.lineTo( decodeX( 2.5926828f ), decodeY( 0.0f ) );
		path.lineTo( decodeX( 3.0f ), decodeY( 0.0f ) );
		path.lineTo( decodeX( 3.0f ), decodeY( 0.2f ) );
		path.lineTo( decodeX( 2.8317075f ), decodeY( 0.39512196f ) );
		path.lineTo( decodeX( 0.8f ), decodeY( 3.0f ) );
		path.lineTo( decodeX( 0.5731707f ), decodeY( 3.0f ) );
		path.lineTo( decodeX( 0.0f ), decodeY( 1.5f ) );
		path.closePath();
		return path;
	}

}


text:
package com.vgerbot.test.orm.influxdb.common;

import java.io.IOException;
import java.io.StringWriter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.vgerbot.test.orm.influxdb.intergration.entity.CensusMeasurement;

public class JSON {
	private static ObjectMapper mapper = new ObjectMapper();

	public static String stringify(Object value) {
		if (value == null) {
			return "null";
		} else {
			StringWriter sw = new StringWriter();
			try {
				mapper.writerFor(value.getClass()).writeValue(sw, value);
			} catch (IOException e) {
				throw new RuntimeException(e);
			}
			return sw.toString();
		}
	}

	public static void main(String[] args) throws Exception {
		// mapper.configure(Feature.IGNORE_UNKNOWN, true);

		CensusMeasurement m = new CensusMeasurement();
		m.setButterflies(100);
		m.setLocation("Shanghai,China");
		mapper.writerFor(CensusMeasurement.class).writeValue(System.out, m);
	}
}


text:
// Copyright (c) 2022, WNProject Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// clang-format off

#include "XMLNodeHandlerDefault.h"
#include "../../Include/Rocket/Core/Element.h"
#include "../../Include/Rocket/Core/Factory.h"
#include "../../Include/Rocket/Core/Log.h"
#include "../../Include/Rocket/Core/XMLParser.h"
#include "XMLParseTools.h"
#include "precompiled.h"

namespace Rocket {
namespace Core {

XMLNodeHandlerDefault::XMLNodeHandlerDefault(Context* _context)
  : m_context(_context) {}

XMLNodeHandlerDefault::~XMLNodeHandlerDefault() {}

Element* XMLNodeHandlerDefault::ElementStart(
    XMLParser* parser, const String& name, const XMLAttributes& attributes) {
  // Determine the parent
  Element* parent = parser->GetParseFrame()->element;

  // Attempt to instance the element with the instancer
  Element* element =
      Factory::InstanceElement(m_context, parent, name, name, attributes);
  if (!element) {
    Log::Message(m_context, Log::LT_ERROR,
        "Failed to create element for tag %s, instancer returned NULL.",
        name.CString());
    return NULL;
  }

  // Add the element to its parent and remove the reference
  parent->AppendChild(element);
  element->RemoveReference();

  return element;
}

bool XMLNodeHandlerDefault::ElementEnd(
    XMLParser* ROCKET_UNUSED_PARAMETER(parser),
    const String& ROCKET_UNUSED_PARAMETER(name)) {
  return true;
}

bool XMLNodeHandlerDefault::ElementData(XMLParser* parser, const String& data) {
  // Determine the parent
  Element* parent = parser->GetParseFrame()->element;

  // Parse the text into the element
  return Factory::InstanceElementText(m_context, parent, data);
}

void XMLNodeHandlerDefault::Release() {
  delete this;
}
}  // namespace Core
}  // namespace Rocket


text:
    (Edit)

  <rich-text-editor html-content="localValue.label">
  </rich-text-editor>
  <button ng-if="!alwaysEditable" type="button" ng-click="replaceValue(localValue.label)">
    Close
  </button>


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package sba.lib.mail;

import java.util.Base64;

/**
 *
 * @author Sergio Flores
 */
public abstract class DMailUtils {

    /**
     * Encondes raw text for subject into an UTF-8 encoded and properly enclosed string ready to be used in mailing.
     * @param subject
     * @return
     */
    public static String encodeSubjectUtf8(final String subject) {
        return DMailConsts.SUBJECT_ENC_UTF8_BEGIN +
                Base64.getEncoder().encodeToString(subject.getBytes()) +
                DMailConsts.SUBJECT_ENC_UTF8_END;
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE xml>
<Context allowCasualMultipartParsing="true">
   <!-- disable storage of sessions across restarts -->
   <Manager pathname=""/>
</Context>


text:
    <title>LA SECTION «LES ARTISTES RUSSES DU ХХE SIECLE A ABRAMTSEVO»</title>
    <meta http-equiv="content-type" content="text/html; charset=utf-8" />

		Министерство культуры
Российской Федерации
Портал Культура.рф
Проект «Образы России»

Le musée-réserve naturel Abramtsevo

LA SECTION «LES ARTISTES RUSSES DU ХХE SIECLE A ABRAMTSEVO»

Le bâtiment a été construit en 1938. Au début c'était le bâtiment des soins du sanatorium  existant dans les années 1930 sur le territoire du domaine. Il est ouvert au public depuis 1971.
Actuellement ici sont représentées les oeuvres des artistes du ХХe siècle, qui étaient rattachés à Abramtsevo: participants de l'association créatrice «Le valet de carreau» (P. P. Kontchalovskyi, А. V. Lentoulov, I. I. Machkov, А. А. Osmerkin, V.V. Rogdestvenskyi, R. R. Falk), ainsi que les oeuvres de I.E.Grabar, D. А. Chmarinov, N.I.Andronov, А. V. Vasnetsov, Е. А. Maleina, D. А. Chmarinov, N. А. Oudaltsov et d'autres. Dans la collection il y a des sculptures, oeuvres de V.I. Moukhina, B. D. Korolev, S. D. Tavasiev et d'autres. Plusieurs desdits artistes vivaient et travaillaient dans le village de datcha des artistes «Novo-Abramtsevo» fondé dans les années 1930 près du domaine Abramtsevo sur l'autre rive de la rivière Vor.

Культура.рф © Портал культурного наследия России


text:
<?php

/**
  * @package sfLucenePlugin
  * @subpackage Test
  * @author Carl Vondrick
  * @version SVN: $Id$
  */

require dirname(__FILE__) . '/../../bootstrap/unit.php';

$t = new limeade_test(5, limeade_output::get());

class FooListener
{
  public $event;

  public function listen($event)
  {
    $this->event = $event;
  }
}

$source = new sfEventDispatcher();
$target = new sfEventDispatcher();

$connector = new sfLuceneEventConnector($source, 'foo', $target, 'bar');

$t->ok($source->hasListeners('foo'), '__construct() connects a listener to the source');

$subject = 'Fabien';
$params = array('a', 'b', 'c');

$listener = new FooListener;
$target->connect('bar', array($listener, 'listen'));

$source->notify(new sfEvent($subject, 'foo', $params));

$t->isa_ok($listener->event, 'sfEvent', 'calling a linked event calls target');
$t->is($listener->event->getSubject(), $subject, 'calling a linked event sends correct subject');
$t->is($listener->event->getName(), 'bar', 'calling a linked event sends correct name');
$t->is($listener->event->getParameters(), $params, 'calling a linked event sends correct parameters');


text:
module.exports = require('../_test-base');
module.exports.setContext('Component');


text:
@interface DMMenuItemCustomView : NSView

+ (instancetype)customViewWithTitle:(NSString *)title;
+ (instancetype)customViewWithTitle:(NSString *)title tileColor:(NSColor *)color;

@property (nonatomic, copy) NSString *title;
@property (nonatomic, strong) NSColor *backgroundColor;
@property (nonatomic, strong) NSColor *tileColor;

@end


text:
$('.imp-actionbtn').click(function() {
	window.location.href($(this).parent().attr('href'));
});


text:
#ifndef VPX_VP9_ENCODER_VP9_EXT_RATECTRL_H_
#define VPX_VP9_ENCODER_VP9_EXT_RATECTRL_H_

#include "vpx/vpx_ext_ratectrl.h"
#include "vp9/encoder/vp9_firstpass.h"

typedef struct EXT_RATECTRL {
  int ready;
  vpx_rc_model_t model;
  vpx_rc_funcs_t funcs;
  vpx_rc_config_t ratectrl_config;
  vpx_rc_firstpass_stats_t rc_firstpass_stats;
} EXT_RATECTRL;

vpx_codec_err_t vp9_extrc_init(EXT_RATECTRL *ext_ratectrl);

vpx_codec_err_t vp9_extrc_create(vpx_rc_funcs_t funcs,
                                 vpx_rc_config_t ratectrl_config,
                                 EXT_RATECTRL *ext_ratectrl);

vpx_codec_err_t vp9_extrc_delete(EXT_RATECTRL *ext_ratectrl);

vpx_codec_err_t vp9_extrc_send_firstpass_stats(
    EXT_RATECTRL *ext_ratectrl, const FIRST_PASS_INFO *first_pass_info);

vpx_codec_err_t vp9_extrc_get_encodeframe_decision(
    EXT_RATECTRL *ext_ratectrl, int show_index, int coding_index, int gop_index,
    FRAME_UPDATE_TYPE update_type, int gop_size, int use_alt_ref,
    RefCntBuffer *ref_frame_bufs[MAX_INTER_REF_FRAMES], int ref_frame_flags,
    vpx_rc_encodeframe_decision_t *encode_frame_decision);

vpx_codec_err_t vp9_extrc_update_encodeframe_result(
    EXT_RATECTRL *ext_ratectrl, int64_t bit_count,
    const YV12_BUFFER_CONFIG *source_frame,
    const YV12_BUFFER_CONFIG *coded_frame, uint32_t bit_depth,
    uint32_t input_bit_depth, const int actual_encoding_qindex);

vpx_codec_err_t vp9_extrc_get_gop_decision(
    EXT_RATECTRL *ext_ratectrl, const vpx_rc_gop_info_t *const gop_info,
    vpx_rc_gop_decision_t *gop_decision);

#endif  // VPX_VP9_ENCODER_VP9_EXT_RATECTRL_H_


text:
Meteor simple navigation app example for re-route issue with dburles:google-maps package

HTML file for map is in client/views/ui/map.html
Script for map is in client/views/ui/map.coffee
Style for map-container is in client/style/base.import.less
Routes are in lib/router/main.coffee

I'm using yogiben:meteor-starter for boilerplates so it might be an issue (maybe some incompatibilities between packages). Sorry for the unnecessary codes.


text:
class RankingController < ApplicationController
  def have
    ids = Have.group(:item_id).order('count_item_id desc').limit(10).count(:item_id).keys

    #findでidsを取得(この状態では並べ替え未完成)。itemのidをindexでidsに合致させ出力し、並べ替え。
    @items = Item.find(ids).sort_by{|i| ids.index(i.id)}

    #itemのID番号
    @counts = ids
  end

  def want
    ids = Want.group(:item_id).order('count_item_id desc').limit(10).count(:item_id).keys
    @items = Item.find(ids).sort_by{|i| ids.index(i.id)}
    @counts = ids
  end
end


text:
<?php

namespace Deblan\PowerDNS\Command;

use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Deblan\Console\Command\AbstractCommand;
use Symfony\Component\Console\Input\InputArgument;
use Deblan\PowerDNS\Model\ZoneRecordQuery;
use Symfony\Component\Console\Input\InputOption;

class ZoneRecordRemoveCommand extends AbstractCommand
{
    protected function configure()
    {
        parent::configure();

        $this
            ->setName('zone:record:remove')
            ->setDescription('Remove a zone record')
            ->addArgument('id', InputArgument::REQUIRED, 'Record ID (the record can not be associated with an active zone version)')
            ->addOption('confirm', null, InputOption::VALUE_NONE, 'Confirmation');
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        parent::execute($input, $output);

        $id = (int) $this->getInput()->getArgument('id');

        $zoneRecord = ZoneRecordQuery::create()->findOneById($id);

        if (null === $zoneRecord) {
            $this->getOutput()->writeln('<error>Zone record not found.</error>');

            return;
        }

        if ($zoneRecord->getZoneVersion()->getIsActive()) {
            $this->getOutput()->writeln('<error>You can not remove a record of an active zone version.</error>');

            return;
        }

        $confirm = $this->getInput()->getOption('confirm');

        if (false === $confirm) {
            $confirm = $this->getHelper('dialog')->askConfirmation($this->getOutput(), '<info>Do you confirm? [<comment>no</comment>] ', false);
        }

        if ($confirm) {
            $zoneRecord->delete();

            $this->getOutput()->writeln('<info>Zone record removed.</info>');
        } else {
            $this->getOutput()->writeln('<info>Aborted.</info>');
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.navercorp.pinpoint.web.dao.ServiceTracesDao">

    <select id="getTraceList" resultType="ServiceTraces" parameterType="string">
        SELECT *
        FROM service_traces WHERE 1=1
        <if test="_parameter != null and _parameter != ''">
            and service = #{_parameter}
        </if>
    </select>

    <select id="getTraceById" resultType="ServiceTraces" parameterType="string">
        SELECT *
        FROM service_traces WHERE id = #{_parameter}
    </select>

</mapper>


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mbean PUBLIC
   "-//JBoss//DTD JBOSS XMBEAN 1.1//EN"
   "http://www.jboss.org/j2ee/dtd/jboss_xmbean_1_1.dtd">

<mbean>
   <description>Forward Service. Provides auto-routing of DICOM objects
   that are received by the DICOM Storage Service to remote DICOM applications.
   This is done by queueing corresponding retrieve requests to the
   Move SCU service.</description>

   <descriptors>
      <persistence persistPolicy="OnUpdate"/>
      <persistence-manager value="org.jboss.mx.persistence.DelegatingPersistenceManager" />
   </descriptors>

   <class>org.dcm4chex.archive.dcm.movescu.ForwardService</class>

   <constructor>
      <description>The default constructor</description>
      <name>ForwardService</name>
   </constructor>

   <attribute access="read-write"
      getMethod="getForwardingRules"
      setMethod="setForwardingRules">
      <description><![CDATA[List of forwarding rules.

Format:

[calling|called=AEtitle]AEtitle!from-to | NONE

where

calling = create a condition for calling AE titles that objects are forwarded from.

called = create a condition for called AE titles that objects are forwared from

AEtitle = the calling AE titles, or the called AE titles, separated by commas.

AEtitle = the AE titles that objects are forwarded to

From =

To =

NONE =
      ]]>
      </description>
      <name>ForwardingRules</name>
      <type>java.lang.String</type>
      <descriptors>
         <value value="[calling=SAMPLE_SCU1|SAMPLE_SCU2]SAMPLE_SCP3,SAMPLE_SCP4!8-16;NONE" />
      </descriptors>
   </attribute>
   <attribute access="read-write"
      getMethod="getForwardModifiedToAETs"
      setMethod="setForwardModifiedToAETs">
      <description>Comma separated list of AE titles to which objects modified
          by using the web application are re-forwarded. NONE = do not forward
          modified objects.
      </description>
      <name>ForwardModifiedToAETitles</name>
      <type>java.lang.String</type>
      <descriptors>
         <value value="NONE" />
      </descriptors>
   </attribute>
   <attribute access="read-write"
      getMethod="getForwardPriority"
      setMethod="setForwardPriority">
      <description>Forwarding priority. 0=medium, 1=high, 2=low.
      </description>
      <name>ForwardPriority</name>
      <type>int</type>
      <descriptors>
         <value value="0" />
      </descriptors>
   </attribute>
   <attribute access="read-write"
      getMethod="getMaxSOPInstanceUIDsPerMoveRQ"
      setMethod="setMaxSOPInstanceUIDsPerMoveRQ">
      <description>Maximum number of SOP Instance UIDs per Move Request.
      </description>
      <name>MaximumSOPInstanceUIDs</name>
      <type>int</type>
      <descriptors>
         <value value="100" />
      </descriptors>
   </attribute>
   <attribute access="read-write"
      getMethod="getStoreScpServiceName"
      setMethod="setStoreScpServiceName">
      <description>Used internally. Do NOT modify.
      </description>
      <name>StoreScpServiceName</name>
      <type>javax.management.ObjectName</type>
      <descriptors>
         <value value="tiani.archive:service=StoreScp" />
      </descriptors>
   </attribute>
   <attribute access="read-write"
      getMethod="getEditContentServiceName"
      setMethod="setEditContentServiceName">
      <description>Used internally. Do NOT modify.
      </description>
      <name>EditContentServiceName</name>
      <type>javax.management.ObjectName</type>
      <descriptors>
         <value value="tiani.archive:service=ContentEditService" />
      </descriptors>
   </attribute>
   &defaultAttributes;

   &defaultOperations;
</mbean>


text:
namespace bpn = boost::python::numpy;
namespace bp =  boost::python;

typedef boost::tuple< std::vector< std::vector<uint32_t> >, std::vector<uint32_t> > Custom_tuple;

struct VecToArray
{//converts a vector<uint32_t> to a numpy array
    static PyObject * convert(const std::vector<uint32_t> & vec)
    {
        npy_intp dims = vec.size();
        PyObject * obj = PyArray_SimpleNew(1, &dims, NPY_UINT32);
        void * arr_data = PyArray_DATA((PyArrayObject*)obj);
        memcpy(arr_data, &vec[0], dims * sizeof(uint32_t));
        return obj;
    }
};

struct VecToArray_float
{//converts a vector<uint32_t> to a numpy array
    static PyObject * convert(const std::vector<float> & vec)
    {
        npy_intp dims = vec.size();
        PyObject * obj = PyArray_SimpleNew(1, &dims, NPY_FLOAT32);
        void * arr_data = PyArray_DATA((PyArrayObject*)obj);
        memcpy(arr_data, &vec[0], dims * sizeof(float));
        return obj;
    }
};

template<class T>
struct VecvecToList
{//converts a vector< vector<T> > to a list
        static PyObject* convert(const std::vector< std::vector<T> > & vecvec)
    {
        boost::python::list* pylistlist = new boost::python::list();
        for(size_t i = 0; i < vecvec.size(); i++)
        {
            boost::python::list* pylist = new boost::python::list();
            for(size_t j = 0; j < vecvec[i].size(); j++)
            {
                pylist->append(vecvec[i][j]);
            }
            pylistlist->append((pylist, pylist[0]));
        }
        return pylistlist->ptr();
    }
};

struct to_py_tuple
{//converts output to a python tuple
    static PyObject* convert(const Custom_tuple& c_tuple){
        bp::list values;
        //add all c_tuple items to "values" list

        PyObject * vecvec_pyo = VecvecToList<uint32_t>::convert(c_tuple.get<0>());
        PyObject * vec_pyo = VecToArray::convert(c_tuple.get<1>());

        values.append(bp::handle<>(bp::borrowed(vecvec_pyo)));
        values.append(bp::handle<>(bp::borrowed(vec_pyo)));

        return bp::incref( bp::tuple( values ).ptr() );
    }
};

struct to_py_tuple_list
{//converts output to a python list of tuples
    static PyObject* convert(const std::vector <Custom_tuple > & c_tuple_vec){
        int n_hierarchy = c_tuple_vec.size();
        bp::list values;
        //add all c_tuple items to "values" list
        for (int i_hierarchy = 0; i_hierarchy < n_hierarchy; i_hierarchy++)
        {
            PyObject * tuple_pyo = to_py_tuple::convert(c_tuple_vec[i_hierarchy]);
            values.append(bp::handle<>(bp::borrowed(tuple_pyo)));
        }
        return bp::incref(values.ptr());
    }
};

PyObject * cutpursuit(const bpn::ndarray & obs, const bpn::ndarray & source, const bpn::ndarray & target,const bpn::ndarray & edge_weight,
                      float lambda, const int cutoff, const int spatial, float weight_decay)
{//read data and run the L0-cut pursuit partition algorithm
    srand(0);

    const uint32_t n_ver = bp::len(obs);
    const uint32_t n_edg = bp::len(source);
    const uint32_t n_obs = bp::len(obs[0]);
    const float * obs_data = reinterpret_cast<float*>(obs.get_data());
    const uint32_t * source_data = reinterpret_cast<uint32_t*>(source.get_data());
    const uint32_t * target_data = reinterpret_cast<uint32_t*>(target.get_data());
    const float * edge_weight_data = reinterpret_cast<float*>(edge_weight.get_data());
    std::vector<float> solution(n_ver *n_obs);
    //float solution [n_ver * n_obs];
    std::vector<float> node_weight(n_ver, 1.0f);
    std::vector<uint32_t> in_component(n_ver,0);
    std::vector< std::vector<uint32_t> > components(1,std::vector<uint32_t>(1,0.f));
    if (spatial == 0)
    {
        CP::cut_pursuit<float>(n_ver, n_edg, n_obs, obs_data, source_data, target_data, edge_weight_data, &node_weight[0]
                 , solution.data(), in_component, components, lambda, (uint32_t)cutoff,  1.f, 4.f, weight_decay, 0.f);
    }
    else
    {
        CP::cut_pursuit<float>(n_ver, n_edg, n_obs, obs_data, source_data, target_data, edge_weight_data, &node_weight[0]
                 , solution.data(), in_component, components, lambda, (uint32_t)cutoff,  2.f, 4.f, weight_decay, 0.f);
    }
    return to_py_tuple::convert(Custom_tuple(components, in_component));
}

PyObject * cutpursuit_hierarchy(const bpn::ndarray & obs, const bpn::ndarray & source, const bpn::ndarray & target, const bpn::ndarray & edge_weight,
                      const bpn::ndarray & lambda, const bpn::ndarray & cutoff, const int spatial, float weight_decay)
{//read data and run the L0-cut pursuit partition algorithm
    srand(0);
    uint32_t n_ver = bp::len(obs);
    uint32_t n_edg = bp::len(source);
    const uint32_t n_obs = bp::len(obs[0]);
    const uint32_t n_hierarchy = bp::len(lambda);
    float * obs_data = reinterpret_cast<float*>(obs.get_data());
    uint32_t * source_data = reinterpret_cast<uint32_t*>(source.get_data());
    uint32_t * target_data = reinterpret_cast<uint32_t*>(target.get_data());
    float * edge_weight_data = reinterpret_cast<float*>(edge_weight.get_data());
    const float * lambda_data = reinterpret_cast<float*>(lambda.get_data());
    const uint32_t * cutoff_data = reinterpret_cast<uint32_t*>(cutoff.get_data());
    std::vector<float> node_weight(n_ver, 1.0f);
    //prepare outputs
    std::vector<float> solution(n_ver *n_obs);
    std::vector<uint32_t> in_component(n_ver,0);
    std::vector< std::vector<uint32_t> > components(1,std::vector<uint32_t>(1,0.f));
    //prepare hierarchical intermediaries
    uint32_t n_nodes_red;
    uint32_t n_edges_red;
    std::vector<uint32_t> Eu_red(1,0);
    std::vector<uint32_t> Ev_red(1,0);
    std::vector< float > edgeWeight_red(1,0);
    std::vector< float > nodeWeight_red(1,0);
    //prepare list of outputs
    std::vector< Custom_tuple > output_hierarchy(n_hierarchy);
    for (int ite_hierarchy = 0; ite_hierarchy < n_hierarchy; ite_hierarchy++)
    {
        if (spatial == 0)
        {
            CP::cut_pursuit<float>(n_ver, n_edg, n_obs, obs_data, source_data, target_data, edge_weight_data, &node_weight[0]
                     , solution.data(), in_component, components
                     , n_nodes_red, n_edges_red, Eu_red, Ev_red, edgeWeight_red, nodeWeight_red
                     , lambda_data[ite_hierarchy], (uint32_t)cutoff_data[ite_hierarchy],  1.f, 4.f, weight_decay, 0.f);
        }
        else
        {
            CP::cut_pursuit<float>(n_ver, n_edg, n_obs, obs_data, source_data, target_data, edge_weight_data, &node_weight[0]
                     , solution.data(), in_component, components
                     , n_nodes_red, n_edges_red, Eu_red, Ev_red, edgeWeight_red, nodeWeight_red
                     , lambda_data[ite_hierarchy], (uint32_t)cutoff_data[ite_hierarchy],  2.f, 4.f, weight_decay, 0.f);
        }
        n_ver = n_nodes_red;
        n_edg = n_edges_red;
        source_data = Eu_red.data();
        target_data = Ev_red.data();
        edge_weight_data = edgeWeight_red.data();
        node_weight = nodeWeight_red;
        uint32_t ind_sol = 0;
        int index = 0;
        for(uint32_t ind_comp = 0; ind_comp < n_ver; ind_comp++ )
        {
            for(uint32_t i_obs=0; i_obs < n_obs; i_obs++)
            {
                obs_data[index] = solution[components[ind_comp][0] * n_obs + i_obs];
                index++;
            }
        }
        solution = std::vector<float> (n_ver * n_obs,0.);
        output_hierarchy[ite_hierarchy] = Custom_tuple(components, in_component);
    }

    return to_py_tuple_list::convert(output_hierarchy);
}

PyObject * cutpursuit2(const bpn::ndarray & obs, const bpn::ndarray & source, const bpn::ndarray & target,const bpn::ndarray & edge_weight,
                       const bpn::ndarray & node_weight, float lambda)
{//read data and run the L0-cut pursuit partition algorithm
    srand(0);
    const uint32_t n_ver = bp::len(obs);
    const uint32_t n_edg = bp::len(source);
    const uint32_t n_obs = bp::len(obs[0]);
    const float * obs_data = reinterpret_cast<float*>(obs.get_data());
    const uint32_t * source_data = reinterpret_cast<uint32_t*>(source.get_data());
    const uint32_t * target_data = reinterpret_cast<uint32_t*>(target.get_data());
    const float * edge_weight_data = reinterpret_cast<float*>(edge_weight.get_data());
    const float * node_weight_data = reinterpret_cast<float*>(node_weight.get_data());
    std::vector<float> solution(n_ver *n_obs);
    //float solution [n_ver * n_obs];
    //std::vector<float> node_weight(n_ver, 1.0f);
    std::vector<uint32_t> in_component(n_ver,0);
    std::vector< std::vector<uint32_t> > components(1,std::vector<uint32_t>(1,0.f));
    CP::cut_pursuit<float>(n_ver, n_edg, n_obs, obs_data, source_data, target_data, edge_weight_data, node_weight_data
                 , solution.data(), in_component, components, lambda, (uint32_t)0,  2.f, 4.f, 1.f, 1.f);
    return to_py_tuple::convert(Custom_tuple(components, in_component));
}

BOOST_PYTHON_MODULE(libcp)
{
    _import_array();
    Py_Initialize();
    bpn::initialize();
    bp::to_python_converter< Custom_tuple, to_py_tuple>();

    def("cutpursuit", cutpursuit);
    def("cutpursuit", cutpursuit, (bp::args("cutoff")=0, bp::args("spatial")=0, bp::args("weight_decay")=1));
    def("cutpursuit_hierarchy", cutpursuit_hierarchy, (bp::args("cutoff")=0, bp::args("spatial")=0, bp::args("weight_decay")=1));
    def("cutpursuit2", cutpursuit2);
}


text:
package org.apache.jackrabbit.test.api;

import org.apache.jackrabbit.test.AbstractJCRTest;
import org.apache.jackrabbit.test.NotExecutableException;

import javax.jcr.Property;
import javax.jcr.Value;
import javax.jcr.RepositoryException;
import javax.jcr.Node;
import javax.jcr.PathNotFoundException;

/**
 * Tests the various {@link Property#setValue(Value)} methods.
 *

 * Configuration requirements:
 *

 * The node at {@link #testRoot} must allow a
 * child node of type {@link #testNodeType} with name {@link #nodeName1}. The
 * node type {@link #testNodeType} must define a single value reference property
 * with name {@link #propertyName1}. The node type {@link #testNodeType} must
 * be referenceable or allow to add a mix:referenceable, otherwise a
 * {@link NotExecutableException} is thrown.
 *
 * @test
 * @sources SetValueReferenceTest.java
 * @executeClass org.apache.jackrabbit.test.api.SetValueReferenceTest
 * @keywords level2
 */
public class SetValueReferenceTest extends AbstractJCRTest {

    /**
     * The reference value
     */
    private Value value;

    /**
     * The node with the reference property
     */
    private Node node;

    /**
     * The reference property
     */
    private Property property1;

    /**
     * @throws NotExecutableException if the node is not referenceable and does
     *                                not allow to add a mix:referenceable.
     */
    protected void setUp() throws Exception {
        super.setUp();

        // create a new node under the testRootNode
        node = testRootNode.addNode(nodeName1, testNodeType);
        ensureReferenceable(node);

        // initialize some reference value
        value = superuser.getValueFactory().createValue(node);

        // create a new single-value property and save it
        property1 = node.setProperty(propertyName1, value);
        superuser.save();
    }

    protected void tearDown() throws Exception {
        value = null;
        node = null;
        property1 = null;
        super.tearDown();
    }

    /**
     * Test the persistence of a property modified with an Node parameter and
     * saved from the Session Requires a Node value (node)
     */
    public void testNodeSession() throws RepositoryException, NotExecutableException {
        property1.setValue(node);
        superuser.save();
        assertTrue("Reference property not saved", node.isSame(property1.getNode()));
    }

    /**
     * Test the persistence of a property modified with an Node parameter and
     * saved from the parent Node Requires a Node value (node)
     */
    public void testNodeParent() throws RepositoryException {
        property1.setValue(node);
        node.save();
        assertTrue("Reference property not saved", node.isSame(property1.getNode()));
    }

    /**
     * Test the deletion of a property by assigning it a null value, saved from
     * the Session
     */
    public void testRemoveNodeSession() throws RepositoryException {
        property1.setValue((Value) null);
        superuser.save();

        try {
            node.getProperty(propertyName1);
            fail("The property should not exist anymore, as a null Value has been assigned");
        } catch (PathNotFoundException e) {
            //success : the property has been deleted by assigning it a null value
        }
    }

    /**
     * Test the deletion of a property by assigning it a null value, saved from
     * the parent Node
     */
    public void testRemoveNodeParent() throws RepositoryException {
        property1.setValue((Node) null);
        node.save();

        try {
            node.getProperty(propertyName1);
            fail("The property should not exist anymore, as a null Value has been assigned");
        } catch (PathNotFoundException e) {
            //success : the property has been deleted by assigning it a null value
        }
    }

    //-------------------< internal >-------------------------------------------

    /**
     * Ensures that node n is referenceable. If the node is not of
     * type mix:referenceable this method tries to add the mixin
     * mix:referenceable. If the node does not allow to add the mixin, or the
     * repository does not support referenceable nodes a {@link
     * NotExecutableException} is thrown.
     *
     * @param n the node to check.
     * @throws NotExecutableException if the node cannot be made referenceable
     *                                or if the repository does not support
     *                                referenceable nodes.
     */
    private void ensureReferenceable(Node n) throws RepositoryException, NotExecutableException {
        ensureMixinType(n, mixReferenceable);
        n.getSession().save();
    }
}


text:
import { createPromiseCapability, PasswordResponses } from "pdfjs-lib";

/**
 * @typedef {Object} PasswordPromptOptions
 * @property {HTMLDialogElement} dialog - The overlay's DOM element.
 * @property {HTMLParagraphElement} label - Label containing instructions for
 *                                          entering the password.
 * @property {HTMLInputElement} input - Input field for entering the password.
 * @property {HTMLButtonElement} submitButton - Button for submitting the
 *                                              password.
 * @property {HTMLButtonElement} cancelButton - Button for cancelling password
 *                                              entry.
 */

class PasswordPrompt {
  #activeCapability = null;

  #updateCallback = null;

  #reason = null;

  /**
   * @param {PasswordPromptOptions} options
   * @param {OverlayManager} overlayManager - Manager for the viewer overlays.
   * @param {IL10n} l10n - Localization service.
   * @param {boolean} [isViewerEmbedded] - If the viewer is embedded, in e.g.
   *   an <iframe> or an <object>. The default value is `false`.
   */
  constructor(options, overlayManager, l10n, isViewerEmbedded = false) {
    this.dialog = options.dialog;
    this.label = options.label;
    this.input = options.input;
    this.submitButton = options.submitButton;
    this.cancelButton = options.cancelButton;
    this.overlayManager = overlayManager;
    this.l10n = l10n;
    this._isViewerEmbedded = isViewerEmbedded;

    // Attach the event listeners.
    this.submitButton.addEventListener("click", this.#verify.bind(this));
    this.cancelButton.addEventListener("click", this.close.bind(this));
    this.input.addEventListener("keydown", e => {
      if (e.keyCode === /* Enter = */ 13) {
        this.#verify();
      }
    });

    this.overlayManager.register(this.dialog, /* canForceClose = */ true);

    this.dialog.addEventListener("close", this.#cancel.bind(this));
  }

  async open() {
    if (this.#activeCapability) {
      await this.#activeCapability.promise;
    }
    this.#activeCapability = createPromiseCapability();

    try {
      await this.overlayManager.open(this.dialog);
    } catch (ex) {
      this.#activeCapability = null;
      throw ex;
    }

    const passwordIncorrect =
      this.#reason === PasswordResponses.INCORRECT_PASSWORD;

    if (!this._isViewerEmbedded || passwordIncorrect) {
      this.input.focus();
    }
    this.label.textContent = await this.l10n.get(
      `password_${passwordIncorrect ? "invalid" : "label"}`
    );
  }

  async close() {
    if (this.overlayManager.active === this.dialog) {
      this.overlayManager.close(this.dialog);
    }
  }

  #verify() {
    const password = this.input.value;
    if (password?.length > 0) {
      this.#invokeCallback(password);
    }
  }

  #cancel() {
    this.#invokeCallback(new Error("PasswordPrompt cancelled."));
    this.#activeCapability.resolve();
  }

  #invokeCallback(password) {
    if (!this.#updateCallback) {
      return; // Ensure that the callback is only invoked once.
    }
    this.close();
    this.input.value = "";

    this.#updateCallback(password);
    this.#updateCallback = null;
  }

  async setUpdateCallback(updateCallback, reason) {
    if (this.#activeCapability) {
      await this.#activeCapability.promise;
    }
    this.#updateCallback = updateCallback;
    this.#reason = reason;
  }
}

export { PasswordPrompt };


text:
define('ace/mode/text', ['require', 'exports', 'module' , 'pilot/oop', 'ace/tokenizer', 'ace/mode/behaviour', 'ace/mode/text_highlight_rules'],
function(require, exports, module) {

var Tokenizer = require("ace/tokenizer").Tokenizer;
var TextHighlightRules = require("ace/mode/text_highlight_rules").TextHighlightRules;
var Behaviour = require("ace/mode/behaviour").Behaviour;

var Mode = function() {
    this.$tokenizer = new Tokenizer(new TextHighlightRules().getRules());
    this.$behaviour = new Behaviour();
};

(function() {

    this.getTokenizer = function() {
        return this.$tokenizer;
    };

    this.toggleCommentLines = function(state, doc, startRow, endRow) {
    };

    this.getNextLineIndent = function(state, line, tab) {
        return "";
    };

    this.checkOutdent = function(state, line, input) {
        return false;
    };

    this.autoOutdent = function(state, doc, row) {
    };

    this.$getIndent = function(line) {
        var match = line.match(/^(\s+)/);
        if (match) {
            return match[1];
        }

        return "";
    };

    this.createWorker = function(session) {
        return null;
    };

    this.highlightSelection = function(editor) {
        var session = editor.session;
        if (!session.$selectionOccurrences)
            session.$selectionOccurrences = [];

        if (session.$selectionOccurrences.length)
            this.clearSelectionHighlight(editor);

        var selection = editor.getSelectionRange();
        if (selection.isEmpty() || selection.isMultiLine())
            return;

        var startOuter = selection.start.column - 1;
        var endOuter = selection.end.column + 1;
        var line = session.getLine(selection.start.row);
        var lineCols = line.length;
        var needle = line.substring(Math.max(startOuter, 0),
                                    Math.min(endOuter, lineCols));

        // Make sure the outer characters are not part of the word.
        if ((startOuter >= 0 && /^[\w\d]/.test(needle)) ||
            (endOuter <= lineCols && /[\w\d]$/.test(needle)))
            return;

        needle = line.substring(selection.start.column, selection.end.column);
        if (!/^[\w\d]+$/.test(needle))
            return;

        var cursor = editor.getCursorPosition();

        var newOptions = {
            wrap: true,
            wholeWord: true,
            caseSensitive: true,
            needle: needle
        };

        var currentOptions = editor.$search.getOptions();
        editor.$search.set(newOptions);

        var ranges = editor.$search.findAll(session);
        ranges.forEach(function(range) {
            if (!range.contains(cursor.row, cursor.column)) {
                var marker = session.addMarker(range, "ace_selected_word");
                session.$selectionOccurrences.push(marker);
            }
        });

        editor.$search.set(currentOptions);
    };

    this.clearSelectionHighlight = function(editor) {
        if (!editor.session.$selectionOccurrences)
            return;

        editor.session.$selectionOccurrences.forEach(function(marker) {
            editor.session.removeMarker(marker);
        });

        editor.session.$selectionOccurrences = [];
    };

    this.createModeDelegates = function (mapping) {
        if (!this.$embeds) {
            return;
        }
        this.$modes = {};
        for (var i = 0; i < this.$embeds.length; i++) {
            if (mapping[this.$embeds[i]]) {
                this.$modes[this.$embeds[i]] = new mapping[this.$embeds[i]]();
            }
        }

        var delegations = ['toggleCommentLines', 'getNextLineIndent', 'checkOutdent', 'autoOutdent', 'transformAction'];

        for (var i = 0; i < delegations.length; i++) {
            (function(scope) {
              var functionName = delegations[i];
              var defaultHandler = scope[functionName];
              scope[delegations[i]] = function() {
                  return this.$delegator(functionName, arguments, defaultHandler);
              }
            } (this));
        }
    }

    this.$delegator = function(method, args, defaultHandler) {
        var state = args[0];

        for (var i = 0; i < this.$embeds.length; i++) {
            if (!this.$modes[this.$embeds[i]]) continue;

            var split = state.split(this.$embeds[i]);
            if (!split[0] && split[1]) {
                args[0] = split[1];
                var mode = this.$modes[this.$embeds[i]];
                return mode[method].apply(mode, args);
            }
        }
        var ret = defaultHandler.apply(this, args);
        return defaultHandler ? ret : undefined;
    };

    this.transformAction = function(state, action, editor, session, param) {
        if (this.$behaviour) {
            var behaviours = this.$behaviour.getBehaviours();
            for (var key in behaviours) {
                if (behaviours[key][action]) {
                    var ret = behaviours[key][action].apply(this, arguments);
                    if (ret !== false) {
                        return ret;
                    }
                }
            }
        }
        return false;
    }

}).call(Mode.prototype);

exports.Mode = Mode;
});

/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (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.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is Ajax.org Code Editor (ACE).
 *
 * The Initial Developer of the Original Code is
 * Ajax.org B.V.
 * Portions created by the Initial Developer are Copyright (C) 2010
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *      Fabian Jakobs <fabian AT ajax DOT org>
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */

define('ace/mode/text_highlight_rules', ['require', 'exports', 'module', 'pilot/oop' ], function(require, exports, module) {

var lang = require("pilot/lang");

var TextHighlightRules = function() {

    // regexp must not have capturing parentheses
    // regexps are ordered -> the first match is used

    this.$rules = {
        "start" : [ {
            token : "empty_line",
            regex : '^$'
        }, {
            token : "text",
            regex : ".+"
        } ]
    };
};

(function() {

    this.addRules = function(rules, prefix) {
        for (var key in rules) {
            var state = rules[key];
            for (var i=0; i<state.length; i++) {
                var rule = state[i];
                if (rule.next) {
                    rule.next = prefix + rule.next;
                } else {
                    rule.next = prefix + key;
                }
            }
            this.$rules[prefix + key] = state;
        }
    };

    this.getRules = function() {
        return this.$rules;
    };

    this.embedRules = function (HighlightRules, prefix, escapeRules, states) {
        var embedRules = new HighlightRules().getRules();
        if (states) {
            for (var i = 0; i < states.length; i++) {
                states[i] = prefix + states[i];
            }
        } else {
            states = [];
            for (var key in embedRules) {
                states.push(prefix + key);
            }
        }
        this.addRules(embedRules, prefix);

        for (var i = 0; i < states.length; i++) {
            Array.prototype.unshift.apply(this.$rules[states[i]], lang.deepCopy(escapeRules));
        }

        if (!this.$embeds) {
            this.$embeds = [];
        }
        this.$embeds.push(prefix);
    }

    this.getEmbeds = function() {
        return this.$embeds;
    }

}).call(TextHighlightRules.prototype);

exports.TextHighlightRules = TextHighlightRules;
});


text:
require 'sinatra'

get '/number_generator' do
  '5'
end


text:
const auth = require('./auth');
const main = require('./main');

let _private = function(options) {
    options = options || {};
    let routes = {}

    routes.auth = auth;
    routes.main = main;

    return routes;
}

module.exports = _private;


text:
package io.joynr.discovery.pt.jee;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.transaction.Transactional;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.joynr.capabilities.CapabilityUtils;
import io.joynr.jeeintegration.api.ServiceProvider;
import io.joynr.jeeintegration.api.SubscriptionPublisher;
import joynr.exceptions.ApplicationException;
import joynr.exceptions.ProviderRuntimeException;
import joynr.infrastructure.GlobalCapabilitiesDirectorySubscriptionPublisher;
import joynr.infrastructure.GlobalCapabilitiesDirectorySync;
import joynr.system.RoutingTypes.MqttAddress;
import joynr.types.GlobalDiscoveryEntry;
import joynr.types.ProviderQos;
import joynr.types.Version;

@Stateless
@ServiceProvider(serviceInterface = GlobalCapabilitiesDirectorySync.class)
@Transactional(rollbackOn = Exception.class)
public class GlobalCapabilitiesDirectoryEjb implements GlobalCapabilitiesDirectoryService {
    private static final Logger logger = LoggerFactory.getLogger(GlobalCapabilitiesDirectoryEjb.class);
    @SuppressWarnings("unused")
    private GlobalCapabilitiesDirectorySubscriptionPublisher gcdSubPublisher;

    final private String fakedParticipantId1 = "lrc.erqw.sde.vbgf.as.nmc.tt.yte.bgtrfvcd.OtmvqaZwertvbgfdwqBTG";
    final private String fakedParticipantId2 = "anotherFakedParticipantId";
    final private String[] fakedDomains = new String[]{ "gfz.abcd" };
    final private String interfaceName = "go/wef/yg/sdf/ghtrqazs/OtmvqaZwertvbgfdwqBTG";
    private static final String TOPIC_NAME = "h/f/gfz.abcds";

    @Inject
    public GlobalCapabilitiesDirectoryEjb(@SubscriptionPublisher GlobalCapabilitiesDirectorySubscriptionPublisher gcdSubPublisher) {
        logger.trace("### CONSTRUCTOR called");
        this.gcdSubPublisher = gcdSubPublisher;
    }

    @Override
    public void add(GlobalDiscoveryEntry[] globalDiscoveryEntries) {
        throw new ProviderRuntimeException("Not implemented yet");
    }

    @Override
    public void add(GlobalDiscoveryEntry globalDiscoveryEntry) {
        throw new ProviderRuntimeException("Not implemented yet");
    }

    @Override
    public void add(GlobalDiscoveryEntry globalDiscoveryEntry, String[] gbids) throws ApplicationException {
        throw new ProviderRuntimeException("Not implemented yet");
    }

    @Override
    public void fireGlobalDiscoveryEntryChanged() {
        throw new UnsupportedOperationException("Not implemented yet");
    }

    @Override
    public GlobalDiscoveryEntry[] lookup(String[] domains, String interfaceName) {
        throw new ProviderRuntimeException("Not implemented yet");
    }

    @Override
    public GlobalDiscoveryEntry[] lookup(String[] domains,
                                         String interfaceName,
                                         String[] gbids) throws ApplicationException {
        logger.debug("Looking up global discovery entries for domains {} and interfaceName {} and Gbids {}",
                     Arrays.toString(domains),
                     interfaceName,
                     Arrays.toString(gbids));

        GlobalDiscoveryEntry fakedGlobalDiscoveryEntry1 = CapabilityUtils.newGlobalDiscoveryEntry(new Version(0, 5),
                                                                                domains[0],
                                                                                interfaceName,
                                                                                fakedParticipantId1,
                                                                                new ProviderQos(),
                                                                                System.currentTimeMillis(),
                                                                                System.currentTimeMillis()
                                                                                + 1000L,
                                                                                "fakedPublicKeyId",
                                                                                new MqttAddress("tcp://mqttbroker-1:1883",
                                                                                TOPIC_NAME));

        GlobalDiscoveryEntry fakedGlobalDiscoveryEntry2 = CapabilityUtils.newGlobalDiscoveryEntry(new Version(0, 5),
                                                                                domains[0],
                                                                                interfaceName,
                                                                                fakedParticipantId2,
                                                                                new ProviderQos(),
                                                                                System.currentTimeMillis(),
                                                                                System.currentTimeMillis()
                                                                                + 1000L,
                                                                                "fakedPublicKeyId",
                                                                                new MqttAddress("tcp://mqttbroker-1:1883",
                                                                                TOPIC_NAME));

        List<GlobalDiscoveryEntry> globalDiscoveryEntries = new ArrayList<GlobalDiscoveryEntry>();
        globalDiscoveryEntries.add(fakedGlobalDiscoveryEntry1);
        globalDiscoveryEntries.add(fakedGlobalDiscoveryEntry2);

        GlobalDiscoveryEntry[] globalDiscoveryEntriesArray = new GlobalDiscoveryEntry[2];
        globalDiscoveryEntriesArray = globalDiscoveryEntries.toArray(globalDiscoveryEntriesArray);
        return globalDiscoveryEntriesArray;
    }

    @Override
    public GlobalDiscoveryEntry lookup(String participantId, String[] gbids) throws ApplicationException {
        logger.debug("Looking up global discovery entry for participantId {} and Gbids {}",
                     participantId,
                     Arrays.toString(gbids));

        GlobalDiscoveryEntry fakedGlobalDiscoveryEntry1 = CapabilityUtils.newGlobalDiscoveryEntry(new Version(0, 5),
                                                                                fakedDomains[0],
                                                                                interfaceName,
                                                                                participantId,
                                                                                new ProviderQos(),
                                                                                System.currentTimeMillis(),
                                                                                System.currentTimeMillis()
                                                                                + 1000L,
                                                                                "fakedPublicKeyId",
                                                                                new MqttAddress("tcp://mqttbroker-1:1883",
                                                                                TOPIC_NAME));

        return fakedGlobalDiscoveryEntry1;
    }

    @Override
    public GlobalDiscoveryEntry lookup(String participantId) {
        throw new ProviderRuntimeException("Not implemented yet");
    }

    @Override
    public void remove(String[] participantIds) {
        throw new ProviderRuntimeException("Not implemented yet");
    }

    @Override
    public void remove(String participantId) {
        throw new ProviderRuntimeException("Not implemented yet");
    }

    @Override
    public void remove(String participantId, String[] gbids) throws ApplicationException {
        logger.debug("Calling remove entries for participantId {} and gbids )", participantId, Arrays.toString(gbids));
    }

    @Override
    public void touch(String clusterControllerId) {
        throw new ProviderRuntimeException("Not implemented yet");
    }

    @Override
    public void touch(String clusterControllerId, String[] participantIds) {
        throw new ProviderRuntimeException("Not implemented yet");
    }

    @Override
    public void removeStale(String clusterControllerId, Long maxLastSeenDateMs) {
        throw new ProviderRuntimeException("Not implemented yet");
    }

}


text:
namespace OpenRiaServices.DomainServices.Server
{
    /// <summary>
    /// Enumeration of the core operations a <see cref="DomainService"/> can perform.
    /// </summary>
    public enum DomainOperationType
    {
        /// <summary>
        /// Indicates a query operation.
        /// </summary>
        Query = 0,

        /// <summary>
        /// Indicates a submit operation.
        /// </summary>
        Submit = 1,

        /// <summary>
        /// Indicates an invoke operation.
        /// </summary>
        Invoke = 2,

        /// <summary>
        /// Indicates a metadata analysis operation
        /// </summary>
        Metadata = 3
    }
}


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

namespace Microsoft.CodeAnalysis.TestImpact.BuildManagement
{
    internal struct Diagnostic
    {
        public DiagnosticSeverity Severity;
        public string Message;
    }
}


text:
package org.springframework.osgi.context.support.internal.classloader;

/**
 * Internal contract for creating standard AOP class loaders. Implementations
 * can differ by using caching or returning new objects on each call.
 *
 * <p/> Implementations <b>must</b> be thread-safe since the proxy generation
 * can occur at any time.
 *
 * @author Costin Leau
 */
interface InternalAopClassLoaderFactory {

	/**
	 * Return the AOP class loader for the given bundle.
	 *
	 * @param classLoader OSGi bundle
	 * @return AOP class loader for it
	 */
	ChainedClassLoader createClassLoader(ClassLoader classLoader);
}


text:
<?xml version="1.0" encoding="utf-8"?>
<CalendarView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/root_calendar"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:dateTextAppearance="?android:attr/textAppearanceLarge">

</CalendarView>


text:
require "rails_helper"

RSpec.describe My::ProfilesController, type: :controller do
  let(:user) { FactoryGirl.create(:user) }

  before do
    sign_in(user)
  end

  describe "#show" do
    before { get :show }

    it { expect(response).to have_http_status(:success) }
  end

  describe "#edit" do
    before { get :edit }

    it { expect(response).to have_http_status(:success) }
  end

  describe "#update" do
    let(:user) { FactoryGirl.create(:user) }

    context "with valid params" do
      before { patch :update, params: { id: user.id, user: FactoryGirl.attributes_for(:user, bio: "Hello world!") } }

      it { expect(response).to have_http_status(:found) }
    end

    context "with invalid params" do
      before { patch :update, params: { id: user.id, user: FactoryGirl.attributes_for(:user, :invalid) } }

      it { is_expected.to set_flash[:error] }
      it { expect(response).to have_http_status(:success) }
    end
  end
end


text:
package org.provost.graphics2d;

import javax.swing.UIManager;

import org.apache.log4j.Logger;
import org.provost.tools.Graphics;

/**
 * App entry point.
 */
public class Main
{

	private static final org.apache.log4j.Logger log = Logger.getLogger(Main.class);

	public static void main(String[] args)
	{
		log.info("Graphics device information: " + Graphics.printAllDevicesInformation("\n", true));
		try {
			UIManager.setLookAndFeel(
					UIManager.getSystemLookAndFeelClassName());
		} catch (Exception x) {
			log.error("Problem setting look&feel", x);
		}
		java.awt.EventQueue.invokeLater(new Runnable() {
			@Override
			public void run() {
				Engine eng = null;
				try {
					eng = Engine.getInstance();
					eng.start();

					/*
					synchronized(Thread.currentThread()) {
						Thread.currentThread().wait(5000L);
						throw new NullPointerException("Simulated error");
					}
					*/
				} catch(Exception x) {
					log.error("Problem making visible, closing", x);
					if(eng != null) {
						eng.end();
					}
				}
			}
		});
	}
}


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE121_Stack_Based_Buffer_Overflow__CWE805_char_alloca_ncat_67b.c
Label Definition File: CWE121_Stack_Based_Buffer_Overflow__CWE805.string.label.xml
Template File: sources-sink-67b.tmpl.c
*/
/*
 * @description
 * CWE: 121 Stack Based Buffer Overflow
 * BadSource:  Set data pointer to the bad buffer
 * GoodSource: Set data pointer to the good buffer
 * Sinks: ncat
 *    BadSink : Copy string to data using strncat
 * Flow Variant: 67 Data flow: data passed in a struct from one function to another in different source files
 *
 * */

#include "std_testcase.h"

#include <wchar.h>

typedef struct _CWE121_Stack_Based_Buffer_Overflow__CWE805_char_alloca_ncat_67_structType
{
    char * structFirst;
} CWE121_Stack_Based_Buffer_Overflow__CWE805_char_alloca_ncat_67_structType;

#ifndef OMITBAD

void CWE121_Stack_Based_Buffer_Overflow__CWE805_char_alloca_ncat_67b_badSink(CWE121_Stack_Based_Buffer_Overflow__CWE805_char_alloca_ncat_67_structType myStruct)
{
    char * data = myStruct.structFirst;
    {
        char source[100];
        memset(source, 'C', 100-1); /* fill with 'C's */
        source[100-1] = '\0'; /* null terminate */
        /* POTENTIAL FLAW: Possible buffer overflow if the sizeof(data)-strlen(data) is less than the length of source */
        strncat(data, source, 100);
        printLine(data);
    }
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* goodG2B uses the GoodSource with the BadSink */
void CWE121_Stack_Based_Buffer_Overflow__CWE805_char_alloca_ncat_67b_goodG2BSink(CWE121_Stack_Based_Buffer_Overflow__CWE805_char_alloca_ncat_67_structType myStruct)
{
    char * data = myStruct.structFirst;
    {
        char source[100];
        memset(source, 'C', 100-1); /* fill with 'C's */
        source[100-1] = '\0'; /* null terminate */
        /* POTENTIAL FLAW: Possible buffer overflow if the sizeof(data)-strlen(data) is less than the length of source */
        strncat(data, source, 100);
        printLine(data);
    }
}

#endif /* OMITGOOD */


text:
<?php

/* YallaWebsiteFrontendBundle:Events:index.html.twig */
class __TwigTemplate_e6e1478225aa687ef506b91f58bc48b6b7ab1b049d167c7a86598faa934cac4e extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        // line 1
        $this->parent = $this->loadTemplate("@YallaWebsiteFrontendBundle/views/front_base.html.twig", "YallaWebsiteFrontendBundle:Events:index.html.twig", 1);
        $this->blocks = array(
            'body' => array($this, 'block_body'),
            'js_calednar' => array($this, 'block_js_calednar'),
        );
    }

    protected function doGetParent(array $context)
    {
        return "@YallaWebsiteFrontendBundle/views/front_base.html.twig";
    }

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

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

Events

 ";
    }

    // line 14
    public function block_js_calednar($context, array $blocks = array())
    {
        // line 15
        echo "
";
    }

    public function getTemplateName()
    {
        return "YallaWebsiteFrontendBundle:Events:index.html.twig";
    }

    public function isTraitable()
    {
        return false;
    }

    public function getDebugInfo()
    {
        return array (  48 => 15,  45 => 14,  32 => 3,  29 => 2,  11 => 1,);
    }
}
/* {% extends "@YallaWebsiteFrontendBundle/views/front_base.html.twig" %}*/
/* {% block body %}*/
/*
*/
/*
*/
/*
Events
*/
/*
*/
/*
*/
/*

*/
/*
*/
/*

*/
/*
*/
/*  {% endblock %}*/
/* */
/* {% block js_calednar %}*/
/*     */
/* {% endblock %}*/


text:
using Microsoft.Azure.Commands.Common.Authentication;
using Microsoft.Azure.Commands.Common.Authentication.Abstractions;
using Microsoft.Azure.Commands.Common.Authentication.Models;
using Microsoft.Azure.Commands.Sql.Common;
using Microsoft.Azure.Management.Sql.LegacySdk;
using Microsoft.Azure.Management.Sql.LegacySdk.Models;

namespace Microsoft.Azure.Commands.Sql.SecureConnection.Services
{
    /// <summary>
    /// This class is responsible for all the REST communication with the secure connection endpoints
    /// </summary>
    public class SecureConnectionEndpointsCommunicator
    {
        private static SqlManagementClient SqlClient { get; set; }

        private static IAzureSubscription Subscription { get; set; }

        public IAzureContext Context { get; set; }

        public SecureConnectionEndpointsCommunicator(IAzureContext context)
        {
            Context = context;
            if (context.Subscription != Subscription)
            {
                Subscription = context.Subscription;
                SqlClient = null;
            }
        }

        /// <summary>
        /// Get the secure connection policy for a specific database
        /// </summary>
        public DatabaseSecureConnectionPolicy GetDatabaseSecureConnectionPolicy(string resourceGroupName, string serverName, string databaseName)
        {
            ISecureConnectionPolicyOperations operations = GetCurrentSqlClient().SecureConnection;
            DatabaseSecureConnectionPolicyGetResponse response = operations.GetDatabasePolicy(resourceGroupName, serverName, databaseName);
            return response.SecureConnectionPolicy;
        }

        /// <summary>
        /// Set (or create) the secure connection policy for a specific database
        /// </summary>
        public void SetDatabaseSecureConnectionPolicy(string resourceGroupName, string serverName, string databaseName, DatabaseSecureConnectionPolicyCreateOrUpdateParameters parameters)
        {
            ISecureConnectionPolicyOperations operations = GetCurrentSqlClient().SecureConnection;
            operations.CreateOrUpdateDatabasePolicy(resourceGroupName, serverName, databaseName, parameters);
        }

        /// <summary>
        /// Retrieve the SQL Management client for the currently selected subscription, adding the session and request
        /// id tracing headers for the current cmdlet invocation.
        /// </summary>
        /// <returns>The SQL Management client for the currently selected subscription.</returns>
        private SqlManagementClient GetCurrentSqlClient()
        {
            // Get the SQL management client for the current subscription
            if (SqlClient == null)
            {
                SqlClient = AzureSession.Instance.ClientFactory.CreateClient<SqlManagementClient>(Context, AzureEnvironment.Endpoint.ResourceManager);
            }
            return SqlClient;
        }
    }
}


text:
package com.github.vbauer.houdini.model;

import com.github.vbauer.houdini.core.BasicTest;
import org.junit.Test;

import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
import static org.hamcrest.collection.IsArrayContainingInAnyOrder.arrayContainingInAnyOrder;
import static org.junit.Assert.assertThat;

/**
 * @author Vladislav Bauer
 */

public class ModelTest extends BasicTest {

    @Test
    public void testObjectConverterInfoKey() {
        final Class<Integer> returnType1 = Integer.class;
        final Class<String> returnType2 = String.class;

        final Class<?>[] sourceTypes1 = new Class<?>[] { String.class };
        final Class<?>[] sourceTypes2 = new Class<?>[] { Integer.class };

        final ObjectConverterInfoKey<Integer> key1 = new ObjectConverterInfoKey<>(returnType1, sourceTypes1);

        assertThat(key1.getSources(), arrayContainingInAnyOrder(sourceTypes1));
        assertThat(key1.getTarget(), equalTo(returnType1));

        assertThat(key1.hashCode(), not(equalTo(0)));
        assertThat(key1.toString(), notNullValue());

        assertThat(new ObjectConverterInfoKey<>(returnType1, sourceTypes1), equalTo(key1));
        assertThat(new ObjectConverterInfoKey<>(returnType1), not(equalTo(key1)));
        assertThat(new ObjectConverterInfoKey<>(returnType1, sourceTypes2), not(equalTo(key1)));

        assertThat(
            new ObjectConverterInfoKey<>(returnType2, sourceTypes1),
            not(equalTo((ObjectConverterInfoKey) key1))
        );

        assertThat(
            new ObjectConverterInfoKey<>(returnType1),
            equalTo(new ObjectConverterInfoKey<>(returnType1))
        );

        assertThat(key1, not(equalTo(new Object())));
    }

    @Test
    public void testObjectConverterInfoValue() {
        final Integer object = 1;
        final ObjectConverterInfoValue<Integer> value =
            new ObjectConverterInfoValue<>(null, object);

        assertThat(value.getObject(), equalTo(object));
        assertThat(value.getMethod(), nullValue());
        assertThat(value.toString(), notNullValue());
    }

}


text:
define(
  ["./stores/classic","./authorizers/classic","./authenticators/classic","./authenticators/auto","exports"],
  function(__dependency1__, __dependency2__, __dependency3__, __dependency4__, __exports__) {
    "use strict";
    var ClassicStore = __dependency1__["default"] || __dependency1__;
    var ClassicAuthorizer = __dependency2__["default"] || __dependency2__;
    var ClassicAuthenticator = __dependency3__["default"] || __dependency3__;
    var AutoAuthenticator = __dependency4__["default"] || __dependency4__;

    __exports__["default"] = {
      name: 'simple-auth-classic',
      before: 'simple-auth',

      initialize: function(container, application) {
        container.register('simple-auth-session-store:classic', ClassicStore);
        container.register('simple-auth-authorizer:classic', ClassicAuthorizer);
        container.register('simple-auth-authenticator:classic', ClassicAuthenticator);
        container.register('simple-auth-authenticator:auto', AutoAuthenticator);
      }
    };
  });


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

using System.Buffers;
using System.Threading;
using System.Threading.Tasks;

namespace System.IO.Pipelines
{
    /// <summary>
    /// Defines a class that provides access to a read side of pipe.
    /// </summary>
    public abstract partial class PipeReader
    {
        private PipeReaderStream? _stream;

        /// <summary>
        /// Attempt to synchronously read data the <see cref="PipeReader"/>.
        /// </summary>
        /// <param name="result">The <see cref="ReadResult"/></param>
        /// <returns>True if data was available, or if the call was canceled or the writer was completed.</returns>
        /// <remarks>If the pipe returns false, there's no need to call <see cref="AdvanceTo(SequencePosition, SequencePosition)"/>.</remarks>
        public abstract bool TryRead(out ReadResult result);

        /// <summary>
        /// Asynchronously reads a sequence of bytes from the current <see cref="PipeReader"/>.
        /// </summary>
        /// <returns>A <see cref="ValueTask{T}"/> representing the asynchronous read operation.</returns>
        public abstract ValueTask<ReadResult> ReadAsync(CancellationToken cancellationToken = default);

        /// <summary>
        /// Moves forward the pipeline's read cursor to after the consumed data.
        /// </summary>
        /// <param name="consumed">Marks the extent of the data that has been successfully processed.</param>
        /// <remarks>
        /// The memory for the consumed data will be released and no longer available.
        /// The examined data communicates to the pipeline when it should signal more data is available.
        /// </remarks>
        public abstract void AdvanceTo(SequencePosition consumed);

        /// <summary>
        /// Moves forward the pipeline's read cursor to after the consumed data.
        /// </summary>
        /// <param name="consumed">Marks the extent of the data that has been successfully processed.</param>
        /// <param name="examined">Marks the extent of the data that has been read and examined.</param>
        /// <remarks>
        /// The memory for the consumed data will be released and no longer available.
        /// The examined data communicates to the pipeline when it should signal more data is available.
        /// </remarks>
        public abstract void AdvanceTo(SequencePosition consumed, SequencePosition examined);

        /// <summary>
        /// Returns a <see cref="Stream"/> that wraps the <see cref="PipeReader"/>.
        /// </summary>
        /// <param name="leaveOpen">Optional flag indicating disposing returned <see cref="Stream"/> won't complete <see cref="PipeReader"/>.</param>
        /// <returns>The <see cref="Stream"/>.</returns>
        public virtual Stream AsStream(bool leaveOpen = false)
        {
            if (_stream == null)
            {
                _stream = new PipeReaderStream(this, leaveOpen);
            }
            else if (leaveOpen)
            {
                _stream.LeaveOpen = leaveOpen;
            }

            return _stream;
        }

        /// <summary>
        /// Cancel to currently pending or if none is pending next call to <see cref="ReadAsync"/>, without completing the <see cref="PipeReader"/>.
        /// </summary>
        public abstract void CancelPendingRead();

        /// <summary>
        /// Marks the <see cref="PipeReader"/> as being complete, meaning no more data will be read from it.
        /// </summary>
        /// <param name="exception">Optional <see cref="Exception"/> indicating a failure that's causing the reader to complete.</param>
        public abstract void Complete(Exception? exception = null);

        /// <summary>
        /// Marks the <see cref="PipeReader"/> as being complete, meaning no more data will be read from it.
        /// </summary>
        /// <param name="exception">Optional <see cref="Exception"/> indicating a failure that's causing the reader to complete.</param>
        public virtual ValueTask CompleteAsync(Exception? exception = null)
        {
            try
            {
                Complete(exception);
                return default;
            }
            catch (Exception ex)
            {
                return new ValueTask(Task.FromException(ex));
            }
        }

        /// <summary>
        /// Registers a callback that gets executed when the <see cref="PipeWriter"/> side of the pipe is completed
        /// </summary>
        [Obsolete("OnWriterCompleted may not be invoked on all implementations of PipeReader. This will be removed in a future release.")]
        public virtual void OnWriterCompleted(Action<Exception?, object?> callback, object? state)
        {

        }

        /// <summary>
        /// Creates a <see cref="PipeReader"/> wrapping the specified <see cref="Stream"/>.
        /// </summary>
        /// <param name="stream">The stream.</param>
        /// <param name="readerOptions">The options.</param>
        /// <returns>A <see cref="PipeReader"/> that wraps the <see cref="Stream"/>.</returns>
        public static PipeReader Create(Stream stream, StreamPipeReaderOptions? readerOptions = null)
        {
            return new StreamPipeReader(stream, readerOptions ?? StreamPipeReaderOptions.s_default);
        }

        /// <summary>
        /// Asynchronously reads the bytes from the <see cref="PipeReader"/> and writes them to the specified stream, using a specified buffer size and cancellation token.
        /// </summary>
        /// <param name="destination">The <see cref="PipeWriter"/> to which the contents of the current stream will be copied.</param>
        /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
        /// <returns>A task that represents the asynchronous copy operation.</returns>
        public virtual Task CopyToAsync(PipeWriter destination, CancellationToken cancellationToken = default)
        {
            if (destination == null)
            {
                throw new ArgumentNullException(nameof(destination));
            }

            if (cancellationToken.IsCancellationRequested)
            {
                return Task.FromCanceled(cancellationToken);
            }

            return CopyToAsyncCore(destination, async (destination, memory, cancellationToken) =>
            {
                FlushResult result = await destination.WriteAsync(memory, cancellationToken).ConfigureAwait(false);

                if (result.IsCanceled)
                {
                    ThrowHelper.ThrowOperationCanceledException_FlushCanceled();
                }
            },
            cancellationToken);
        }

        /// <summary>
        /// Asynchronously reads the bytes from the <see cref="PipeReader"/> and writes them to the specified stream, using a specified buffer size and cancellation token.
        /// </summary>
        /// <param name="destination">The <see cref="Stream"/> to which the contents of the current stream will be copied.</param>
        /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
        /// <returns>A task that represents the asynchronous copy operation.</returns>
        public virtual Task CopyToAsync(Stream destination, CancellationToken cancellationToken = default)
        {
            if (destination == null)
            {
                throw new ArgumentNullException(nameof(destination));
            }

            if (cancellationToken.IsCancellationRequested)
            {
                return Task.FromCanceled(cancellationToken);
            }

            return CopyToAsyncCore(
                destination,
                (destination, memory, cancellationToken) => destination.WriteAsync(memory, cancellationToken),
                cancellationToken);
        }

        private async Task CopyToAsyncCore<TStream>(TStream destination, Func<TStream, ReadOnlyMemory<byte>, CancellationToken, ValueTask> writeAsync, CancellationToken cancellationToken)
        {
            while (true)
            {
                SequencePosition consumed = default;

                ReadResult result = await ReadAsync(cancellationToken).ConfigureAwait(false);
                try
                {
                    ReadOnlySequence<byte> buffer = result.Buffer;
                    SequencePosition position = buffer.Start;

                    if (result.IsCanceled)
                    {
                        ThrowHelper.ThrowOperationCanceledException_ReadCanceled();
                    }

                    while (buffer.TryGet(ref position, out ReadOnlyMemory<byte> memory))
                    {
                        await writeAsync(destination, memory, cancellationToken).ConfigureAwait(false);

                        consumed = position;
                    }

                    if (consumed.Equals(default))
                    {
                        consumed = buffer.End;
                    }

                    if (result.IsCompleted)
                    {
                        break;
                    }
                }
                finally
                {
                    // Advance even if WriteAsync throws so the PipeReader is not left in the
                    // currently reading state
                    AdvanceTo(consumed);
                }
            }
        }
    }
}


text:
/**
 * @file IRCClientSession.h
 * @author Nathan Ollerenshaw
 * @version 1.0
 * @date 01.2009
 * @brief Represents a connected IRC Session.
 */

#import "IRCClientSessionDelegate.h"
#include "libircclient.h"

/** @class IRCClientSession
 *	@brief Represents a connected IRC Session.
 *
 *	IRCClientSession represents a single connection to an IRC server. On initialising
 *  the object, and setting the delegate, server, port, password, nickname, username and realname
 *	properties, you call the connect: and run: methods to connect to the IRC server
 *	and start a new thread.
 *
 *	This thread then sends messages back to the main runloop to the IRC server delegate,
 *	or to the IRCClientChannel delegate as required.
 */

@class IRCClientChannel;
@interface IRCClientSession : NSObject {
	id					delegate;
	irc_callbacks_t		callbacks;
	irc_session_t		*session;
	NSThread			*thread;

	NSString			*version;
	NSString			*server;
	NSString			*port;
	NSString			*password;

	NSString			*nickname;
	NSString			*username;
	NSString			*realname;

	NSMutableDictionary	*channels;
	NSMutableDictionary *nicks;
	NSStringEncoding	encoding;
}

/** delegate to send events to. */
@property (assign) id delegate;

/** The underlying libircclient handle */
@property (assign) irc_session_t *session;

/** The version string for the client to send back on CTCP VERSION requests */
@property (copy) NSString *version;

/** IRC server to connect to */
@property (copy) NSString *server;

/** IRC port to connect to */
@property (copy) NSString *port;

/** Server password to provide on connect (may be left empty or nil) */
@property (copy) NSString *password;

/** Nickname of the connected client. Note that setting this after connection will
    not result in the client renaming on IRC. You need to send a nick: message instead.
 */
@property (copy) NSString *nickname;

/** Username of the connected client. Also known as the ident.

	Setting this after connection does nothing.
 */
@property (copy) NSString *username;

/** Realname of the connected client.

	Setting this after connection does nothing. */
@property (copy) NSString *realname;

/** An NSMutableDictionary of channels that the client is currently connected to.

	You should not modify this. */
@property (assign,readonly) NSMutableDictionary *channels;

/** The default text encoding for messages on this server.

	This affects messages received via PRIVMSG and NOTICE, and TOPIC in a channel.
	You may change this at any time.
 */

@property (assign) NSStringEncoding encoding;

/** Connect to the IRC server.

	Note that this performs the initial DNS lookup and the TCP connection, so if
	there are any problems you will be notified via the return code of the message.

	Look at the libircclient documentation for the different return codes. */

- (int)connect;

/** Disconnect from the IRC server.

	This always works, as it simply shuts down the socket. If you want to disconnect
	in a friendly way, you should use the quit: message. */

- (void)disconnect;

/** returns YES if the server is currently connected successfully, and NO if
	it is not. */

- (bool)isConnected;

/**	Starts a new thread and starts the libircclient runloop, processing events and
	firing messages back to the main runloop as required. Calling this again will
	do nothing other than raise a warning in your logs. */

- (void)run;

/** Sends a raw message to the IRC server. Please consult rfc1459 for the format
	of IRC commands. */

- (int)sendRawWithFormat:(NSString *)format, ...;

/** quits the IRC server with the given reason. On success, an onQuit event will be
	sent to the IRCClientSessionDelegate with the nickname of the IRC client.

	The format is a standard NSString format string, followed by optional arguments.
 */

- (int)quit:(NSString *)reason;

/** Joins a channel with a given name and key

	@param channel the channel to join
	@param key they key for the channel (may be nil)
 */

- (int)join:(NSString *)channel key:(NSString *)key;

/**	lists channels on the IRC server.

	@param channel a channel name or string to pass to the LIST command. Implementation specific.
 */

- (int)list:(NSString *)channel;

/** sets the user mode for the IRC client

	@param mode string to set
 */

- (int)userMode:(NSString *)mode;

/**	sets the IRC client nickname. On success, an onNick event will be sent to the delegate

	@param newnick new nickname to set.
 */

- (int)nick:(NSString *)newnick;

/**	sends a WHOIS request to the IRC server

	@param nick nickname of the irc client to whois.
*/

- (int)whois:(NSString *)nick;

/**	send a PRIVMSG to another IRC client

	@param message message to send
	@param target the other IRC client to send the message to.
 */

- (int)message:(NSString *)message to:(NSString *)target;

/**	send a CTCP ACTION to another IRC client

	@param action the action message to send
	@param target the nickname of the irc client to send the message to.
 */

- (int)action:(NSString *)action to:(NSString *)target;

/**	send a NOTICE to another IRC client

	@param notice the message text to send
	@param target the nickname of the irc client to send the notice to.
 */

- (int)notice:(NSString *)notice to:(NSString *)target;

/** send a CTCP request to another IRC client

	@param request the CTCP request string to send
	@param target the nickname of the IRC client to send the request to.
 */

- (int)ctcpRequest:(NSString *)request target:(NSString *)target;

/** send a CTCP reply to another IRC client

 @param reply the CTCP reply string to send
 @param target the nickname of the IRC client to send the reply to.
 */

- (int)ctcpReply:(NSString *)reply target:(NSString *)target;

@end