text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>it.smartcommunitylab</groupId>
	<artifactId>sco.riciclo-web</artifactId>
	<version>1.0</version>
	<packaging>war</packaging>

	<properties>
		<spring-version>4.0.7.RELEASE</spring-version>
		<spring.test.version>3.2.1.RELEASE</spring.test.version>
		<spring-security-version>3.2.4.RELEASE</spring-security-version>
	</properties>

	<dependencies>

		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>3.1.0</version>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>
		<dependency>
			<groupId>cglib</groupId>
			<artifactId>cglib</artifactId>
			<version>2.2.2</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring-version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-beans</artifactId>
			<version>${spring-version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${spring-version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>${spring-version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${spring-version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-expression</artifactId>
			<version>${spring-version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-aop</artifactId>
			<version>${spring-version}</version>
		</dependency>

		<!-- Security -->
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-core</artifactId>
			<version>${spring-security-version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-web</artifactId>
			<version>${spring-security-version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-config</artifactId>
			<version>${spring-security-version}</version>
		</dependency>

		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.14</version>
			<type>jar</type>
			<scope>compile</scope>
		</dependency>

		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-core</artifactId>
			<version>2.3.0</version>
		</dependency>

		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-databind</artifactId>
			<version>2.3.0</version>
		</dependency>

		<dependency>
			<groupId>com.google.guava</groupId>
			<artifactId>guava</artifactId>
			<version>15.0</version>
			<type>jar</type>
		</dependency>
		<dependency>
			<groupId>commons-lang</groupId>
			<artifactId>commons-lang</artifactId>
			<version>2.6</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.data</groupId>
			<artifactId>spring-data-mongodb</artifactId>
			<version>1.6.2.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>commons-fileupload</groupId>
			<artifactId>commons-fileupload</artifactId>
			<version>1.3</version>
		</dependency>
		<dependency>
			<groupId>commons-io</groupId>
			<artifactId>commons-io</artifactId>
			<version>2.4</version>
		</dependency>

		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi</artifactId>
			<version>3.9</version>
		</dependency>
		<dependency>
			<groupId>de.micromata.jak</groupId>
			<artifactId>JavaAPIforKml</artifactId>
			<version>2.2.0</version>
		</dependency>

		<dependency>
            <groupId>org.yaml</groupId>
            <artifactId>snakeyaml</artifactId>
            <version>1.13</version>
        </dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>${spring.test.version}</version>
			<scope>test</scope>
		</dependency>

		<dependency>
		    <groupId>org.slf4j</groupId>
		    <artifactId>slf4j-log4j12</artifactId>
		    <version>1.7.7</version>
		</dependency>

		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.11</version>
			<scope>test</scope>
		</dependency>

		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-validator</artifactId>
			<version>5.1.3.Final</version>
			</dependency>
		<dependency>
			<groupId>org.glassfish.web</groupId>
			<artifactId>javax.el</artifactId>
			<version>2.2.4</version>
		</dependency>
		<!--
 		<dependency>
			<groupId>javax.el</groupId>
			<artifactId>javax.el-api</artifactId>
			<version>2.2.4</version>
		</dependency>
		<dependency>
			<groupId>javax.validation</groupId>
			<artifactId>validation-api</artifactId>
			<version>1.1.0.Final</version>
		</dependency>
		<dependency>
		   <groupId>javax.el</groupId>
		   <artifactId>javax.el-api</artifactId>
		   <version>2.2.4</version>
		</dependency> -->
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>2.3.2</version>
				<configuration>
					<source>1.7</source>
					<target>1.7</target>
				</configuration>
			</plugin>

			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-surefire-plugin</artifactId>
				<version>2.6</version>
				<configuration>
					<skipTests>true</skipTests>
				</configuration>
			</plugin>

			<plugin>
				<inherited>false</inherited>
				<groupId>com.mycila.maven-license-plugin</groupId>
				<artifactId>maven-license-plugin</artifactId>
				<version>1.8.0</version>
				<configuration>
					<header>${basedir}/license/license.txt</header>
					<failIfMissing>true</failIfMissing>
					<aggregate>true</aggregate>
					<includes>
						<include>src/**/*.java</include>
					</includes>
				</configuration>
			</plugin>

		</plugins>
		<finalName>riciclo</finalName>
	</build>

</project>


text:
using System.Collections.Generic;

namespace NuPattern.Runtime.Bindings
{
    /// <summary>
    /// Defines a binding.
    /// </summary>
    public interface IBinding<T> where T : class
    {
        /// <summary>
        /// Gets the evaluation results of the binding.
        /// </summary>
        IEnumerable<BindingResult> EvaluationResults { get; }

        /// <summary>
        /// Gets a value to indicate whether the binding has errors.
        /// </summary>
        bool HasErrors { get; }

        /// <summary>
        /// Gets or sets the user readable message for the binding.
        /// </summary>
        string UserMessage { get; set; }

        /// <summary>
        /// Gets the value of the binding.
        /// </summary>
        T Value { get; }

        /// <summary>
        /// Evaluates the binding.
        /// </summary>
        /// <returns></returns>
        bool Evaluate();
    }
}

redpajama_set_name: RedPajamaGithub


text:
local nn = require 'nn'

-- Helper functions

-- Calculates fan in and fan out of module
local function calcFan(module)
  local typename = torch.type(module)
  if typename == 'nn.Linear' or
     typename == 'nn.LinearNoBias' or
     typename == 'nn.LookupTable' then
    return module.weight:size(2), module.weight:size(1)
  elseif typename:find('TemporalConvolution') then
    return module.weight:size(2), module.weight:size(1)
  elseif typename:find('SpatialConvolution') or typename:find('SpatialFullConvolution') then
    return module.nInputPlane * module.kW * module.kH, module.nOutputPlane * module.kW * module.kH
  elseif typename:find('VolumetricConvolution') or typename:find('VolumetricFullConvolution') then
    return module.nInputPlane * module.kT * module.kW * module.kH, module.nOutputPlane * module.kT * module.kW * module.kH
  else
    error("Unsupported module")
  end
end

-- Returns the gain or calculates if given a gain type (with optional args)
local function calcGain(gain)
  -- Return gain if a number already
  if type(gain) == 'number' then
    return gain
  end

  -- Extract gain string if table
  local args
  if type(gain) == 'table' then
    args = gain
    gain = gain[1]
  end

  -- Process gain strings with optional args
  if gain == 'linear' or gain == 'sigmoid' then
    return 1
  elseif gain == 'relu' then
    return math.sqrt(2)
  elseif gain == 'lrelu' then
    return math.sqrt(2 / (1 + math.pow(args.leakiness, 2)))
  end

  -- Return 1 by default
  return 1
end

-- init method

-- Add init to nn.Module
nn.Module.init = function(self, accessor, initialiser, ...)
  -- Extract tensor to initialise
  local tensor
  if type(accessor) == 'string' then
    tensor = self[accessor]
  elseif type(accessor) == 'table' then
    tensor = self[accessor[1]][accessor[2]]
  elseif type(accessor) == 'function' then
    tensor = accessor(self)
  else
    error("Unsupported accessor")
  end

  -- Initialise tensor (given module and options)
  initialiser(self, tensor, ...)

  -- Return module for chaining
  return self
end

-- nninit

local nninit = {}

-- Copies another tensor to the tensor to be initialised
nninit.copy = function(module, tensor, init)
  tensor:copy(init)

  return module
end

-- Fills tensor with a constant value
nninit.constant = function(module, tensor, val)
  tensor:fill(val)

  return module
end

-- Adds to current tensor with a constant value
nninit.addConstant = function(module, tensor, val)
  tensor:add(val)

  return module
end

-- Multiplies current tensor by a constant value
nninit.mulConstant = function(module, tensor, val)
  tensor:mul(val)

  return module
end

-- Fills tensor ~ N(mean, stdv)
nninit.normal = function(module, tensor, mean, stdv)
  tensor:normal(mean, stdv)

  return module
end

-- Adds to current tensor with ~ N(mean, stdv)
nninit.addNormal = function(module, tensor, mean, stdv)
  tensor:add(torch.Tensor(tensor:size()):normal(mean, stdv))

  return module
end

-- Fills tensor ~ U(a, b)
nninit.uniform = function(module, tensor, a, b)
  tensor:uniform(a, b)

  return module
end

-- Adds to current tensor with ~ U(a, b)
nninit.addUniform = function(module, tensor, a, b)
  tensor:add(torch.Tensor(tensor:size()):uniform(a, b))

  return module
end

-- Fills weights with the identity matrix (for linear layers)
-- Fills filters with the Dirac delta function (for convolutional layers)
-- TODO: Generalise for arbitrary tensors?
nninit.eye = function(module, tensor)
  if module.weight ~= tensor then
    error("nninit.eye only supports 'weight' tensor")
  end

  local typename = torch.type(module)

  if typename == 'nn.Linear' or
     typename == 'nn.LinearNoBias' or
     typename == 'nn.LookupTable' then
    local I = torch.eye(tensor:size(1), tensor:size(2))
    tensor:copy(I)
  elseif typename:find('TemporalConvolution') then
    tensor:zero()
    for i = 1, module.inputFrameSize do
      tensor[{{}, {(i-1)*module.kW + math.ceil(module.kW/2)}}]:fill(1/module.inputFrameSize)
    end
  elseif typename:find('SpatialConvolution') or typename:find('SpatialFullConvolution') then
    tensor:zero():view(module.nInputPlane, module.nOutputPlane, module.kW, module.kH)[{{}, {}, math.ceil(module.kW/2), math.ceil(module.kH/2)}]:fill(1/module.nInputPlane)
  elseif typename:find('VolumetricConvolution') or typename:find('VolumetricFullConvolution') then
    tensor:zero():view(module.nInputPlane, module.nOutputPlane, module.kT, module.kW, module.kH)[{{}, {}, math.ceil(module.kT/2), math.ceil(module.kW/2), math.ceil(module.kH/2)}]:fill(1/module.nInputPlane)
  else
    error("Unsupported module for 'eye'")
  end

  return module
end

--[[
--  Glorot, X., & Bengio, Y. (2010)
--  Understanding the difficulty of training deep feedforward neural networks
--  In International Conference on Artificial Intelligence and Statistics
--
--  Also known as Glorot initialisation
--]]
nninit.xavier = function(module, tensor, options)
  local fanIn, fanOut = calcFan(module)
  options = options or {}
  gain = calcGain(options.gain)
  dist = options.dist or 'uniform' -- Uniform by default

  local stdv = gain * math.sqrt(2 / (fanIn + fanOut))
  if dist == 'uniform' then
    local b = stdv * math.sqrt(3)
    tensor:uniform(-b, b)
  elseif dist == 'normal' then
    tensor:normal(0, stdv)
  end

  return module
end

--[[
--  He, K., Zhang, X., Ren, S., & Sun, J. (2015)
--  Delving deep into rectifiers: Surpassing human-level performance on ImageNet classification
--  arXiv preprint arXiv:1502.01852
--
--  Also known as He initialisation
--]]
nninit.kaiming = function(module, tensor, options)
  local fanIn = calcFan(module)
  options = options or {}
  gain = calcGain(options.gain)
  dist = options.dist or 'normal' -- Normal by default

  local stdv = gain * math.sqrt(1 / fanIn)
  if dist == 'uniform' then
    local b = stdv * math.sqrt(3)
    tensor:uniform(-b, b)
  elseif dist == 'normal' then
    tensor:normal(0, stdv)
  end

  return module
end

--[[
--  Saxe, A. M., McClelland, J. L., & Ganguli, S. (2013)
--  Exact solutions to the nonlinear dynamics of learning in deep linear neural networks
--  arXiv preprint arXiv:1312.6120
--]]
nninit.orthogonal = function(module, tensor, options)
  local sizes = tensor:size()
  if #sizes < 2 then
    error("nninit.orthogonal only supports tensors with 2 or more dimensions")
  end

  -- Calculate "fan in" and "fan out" for arbitrary tensors based on module conventions
  local fanIn = sizes[2]
  local fanOut = sizes[1]
  for d = 3, #sizes do
    fanIn = fanIn * sizes[d]
  end

  options = options or {}
  gain = calcGain(options.gain)

  -- Construct random matrix
  local randMat = torch.Tensor(fanOut, fanIn):normal(0, 1)
  local U, __, V = torch.svd(randMat, 'S')

  -- Pick out orthogonal matrix
  local W
  if fanOut > fanIn then
    W = U
  else
    W = V:narrow(1, 1, fanOut)
  end
  -- Resize
  W:resize(tensor:size())
  -- Multiply by gain
  W:mul(gain)

  tensor:copy(W)

  return module
end

--[[
-- Martens, J. (2010)
-- Deep learning via Hessian-free optimization
-- In Proceedings of the 27th International Conference on Machine Learning (ICML-10)
--]]
nninit.sparse = function(module, tensor, sparsity)
  local nElements = tensor:nElement()
  local nSparseElements = math.floor(sparsity * nElements)
  local randIndices = torch.randperm(nElements):long()
  local sparseIndices = randIndices:narrow(1, 1, nSparseElements)

  -- Zero out selected indices
  tensor:view(nElements):indexFill(1, sparseIndices, 0)

  return module
end

return nninit


text:
/**
 * Documentation meta data for a single documentation comment.
 */
dbm.registerClass("dbm.compiler.compiledata.documentation.DocumentationData", "dbm.core.ExtendedEventBaseObject", function(objectFunctions, staticFunctions, ClassReference) {
	//console.log("dbm.compiler.compiledata.documentation.DocumentationData");

	//Self reference
	var DocumentationData = dbm.importClass("dbm.compiler.compiledata.documentation.DocumentationData");

	//Error report
	var ErrorManager = dbm.importClass("dbm.core.globalobjects.errormanager.ErrorManager");
	var ReportTypes = dbm.importClass("dbm.constants.error.ReportTypes");
	var ReportLevelTypes = dbm.importClass("dbm.constants.error.ReportLevelTypes");

	//Dependencies
	var DocumentationFlagData = dbm.importClass("dbm.compiler.compiledata.documentation.DocumentationFlagData");

	//Utils
	var StringFunctions = dbm.importClass("dbm.utils.native.string.StringFunctions");

	//Constants

	/**
	 * Constructor
	 */
	objectFunctions._init = function() {
		//console.log("dbm.compiler.compiledata.documentation.DocumentationData::_init");

		this.superCall();

		this._description = null;
		this._flags = new Array();

		return this;
	};

	/**
	 * Gets the flags of this documentation.
	 *
	 * @return	Array<DocumentationFlagData>	The flags.
	 */
	objectFunctions.getFlags = function() {
		return this._flags;
	};

	/**
	 * Parse the raw documentation code.
	 *
	 * @param	aCode	String	The raw documentation comment.
	 *
	 * @return	self
	 */
	objectFunctions.parseDocumentationCode = function(aCode) {
		//console.log("dbm.compiler.compiledata.documentation.DocumentationData::parseDocumentationCode");

		var description = "";
		var lineStartRegExp = new RegExp("^[\\s]*\\/?[\\*]*[\\s]*");
		var lineEndRegExp = new RegExp("[\\s]*[\*]*\\/?[\\s]*$");
		var argumentsSplitRegExp = new RegExp("[\\s]*[\\t]+[\\s]*");

		var currentArray = aCode.split("\n");
		var currentArrayLength = currentArray.length;

		for(var i = 0; i < currentArrayLength; i++) {
			var currentLine = currentArray[i];

			currentLine = currentLine.replace(lineStartRegExp, "");
			currentLine = currentLine.replace(lineEndRegExp, "");

			if(currentLine.length > 0 && currentLine[0] === "@") {

				var currentArguments = currentLine.split(argumentsSplitRegExp);
				var currentLineType = currentArguments.shift();
				currentLineType = currentLineType.substring(1, currentLineType.length);

				this._flags.push(DocumentationFlagData.create(currentLineType, currentArguments));
			}
			else {
				description += currentLine + "\n";
			}
		}

		this._description = StringFunctions.trim(description);
		//console.log(this._description);
		//console.log(this._flags);

		return this;
	};

	/**
	 * Sets all the references to null. Part of the destroy function.
	 */
	objectFunctions.setAllReferencesToNull = function() {

		this._description = null;
		this._flags = null;

		this.superCall();
	};

	/**
	 * Creates a new instance of this class.
	 *
	 * @param	aCode	String	The raw documentation comment.
	 *
	 * @return	DocumentationData	The newly created instance.
	 */
	staticFunctions.create = function(aCode) {
		var newDocumentationData = (new ClassReference()).init();
		newDocumentationData.parseDocumentationCode(aCode);

		return newDocumentationData;
	};

	/**
	 * Creates a new instance of this class, without parsing any data.
	 *
	 * @return	DocumentationData	The newly created instance.
	 */
	staticFunctions.createEmpty = function() {
		var newDocumentationData = (new ClassReference()).init();

		return newDocumentationData;
	};
});


text:
package com.beanu.sf.ui.layer2.imageselector;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.beanu.l2_imageselector.R;
import com.bumptech.glide.Glide;

import java.util.List;

/**
 * DEMO adapter
 * Created by Beanu on 2016/12/15.
 */

public class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder> {

    private Context context;
    private LayoutInflater mLayoutInflater;
    private List<String> result;
    private final static String TAG = "Adapter";

    public Adapter(Context context, List<String> result) {
        mLayoutInflater = LayoutInflater.from(context);
        this.context = context;
        this.result = result;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return new ViewHolder(mLayoutInflater.inflate(R.layout.item_image, null));
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        Glide.with(context)
                .load(result.get(position))
                .centerCrop()
                .into(holder.image);

    }

    @Override
    public int getItemCount() {
        return result.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {

        ImageView image;

        public ViewHolder(View itemView) {
            super(itemView);
            image = (ImageView) itemView.findViewById(R.id.image);
        }

    }

}


text:
using System;

namespace RepositoryPattern.Core
{
    public abstract class AuditedEntity<T> : KeyedEntity<T>
    {
        public DateTime Created { get; set; }
        public string CreatedBy { get; set; }
        public DateTime Updated { get; set; }
        public string UpdatedBy { get; set; }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate
        android:duration="2000"
        android:fromXDelta="10"
        android:fromYDelta="50"
        android:toXDelta="0"
        android:toYDelta="330">

    </translate>
</set>


text:
using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Windows.Input;
using W3SavegameEditor.Core.Common;
using W3SavegameEditor.Core.Savegame;
using W3SavegameEditor.Core.Savegame.Variables;
using W3SavegameEditor.Models;

namespace W3SavegameEditor.ViewModels
{
    public class SavegameViewModel : INotifyPropertyChanged
    {
        private SavegameModel _selectedSavegame;

        public ObservableCollection<SavegameModel> Savegames { get; set; }

        public SavegameModel SelectedSavegame
        {
            get
            {
                return _selectedSavegame;
            }
            set
            {
                if (_selectedSavegame != value)
                {
                    _selectedSavegame = value;
                    OnPropertyChanged();
                }
            }
        }

        public ReadSavegameProgress Progress { get; set; }

        public ICommand InitializeSavegames { get; private set; }

        public ICommand OpenSavegame { get; private set; }

        public SavegameViewModel()
        {
            InitializeSavegames = new DelegateCommand(ExecuteInitializeSavegameList);
            OpenSavegame = new DelegateCommand(ExecuteOpenSavegame);
            Savegames = new ObservableCollection<SavegameModel>();
            Progress = new ReadSavegameProgress();
            ExecuteInitializeSavegameList(null);
        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            var handler = PropertyChanged;
            if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
        }

        private void ExecuteInitializeSavegameList(object obj)
        {
            Savegames.Clear();
            string gamesavesPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "The Witcher 3\\gamesaves");
            var filesPaths = Directory.GetFiles(gamesavesPath, "*.sav");

            foreach (var filePath in filesPaths)
            {
                var thumbnailFilePath = Path.Combine(Path.GetDirectoryName(filePath) ?? "", Path.GetFileNameWithoutExtension(filePath) + ".png");

                Savegames.Add(new SavegameModel
                {
                    Name = Path.GetFileName(filePath),
                    Path = filePath,
                    ThumbnailPath = thumbnailFilePath
                });
            }
        }

        private void ExecuteOpenSavegame(object parameter)
        {
            if (parameter == null)
            {
                return;
            }

            var savegame = parameter as SavegameModel;
            if (savegame == null)
            {
                throw new ArgumentException("parameter");
            }

            SavegameFile.ReadAsync(savegame.Path, Progress)
                .ContinueWith(t =>
                {
                    var file = t.Result;
                    var savegameDataModel = new SavegameDataModel
                    {
                        Version1 = file.TypeCode1,
                        Version2 = file.TypeCode2,
                        Version3 = file.TypeCode3,
                        VariableNames = new ObservableCollection<string>(file.VariableNames),
                        Variables = new ObservableCollection<VariableModel>(file.Variables.Select(ToVariableModel))
                    };
                    SelectedSavegame = new SavegameModel
                    {
                        Name = savegame.Name,
                        Path = savegame.Path,
                        Data = savegameDataModel
                    };
                });
        }

        private static VariableModel ToVariableModel(Variable v, int i)
        {
            var set = v as VariableSet;
            var children = set == null
                ? new ObservableCollection<VariableModel>()
                : new ObservableCollection<VariableModel>(set.Variables.Select(ToVariableModel));

            var typed = v as TypedVariable;
            var type = typed == null
                ? "None"
                : typed.Type;

            var value = typed == null || typed.Value == null
                ? ""
                : typed.Value.ToString();

            return new VariableModel
            {
                Index = i,
                Name = v == null ? "" : v.Name,
                Type = type,
                Value = value,
                DebugString = v == null ? "" : v.ToString(),
                Children = children
            };
        }
    }
}


text:
/**
 * @test
 * @bug 4213822
 * @summary Test that checkError() returns a correct value
 *      when a PrintWriter is wrapped with another
 *      PrintWriter.
 */

import java.io.*;

public class CheckError {
    public static void main(String[] args) throws Exception {

        boolean passTest1 = false;
        File file = new File(System.getProperty("test.dir", "."),
                          "junkie.out");

        FileWriter fw = new FileWriter(file);

        PrintWriter ppw  = new PrintWriter(
                           new PrintWriter(fw));

        fw.close();
        ppw.println("Hello World!");

        file.deleteOnExit();

        if (ppw.checkError()) {
            System.out.println("Correct: An error occured in the" +
                " underlying writer");
            passTest1 = true;
        }
        ppw.close();

        // Test when the underlying stream is a PrintStream
        FileOutputStream fos = new FileOutputStream(file);
        PrintWriter pps  = new PrintWriter(
                            new PrintStream(fos));

        fos.close();
        pps.println("Hello World!");

        if (pps.checkError()) {
            System.out.println("Correct: An error occured in the" +
                " underlying Stream");
        } else {
            if (!passTest1) {
                throw new Exception("CheckError() returned an incorrect value" +
                    " when error occured in the underlying Stream" +
                        " and when error occured in the underlying writer");
            } else {
                throw new Exception("CheckError() returned an incorrect value" +
                    " when the error has occured in the underlying Stream");
            }
        }
        if (!passTest1) {
                throw new Exception("CheckError() returned an incorrect value" +
                    " when the error has occured in the underlying Writer");
        }
        pps.close();
    }
}


text:
import type { SDLValidationContext } from '../ValidationContext';
import { GraphQLError } from '../../error/GraphQLError';
import type { ASTVisitor } from '../../language/visitor';
import type { TypeDefinitionNode } from '../../language/ast';

export function duplicateTypeNameMessage(typeName: string): string {
  return `There can be only one type named "${typeName}".`;
}

export function existedTypeNameMessage(typeName: string): string {
  return (
    `Type "${typeName}" already exists in the schema. ` +
    'It cannot also be defined in this type definition.'
  );
}

/**
 * Unique type names
 *
 * A GraphQL document is only valid if all defined types have unique names.
 */
export function UniqueTypeNames(context: SDLValidationContext): ASTVisitor {
  const knownTypeNames = Object.create(null);
  const schema = context.getSchema();

  return {
    ScalarTypeDefinition: checkTypeName,
    ObjectTypeDefinition: checkTypeName,
    InterfaceTypeDefinition: checkTypeName,
    UnionTypeDefinition: checkTypeName,
    EnumTypeDefinition: checkTypeName,
    InputObjectTypeDefinition: checkTypeName,
  };

  function checkTypeName(node: TypeDefinitionNode) {
    const typeName = node.name.value;

    if (schema && schema.getType(typeName)) {
      context.reportError(
        new GraphQLError(existedTypeNameMessage(typeName), node.name),
      );
      return;
    }

    if (knownTypeNames[typeName]) {
      context.reportError(
        new GraphQLError(duplicateTypeNameMessage(typeName), [
          knownTypeNames[typeName],
          node.name,
        ]),
      );
    } else {
      knownTypeNames[typeName] = node.name;
    }

    return false;
  }
}


text:
namespace nt2 { namespace ext
{
  NT2_FUNCTOR_IMPLEMENTATION( nt2::tag::maximum_, tag::cpu_
                            , (A0)
                            , (generic_< dry_< arithmetic_<A0> > >)
                            )
  {
    typedef typename meta::scalar_of<A0>::type  result_type;
    typedef typename meta::as_real<A0>::type    r_t;

    BOOST_FORCEINLINE result_type operator()(A0 const& a0) const
    {
      return bitwise_cast<result_type>(maximum(bitwise_cast<r_t>(a0)));
    }
  };
} }

#endif


text:
'''
Created on Jul 18, 2015

@author: patrick
'''
import argparse
import pprint

from django.utils import timezone

from trackbuild.models import Release, Build, Product

builds = {}

z = lambda v, d=None : v if (v is not None and ('%s' % v)[0] != "+") else d

class BuildTracker:
    def __init__(self, user):
        self.releases = Release.objects.all()
        self.user = user

    def list_builds(self, release=None, product=None):
        # if specific release given, get its builds
        for release in Release.objects.filter(name=release, user=self.user):
            (major, minor, patch) = self.get_full_version(release)
            print "Product %s Release %s.%s.%s has %d builds" % (release.product.name,
                                                                 major, minor, patch, release.builds.count())
            for build in release.builds.all():
                yield build

    def get_release(self, release, product=None, major=None, minor=None, patch=None):
        if isinstance(release, Release):
            return release
        opts = dict(major=z(major), minor=z(minor), patch=z(patch),
                    product=product)
        opts = { k:v for k,v in opts.iteritems() if v is not None}
        print opts
        return Release.objects.filter(name=release, user=self.user,
                                    **opts).latest()

    def get_full_version(self, release):
        release = self.get_release(release)
        major = release.major
        minor = release.minor
        patch = release.patch
        return (major, minor, patch)

    def get_latest_build(self, release, major=None, minor=None, patch=None):
        release = self.get_release(release, major=major, minor=minor,
                                   patch=patch)
        try:
            return release.builds.latest()
        except Build.DoesNotExist:
            return None

    def add_product(self, name=None):
        product, cr_product = Product.objects.get_or_create(name=name,
                                                            user=self.user)
        return product

    def add_release(self, release, base_release=None, product=None,
                    major=0, minor=1, patch=0):
        if base_release:
            return Release.from_release(base_release, name=release, major=major,
                                    minor=minor, patch=patch)
        if not isinstance(product, Product):
            product_opts = dict(name=product or release, user=self.user)
            product, cr_product = Product.objects.get_or_create(**product_opts)
        release_opts = dict(name=release, major=major,
                            minor=minor, patch=patch,
                            product=product, user=self.user)
        release_opts = { k : v for k,v in release_opts.iteritems() if v}
        release, cr_release = Release.objects.get_or_create(**release_opts)
        return release

    def add_build(self, release=None, tag=None):
        tag = 'n/a' if not tag else tag
        if not isinstance(release, Release):
            release = Release.objects.get(name=release, user=self.user)
        build = Build.objects.create(release=release, tag=tag, user=self.user)
        return build

    def format(self, release=None, build=None, buildno=False, nice=True, display=False, date=False,
               filename=False, product=None, full=False, custom=None):
        assert release or build, "need at least a build or a release object"
        # make sure we have model instances
        if release and not isinstance(release, Release):
            release = self.get_release(release)
        if build and not isinstance(build, Build):
            build = self.get_latest_build(release)
        # process
        release = release or build.release
        build = build or self.get_latest_build(release)
        opts=dict(
            pname=product.name if product else release.product.name,
            rname=release.name,
            major=release.major,
            minor=release.minor,
            patch=release.patch,
            build=build,
            buildno="%003d" % (build.buildno if build else 0),
            builddt=build.created if build else timezone.datetime.now(),
        )
        if custom:
            return custom.format(**opts)
        fmt = ''
        if nice:
            fmt = '{major}.{minor}.{patch}'
        if display:
            fmt = '{pname}-{rname}#{major}.{minor}.{patch}'
        if full:
            fmt = "{pname}-{rname}#{major}.{minor}.{patch}#{buildno}"
        if date:
            fmt += " {builddt}"
        if buildno and not "buildno" in fmt:
            fmt = "{buildno}"
        sep = '.' if filename else ' '
        fmt = fmt.replace('#', '-' if filename else ' ')
        return sep.join(fmt.split(' ')).format(**opts)

    @staticmethod
    def parseArgs(self, args):
        # get args
        parser = argparse.ArgumentParser()
        parser.add_argument("--product", "-P", help="add or set product", action="store")
        parser.add_argument("--release", "-r", help="add a release for product", action="store")
        parser.add_argument("--build", "-b", help="add a build log and print build no", action="store_true")
        parser.add_argument("--tag", "-t", help="the build tag (eg git commit id)", action="store")
        parser.add_argument("--major", "-M", help="set major version (default: 0)", action="store")
        parser.add_argument("--minor", "-m", help="set minor version (default: 1)", action="store")
        parser.add_argument("--patch", "-p", help="set patch number (default: 0)", action="store")
        parser.add_argument("--list", "-l", help="list release(s)", action="store_true")
        parser.add_argument("--nice", "-n", help="print major.minor.patch", action="store_true")
        parser.add_argument("--full", "-f", help="print <release> <major.minor.patch> build <buildno>", action="store_true")
        parser.add_argument("--display", "-d", help="print release major.minor.patch.build", action="store_true")
        parser.add_argument("--date", "-D", help="print release major.minor.patch.build date", action="store_true")
        parser.add_argument("--filename", "-i", help="print version as release-major.minor.patch.build (use with --full, --display, --nice)", action="store_true")
        args = parser.parse_args(args=args)
        return args

    def processArgs(self, args):
        # process
        tracker = self
        product = None
        release = None
        build = None
        fmtopts = dict(filename=args.filename,
                       nice=args.nice, display=args.display,
                       full=args.full, date=args.date)
        if args.product:
            product = tracker.add_product(args.product)
        if not args.release:
            return (product, release, build, "No release specified")
        try:
            # see if we know this release
            release = self.get_release(args.release, product=product,
                                       major=args.major,
                                       minor=args.minor,
                                       patch=args.patch)
        except Release.DoesNotExist:
            release = None
        if not release and not args.build and not any([args.major, args.minor, args.patch]):
            release = tracker.add_release(args.release, product=args.product)
        elif release and not args.build and any([args.major, args.minor, args.patch]):
            release = tracker.add_release(args.release, base_release=release,
                                          major=args.major, minor=args.minor,
                                          patch=args.patch, product=product)
        elif not release and not args.build and any([args.major, args.minor, args.patch]):
            release = tracker.add_release(args.release, base_release=release,
                                          major=args.major, minor=args.minor,
                                          patch=args.patch, product=product)
        elif args.build:
            # get existing release
            try:
                release = self.get_release(args.release, major=args.major,
                                                         minor=args.minor,
                                                         patch=args.patch,
                                                         product=product)
            except Release.DoesNotExist:
                return (product, release, build, "Release not yet created. Try without --build")

        if args.list:
            builds = self.list_builds(release=args.release, product=args.product)
            for build in builds:
                print self.format(build=build, **fmtopts)
            return (product, release, build, "All Builds listed.")
        if args.build:
            if not args.release:
                return (product, release, build, "No release specified")
            build = tracker.add_build(release, args.tag)
            fmtopts['full'] = True
            if not any([args.full, args.display, args.nice]):
                return (product, release, build, tracker.format(release, build=True))
        if not release and not build:
                return (product, release, build, "No release specified or no build created.")
        return (product, release, build, self.format(release, build, **fmtopts))


text:
namespace cc {

class TimerTask : public Thread::Task {
public:
    explicit TimerTask(Timer* timer)
        : Thread::Task(0)
        , m_timer(timer)
    {
    }

    virtual ~TimerTask()
    {
        if (!m_timer)
            return;

        DCHECK(m_timer->m_task == this);
        m_timer->stop();
    }

    virtual void performTask() OVERRIDE
    {
        if (!m_timer)
            return;

        TimerClient* client = m_timer->m_client;

        m_timer->stop();
        if (client)
            client->onTimerFired();
    }

private:
    friend class Timer;

    Timer* m_timer; // null if cancelled
};

Timer::Timer(Thread* thread, TimerClient* client)
    : m_client(client)
    , m_thread(thread)
    , m_task(0)
{
}

Timer::~Timer()
{
    stop();
}

void Timer::startOneShot(double intervalSeconds)
{
    stop();

    m_task = new TimerTask(this);

    // The thread expects delays in milliseconds.
    m_thread->postDelayedTask(adoptPtr(m_task), intervalSeconds * 1000.0);
}

void Timer::stop()
{
    if (!m_task)
        return;

    m_task->m_timer = 0;
    m_task = 0;
}

} // namespace cc


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

<TITLE>
AlphaRasterImage (Apache FOP 1.1 API)
</TITLE>

<META NAME="date" CONTENT="2012-10-16">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

fop 1.1

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

org.apache.fop.pdf

Class AlphaRasterImage

java.lang.Object
  org.apache.fop.pdf.AlphaRasterImage

All Implemented Interfaces:
PDFImage

public class AlphaRasterImage
extends java.lang.Object
implements PDFImage

PDFImage implementation for alpha channel "images".

Constructor Summary

AlphaRasterImage(java.lang.String k,
                 java.awt.image.Raster alpha)

          Create a alpha channel image.

AlphaRasterImage(java.lang.String k,
                 java.awt.image.RenderedImage image)

          Create a alpha channel image.

Method Summary

 int
getBitsPerComponent()

          Get the bits per color component for this image.

 PDFDeviceColorSpace
getColorSpace()

          Get the color space for this image.

 java.lang.String
getFilterHint()

          Returns a hint in form of a String (Possible values from PDFFilterList)
 indicating which filter setup should be used to encode the object.

 int
getHeight()

          Get the image height in pixels.

 PDFICCStream
getICCStream()

          Get the ICC stream for this image.

 java.lang.String
getKey()

          Key to look up XObject.

 java.lang.String
getMask()

          Get the PDF reference for a bitmap mask.

 PDFFilter
getPDFFilter()

          Get the PDF Filter to be applied to the image.

 java.lang.String
getSoftMask()

 PDFReference
getSoftMaskReference()

          Get the PDF reference for a soft mask.

 PDFColor
getTransparentColor()

          Get the transparent color.

 int
getWidth()

          Get the image width in pixels.

 boolean
isInverted()

 boolean
isPS()

          Check if this image is a PostScript image.

 boolean
isTransparent()

          Check if this image has a transparent color transparency.

 boolean
multipleFiltersAllowed()

          Indicates whether multiple image filters are allowed; this is implemented because Adobe
 Reader does not like multiple FlateDecode filters applied to an image even though that
 allowed by the PDF spec; this is probable due to security concerns since many PDF malware
 exploits, like zip bombs, make use of a chain of FlateDecode filters.

 void
outputContents(java.io.OutputStream out)

          Writes the raw, unencoded contents of the image to a given output stream.

 void
populateXObjectDictionary(PDFDictionary dict)

          Populates the XObject's dictionary with additional values.

 void
setup(PDFDocument doc)

          Setup the PDF image for the current document.

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

AlphaRasterImage

public AlphaRasterImage(java.lang.String k,
                        java.awt.image.Raster alpha)

Create a alpha channel image.
 Creates a new bitmap image with the given data.

Parameters:
k - the key to be used to lookup the image
alpha - the alpha channel raster

AlphaRasterImage

public AlphaRasterImage(java.lang.String k,
                        java.awt.image.RenderedImage image)

Create a alpha channel image.
 Extracts the alpha channel from the RenderedImage and creates a new bitmap image
 with the given data.

Parameters:
k - the key to be used to lookup the image
image - the image (must have an alpha channel)

Method Detail

setup

public void setup(PDFDocument doc)

Setup the PDF image for the current document.
 Some image formats may need to access the document (for example to
 add an ICC profile to the document).

Specified by:
setup in interface PDFImage

Parameters:
doc - the PDF parent document
 (todo) Remove this and delegate to the XObject

getKey

public java.lang.String getKey()

Key to look up XObject.
 This should be a unique key to refer to the image.

Specified by:
getKey in interface PDFImage

Returns:
the key for this image

getWidth

public int getWidth()

Get the image width in pixels.

Specified by:
getWidth in interface PDFImage

Returns:
the image width

getHeight

public int getHeight()

Get the image height in pixels.

Specified by:
getHeight in interface PDFImage

Returns:
the image height

getColorSpace

public PDFDeviceColorSpace getColorSpace()

Get the color space for this image.
 Possible results are: DeviceGray, DeviceRGB, or DeviceCMYK

Specified by:
getColorSpace in interface PDFImage

Returns:
the color space

getBitsPerComponent

public int getBitsPerComponent()

Get the bits per color component for this image.

Specified by:
getBitsPerComponent in interface PDFImage

Returns:
the bits per component

isTransparent

public boolean isTransparent()

Check if this image has a transparent color transparency.

Specified by:
isTransparent in interface PDFImage

Returns:
true if it has transparency

getTransparentColor

public PDFColor getTransparentColor()

Get the transparent color.

Specified by:
getTransparentColor in interface PDFImage

Returns:
the transparent color for this image

getMask

public java.lang.String getMask()

Get the PDF reference for a bitmap mask.

Specified by:
getMask in interface PDFImage

Returns:
the PDF reference for the mask image

getSoftMask

public java.lang.String getSoftMask()

Returns:
null (unless overridden)

getSoftMaskReference

public PDFReference getSoftMaskReference()

Get the PDF reference for a soft mask.

Specified by:
getSoftMaskReference in interface PDFImage

Returns:
the PDF reference for a soft mask image (or null if there's no soft mask)

isInverted

public boolean isInverted()

Specified by:
isInverted in interface PDFImage

Returns:
true for CMYK images generated by Adobe Photoshop

outputContents

public void outputContents(java.io.OutputStream out)
                    throws java.io.IOException

Writes the raw, unencoded contents of the image to a given output stream.

Specified by:
outputContents in interface PDFImage

Parameters:
out - OutputStream to write to

Throws:

java.io.IOException - if there creating stream

populateXObjectDictionary

public void populateXObjectDictionary(PDFDictionary dict)

Populates the XObject's dictionary with additional values. The values are added to the
 dictionary after all the values obtained from other methods from this interface have
 been put into the dictionary. That allows to override certain values.

Specified by:
populateXObjectDictionary in interface PDFImage

Parameters:
dict - the dictionary to fill

getICCStream

public PDFICCStream getICCStream()

Get the ICC stream for this image.

Specified by:
getICCStream in interface PDFImage

Returns:
the ICC stream for this image if any

isPS

public boolean isPS()

Check if this image is a PostScript image.

Specified by:
isPS in interface PDFImage

Returns:
true if this is a PostScript image

getFilterHint

public java.lang.String getFilterHint()

Returns a hint in form of a String (Possible values from PDFFilterList)
 indicating which filter setup should be used to encode the object.

Specified by:
getFilterHint in interface PDFImage

Returns:
the filter setup hint

getPDFFilter

public PDFFilter getPDFFilter()

Get the PDF Filter to be applied to the image.

Specified by:
getPDFFilter in interface PDFImage

Returns:
the PDF Filter or null

multipleFiltersAllowed

public boolean multipleFiltersAllowed()

Indicates whether multiple image filters are allowed; this is implemented because Adobe
 Reader does not like multiple FlateDecode filters applied to an image even though that
 allowed by the PDF spec; this is probable due to security concerns since many PDF malware
 exploits, like zip bombs, make use of a chain of FlateDecode filters.

Specified by:
multipleFiltersAllowed in interface PDFImage

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

fop 1.1

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

Copyright 1999-2012 The Apache Software Foundation. All Rights Reserved.


text:
using Foundation;
using System;
using System.CodeDom.Compiler;
using UIKit;
using System.Linq;
using CoreSpotlight;
using MonkeySearch.Models;

namespace MonkeySearch
{
    partial class DetailsViewController : UIViewController
    {
        const string activityName = "com.xamarin.monkeys.monkey";

        public DetailsViewController(IntPtr handle)
            : base(handle)
        {
        }

        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            UserActivity = CreateActivity();

            lblName.Text = monkey.Name;
            lblDescription.Text = monkey.Details;
        }

        Monkey monkey;

        public void SetMonkey(Monkey monkey)
        {
            this.monkey = monkey;
        }

        NSUserActivity CreateActivity()
        {

            var activity = new NSUserActivity(activityName);
            activity.EligibleForSearch = true;
            activity.EligibleForPublicIndexing = true;
            activity.EligibleForHandoff = false;

            activity.Title = monkey.Name;
            activity.AddUserInfoEntries(NSDictionary.FromObjectAndKey(new NSString(monkey.Name), new NSString("Name")));

			var keywords = new NSString[] { (NSString)monkey.Name, (NSString)"Monkey" };
            activity.Keywords = new NSSet<NSString>(keywords);
            activity.ContentAttributeSet = new CoreSpotlight.CSSearchableItemAttributeSet(monkey.Details);

            return activity;

        }
    }
}


text:
import * as React from 'react'
import { StatelessComponent } from 'react'

export const Title: StatelessComponent<TitleProps> = ({
  fullScreen,
  handlers,
  inset,
  title,
  TitleBar,
  transparent,
}) => (
  <TitleBar
    {...{inset, title, transparent}}
    controls
    isFullscreen={fullScreen}
    {...handlers}
  />
)


text:
The ICollectionManager class exposes methods to manage the assets collections:

```python
from unreal_engine import ICollectionManager

print(ICollectionManager.get_collections())
# 1 means ECollectionShareType::CST_Local
print(ICollectionManager.get_child_collections('FooBar', 1))
```

Collections can be 'static' (they contain references to assets) or 'dynamic' (they apply a search string to get a list of assets)

The api expects knowledge of a bunch of enums mapped as int:

`ECollectionShareType`

```c
enum Type
{
    CST_System,
    CST_Local,
    CST_Private,
    CST_Shared,
    CST_All,
}
```

`ECollectionStorageMode`

```c
enum Type
{
    Static,
    Dynamic,
}
```

### get_collections()

returns the list of collections as a python list of tuples with the form (name, ECollectionShareType)

### get_root_collections()

returns the list of root collections as a python list of tuples with the form (name, ECollectionShareType)

### get_child_collections(name, ECollectionShareType)

returns the list of child collections for a collection (given as name and type) as a python list of tuples with the form (name, ECollectionShareType)

### get_root_collection_names()

returns the names of root collections as a python list of strings

### get_collection_names()

returns the names of collections as a python list of strings

### create_static_collection(name, ECollectionShareType)

create a new static collections given a name and a type

### create_dynamic_collection(name, ECollectionShareType)

create a new dynamic collections given a name and a type

### create_collection(name, ECollectionShareType, ECollectionStorageMode)

create a new dynamic collections given a name, a type and a storage mode

### reparent_collection(name, ECollectionShareType, new_name, ECollectionShareType)

move the 'name' collection to the 'new_name' parent

### add_to_collection(name, ECollectionShareType, objectPath)

add an asset to a static collection using asset's path

### collection_exists(name, ECollectionShareType)

Returns true if a collection already exists

### create_unique_collection_name(name, ECollectionShareType)

returns a string with a unique collection name

### destroy_collection(name, ECollectionShareType)

deletes an existing collection and returns true on success and false on failure

### empty_collection(name, ECollectionShareType)

removes all the existing assets from a collection. Returns true on success and false on failure

### get_dynamic_query_text(name, ECollectionShareType)

returns the search text from a dynamic collection. If you use it on a static collection you will get an error

### set_dynamic_query_text(name, ECollectionShareType, searchText)

sets the search text to a dynamic collection. Returns true on success and false on failure

### remove_from_collection(name, ECollectionShareType, objectPath)

removes an asset from a static collection using asset's path. Returns true on success and false on failure

### get_assets_in_collection(name, ECollectionShareType, recursion(optional))

returns a list with all the asset paths. There is a third optional parameter for recursion. Default value is 1. This function works only with static collections

### get_objects_in_collection(name, ECollectionShareType, recursion(optional))

returns a list with all the object paths. There is a third optional parameter for recursion. Default value is 1. This function works only with static collections

### get_classes_in_collection(name, ECollectionShareType, recursion(optional))

returns a list with all the Classes. There is a third optional parameter for recursion. Default value is 1. This function works only with static collections

### get_parent_collection(name, ECollectionShareType)

returns the parent collection. If the collection has no parent, it returns None.

### has_collections()

returns True or False if the project has or doesn't have any collections.


text:
@extends('layouts.blank')

@section('content')

Panel heading without title

    Email address
    <input type="email" class="form-control" id="exampleInputEmail1" placeholder="Email">

    Password
    <input type="password" class="form-control" id="exampleInputPassword1" placeholder="Password">
    <input type="hidden" value="https://laravel.com/assets/img/laravel-logo.png">

    File input
    <input type="file" id="exampleInputFile">

Example block-level help text here.

      <input type="checkbox"> Check me out

  <button onclick="top.tinymce.activeEditor.insertContent(' ');" class="btn btn-default">Submit</button>
    <button onclick="top.tinymce.activeEditor.windowManager.getWindows()[0].close();">Close window</button>

@endsection


text:
<md-dialog aria-label="Hint Popup" ng-cloak class="dialog-hint">
  <md-toolbar class="md-accent">

{{ctrl.hintObj.name}}

      <md-button class="md-icon-button" ng-click="ctrl.cancel()">
        <md-icon>close</md-icon>
      </md-button>

  </md-toolbar>
  <md-dialog-content class="dialog-hint-content" ng-include="ctrl.hintView">

  </md-dialog-content>
</md-dialog>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using StringToExpression.Parser;
using StringToExpression.Tokenizer;
using StringToExpression.Exceptions;

namespace StringToExpression.GrammerDefinitions
{
    /// <summary>
    /// Represents the grammer that seperates items in a list.
    /// </summary>
    /// <seealso cref="StringToExpression.GrammerDefinitions.GrammerDefinition" />
    public class ListDelimiterDefinition : GrammerDefinition
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="ListDelimiterDefinition"/> class.
        /// </summary>
        /// <param name="name">The name of the definition.</param>
        /// <param name="regex">The regex to match tokens.</param>
        public ListDelimiterDefinition(string name, string regex)
            : base(name, regex)
        {

        }

        /// <summary>
        /// Applies the token to the parsing state. Adds an error operator, it is expected that a close bracket will consume the
        /// error operator before it gets executed.
        /// </summary>
        /// <param name="token">The token to apply.</param>
        /// <param name="state">The state to apply the token to.</param>
        public override void Apply(Token token, ParseState state)
        {
            state.Operators.Push(new Operator(this, token.SourceMap, () =>
            {
                //if we ever executed this its because the correspdoning close bracket didnt
                //pop it from the operators
                throw new ListDelimeterNotWithinBrackets(token.SourceMap);
            }));
        }
    }
}


text:
namespace blink {

OffscreenCanvasRenderingContext::OffscreenCanvasRenderingContext(OffscreenCanvas* canvas)
    : m_offscreenCanvas(canvas)
{
}

OffscreenCanvasRenderingContext::ContextType OffscreenCanvasRenderingContext::contextTypeFromId(const String& id)
{
    if (id == "2d")
        return Context2d;
    if (id == "webgl")
        return ContextWebgl;
    if (id == "webgl2")
        return ContextWebgl2;
    return ContextTypeCount;
}

DEFINE_TRACE(OffscreenCanvasRenderingContext)
{
    visitor->trace(m_offscreenCanvas);
}

} // namespace blink


text:
/*
 * DFormCompany.java
 *
 * Created on 19 de agosto de 2008, 11:10 AM
 */

package erp.mmfg.form;

import java.util.Vector;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.AbstractAction;

import erp.data.SDataConstants;
import erp.data.SDataConstantsSys;
import erp.lib.form.SFormField;
import erp.lib.form.SFormValidation;
import erp.lib.form.SFormUtilities;
import erp.lib.SLibConstants;
import erp.mmfg.data.SDataProductionOrderNotes;

/**
 *
 * @author  Néstor Ávalos
 */
public class SFormProductionOrderNotes extends javax.swing.JDialog implements erp.lib.form.SFormInterface, java.awt.event.ActionListener {

    private int mnFormType;
    private int mnFormResult;
    private int mnFormStatus;
    private boolean mbFirstTime;
    private boolean mbResetingForm;
    private java.util.Vector<erp.lib.form.SFormField> mvFields;
    private erp.client.SClientInterface miClient;

    private erp.mmfg.data.SDataProductionOrderNotes moOrdNotes;
    private erp.lib.form.SFormField moFieldNotes;
    private erp.lib.form.SFormField moFieldIsDeleted;

    /** Creates new form DFormCompany */
    public SFormProductionOrderNotes(erp.client.SClientInterface client) {
        super(client.getFrame(), true);
        miClient = client;
        mnFormType = SDataConstants.MFG_ORD_NTS;

        initComponents();
        initComponentsExtra();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jpData = new javax.swing.JPanel();
        jpNotes = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jtaNotes = new javax.swing.JTextArea();
        jlNotes = new javax.swing.JLabel();
        jckIsDeleted = new javax.swing.JCheckBox();
        jPanel2 = new javax.swing.JPanel();
        jbOK = new javax.swing.JButton();
        jbCancel = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Nota"); // NOI18N
        setModal(true);
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowActivated(java.awt.event.WindowEvent evt) {
                formWindowActivated(evt);
            }
        });

        jpData.setLayout(new java.awt.BorderLayout(5, 5));

        jpNotes.setBorder(javax.swing.BorderFactory.createTitledBorder("Datos del registro:"));
        jpNotes.setLayout(new java.awt.BorderLayout(5, 5));

        jtaNotes.setColumns(20);
        jtaNotes.setRows(5);
        jtaNotes.setText("NOTES");
        jScrollPane1.setViewportView(jtaNotes);

        jpNotes.add(jScrollPane1, java.awt.BorderLayout.CENTER);

        jlNotes.setText("Notas: *");
        jpNotes.add(jlNotes, java.awt.BorderLayout.PAGE_START);

        jckIsDeleted.setText("Registro eliminado");
        jpNotes.add(jckIsDeleted, java.awt.BorderLayout.PAGE_END);

        jpData.add(jpNotes, java.awt.BorderLayout.CENTER);

        getContentPane().add(jpData, java.awt.BorderLayout.CENTER);

        jPanel2.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.RIGHT));

        jbOK.setText("Aceptar"); // NOI18N
        jbOK.setToolTipText("[Ctrl + Enter]");
        jbOK.setPreferredSize(new java.awt.Dimension(75, 23));
        jPanel2.add(jbOK);

        jbCancel.setText("Cancelar"); // NOI18N
        jbCancel.setToolTipText("[Escape]");
        jPanel2.add(jbCancel);

        getContentPane().add(jPanel2, java.awt.BorderLayout.PAGE_END);

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-608)/2, (screenSize.height-334)/2, 608, 334);
    }// </editor-fold>//GEN-END:initComponents

    private void formWindowActivated(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowActivated
        windowActivated();
    }//GEN-LAST:event_formWindowActivated

    private void initComponentsExtra() {
        mvFields = new Vector<SFormField>();

        moFieldNotes = new erp.lib.form.SFormField(miClient, SLibConstants.DATA_TYPE_STRING, true, jtaNotes, jlNotes);
        moFieldNotes.setLengthMax(255);
        moFieldIsDeleted = new erp.lib.form.SFormField(miClient, SLibConstants.DATA_TYPE_BOOLEAN, false, jckIsDeleted);

        mvFields.add(moFieldNotes);
        mvFields.add(moFieldIsDeleted);

        jbOK.addActionListener(this);
        jbCancel.addActionListener(this);

        AbstractAction actionOk = new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) { actionOk(); }
        };

        SFormUtilities.putActionMap(getRootPane(), actionOk, "ok", KeyEvent.VK_ENTER, KeyEvent.CTRL_DOWN_MASK);

        AbstractAction actionCancel = new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) { actionCancel(); }
        };

        SFormUtilities.putActionMap(getRootPane(), actionCancel, "cancel", KeyEvent.VK_ESCAPE, 0);
    }

     private void windowActivated() {
        if (mbFirstTime) {
            mbFirstTime = false;
            jtaNotes.requestFocus();
        }
    }

    private void actionEdit(boolean edit) {

    }

    private void actionOk() {
        erp.lib.form.SFormValidation validation = formValidate();

        if (validation.getIsError()) {
            if (validation.getComponent() != null) {
                validation.getComponent().requestFocus();
            }
            if (validation.getMessage().length() > 0) {
                miClient.showMsgBoxWarning(validation.getMessage());
            }
        }
        else {
            mnFormResult = SLibConstants.FORM_RESULT_OK;
            setVisible(false);
        }
    }

    private void actionCancel() {
        mnFormResult = SLibConstants.FORM_RESULT_CANCEL;
        setVisible(false);
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton jbCancel;
    private javax.swing.JButton jbOK;
    private javax.swing.JCheckBox jckIsDeleted;
    private javax.swing.JLabel jlNotes;
    private javax.swing.JPanel jpData;
    private javax.swing.JPanel jpNotes;
    private javax.swing.JTextArea jtaNotes;
    // End of variables declaration//GEN-END:variables

    @Override
    public void formClearRegistry() {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void formReset() {
        mnFormResult = SLibConstants.UNDEFINED;
        mnFormStatus = SLibConstants.UNDEFINED;
        mbFirstTime = true;

        moOrdNotes = null;

        for (int i = 0; i < mvFields.size(); i++) {
            ((erp.lib.form.SFormField) mvFields.get(i)).resetField();
        }

        jckIsDeleted.setEnabled(false);
    }

    @Override
    public void formRefreshCatalogues() {

    }

    @Override
    public erp.lib.form.SFormValidation formValidate() {
        erp.lib.form.SFormValidation validation = new SFormValidation();

        for (int i = 0; i < mvFields.size(); i++) {
            if (!((erp.lib.form.SFormField) mvFields.get(i)).validateField()) {
                validation.setIsError(true);
                validation.setComponent(((erp.lib.form.SFormField) mvFields.get(i)).getComponent());
                break;
            }
        }

        return validation;
    }

    @Override
    public void setFormStatus(int status) {
        mnFormStatus = status;
    }

    @Override
    public void setFormVisible(boolean visible) {
        setVisible(visible);
    }

    @Override
    public int getFormStatus() {
        return mnFormStatus;
    }

    @Override
    public int getFormResult() {
        return mnFormResult;
    }

    @Override
    public void setRegistry(erp.lib.data.SDataRegistry registry) {
        moOrdNotes = (SDataProductionOrderNotes) registry;

        moFieldNotes.setFieldValue(moOrdNotes.getNotes());
        moFieldIsDeleted.setBoolean(moOrdNotes.getIsDeleted());

        jckIsDeleted.setEnabled(true);
    }

    @Override
    public erp.lib.data.SDataRegistry getRegistry() {
        if (moOrdNotes == null) {
            moOrdNotes = new SDataProductionOrderNotes();
            moOrdNotes.setFkUserNewId(miClient.getSession().getUser().getPkUserId());
        }
        else
            moOrdNotes.setFkUserEditId(miClient.getSession().getUser().getPkUserId());

        moOrdNotes.setNotes(moFieldNotes.getString());
        moOrdNotes.setIsDeleted(moFieldIsDeleted.getBoolean());

        return moOrdNotes;
    }

    @Override
    public void setValue(int type, java.lang.Object value) {
        switch (type) {
            case 1:
                // Validate if is enabled 'save' button:

                if ((Integer) value < SDataConstantsSys.MFGS_ST_ORD_PROC) {
                    jbOK.setEnabled(true);
                }
                else {
                    jbOK.setEnabled(false);
                }

                break;
        }
    }

    @Override
    public java.lang.Object getValue(int type) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public javax.swing.JLabel getTimeoutLabel() {
        return null;
    }

    @Override
    public void actionPerformed(java.awt.event.ActionEvent e) {
        if (e.getSource() instanceof javax.swing.JButton) {
            javax.swing.JButton button = (javax.swing.JButton) e.getSource();

            if (button == jbOK) {
                actionOk();
            }
            else if (button == jbCancel) {
                actionCancel();
            }
        }
    }
}


text:
<?php

namespace Spoort\Bundle\Symfony2EconomicBundle\Entity\Handle;

use Spoort\Bundle\Symfony2EconomicBundle\Entity\EconomicSoapEntity;

class CurrencyHandle extends EconomicSoapEntity
{

    /** @var string $Code */
    private $Code;

    /**
     * @return string
     */
    public function getCode()
    {
        return $this->Code;
    }

    /**
     * @param string $code
     * @return self
     */
    public function setCode($code)
    {
        $this->Code = $code;

        return $this;
    }
}


text:
#ifndef _F_B2_CONTACT_LISTENER_H_
#define _F_B2_CONTACT_LISTENER_H_

#include "FsMacros.h"
#include "Box2D/Box2D.h"
#include "FsObject.h"
NS_FS_BEGIN

class fb2ContactListener:public b2ContactListener
{
	public:

		fb2ContactListener();
		~fb2ContactListener();

	public:
		virtual void BeginContact(b2Contact* contact);
		virtual void EndContact(b2Contact* contact);
		virtual void PreSolve(b2Contact* contact, const b2Manifold* old_mf);
		virtual void PostSolve(b2Contact* contact, const b2ContactImpulse* impulse);

	public:
		int m_scriptData;

};

#endif /*_F_B2_CONTACT_LISTENER_H_*/
NS_FS_END


text:
import pytest

from marrow.mongo.core.document import Document
from marrow.mongo.field.base import Field

class Person(Document):
	name = Field()
	age = Field()

@pytest.fixture
def doc(request):
	return Person("Alice", 27)

class TestDocumentMapping(object):
	def test_getitem(self, doc):
		with pytest.raises(KeyError):
			doc['foo']

		assert doc['age'] == 27

	def test_setitem(self, doc):
		assert len(doc) == 2
		doc['meaning'] = 42
		assert len(doc) == 3

	def test_delitem(self, doc):
		with pytest.raises(KeyError):
			del doc['roll']

		assert len(doc) == 2
		del doc['name']
		assert len(doc) == 1

	def test_length(self, doc):
		assert len(doc) == 2

	def test_keys(self, doc):
		assert list(doc.keys()) == ['name', 'age']

	def test_items(self, doc):
		assert list(doc.items()) == [('name', "Alice"), ('age', 27)]

	def test_values(self, doc):
		assert list(doc.values()) == ["Alice", 27]

	def test_contains(self, doc):
		assert 'foo' not in doc
		assert 'name' in doc

	def test_equality_inequality(self, doc):
		assert doc != {}
		assert doc == {'name': "Alice", 'age': 27}

	def test_get(self, doc):
		assert doc.get('foo') is None
		assert doc.get('foo', 42) == 42
		assert doc.get('age') == 27

	def test_clear(self, doc):
		assert len(doc.__data__) == 2
		doc.clear()
		assert len(doc.__data__) == 0

	def test_pop(self, doc):
		assert len(doc.__data__) == 2

		with pytest.raises(KeyError):
			doc.pop('foo')

		assert doc.pop('foo', 42) == 42
		assert len(doc.__data__) == 2

		assert doc.pop('age') == 27
		assert len(doc.__data__) == 1

	def test_popitem(self, doc):
		assert len(doc.__data__) == 2
		assert doc.popitem() == ('age', 27)
		assert len(doc.__data__) == 1

		doc.popitem()

		with pytest.raises(KeyError):
			doc.popitem()

	def test_update(self, doc):
		assert len(doc.__data__) == 2
		doc.update(name="Bob Dole")
		assert len(doc.__data__) == 2
		assert doc.name == "Bob Dole"

		doc.update([('bob', "Bob Dole")])
		assert len(doc.__data__) == 3

	def test_setdefault(self, doc):
		assert len(doc.__data__) == 2
		doc.setdefault('fnord', 42)
		assert len(doc.__data__) == 3
		assert doc.__data__['fnord'] == 42
		doc.setdefault('fnord', 27)
		assert len(doc.__data__) == 3
		assert doc.__data__['fnord'] == 42


text:
Enquete com os candidatos para presidente do Brasil das eleições de 2018.

Projeto publicado em: https://vozdoeleitor.com/


text:
storage

service in module esef.frontend.storage

Description

Storage service which stores key/value objects and notifies changes with observer pattern.

Methods

get(key)

Get method for storage service.

Parameters

Param	Type	Details

key	string

Key of desired object.

Returns

object

Desired object stored on given key.

notifyObservers()

Notifies registered observers by running callbacks.

Returns

object

Storage service.

registerObserverCallback(callback)

Registers callback to observe changes on service.

Parameters

Param	Type	Details

callback	function

Observer callback function

Returns

object

storage service.

removeProperty(key, key)

Remove a single property on given object. Calls registered callback functions to inform about the change.

Parameters

Param	Type	Details

key	string

Object key.

key	string

Property key stored on given object key.

Returns

object

storage service.

set()

Set method for storage service. Sets given object as storage.

Returns

object

storage service.

setProperty(key, propKey, val)

Set method for single property on given key. Calls registered callback functions to inform about the change.

Parameters

Param	Type	Details

key	string

Object key.

propKey	string

Property key on desired object.

val	string

New value to be set.

Returns

object

storage service.

store(key, newValues)

Store method for storage. Stores given object with given key. Calls registered callback functions to inform about the change.

Parameters

Param	Type	Details

key	string

Storage key.

newValues	object

Object to be stored on given key.

Returns

object

storage service.


text:
package org.motechproject.tasks.repository;

import com.google.gson.reflect.TypeToken;
import org.ektorp.CouchDbConnector;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.motechproject.commons.api.json.MotechJsonReader;
import org.motechproject.tasks.domain.Channel;
import org.motechproject.testing.utils.SpringIntegrationTest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.io.InputStream;
import java.lang.reflect.Type;
import java.util.List;

import static java.util.Arrays.asList;
import static org.junit.Assert.assertEquals;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath*:/META-INF/motech/*.xml"})
public class AllChannelsIT extends SpringIntegrationTest {

    @Autowired
    private AllChannels allChannels;

    @Autowired
    @Qualifier("taskDbConnector")
    private CouchDbConnector couchDbConnector;

    private MotechJsonReader motechJsonReader = new MotechJsonReader();

    @Test
    public void shouldAddAndUpdateChannels() {
        List<Channel> channels = loadChannels();

        allChannels.addOrUpdate(channels.get(0));
        allChannels.addOrUpdate(channels.get(1));

        assertEquals(channels, allChannels.getAll());

        allChannels.addOrUpdate(channels.get(1));

        assertEquals(channels, allChannels.getAll());

        markForDeletion(allChannels.getAll());
    }

    @Test
    public void shouldFindChannelByChannelInfo() throws Exception {
        List<Channel> channels = loadChannels();

        allChannels.addOrUpdate(channels.get(0));
        allChannels.addOrUpdate(channels.get(1));

        List<Channel> channelList = allChannels.getAll();

        assertEquals(channels, channelList);

        Channel channel = channelList.get(0);
        Channel actual = allChannels.byChannelInfo(channel.getDisplayName(), channel.getModuleName(), channel.getModuleVersion());

        assertEquals(channel, actual);

        channel = channelList.get(1);
        actual = allChannels.byChannelInfo(channel.getDisplayName(), channel.getModuleName(), channel.getModuleVersion());

        assertEquals(channel, actual);

        markForDeletion(channelList);
    }

    private List<Channel> loadChannels() {
        ClassLoader classLoader = getClass().getClassLoader();

        InputStream messageCampaignChannelStream = classLoader.getResourceAsStream("message-campaign-test-channel.json");
        InputStream pillReminderChannelStream = classLoader.getResourceAsStream("pillreminder-test-channel.json");

        Type type = new TypeToken<Channel>() {
        }.getType();
        Channel messageCampaignChannel = (Channel) motechJsonReader.readFromStream(messageCampaignChannelStream, type);
        Channel pillReminderChannel = (Channel) motechJsonReader.readFromStream(pillReminderChannelStream, type);

        return asList(messageCampaignChannel, pillReminderChannel);
    }

    @Override
    public CouchDbConnector getDBConnector() {
        return couchDbConnector;
    }
}


text: google-site-verification: googlefb2e8e406f95dde0.html


text:
<?php
namespace einfach\representer\serializer;

use Symfony\Component\Yaml\Yaml as YamlDumper;

/**
 * Class JSON
 *
 * @package einfach\representer\serializer
 *
 */
trait YAML
{
    public function toYAML()
    {
        return YamlDumper::dump($this->getRepresentation());
    }

    public function fromYAML($string)
    {
        $projection = YamlDumper::parse($string);
        return $this->getReverseRepresentation($projection);
    }

    protected abstract function getRepresentation();

    protected abstract function getReverseRepresentation($projection);
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- $Revision: 334955 $ -->

<refentry xml:id="function.trader-errno" xmlns="http://docbook.org/ns/docbook" xmlns:xlink="http://www.w3.org/1999/xlink">
 <refnamediv>
  <refname>trader_errno</refname>
  <refpurpose>Get error code</refpurpose>
 </refnamediv>

 <refsect1 role="description">
  &reftitle.description;
  <methodsynopsis>
   <type>integer</type><methodname>trader_errno</methodname>
   <void/>
  </methodsynopsis>
  <para>
   Get error code of the last operation.
  </para>
 </refsect1>
 <refsect1 role="returnvalues">
  &reftitle.returnvalues;
  <para>Returns the error code identified by one of the <link xmlns="http://docbook.org/ns/docbook" linkend="trader.constants">TRADER_ERR_*</link> constants.</para>
 </refsect1>

</refentry>

<!-- Keep this comment at the end of the file
Local variables:
mode: sgml
sgml-omittag:t
sgml-shorttag:t
sgml-minimize-attributes:nil
sgml-always-quote-attributes:t
sgml-indent-step:1
sgml-indent-data:t
indent-tabs-mode:nil
sgml-parent-document:nil
sgml-default-dtd-file:"~/.phpdoc/manual.ced"
sgml-exposed-tags:nil
sgml-local-catalogs:nil
sgml-local-ecat-files:nil
End:
vim600: syn=xml fen fdm=syntax fdl=2 si
vim: et tw=78 syn=sgml
vi: ts=1 sw=1
-->


text:
/**
 * 通信最適化 Checker
 */
/* globals CryptoJS */

if (location.protocol === "https:") {
  location.protocol = "http:";
}

$(function () {
  $.getJSON("http://ip-api.com/json").then(function (data) {
    $("#ip").text(data.query);
    $("#as").text(data.as);
    $("#isp").text(data.isp);
  });

  $("#ua").text(navigator.userAgent);

  var valid = $("#valid").text();

  function print(protocol) {
    return function () {
      var $field = $("#" + protocol).text(hash);

      if (this.status !== 200) {
        $field.text("Error = " + this.statusText);
        $field.addClass("error");
        return;
      }

      var bytes = new Uint8Array(this.response);
      var hash = shasum(bytes);
      var url = createURL(bytes);

      $("#" + protocol + "-img").attr("src", url);

      $field.text(hash);
      if (hash === valid) {
        $field.addClass("valid");
      } else {
        $field.addClass("invalid");
      }
    };
  }

  ajax("http://" + location.host + location.pathname + "photo.jpg", print("http"));
  ajax("https://" + location.host + location.pathname + "photo.jpg", print("https"));
});

function ajax(url, callback) {
  var xhr = new XMLHttpRequest();
  xhr.open("get", url, true);
  xhr.responseType = "arraybuffer";
  xhr.addEventListener("load", callback);
  xhr.addEventListener("error", callback);
  xhr.send();
}

function shasum(bytes) {
  var byte_string = "";
  [].forEach.call(bytes, function (byte) {
    byte_string += String.fromCharCode(byte);
  });
  var base64_str = btoa(byte_string);

  var binary = CryptoJS.enc.Base64.parse(base64_str);
  var hash = CryptoJS.SHA1(binary);
  return hash.toString();
}

function createURL(bytes) {
  var blob = new Blob([bytes], {type: "image/png"});
  return URL.createObjectURL(blob);
}


text:
package com.intellij.codeInsight.slice;

import com.intellij.analysis.AnalysisScope;
import com.intellij.codeInsight.daemon.DaemonAnalyzerTestCase;
import com.intellij.codeInsight.daemon.LightDaemonAnalyzerTestCase;
import com.intellij.codeInsight.daemon.impl.HighlightInfo;
import com.intellij.ide.util.treeView.AbstractTreeNode;
import com.intellij.lang.annotation.HighlightSeverity;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.wm.impl.ToolWindowHeadlessManagerImpl;
import com.intellij.psi.*;
import com.intellij.slicer.*;
import com.intellij.util.ArrayUtil;
import com.intellij.util.Function;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NonNls;

import java.util.*;

/**
 * @author cdr
 */
public class SliceTreeTest extends LightDaemonAnalyzerTestCase {
  private SliceTreeStructure configureTree(@NonNls final String name) throws Exception {
    configureByFile("/codeInsight/slice/backward/"+ name +".java");
    PsiDocumentManager.getInstance(getProject()).commitAllDocuments();
    PsiElement element = new SliceHandler(true).getExpressionAtCaret(getEditor(), getFile());
    assertNotNull(element);
    Collection<HighlightInfo> errors = highlightErrors();
    assertEmpty(errors);

    SliceAnalysisParams params = new SliceAnalysisParams();
    params.scope = new AnalysisScope(getProject());
    params.dataFlowToThis = true;

    SliceUsage usage = SliceManager.createRootUsage(element, params);

    SlicePanel panel = new SlicePanel(getProject(), true, new SliceRootNode(getProject(), new DuplicateMap(), usage), false, ToolWindowHeadlessManagerImpl.HEADLESS_WINDOW) {
      @Override
      protected void close() {
      }

      @Override
      public boolean isAutoScroll() {
        return false;
      }

      @Override
      public void setAutoScroll(boolean autoScroll) {
      }

      @Override
      public boolean isPreview() {
        return false;
      }

      @Override
      public void setPreview(boolean preview) {
      }
    };
    Disposer.register(getProject(), panel);
    return (SliceTreeStructure)panel.getBuilder().getTreeStructure();
  }

  private static void expandNodesTo(final SliceNode node, List<SliceNode> to) {
    node.update();
    node.calculateDupNode();
    to.add(node);
    Collection<? extends AbstractTreeNode> nodes = node.getChildren();
    for (AbstractTreeNode child : nodes) {
      expandNodesTo((SliceNode)child, to);
    }
  }

  public void testTypingDoesNotInterfereWithDuplicates() throws Exception {
    SliceTreeStructure treeStructure = configureTree("DupSlice");
    SliceNode root = (SliceNode)treeStructure.getRootElement();
    List<SliceNode> nodes = new ArrayList<SliceNode>();
    expandNodesTo(root, nodes);

    for (int i = 0; i < nodes.size()-1; i++) {
      SliceNode node = nodes.get(i);
      assertNull(node.getDuplicate());
    }
    SliceNode last = nodes.get(nodes.size() - 1);
    assertNotNull(last.getDuplicate());

    type("   xx");
    PsiDocumentManager.getInstance(getProject()).commitAllDocuments();
    backspace();
    backspace();
    PsiDocumentManager.getInstance(getProject()).commitAllDocuments();

    nodes.clear();
    expandNodesTo(root, nodes);
    for (int i = 0; i < nodes.size()-1; i++) {
      SliceNode node = nodes.get(i);
      assertNull(node.getDuplicate());
    }
    assertNotNull(last.getDuplicate());
  }

  public void testLeafExpressionsAreEmptyInCaseOfInfinitelyExpandingTreeWithDuplicateNodes() throws Exception {
    SliceTreeStructure treeStructure = configureTree("Tuple");
    SliceNode root = (SliceNode)treeStructure.getRootElement();
    Collection<PsiElement> leaves = SliceLeafAnalyzer.calcLeafExpressions(root, treeStructure, SliceLeafAnalyzer.createMap());
    assertNotNull(leaves);
    assertEmpty(leaves);
  }
  public void testLeafExpressionsSimple() throws Exception {
    SliceTreeStructure treeStructure = configureTree("DupSlice");
    SliceNode root = (SliceNode)treeStructure.getRootElement();
    Collection<PsiElement> leaves = SliceLeafAnalyzer.calcLeafExpressions(root, treeStructure, SliceLeafAnalyzer.createMap());
    assertNotNull(leaves);
    PsiElement element = assertOneElement(leaves);
    assertTrue(element instanceof PsiLiteralExpression);
    assertEquals(1111111111, ((PsiLiteral)element).getValue());
  }
  public void testLeafExpressionsMoreComplex() throws Exception {
    SliceTreeStructure treeStructure = configureTree("Duplicate");
    SliceNode root = (SliceNode)treeStructure.getRootElement();
    Collection<PsiElement> leaves = SliceLeafAnalyzer.calcLeafExpressions(root, treeStructure, SliceLeafAnalyzer.createMap());
    assertNotNull(leaves);
    assertEquals(2, leaves.size());
    List<PsiElement> list = new ArrayList<PsiElement>(leaves);
    Collections.sort(list, new Comparator<PsiElement>() {
      @Override
      public int compare(PsiElement o1, PsiElement o2) {
        return o1.getText().compareTo(o2.getText());
      }
    });
    assertTrue(list.get(0) instanceof PsiLiteralExpression);
    assertEquals(false, ((PsiLiteral)list.get(0)).getValue());
    assertTrue(list.get(1) instanceof PsiLiteralExpression);
    assertEquals(true, ((PsiLiteral)list.get(1)).getValue());
  }

  public void testGroupByValuesCorrectLeaves() throws Exception {
    SliceTreeStructure treeStructure = configureTree("DuplicateLeaves");
    SliceRootNode root = (SliceRootNode)treeStructure.getRootElement();
    Map<SliceNode, Collection<PsiElement>> map = SliceLeafAnalyzer.createMap();
    Collection<PsiElement> leaves = SliceLeafAnalyzer.calcLeafExpressions(root, treeStructure, map);
    assertNotNull(leaves);
    assertEquals(1, leaves.size());
    PsiElement leaf = leaves.iterator().next();
    assertTrue(leaf instanceof PsiLiteralExpression);
    assertEquals("\"oo\"", leaf.getText());

    SliceRootNode newRoot = SliceLeafAnalyzer.createTreeGroupedByValues(leaves, root, map);
    Collection<? extends AbstractTreeNode> children = newRoot.getChildren();
    assertEquals(1, children.size());
    SliceNode child = (SliceNode)children.iterator().next();
    assertTrue(child instanceof SliceLeafValueRootNode);

    children = child.getChildren();
    assertEquals(1, children.size());
    child = (SliceNode)children.iterator().next();
    assertTrue(child.getValue().getElement() instanceof PsiField);

    children = child.getChildren();
    assertEquals(1, children.size());
    child = (SliceNode)children.iterator().next();
    assertTrue(child.getValue().getElement() instanceof PsiReferenceExpression);

    children = child.getChildren();
    assertEquals(1, children.size());
    child = (SliceNode)children.iterator().next();
    assertTrue(child.getValue().getElement() instanceof PsiReferenceExpression);

    children = child.getChildren();
    assertEquals(1, children.size());
    child = (SliceNode)children.iterator().next();
    assertTrue(child.getValue().getElement() instanceof PsiLiteralExpression);
    assertEquals(child.getValue().getElement(), leaf);
  }
  public void testNullness() throws Exception {
    SliceTreeStructure treeStructure = configureTree("Nulls");
    final SliceRootNode root = (SliceRootNode)treeStructure.getRootElement();
    Map<SliceNode, SliceNullnessAnalyzer.NullAnalysisResult> map = SliceNullnessAnalyzer.createMap();
    SliceNullnessAnalyzer.NullAnalysisResult leaves = SliceNullnessAnalyzer.calcNullableLeaves(root, treeStructure, map);

    SliceRootNode newRoot = SliceNullnessAnalyzer.createNewTree(leaves, root, map);

    checkStructure(newRoot, "Null Values\n" +
                            "  Value: o\n" +
                            "    (6: 12) |String| |l|;\n" +
                            "      (52: 13) |l| |=| |d|;\n" +
                            "        (15: 13) |set|(|o|)|;\n" +
                            "  Value: nu()\n" +
                            "    (6: 12) |String| |l|;\n" +
                            "      (52: 13) |l| |=| |d|;\n" +
                            "        (29: 13) |set|(|nu|(|)|)|;\n" +
                            "  Value: t\n" +
                            "    (6: 12) |String| |l|;\n" +
                            "      (52: 13) |l| |=| |d|;\n" +
                            "        (46: 15) |x|.|set|(|t|)|;\n" +
                            "NotNull Values\n" +
                            "  Value: \"\"\n" +
                            "    (6: 12) |String| |l|;\n" +
                            "      (52: 13) |l| |=| |d|;\n" +
                            "        (19: 13) |set|(|CON|)|;\n" +
                            "          (5: 39) |private| |final| |static| |String| |CON| |=| |\"\"|;\n" +
                            "  Value: \"xxx\"\n" +
                            "    (6: 12) |String| |l|;\n" +
                            "      (52: 13) |l| |=| |d|;\n" +
                            "        (10: 13) |set|(|\"xxx\"|)|;\n" +
                            "  Value: new String()\n" +
                            "    (6: 12) |String| |l|;\n" +
                            "      (52: 13) |l| |=| |d|;\n" +
                            "        (17: 13) |set|(|new| |String|(|)|)|;\n" +
                            "  Value: nn()\n" +
                            "    (6: 12) |String| |l|;\n" +
                            "      (52: 13) |l| |=| |d|;\n" +
                            "        (18: 13) |set|(|nn|(|)|)|;\n" +
                            "  Value: nn\n" +
                            "    (6: 12) |String| |l|;\n" +
                            "      (52: 13) |l| |=| |d|;\n" +
                            "        (21: 13) |set|(|nn|)|;\n" +
                            "  Value: g\n" +
                            "    (6: 12) |String| |l|;\n" +
                            "      (52: 13) |l| |=| |d|;\n" +
                            "        (27: 13) |set|(|g|)|;\n" +
                            "  Value: \"null\"\n" +
                            "    (6: 12) |String| |l|;\n" +
                            "      (52: 13) |l| |=| |d|;\n" +
                            "        (48: 15) |x|.|set|(|t| |==| |null| |?| |\"null\"| |:| |t|)|;\n" +
                            "          (48: 27) |x|.|set|(|t| |==| |null| |?| |\"null\"| |:| |t|)|;\n" +
                            "  Value: t\n" +
                            "    (6: 12) |String| |l|;\n" +
                            "      (52: 13) |l| |=| |d|;\n" +
                            "        (48: 15) |x|.|set|(|t| |==| |null| |?| |\"null\"| |:| |t|)|;\n" +
                            "          (48: 36) |x|.|set|(|t| |==| |null| |?| |\"null\"| |:| |t|)|;\n" +
                            "  Value: d\n" +
                            "    (6: 12) |String| |l|;\n" +
                            "      (55: 13) |l| |=| |d|;\n" +
                            "Other Values\n" +
                            "  Value: g\n" +
                            "    (6: 12) |String| |l|;\n" +
                            "      (52: 13) |l| |=| |d|;\n" +
                            "        (11: 13) |set|(|g|)|;\n" +
                            "        (24: 13) |set|(|other|)|;\n" +
                            "          (23: 24) |String| |other| |=| |g| |==| |\"\"| |?| |CON| |:| |g|;\n" +
                            "            (23: 40) |String| |other| |=| |g| |==| |\"\"| |?| |CON| |:| |g|;\n" +
                            "  Value: d\n" +
                            "    (6: 12) |String| |l|;\n" +
                            "      (52: 13) |l| |=| |d|;\n" +
                            "        (30: 13) |set|(|hz|(|)|)|;\n" +
                            "          (42: 16) |return| |d|;\n" +
                            "");
  }

  private static void checkStructure(final SliceNode root, @NonNls String dataExpected) {
    List<SliceNode> actualNodes = new ArrayList<SliceNode>((Collection<? extends SliceNode>)root.getChildren());
    Collections.sort(actualNodes, SliceTreeBuilder.SLICE_NODE_COMPARATOR);

    Object[] actualStrings = ContainerUtil.map2Array(actualNodes, new Function<SliceNode, Object>() {
      @Override
      public Object fun(SliceNode node) {
        return node.toString();
      }
    });

    String[] childrenExpected = dataExpected.length() == 0 ? ArrayUtil.EMPTY_STRING_ARRAY : dataExpected.split("\n");
    String curChildren = "";
    String curNode = null;
    int iactual = 0;
    for (int iexp = 0; iexp <= childrenExpected.length; iexp++) {
      String e = iexp == childrenExpected.length ? null : childrenExpected[iexp];
      boolean isTopLevel = e == null || e.charAt(0) != ' ';
      if (isTopLevel) {
        if (curNode != null) {
          assertTrue(iactual < actualStrings.length);
          Object actual = actualStrings[iactual];
          assertEquals(curNode, actual);
          checkStructure(actualNodes.get(iactual), curChildren);
          iactual++;
        }

        curNode = e;
        curChildren = "";
      }
      else {
        curChildren += StringUtil.trimStart(e, "  ") + "\n";
      }
    }
    assertEquals(actualNodes.size(), iactual);
  }

  public void testDoubleNullness() throws Exception {
    SliceTreeStructure treeStructure = configureTree("DoubleNulls");
    final SliceRootNode root = (SliceRootNode)treeStructure.getRootElement();
    Map<SliceNode, SliceNullnessAnalyzer.NullAnalysisResult> map = SliceNullnessAnalyzer.createMap();
    SliceNullnessAnalyzer.NullAnalysisResult leaves = SliceNullnessAnalyzer.calcNullableLeaves(root, treeStructure, map);

    SliceRootNode newRoot = SliceNullnessAnalyzer.createNewTree(leaves, root, map);
    checkStructure(newRoot,
        "Null Values\n" +
        "  Value: null\n" +
        "    (2: 10) |String| |l|;\n" +
        "      (4: 9) |l| |=| |null|;\n" +
        "      (7: 9) |l| |=| |null|;\n" +
        ""
                   );
  }
}


text:
import {
  Component,
  Input,
  Output,
  EventEmitter,
  ChangeDetectionStrategy,
  TemplateRef
} from '@angular/core';
import { formatLabel } from '../common/label.helper';
import { ColorHelper } from '../common/color.helper';

@Component({
  selector: 'g[ngx-charts-gauge-arc]',
  template: `
    <svg:g ngx-charts-pie-arc
      class="background-arc"
      [startAngle]="0"
      [endAngle]="backgroundArc.endAngle"
      [innerRadius]="backgroundArc.innerRadius"
      [outerRadius]="backgroundArc.outerRadius"
      [cornerRadius]="cornerRadius"
      [data]="backgroundArc.data"
      [animate]="false"
      [pointerEvents]="false">
    </svg:g>
    <svg:g ngx-charts-pie-arc
      [startAngle]="0"
      [endAngle]="valueArc.endAngle"
      [innerRadius]="valueArc.innerRadius"
      [outerRadius]="valueArc.outerRadius"
      [cornerRadius]="cornerRadius"
      [fill]="colors.getColor(valueArc.data.name)"
      [data]="valueArc.data"
      [animate]="true"
      [isActive]="isActive"
      (select)="select.emit($event)"
      (activate)="activate.emit($event)"
      (deactivate)="deactivate.emit($event)"
      ngx-tooltip
      [tooltipDisabled]="tooltipDisabled"
      [tooltipPlacement]="'top'"
      [tooltipType]="'tooltip'"
      [tooltipTitle]="tooltipTemplate ? undefined : tooltipText(valueArc)"
      [tooltipTemplate]="tooltipTemplate"
      [tooltipContext]="valueArc.data">
    </svg:g>
  `,
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class GaugeArcComponent {

  @Input() backgroundArc: any;
  @Input() valueArc: any;
  @Input() cornerRadius: any;
  @Input() colors: ColorHelper;
  @Input() isActive: boolean = false;
  @Input() tooltipDisabled: boolean = false;
  @Input() valueFormatting: (value: any) => string;
  @Input() tooltipTemplate: TemplateRef<any>;

  @Output() select = new EventEmitter();
  @Output() activate = new EventEmitter();
  @Output() deactivate = new EventEmitter();

  tooltipText(arc): string {
    const label = formatLabel(arc.data.name);
    let val;

    if(this.valueFormatting) {
      val = this.valueFormatting(arc.data.value);
    } else {
      val = formatLabel(arc.data.value);
    }

    return `
      ${label}
      ${val}
    `;
  }
}


text:
cask 'advancedrestclient' do
  version '13.0.7'
  sha256 '1abde754de131b3d2929036950bc363ceaa737abf140259a0938a026d5406c23'

  url "https://github.com/advanced-rest-client/arc-electron/releases/download/v#{version}/arc-#{version}.dmg"
  appcast 'https://github.com/advanced-rest-client/arc-electron/releases.atom'
  name 'Advanced Rest Client'
  homepage 'https://github.com/advanced-rest-client/arc-electron'

  app 'AdvancedRestClient.app'

  zap trash: [
               '~/Library/Application Support/advanced-rest-client',
               '~/Library/Logs/AdvancedRestClient',
             ]
end


text: All kinds of data brokers implemented using spark, e.g. sliding window streaming data broker


text:
require_relative "../proofs_init.rb"
require 'replay/test'

module Replay::SubscriptionManager::Proof
  def only_adds_legit_subs
    begin
      add_subscriber(Object.new)
    rescue Replay::InvalidSubscriberError => e
      return true
    end
    false
  end

  def sub_gets_notified
    sub = Class.new do
      attr_accessor :stream, :event
      def published(envelope)
        self.stream = envelope.stream_id
        self.event = envelope.event
      end
    end.new
    add_subscriber(sub)
    notify_subscribers "123", "456"
    sub.stream == '123' && sub.event == '456'
  end
end

title "Subscription Manager"

proof "raises InvalidSubscriberError when subscriber fails to implement #published" do
  sm = Replay::SubscriptionManager.new
  sm.prove { only_adds_legit_subs }
end

proof "notifies proper subscriber when informed" do
  sm = Replay::SubscriptionManager.new
  sm.prove { sub_gets_notified }
end


text:
namespace MediatR.Pipeline;

using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;

/// <summary>
/// Behavior for executing all <see cref="IRequestPreProcessor{TRequest}"/> instances before handling a request
/// </summary>
/// <typeparam name="TRequest"></typeparam>
/// <typeparam name="TResponse"></typeparam>
public class RequestPreProcessorBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
    where TRequest : IRequest<TResponse>
{
    private readonly IEnumerable<IRequestPreProcessor<TRequest>> _preProcessors;

    public RequestPreProcessorBehavior(IEnumerable<IRequestPreProcessor<TRequest>> preProcessors)
        => _preProcessors = preProcessors;

    public async Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TResponse> next, CancellationToken cancellationToken)
    {
        foreach (var processor in _preProcessors)
        {
            await processor.Process(request, cancellationToken).ConfigureAwait(false);
        }

        return await next().ConfigureAwait(false);
    }
}