text:
package com.playtika.test.storage;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Scanner;

@Slf4j
class GoogleCloudStorageHttpClient {

    //TODO: replace with HttpRequest from Java 11, when migrated
    public void sendUpdateConfigRequest(String containerEndpoint) throws IOException {
        HttpURLConnection connection = null;
        try {

            String requestBody = "{"
                    + "\"externalUrl\": \"" + containerEndpoint + "\""
                    + "}";

            URL url = new URL(containerEndpoint + "/_internal/config");
            connection = (HttpURLConnection) url.openConnection();
            connection.setConnectTimeout(5_000);
            connection.setReadTimeout(5_000);
            connection.setRequestMethod("PUT");
            connection.setDoOutput(true);
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("Accept", "application/json");
            try (OutputStreamWriter osw = new OutputStreamWriter(connection.getOutputStream())) {
                osw.write(requestBody);
                osw.flush();
            }

            int responseCode = connection.getResponseCode();

            if (responseCode != 200) {
                String response = getResponseBody(connection);
                log.error(
                        "error updating Google Cloud Fake Storage Server with external url, response status code {} != 200 message {}",
                        responseCode,
                        response);
            }
        } catch (Exception e) {
            log.error("error updating Google Cloud Fake Storage Server with external host", e);
            throw e;
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
    }

    private String getResponseBody(HttpURLConnection connection) throws IOException {
        try (InputStream inputStream = getStream(connection)) {
            InputStreamReader streamReader = new InputStreamReader(inputStream);
            Scanner s = new Scanner(streamReader).useDelimiter("\\A");
            return s.hasNext() ? s.next() : "";
        }
    }

    private InputStream getStream(HttpURLConnection connection) throws IOException {
        InputStream errorStream = connection.getErrorStream();
        return  errorStream != null ? errorStream : connection.getInputStream();
    }
}


text:
package tools.datasync.dao.jdbc;

public class JdbcCloseUtils {

    public static void closeRuntimeException(AutoCloseable... closables) {
	try {
	    for (AutoCloseable closable : closables) {
		if (closable != null) {
		    closable.close();
		}

	    }
	} catch (Exception e) {
	    throw (new RuntimeException(e));
	}
    }

}

redpajama_set_name: RedPajamaGithub


text:
{% extends "_layout_db.html" %}
{% block body %}

Documents

            Document ID
            Group ID
            Author
            Custodian
            Date Created
            Date Modified
            Date Received
            Date Sent

    {% for document in documents %}

                <input type="checkbox" class="form-check-input">

            {% if document.group_id and document.group_id != document.document_id %}    {% endif %}{{ document.document_id }}

        {{ document.group_id }}
        {% if document.author %}{{ document.author }}{% endif %}
        {% if document.custodian %}{{ document.custodian }}{% endif %}
        {{ document.date_created }}
        {{ document.date_modified }}
        {{ document.date_received }}
        {{ document.date_sent }}

    {% endfor %}

Load File

<form method="post" enctype="multipart/form-data">
    <input type="file" name="file">
    <button type="submit">Upload</button>
</form>
{% endblock %}


text:
CREATE TABLE readme_rendering (
    version_id INTEGER NOT NULL PRIMARY KEY,
    rendered_at TIMESTAMP WITHOUT TIME ZONE
);

ALTER TABLE readme_rendering
ADD CONSTRAINT "fk_readme_rendering_version_id"
FOREIGN KEY (version_id)
REFERENCES versions(id)
ON DELETE CASCADE;


text:
using System.ComponentModel;

namespace SettlementApi.Write.Model.Enums
{
    public enum AuditStatus
    {
        None = -1,
        [Description("未提交")] UnSubmit = 1,
        [Description("审核中")] Auditing = 2,
        [Description("通过")] Pass = 3,
        [Description("未通过")] Fail = 4
    }
}


text:
.class final Landroid/support/v4/app/FragmentTabHost$TabInfo;
.super Ljava/lang/Object;
.source "FragmentTabHost.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/support/v4/app/FragmentTabHost;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x18
    name = "TabInfo"
.end annotation

# instance fields
.field final args:Landroid/os/Bundle;
    .annotation build Landroid/support/annotation/Nullable;
    .end annotation
.end field

.field final clss:Ljava/lang/Class;
    .annotation build Landroid/support/annotation/NonNull;
    .end annotation

    .annotation system Ldalvik/annotation/Signature;
        value = {
            "Ljava/lang/Class",
            "<*>;"
        }
    .end annotation
.end field

.field fragment:Landroid/support/v4/app/Fragment;

.field final tag:Ljava/lang/String;
    .annotation build Landroid/support/annotation/NonNull;
    .end annotation
.end field

# direct methods
.method constructor <init>(Ljava/lang/String;Ljava/lang/Class;Landroid/os/Bundle;)V
    .registers 4
    .param p1, "_tag"    # Ljava/lang/String;
        .annotation build Landroid/support/annotation/NonNull;
        .end annotation
    .end param
    .param p2    # Ljava/lang/Class;
        .annotation build Landroid/support/annotation/NonNull;
        .end annotation
    .end param
    .param p3, "_args"    # Landroid/os/Bundle;
        .annotation build Landroid/support/annotation/Nullable;
        .end annotation
    .end param
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "(",
            "Ljava/lang/String;",
            "Ljava/lang/Class",
            "<*>;",
            "Landroid/os/Bundle;",
            ")V"
        }
    .end annotation

    .prologue
    .line 70
    .local p2, "_class":Ljava/lang/Class;, "Ljava/lang/Class<*>;"
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    .line 71
    iput-object p1, p0, Landroid/support/v4/app/FragmentTabHost$TabInfo;->tag:Ljava/lang/String;

    .line 72
    iput-object p2, p0, Landroid/support/v4/app/FragmentTabHost$TabInfo;->clss:Ljava/lang/Class;

    .line 73
    iput-object p3, p0, Landroid/support/v4/app/FragmentTabHost$TabInfo;->args:Landroid/os/Bundle;

    .line 74
    return-void
.end method


text:
package rpg

type Name string

func NameFactory(name string) ComponentFactory {
	n := Name(name)
	return n.Clone
}

var NameType = RegisterComponent(NameFactory(""))

func (n *Name) Clone(*Object) Component {
	clone := *n
	return &clone
}

func (n *Name) String() string {
	return string(*n)
}


text:
/**
 * Form for cars put in individually
 */
import {Component, OnDestroy, OnInit} from '@angular/core';
import {AppState, selectIsSignedIn, selectUser} from '../../reducers';
import {select, Store} from '@ngrx/store';
import {Subscription} from 'rxjs';

import {CarData} from '../../types/car-dto';

import {ActivatedRoute, Router} from '@angular/router';
import {GetSavedCarDataAction, ResetSavedCarDataAction} from '../../actions/car-data.actions';
import {distinctUntilChanged} from 'rxjs/operators';
import {AngularFireAuth} from '@angular/fire/auth';
import {User} from 'firebase';
import {SpinnerService} from '../../services/spinner.service';

@Component({
	selector: 'ssc-saved-cars',
	templateUrl: './saved-cars.component.html',
	styleUrls: []
})
export class SavedCarsComponent implements OnDestroy, OnInit {
	spinner = true;
	carData: CarData[] = [];
	private subscription: Subscription = new Subscription();

	constructor(private store: Store<AppState>,
				private router: Router,
				private route: ActivatedRoute,
				private authService: AngularFireAuth,
				private spinnerService: SpinnerService) {
	}

	ngOnInit() {
		// TODO: use resolved value?
		this.subscription.add(this.store.pipe(select(state => state.carData)).subscribe((carDataState) => {
			this.carData = carDataState.cars.sort((car1, car2) => car2.worth - car1.worth);
			// this.spinner = !this.carData.length;
		}));
		this.subscription.add(
			this.spinnerService.subscribe(waiting => {
				this.spinner = waiting;
			})
		);

		// TODO: resolver
		this.subscription.add(this.store.pipe(select(selectUser)).subscribe((user: User) => {
			if (user) {
				this.store.dispatch(new GetSavedCarDataAction(user));
			}
		}));

		// TODO: canActivate instead
		this.subscription.add(this.store.pipe(select(selectIsSignedIn), distinctUntilChanged()).subscribe((isSignedIn: boolean) => {
			if (!isSignedIn) {
				this.store.dispatch(new ResetSavedCarDataAction());
				this.router.navigate(['../'], {relativeTo: this.route});
			}
		}));
	}

	ngOnDestroy(): void {
		this.subscription.unsubscribe();
	}
}


text:
<?php
namespace Newsletter2Go;

interface EmailInterface
{

    public function getTo();

    public function setTo($to);

    public function getFrom();

    public function setFrom($from);

    public function getText();

    public function setText($text);

    public function getId();

    public function setId($id);

    public function getDate();

    public function setDate($date);

    public function getRef();

    public function setRef($ref);

    public function getSubject();

    public function setSubject($subject);

    public function getHtml();

    public function setHtml($html);

    public function getReply();

    public function setReply($reply);

    public function getLinktracking();

    public function setLinktracking($linktracking);

    public function getOpentracking();

    public function setOpentracking($opentracking);
}


text:
namespace SQLServerSearcher
{
    partial class FrmAbout
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FrmAbout));
            this.tableLayoutPanel = new System.Windows.Forms.TableLayoutPanel();
            this.logoPictureBox = new System.Windows.Forms.PictureBox();
            this.labelProductName = new System.Windows.Forms.Label();
            this.labelVersion = new System.Windows.Forms.Label();
            this.textBoxDescription = new System.Windows.Forms.TextBox();
            this.okButton = new System.Windows.Forms.Button();
            this.tableLayoutPanel.SuspendLayout();
            ((System.ComponentModel.ISupportInitialize)(this.logoPictureBox)).BeginInit();
            this.SuspendLayout();
            //
            // tableLayoutPanel
            //
            this.tableLayoutPanel.ColumnCount = 2;
            this.tableLayoutPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 33F));
            this.tableLayoutPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 67F));
            this.tableLayoutPanel.Controls.Add(this.logoPictureBox, 0, 0);
            this.tableLayoutPanel.Controls.Add(this.labelProductName, 1, 0);
            this.tableLayoutPanel.Controls.Add(this.labelVersion, 1, 1);
            this.tableLayoutPanel.Controls.Add(this.textBoxDescription, 1, 4);
            this.tableLayoutPanel.Controls.Add(this.okButton, 1, 5);
            this.tableLayoutPanel.Dock = System.Windows.Forms.DockStyle.Fill;
            this.tableLayoutPanel.Location = new System.Drawing.Point(14, 14);
            this.tableLayoutPanel.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5);
            this.tableLayoutPanel.Name = "tableLayoutPanel";
            this.tableLayoutPanel.RowCount = 6;
            this.tableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 10F));
            this.tableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 10F));
            this.tableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 10F));
            this.tableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 10F));
            this.tableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F));
            this.tableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 10F));
            this.tableLayoutPanel.Size = new System.Drawing.Size(624, 407);
            this.tableLayoutPanel.TabIndex = 0;
            //
            // logoPictureBox
            //
            this.logoPictureBox.Dock = System.Windows.Forms.DockStyle.Fill;
            this.logoPictureBox.Image = global::SQLServerSearcher.Properties.Resources.database_search1;
            this.logoPictureBox.Location = new System.Drawing.Point(4, 5);
            this.logoPictureBox.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5);
            this.logoPictureBox.Name = "logoPictureBox";
            this.tableLayoutPanel.SetRowSpan(this.logoPictureBox, 6);
            this.logoPictureBox.Size = new System.Drawing.Size(197, 397);
            this.logoPictureBox.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize;
            this.logoPictureBox.TabIndex = 12;
            this.logoPictureBox.TabStop = false;
            //
            // labelProductName
            //
            this.labelProductName.Dock = System.Windows.Forms.DockStyle.Fill;
            this.labelProductName.Location = new System.Drawing.Point(214, 0);
            this.labelProductName.Margin = new System.Windows.Forms.Padding(9, 0, 4, 0);
            this.labelProductName.MaximumSize = new System.Drawing.Size(0, 26);
            this.labelProductName.Name = "labelProductName";
            this.labelProductName.Size = new System.Drawing.Size(406, 26);
            this.labelProductName.TabIndex = 19;
            this.labelProductName.Text = "Product";
            this.labelProductName.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
            //
            // labelVersion
            //
            this.labelVersion.Dock = System.Windows.Forms.DockStyle.Fill;
            this.labelVersion.Location = new System.Drawing.Point(214, 40);
            this.labelVersion.Margin = new System.Windows.Forms.Padding(9, 0, 4, 0);
            this.labelVersion.MaximumSize = new System.Drawing.Size(0, 26);
            this.labelVersion.Name = "labelVersion";
            this.labelVersion.Size = new System.Drawing.Size(406, 26);
            this.labelVersion.TabIndex = 0;
            this.labelVersion.Text = "Version";
            this.labelVersion.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
            //
            // textBoxDescription
            //
            this.textBoxDescription.Dock = System.Windows.Forms.DockStyle.Fill;
            this.textBoxDescription.Location = new System.Drawing.Point(214, 165);
            this.textBoxDescription.Margin = new System.Windows.Forms.Padding(9, 5, 4, 5);
            this.textBoxDescription.Multiline = true;
            this.textBoxDescription.Name = "textBoxDescription";
            this.textBoxDescription.ReadOnly = true;
            this.textBoxDescription.ScrollBars = System.Windows.Forms.ScrollBars.Both;
            this.textBoxDescription.Size = new System.Drawing.Size(406, 193);
            this.textBoxDescription.TabIndex = 23;
            this.textBoxDescription.TabStop = false;
            this.textBoxDescription.Text = "Description";
            //
            // okButton
            //
            this.okButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
            this.okButton.DialogResult = System.Windows.Forms.DialogResult.Cancel;
            this.okButton.Location = new System.Drawing.Point(508, 368);
            this.okButton.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5);
            this.okButton.Name = "okButton";
            this.okButton.Size = new System.Drawing.Size(112, 34);
            this.okButton.TabIndex = 1;
            this.okButton.Text = "&OK";
            //
            // FrmAbout
            //
            this.AcceptButton = this.okButton;
            this.AutoScaleDimensions = new System.Drawing.SizeF(9F, 20F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(652, 435);
            this.Controls.Add(this.tableLayoutPanel);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
            this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
            this.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5);
            this.MaximizeBox = false;
            this.MinimizeBox = false;
            this.Name = "FrmAbout";
            this.Padding = new System.Windows.Forms.Padding(14);
            this.ShowIcon = false;
            this.ShowInTaskbar = false;
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
            this.Text = "About";
            this.Load += new System.EventHandler(this.FrmAbout_Load);
            this.tableLayoutPanel.ResumeLayout(false);
            this.tableLayoutPanel.PerformLayout();
            ((System.ComponentModel.ISupportInitialize)(this.logoPictureBox)).EndInit();
            this.ResumeLayout(false);

        }

        #endregion

        private System.Windows.Forms.TableLayoutPanel tableLayoutPanel;
        private System.Windows.Forms.PictureBox logoPictureBox;
        private System.Windows.Forms.Label labelProductName;
        private System.Windows.Forms.Label labelVersion;
        private System.Windows.Forms.TextBox textBoxDescription;
        private System.Windows.Forms.Button okButton;
    }
}


text:
<?php
namespace Milk\WebService;

use \F3;

use \Milk\Utils\Validator;

class Service {

    //! Validator constants
	const OPTIONAL = Validator::OPTIONAL;
	const REQUIRED = Validator::REQUIRED;

    public function __construct($transport, $request) {
        $this->transport = $transport;
        $this->current_request = $request;
    }

    /**
		CRUD placeholder functions
	**/
	public function create() {
		return $this->error(501);
	}

	public function retrieve() {
		return $this->error(501);
	}

	public function update() {
		return $this->error(501);
	}

	public function delete() {
		return $this->error(501);
	}

    public function options() {
		$ref = new ReflectionClass(get_class($this));
		$data = $ref->getMethods(ReflectionMethod::IS_PUBLIC);
		$this->results(200, $data);
	}

    /**
		Validation
	**/
	protected function validate($fields, $values=null) {
		//! instantiate validator
		$validator = new Validator();

		//! if there's no values passed, use args from current request
		$values = $values ? $values : $this->current_request->args;

		//! build fields array
		foreach ($fields as $name => $opt) {
			$field = array('validate' => $opt);
			if (isset($values->$name)) {
				$field['value'] = (array)$values->$name;
			}
			$fields[$name] = $field;
		}

		//! convert from object to array
		if (is_object($fields))
			$fields = $this->objectToArray($fields);

		$validator->setFields($fields);
	    $this->valid = $validator->validate();
		if (!$this->valid)
			$this->errors = $validator->getErrors();

		//! return validation result
		return $this->valid;
	}

	protected function objectToArray($mixed) {
		if(is_object($mixed)) $mixed = (array)$mixed;
		if(is_array($mixed)) {
			$new = array();
			foreach($mixed as $key => $val) {
				$key = preg_replace("/^\\0(.*)\\0/","",$key);
				$new[$key] = $this->objectToArray($val);
			}
		}
		else $new = $mixed;
		return $new;
	}

	protected function getErrors() {
		return $this->errors;
	}

    /**
		Transport responses
	**/
	protected function result($data, $cache=false, $http_code=200) {
		return $this->transport->result($data, $cache, $http_code, $this->current_request->id);
	}

	protected function success($result, $data=null, $cache=null, $http_code=200) {
		return $this->transport->success($result, $data, $cache, $http_code, $this->current_request->id);
	}

	protected function error($http_code=500, $error=null, $data=null) {
		return $this->transport->error($http_code, $error, $data, $this->current_request->id);
	}

	/**
		Shorthand functions
	**/
	protected function syntaxError($error=null, $data=null) {
		return $this->error(400, $error, $data);
	}

	protected function conflict($object='', $data=null) {
		return $this->error(409, $object.' already exists', $data);
	}

	protected function notFound($object, $data=null) {
		return $this->error(404, $object.' could not be found', $data);
	}

	protected function created($object, $data=null) {
		return $this->success($object.' created', $data, false, 201);
	}

	protected function updated($object, $data=null) {
		return $this->success($object.' updated', $data, false);
	}

	protected function deleted($object, $data=null) {
		return $this->success($object.' deleted', $data, false);
	}
}


text:
package ca.uhn.fhir.rest.server.method;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import ca.uhn.fhir.util.ParametersUtil;
import org.hl7.fhir.instance.model.api.IBaseResource;

import ca.uhn.fhir.context.FhirContext;
import ca.uhn.fhir.model.valueset.BundleTypeEnum;
import ca.uhn.fhir.rest.annotation.OperationParam;
import ca.uhn.fhir.rest.annotation.Validate;
import ca.uhn.fhir.rest.api.Constants;
import ca.uhn.fhir.rest.api.EncodingEnum;

public class ValidateMethodBindingDstu2Plus extends OperationMethodBinding {

	public ValidateMethodBindingDstu2Plus(Class<?> theReturnResourceType, Class<? extends IBaseResource> theReturnTypeFromRp, Method theMethod, FhirContext theContext, Object theProvider,
			Validate theAnnotation) {
		super(theReturnResourceType, theReturnTypeFromRp, theMethod, theContext, theProvider, true, Constants.EXTOP_VALIDATE, theAnnotation.type(), null, new OperationParam[0], BundleTypeEnum.COLLECTION, false);

		List<IParameter> newParams = new ArrayList<>();
		int idx = 0;
		for (IParameter next : getParameters()) {
			if (next instanceof ResourceParameter) {
				if (IBaseResource.class.isAssignableFrom(((ResourceParameter) next).getResourceType())) {
					Class<?> parameterType = theMethod.getParameterTypes()[idx];
					if (String.class.equals(parameterType) || EncodingEnum.class.equals(parameterType)) {
						newParams.add(next);
					} else {
						Annotation[] parameterAnnotations = theMethod.getParameterAnnotations()[idx];
						String description = ParametersUtil.extractDescription(parameterAnnotations);
						List<String> examples = ParametersUtil.extractExamples(parameterAnnotations);
						OperationParameter parameter = new OperationParameter(theContext, Constants.EXTOP_VALIDATE, Constants.EXTOP_VALIDATE_RESOURCE, 0, 1, description, examples);
						parameter.initializeTypes(theMethod, null, null, parameterType);
						newParams.add(parameter);
					}
				} else {
					newParams.add(next);
				}
			} else {
				newParams.add(next);
			}
			idx++;
		}
		setParameters(newParams);

	}

}


text:
"""
@brief      test log(time=131s)
"""
import sys
import os
import unittest
from pyquickhelper.loghelper import fLOG
from pyquickhelper.pycode import get_temp_folder
from pymyinstall.installcustom import install_graphviz

class TestGraphviz(unittest.TestCase):

    def test_install_graphviz(self):
        fLOG(
            __file__,
            self._testMethodName,
            OutputPrint=__name__ == "__main__")

        if sys.version_info[0] == 2:
            return

        fold = os.path.abspath(os.path.split(__file__)[0])
        temp = os.path.join(fold, "temp_graphviz")
        if not os.path.exists(temp):
            os.mkdir(temp)
        for _ in os.listdir(temp):
            f = os.path.join(temp, _)
            if os.path.isfile(f):
                os.remove(f)

        if sys.platform.startswith("win"):
            r = install_graphviz(temp, fLOG=fLOG, install=False, source="2")
            exe = os.path.abspath(r)
            self.assertTrue(os.path.exists(exe))

    def test_install_graphviz_zip(self):
        fLOG(
            __file__,
            self._testMethodName,
            OutputPrint=__name__ == "__main__")

        if sys.version_info[0] == 2:
            return

        temp = get_temp_folder(__file__, "temp_graphviz_zip")

        if sys.platform.startswith("win"):
            r = install_graphviz(temp, fLOG=fLOG, install=True, source="zip")
            exe = os.path.abspath(r)
            self.assertTrue(os.path.exists(exe))
            exe = os.path.join(temp, "Graphviz", "bin", "dot.exe")
            self.assertTrue(os.path.exists(exe))

if __name__ == "__main__":
    unittest.main()


text:
rmdir /s /q build
rmdir /s /q dist
venv\scripts\python.exe setup.py py2exe
REM venv\scripts\python.exe setup.py sdist
REM venv\scripts\python.exe setup.py bdist_msi


text:
require 'test_helper'

module Elasticsearch
  module Test
    class IndicesStatsTest < ::Test::Unit::TestCase

      context "Indices: Stats" do
        subject { FakeClient.new }

        should "perform correct request" do
          subject.expects(:perform_request).with do |method, url, params, body|
            assert_equal 'GET', method
            assert_equal '_stats', url
            assert_equal Hash.new, params
            assert_nil   body
            true
          end.returns(FakeResponse.new)

          subject.indices.stats
        end

        should "perform request against an index" do
          subject.expects(:perform_request).with do |method, url, params, body|
            assert_equal 'foo/_stats', url
            true
          end.returns(FakeResponse.new)

          subject.indices.stats :index => 'foo'
        end

        should "perform request against multiple indices" do
          subject.expects(:perform_request).with do |method, url, params, body|
            assert_equal 'foo,bar/_stats', url
            true
          end.returns(FakeResponse.new).twice

          subject.indices.stats :index => ['foo','bar']
          subject.indices.stats :index => 'foo,bar'
        end

        should "pass the URL parameters" do
          subject.expects(:perform_request).with do |method, url, params, body|
            assert_equal 'foo/_stats', url
            assert_equal true, params[:fielddata]
            true
          end.returns(FakeResponse.new)

          subject.indices.stats :index => 'foo', :fielddata => true
        end

        should "URL-escape the parts" do
          subject.expects(:perform_request).with do |method, url, params, body|
            assert_equal 'foo%5Ebar/_stats', url
            true
          end.returns(FakeResponse.new)

          subject.indices.stats :index => 'foo^bar'
        end

        should "pass the fields parameter as a list" do
          subject.expects(:perform_request).with do |method, url, params, body|
            assert_equal 'foo/_stats', url
            assert_equal true, params[:fielddata]
            assert_equal 'foo,bar', params[:fields]
            true
          end.returns(FakeResponse.new)

          subject.indices.stats :index => 'foo', :fielddata => true, :fields => ['foo', 'bar']
        end

        should "pass the groups parameter as a list" do
          subject.expects(:perform_request).with do |method, url, params, body|
            assert_equal '_stats', url
            assert_equal 'groupA,groupB', params[:groups]
            true
          end.returns(FakeResponse.new)

          subject.indices.stats :search => true, :groups => ['groupA','groupB']
        end

      end

    end
  end
end


text:
#ifndef BABYLON_POSTPROCESSES_VR_MULTIVIEW_TO_SINGLEVIEW_POST_PROCESS_H
#define BABYLON_POSTPROCESSES_VR_MULTIVIEW_TO_SINGLEVIEW_POST_PROCESS_H

#include <babylon/babylon_api.h>
#include <babylon/postprocesses/post_process.h>

namespace BABYLON {

/**
 * @brief VRMultiviewToSingleview used to convert multiview texture arrays to standard textures for
 * scenarios such as webVR This will not be used for webXR as it supports displaying texture arrays
 * directly
 */
class BABYLON_SHARED_EXPORT VRMultiviewToSingleviewPostProcess : public PostProcess {

public:
  /**
   * @brief Initializes a VRMultiviewToSingleview.
   * @param name name of the post process
   * @param camera camera to be applied to
   * @param scaleFactor scaling factor to the size of the output texture
   */
  VRMultiviewToSingleviewPostProcess(const std::string& name, const CameraPtr& camera,
                                     float scaleFactor);
  ~VRMultiviewToSingleviewPostProcess() override; // = default

  /**
   * @brief Gets a string identifying the name of the class.
   * @returns "VRMultiviewToSingleviewPostProcess" string
   */
  std::string getClassName() const override;

}; // end of class VRDistortionCorrectionPostProcess

} // end of namespace BABYLON

#endif // end of BABYLON_POSTPROCESSES_VR_MULTIVIEW_TO_SINGLEVIEW_POST_PROCESS_H


text:
#import "HL7ResultSectionParser.h"
#import "HL7Const.h"
#import "HL7CCD.h"
#import "HL7ResultSection.h"
#import "HL7ResultEntry.h"
#import "HL7ResultOrganizer.h"
#import "HL7ResultOrganizerParser.h"
#import "IGXMLReader.h"
#import "IGXMLReader+Additions.h"
#import "ParserContext.h"

@implementation HL7ResultSectionParser

- (NSString *)templateId
{
    return HL7TemplateResultsEntriesRequired;
}

- (BOOL)supportsEntries
{
    return YES;
}

- (nullable HL7Section *)createSectionFromSection:(nullable HL7Section *)section
{
    return [[HL7ResultSection alloc] initWithSection:section];
}

- (HL7Entry *_Nullable)createEntryWithNode:(IGXMLReader *_Nonnull)node
{
    return [[HL7ResultEntry alloc] initWithTypeCode:[node attributeWithName:HL7AttributeTypeCode]];
}

- (void)parse:(ParserContext *)context node:(IGXMLReader *)node into:(HL7Entry *)entry error:(NSError *__autoreleasing *)error
{
    HL7ResultSection *section = (HL7ResultSection *)[context section];

    if ([node isStartOfElementWithName:HL7ElementEntry]) {
        [[section entries] addObject:entry]; // Add entry
    } else if ([node isStartOfElementWithName:HL7ElementOrganizer]) {
        HL7ResultOrganizer *organizer = [HL7ResultOrganizer new];
        [context setElement:organizer];
        [[HL7ResultOrganizerParser new] parse:context error:error];
        [((HL7ResultEntry *)entry) setOrganizer:organizer];
    }
}

- (BOOL)parse:(ParserContext *)context error:(NSError *__autoreleasing *)error
{
    [super parse:context error:error];
    [[[context hl7ccd] sections] addObject:[context section]];
    return YES;
}
@end


text:
package br.com.uol.pagseguro.domain;

import java.util.HashMap;
import java.util.Map;

/**
 * Identifies a PagSeguro account
 */
public class AccountCredentials extends Credentials {

    /**
     * Primary email associated with this account
     */
    private String email;

    /**
     * PagSeguro token
     */
    private String token;

    /**
     * *
     * Initializes a new instance of the AccountCredentials class
     *
     * @param email
     * @param token
     */
    public AccountCredentials(String email, String token) {

        if (email == null || email.trim().equals("") || token == null || token.trim().equals("")) {
            throw new RuntimeException("You must enter your credentials when instantiating ReceiverCredentials."
                    + " Currently email=[" + email + "] and token=[" + token + "].");
        }

        this.email = email.trim();
        this.token = token.trim();
    }

    /* (non-Javadoc)
     * @see br.com.uol.pagseguro.domain.Credentials#getAttributes()
     */
    public Map getAttributes() {
        Map attributeMap = new HashMap(3);
        attributeMap.put("email", this.email);
        attributeMap.put("token", this.token);
        return attributeMap;
    }

}


text:
package org.plexian.grumy.configuration;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.InputStream;

import org.plexian.grumy.Game;
import org.plexian.grumy.launcher.Launcher;

/**
 *
 * @author walt
 * @category Configuration
 */
public abstract class FileConfiguration extends Configuration {
    /**
     * This is an object that points to the folder that holds all our
     * configuration.
     */
    public static File CONFIGURATION_FOLDER = new File(Launcher.GAME_FOLDER, "config/");

    /**
     * This is a file object for the configuration.
     */
    protected File configFile;

    /**
     * This is a string that holds the YAML string.
     */
    protected String data;

    /**
     * Creates a new instance of FileConfiguration, creating the config
     * directory in the process.
     */
    public FileConfiguration() {
        CONFIGURATION_FOLDER.mkdirs();
    }

    /**
     * Gets the given configuration as a File.
     *
     * @param s
     *            The name of the configuration.
     * @return A file object to the file, or CONFIGURATION_FOLDER if given
     *         filename is a directory.
     */
    public File getConfiguration(String s) {
        File f = new File(FileConfiguration.CONFIGURATION_FOLDER, s);

        if (f.isDirectory()) {
            return CONFIGURATION_FOLDER;
        }

        try {
            // f.delete();
            f.createNewFile();
        } catch (Exception e) {
            Game.LOG.info("Exception: " + e.getMessage());
        }

        this.configFile = f;

        return f;
    }

    public File getConfiguration(String s, File directory) {
        File f = new File(directory, s);

        if (f.isDirectory()) {
            return directory;
        }

        try {
            // f.delete();
            f.createNewFile();
        } catch (Exception e) {
            Game.LOG.info("Exception: " + e.getMessage());
        }

        this.configFile = f;

        return f;
    }

    /**
     * Reads a configuration file into a string which can be pumped into a
     * parser.
     *
     * @param s
     *            The name of the file to read.
     * @return The contents of the file, or "" if no such file/directory.
     */
    public String loadConfiguration(String s) {
        File f = getConfiguration(s);
        String everything = "";

        if (f.isDirectory()) {
            return "";
        }

        BufferedReader br = null;

        try {
            br = new BufferedReader(new FileReader(f));
            StringBuilder sb = new StringBuilder();
            String line = br.readLine();

            while (line != null) {
                sb.append(line);
                sb.append(System.lineSeparator());
                line = br.readLine();
            }

            everything = sb.toString();

            br.close();
        } catch (Exception e) {
            Game.LOG.warning("Exception: " + e.getMessage());
        }

        return everything;
    }

    public String loadConfiguration(String s, File directory) {
        File f = getConfiguration(s, directory);
        String everything = "";

        if (f.isDirectory()) {
            return "";
        }

        BufferedReader br = null;

        try {
            br = new BufferedReader(new FileReader(f));
            StringBuilder sb = new StringBuilder();
            String line = br.readLine();

            while (line != null) {
                sb.append(line);
                sb.append(System.lineSeparator());
                line = br.readLine();
            }

            everything = sb.toString();

            br.close();
        } catch (Exception e) {
            Game.LOG.warning("Exception: " + e.getMessage());
        }

        return everything;
    }

    /**
     * Gets the configuration as an input stream, reading from a file.
     *
     * @param s
     *            The configuration name.
     * @return The input stream if file exists, or null if not.
     */
    public InputStream getConfigurationAsStream(String s) {
        InputStream in = null;

        try {
            in = new FileInputStream(getConfiguration(s));
        } catch (Exception e) {
            Game.LOG.warning("Exception: " + e.getMessage());
        }

        return in;
    }

    public InputStream getConfigurationAsStream(String s, File directory) {
        InputStream in = null;

        try {
            in = new FileInputStream(getConfiguration(s, directory));
        } catch (Exception e) {
            Game.LOG.warning("Exception: " + e.getMessage());
        }

        return in;
    }

    /**
     * Saves configuration to file.
     */
    public void save() {
        try {
            FileWriter fileWriter = new FileWriter(this.configFile);
            BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);

            bufferedWriter.write(this.data);
            bufferedWriter.close();
        } catch (Exception e) {
            Game.LOG.severe("Exception: " + e.getMessage());
        }
    }
}


text:
{% comment %}
	generates a navigation based on _config.yml
{% endcomment %}

{% assign locale = site.locales[page.locale] %}
{% assign routing = locale.routing %}
{% assign i18n = locale.i18n %}

{{i18n['navigation']}}

{% for item in site.navigation %}
	{% if routing.routes[item] %}

		{% assign current = nil %}
		{% assign route = routing.routes[item] %}

		{% if page.key == route.key or page.super == route.key %}
			{% assign current = true %}
		{% endif %}

		{% capture url %}{{routing.base}}{{route.url}}{% endcapture %}

{{i18n[route.title]}}

	{% else %}

MISSING NAVIGATION ROUTE:
 "{{item}}" not found

	{% endif %}
{% endfor %}


text:
* [Added] Update HTTP config spec templates. See [#12890](https://github.com/DataDog/integrations-core/pull/12890).

## 2.0.2 / 2022-08-05 / Agent 7.39.0

* [Fixed] Dependency updates. See [#12653](https://github.com/DataDog/integrations-core/pull/12653).

## 2.0.1 / 2022-04-05 / Agent 7.36.0

* [Fixed] Remove check options from jmx template. See [#11686](https://github.com/DataDog/integrations-core/pull/11686).
* [Fixed] Remove outdated warning in the description for the `tls_ignore_warning` option. See [#11591](https://github.com/DataDog/integrations-core/pull/11591).

## 2.0.0 / 2022-02-19 / Agent 7.35.0

* [Added] Add `pyproject.toml` file. See [#11435](https://github.com/DataDog/integrations-core/pull/11435).
* [Fixed] Fix namespace packaging on Python 2. See [#11532](https://github.com/DataDog/integrations-core/pull/11532).
* [Changed] Add tls_protocols_allowed option documentation. See [#11251](https://github.com/DataDog/integrations-core/pull/11251).

## 1.5.2 / 2022-01-08 / Agent 7.34.0

* [Fixed] Bump base check dependency. See [#10926](https://github.com/DataDog/integrations-core/pull/10926).
* [Fixed] Add comment to autogenerated model files. See [#10945](https://github.com/DataDog/integrations-core/pull/10945).

## 1.5.1 / 2021-11-13 / Agent 7.33.0

* [Fixed] Fix description of JMX options. See [#10454](https://github.com/DataDog/integrations-core/pull/10454).

## 1.5.0 / 2021-10-04 / Agent 7.32.0

* [Added] Add HTTP option to control the size of streaming responses. See [#10183](https://github.com/DataDog/integrations-core/pull/10183).
* [Added] Add allow_redirect option. See [#10160](https://github.com/DataDog/integrations-core/pull/10160).
* [Added] Disable generic tags. See [#10027](https://github.com/DataDog/integrations-core/pull/10027).
* [Fixed] Fix the description of the `allow_redirects` HTTP option. See [#10195](https://github.com/DataDog/integrations-core/pull/10195).

## 1.4.0 / 2021-08-22 / Agent 7.31.0

* [Added] Use `display_default` as a fallback for `default` when validating config models. See [#9739](https://github.com/DataDog/integrations-core/pull/9739).

## 1.3.0 / 2021-07-12 / Agent 7.30.0

* [Added] Enable `new_gc_metrics` JMX config option for new installations. See [#9501](https://github.com/DataDog/integrations-core/pull/9501).

## 1.2.0 / 2021-05-28 / Agent 7.29.0

* [Added] Add runtime configuration validation. See [#8985](https://github.com/DataDog/integrations-core/pull/8985).
* [Fixed] Fix defaults for `collect_default_metrics` JMX config option. See [#9441](https://github.com/DataDog/integrations-core/pull/9441).
* [Fixed] Fix JMX config spec. See [#9364](https://github.com/DataDog/integrations-core/pull/9364).

## 1.1.2 / 2021-03-12 / Agent 7.27.0

* [Fixed] Fix collection of PendingTime. See [#8817](https://github.com/DataDog/integrations-core/pull/8817).

## 1.1.1 / 2021-02-16

* [Fixed] Fix automatic discovery of metrics from web API and improve example config documentation. See [#8552](https://github.com/DataDog/integrations-core/pull/8552).
* [Fixed] Bump minimum base package version. See [#8443](https://github.com/DataDog/integrations-core/pull/8443).

## 1.1.0 / 2020-12-11 / Agent 7.25.0

* [Added] Document new collect_default_jvm_metrics flag for JMXFetch integrations. See [#8153](https://github.com/DataDog/integrations-core/pull/8153).

## 1.0.0 / 2020-11-20

* [Added] Add SonarQube integration. See [#7807](https://github.com/DataDog/integrations-core/pull/7807).


text:
class AddUserToLinks < ActiveRecord::Migration
  def self.up
    add_column :links, :user_id, :integer
  end

  def self.down
    remove_column :links, :user_id
  end
end


text:
'use strict';

angular.module('copayApp.controllers').controller('createController',
  function($scope, $rootScope, $timeout, $log, lodash, $state, $ionicScrollDelegate, $ionicHistory, profileService, configService, gettextCatalog, ledger, trezor, intelTEE, derivationPathHelper, ongoingProcess, walletService, storageService, popupService, appConfigService, pushNotificationsService) {

    /* For compressed keys, m*73 + n*34 <= 496 */
    var COPAYER_PAIR_LIMITS = {
      1: 1,
      2: 2,
      3: 3,
      4: 4,
      5: 4,
      6: 4,
      7: 3,
      8: 3,
      9: 2,
      10: 2,
      11: 1,
      12: 1,
    };

    $scope.$on("$ionicView.beforeEnter", function(event, data) {
      $scope.formData = {};
      var defaults = configService.getDefaults();
      var tc = $state.current.name == 'tabs.add.create-personal' ? 1 : defaults.wallet.totalCopayers;
      $scope.formData.account = 1;
      $scope.formData.bwsurl = defaults.bws.url;
      $scope.TCValues = lodash.range(2, defaults.limits.totalCopayers + 1);
      $scope.formData.derivationPath = derivationPathHelper.default;
      $scope.setTotalCopayers(tc);
      updateRCSelect(tc);
      resetPasswordFields();
    });

    $scope.showAdvChange = function() {
      $scope.showAdv = !$scope.showAdv;
      $scope.encrypt = null;
      $scope.resizeView();
    };

    $scope.checkPassword = function(pw1, pw2) {
      if (pw1 && pw1.length > 0) {
        if (pw2 && pw2.length > 0) {
          if (pw1 == pw2) $scope.result = 'correct';
          else {
            $scope.formData.passwordSaved = null;
            $scope.result = 'incorrect';
          }
        } else
          $scope.result = null;
      } else
        $scope.result = null;
    };

    $scope.resizeView = function() {
      $timeout(function() {
        $ionicScrollDelegate.resize();
      }, 10);
      resetPasswordFields();
    };

    function resetPasswordFields() {
      $scope.formData.passphrase = $scope.formData.createPassphrase = $scope.formData.passwordSaved = $scope.formData.repeatPassword = $scope.result = null;
      $timeout(function() {
        $scope.$apply();
      });
    };

    function updateRCSelect(n) {
      $scope.formData.totalCopayers = n;
      var maxReq = COPAYER_PAIR_LIMITS[n];
      $scope.RCValues = lodash.range(1, maxReq + 1);
      $scope.formData.requiredCopayers = Math.min(parseInt(n / 2 + 1), maxReq);
    };

    function updateSeedSourceSelect(n) {
      var seedOptions = [{
        id: 'new',
        label: gettextCatalog.getString('Random'),
        supportsTestnet: true
      }, {
        id: 'set',
        label: gettextCatalog.getString('Specify Recovery Phrase...'),
        supportsTestnet: false
      }];

      $scope.formData.seedSource = seedOptions[0];

      /*

      Disable Hardware Wallets for DigiByte Foundation distribution

      */

      if (appConfigService.name == 'digibytego') {
        if (n > 1 && walletService.externalSource.ledger.supported)
          seedOptions.push({
            id: walletService.externalSource.ledger.id,
            label: walletService.externalSource.ledger.longName,
            supportsTestnet: walletService.externalSource.ledger.supportsTestnet
          });

        if (walletService.externalSource.trezor.supported) {
          seedOptions.push({
            id: walletService.externalSource.trezor.id,
            label: walletService.externalSource.trezor.longName,
            supportsTestnet: walletService.externalSource.trezor.supportsTestnet
          });
        }

        if (walletService.externalSource.intelTEE.supported) {
          seedOptions.push({
            id: walletService.externalSource.intelTEE.id,
            label: walletService.externalSource.intelTEE.longName,
            supportsTestnet: walletService.externalSource.intelTEE.supportsTestnet
          });
        }
      }

      $scope.seedOptions = seedOptions;
    };

    $scope.setTotalCopayers = function(tc) {
      $scope.formData.totalCopayers = tc;
      updateRCSelect(tc);
      updateSeedSourceSelect(tc);
    };

    $scope.create = function() {

      var opts = {
        name: $scope.formData.walletName,
        m: $scope.formData.requiredCopayers,
        n: $scope.formData.totalCopayers,
        myName: $scope.formData.totalCopayers > 1 ? $scope.formData.myName : null,
        networkName: $scope.formData.testnetEnabled ? 'testnet' : 'livenet',
        bwsurl: $scope.formData.bwsurl,
        singleAddress: $scope.formData.singleAddressEnabled,
        walletPrivKey: $scope.formData._walletPrivKey, // Only for testing
      };

      var setSeed = $scope.formData.seedSource.id == 'set';
      if (setSeed) {

        var words = $scope.formData.privateKey || '';
        if (words.indexOf(' ') == -1 && words.indexOf('prv') == 1 && words.length > 108) {
          opts.extendedPrivateKey = words;
        } else {
          opts.mnemonic = words;
        }
        opts.passphrase = $scope.formData.passphrase;

        var pathData = derivationPathHelper.parse($scope.formData.derivationPath);
        if (!pathData) {
          popupService.showAlert(gettextCatalog.getString('Error'), gettextCatalog.getString('Invalid derivation path'));
          return;
        }

        opts.account = pathData.account;
        opts.networkName = pathData.networkName;
        opts.derivationStrategy = pathData.derivationStrategy;

      } else {
        opts.passphrase = $scope.formData.createPassphrase;
      }

      if (setSeed && !opts.mnemonic && !opts.extendedPrivateKey) {
        popupService.showAlert(gettextCatalog.getString('Error'), gettextCatalog.getString('Please enter the wallet recovery phrase'));
        return;
      }

      if ($scope.formData.seedSource.id == walletService.externalSource.ledger.id || $scope.formData.seedSource.id == walletService.externalSource.trezor.id || $scope.formData.seedSource.id == walletService.externalSource.intelTEE.id) {
        var account = $scope.formData.account;
        if (!account || account < 1) {
          popupService.showAlert(gettextCatalog.getString('Error'), gettextCatalog.getString('Invalid account number'));
          return;
        }

        if ($scope.formData.seedSource.id == walletService.externalSource.trezor.id || $scope.formData.seedSource.id == walletService.externalSource.intelTEE.id)
          account = account - 1;

        opts.account = account;
        ongoingProcess.set('connecting ' + $scope.formData.seedSource.id, true);

        var src;
        switch ($scope.formData.seedSource.id) {
          case walletService.externalSource.ledger.id:
            src = ledger;
            break;
          case walletService.externalSource.trezor.id:
            src = trezor;
            break;
          case walletService.externalSource.intelTEE.id:
            src = intelTEE;
            break;
          default:
            popupService.showAlert(gettextCatalog.getString('Error'), 'Invalid seed source id');
            return;
        }

        src.getInfoForNewWallet(opts.n > 1, account, opts.networkName, function(err, lopts) {
          ongoingProcess.set('connecting ' + $scope.formData.seedSource.id, false);
          if (err) {
            popupService.showAlert(gettextCatalog.getString('Error'), err);
            return;
          }
          opts = lodash.assign(lopts, opts);
          _create(opts);
        });
      } else {
        _create(opts);
      }
    };

    function _create(opts) {
      ongoingProcess.set('creatingWallet', true);
      $timeout(function() {
        profileService.createWallet(opts, function(err, client) {
          ongoingProcess.set('creatingWallet', false);
          if (err) {
            $log.warn(err);
            popupService.showAlert(gettextCatalog.getString('Error'), err);
            return;
          }

          walletService.updateRemotePreferences(client);
          pushNotificationsService.updateSubscription(client);

          if ($scope.formData.seedSource.id == 'set') {
            profileService.setBackupFlag(client.credentials.walletId);
          }

          $ionicHistory.removeBackView();

          if (!client.isComplete()) {
            $ionicHistory.nextViewOptions({
              disableAnimate: true
            });
            $state.go('tabs.home');
            $timeout(function() {
              $state.transitionTo('tabs.copayers', {
                walletId: client.credentials.walletId
              });
            }, 100);
          } else $state.go('tabs.home');
        });
      }, 300);
    }
  });


text:
class Note

  attr_accessor :from
  attr_accessor :subject
  attr_accessor :message
  attr_accessor :at

  sandboxed_methods :from, :subject, :message, :at

  def initialize(all_users)
    @from = all_users[(rand * all_users.length).floor]
    @subject = Faker::Lorem.sentence
    @message = Faker::Lorem.paragraph
    @at = DateTime.now - (rand * 10000)
  end
end


text:
#import <XXUnknownSuperclass.h> // Unknown library

@class UIColor;

__attribute__((visibility("hidden")))
@interface DACircularProgressView : XXUnknownSuperclass {
	float _indeterminateDuration;
}
@property(assign, nonatomic) int clockwiseProgress;
@property(assign, nonatomic) int indeterminate;
@property(assign, nonatomic) float indeterminateDuration;
@property(assign, nonatomic) float progress;
@property(retain, nonatomic) UIColor* progressTintColor;
@property(assign, nonatomic) int roundedCorners;
@property(assign, nonatomic) float thicknessRatio;
@property(retain, nonatomic) UIColor* trackTintColor;
+ (void)initialize;
+ (Class)layerClass;
- (id)init;
- (void)animationDidStop:(id)animation finished:(BOOL)finished;
- (id)circularProgressLayer;
- (void)didMoveToWindow;
- (void)setProgress:(float)progress animated:(BOOL)animated;
- (void)setProgress:(float)progress animated:(BOOL)animated initialDelay:(double)delay;
@end


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"

        "http://www.w3.org/TR/html4/loose.dtd">

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

	<title>Présentations</title>

Présentations :

20160601 - Workshop Elasticsearch - Notions de base

20160601 - Workshop Elasticsearch - Infrastructure et cluster

20150330 - Présentation rapide Elasticsearch

201502 - Esup-days 19 - Agimus-NG


text:
package org.apache.ignite.internal.processors.cache;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import javax.cache.CacheException;
import org.apache.ignite.Ignite;
import org.apache.ignite.IgniteCache;
import org.apache.ignite.IgniteCheckedException;
import org.apache.ignite.cache.CacheAtomicityMode;
import org.apache.ignite.cache.CacheExistsException;
import org.apache.ignite.cache.CacheMode;
import org.apache.ignite.cache.CacheWriteSynchronizationMode;
import org.apache.ignite.cluster.ClusterNode;
import org.apache.ignite.configuration.CacheConfiguration;
import org.apache.ignite.configuration.IgniteConfiguration;
import org.apache.ignite.configuration.NearCacheConfiguration;
import org.apache.ignite.events.CacheEvent;
import org.apache.ignite.events.EventType;
import org.apache.ignite.internal.IgniteEx;
import org.apache.ignite.internal.IgniteInternalFuture;
import org.apache.ignite.internal.IgniteKernal;
import org.apache.ignite.internal.managers.discovery.GridDiscoveryManager;
import org.apache.ignite.internal.util.typedef.F;
import org.apache.ignite.internal.util.typedef.G;
import org.apache.ignite.internal.util.typedef.X;
import org.apache.ignite.internal.util.typedef.internal.U;
import org.apache.ignite.lang.IgnitePredicate;
import org.apache.ignite.lang.IgniteUuid;
import org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi;
import org.apache.ignite.testframework.GridTestUtils;
import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
import org.junit.Test;

import static org.apache.ignite.events.EventType.EVT_CACHE_STARTED;
import static org.apache.ignite.events.EventType.EVT_CACHE_STOPPED;

/**
 * Test for dynamic cache start.
 */
@SuppressWarnings("unchecked")
public class IgniteDynamicCacheStartSelfTest extends GridCommonAbstractTest {
    /** */
    private static final String DYNAMIC_CACHE_NAME = "TestDynamicCache";

    /** */
    private static final String STATIC_CACHE_NAME = "TestStaticCache";

    /** */
    private static final String TEST_ATTRIBUTE_NAME = "TEST_ATTRIBUTE_NAME";

    /** */
    public static final IgnitePredicate<ClusterNode> NODE_FILTER = new IgnitePredicate<ClusterNode>() {
        /** {@inheritDoc} */
        @Override public boolean apply(ClusterNode n) {
            Boolean val = n.attribute(TEST_ATTRIBUTE_NAME);

            return val != null && val;
        }
    };

    /** */
    private boolean testAttribute = true;

    /** */
    private boolean daemon;

    /**
     * @return Number of nodes for this test.
     */
    public int nodeCount() {
        return 3;
    }

    /**
     * {@inheritDoc}
     */
    @Override protected IgniteConfiguration getConfiguration(String igniteInstanceName) throws Exception {
        IgniteConfiguration cfg = super.getConfiguration(igniteInstanceName);

        if (cfg.isClientMode())
            ((TcpDiscoverySpi)cfg.getDiscoverySpi()).setForceServerMode(true);

        cfg.setUserAttributes(F.asMap(TEST_ATTRIBUTE_NAME, testAttribute));

        CacheConfiguration cacheCfg = new CacheConfiguration(DEFAULT_CACHE_NAME);

        cacheCfg.setCacheMode(CacheMode.REPLICATED);

        cacheCfg.setName(STATIC_CACHE_NAME);

        cfg.setCacheConfiguration(cacheCfg);

        cfg.setIncludeEventTypes(EVT_CACHE_STARTED, EVT_CACHE_STOPPED, EventType.EVT_CACHE_NODES_LEFT);

        if (daemon)
            cfg.setDaemon(true);

        return cfg;
    }

    /**
     * {@inheritDoc}
     */
    @Override protected void beforeTestsStarted() throws Exception {
        startGridsMultiThreaded(nodeCount());
    }

    /**
     * @throws Exception If failed.
     */
    @Test
    public void testStartStopCacheMultithreadedSameNode() throws Exception {
        final IgniteEx kernal = grid(0);

        final Collection<IgniteInternalFuture<?>> futs = new ConcurrentLinkedDeque<>();

        int threadNum = 20;

        GridTestUtils.runMultiThreaded(new Callable<Object>() {
            @Override public Object call() throws Exception {
                CacheConfiguration ccfg = new CacheConfiguration(DEFAULT_CACHE_NAME);

                ccfg.setName(DYNAMIC_CACHE_NAME);

                futs.add(kernal.context().cache().dynamicStartCache(ccfg,
                    ccfg.getName(),
                    null,
                    true,
                    true,
                    true));

                return null;
            }
        }, threadNum, "cache-starter");

        assertEquals(threadNum, futs.size());

        int succeeded = 0;
        int failed = 0;

        for (IgniteInternalFuture<?> fut : futs) {
            try {
                fut.get();

                info("Succeeded: " + System.identityHashCode(fut));

                succeeded++;
            }
            catch (IgniteCheckedException e) {
                info(e.getMessage());

                failed++;
            }
        }

        assertEquals(1, succeeded);
        assertEquals(threadNum - 1, failed);

        futs.clear();

        GridTestUtils.runMultiThreaded(new Callable<Object>() {
            @Override public Object call() throws Exception {
                futs.add(kernal.context().cache().dynamicDestroyCache(DYNAMIC_CACHE_NAME, false, true, false, null));

                return null;
            }
        }, threadNum, "cache-stopper");

        assertEquals(threadNum, futs.size());

        for (IgniteInternalFuture<?> fut : futs)
            fut.get();
    }

    /**
     * @throws Exception If failed.
     */
    @Test
    public void testStartCacheMultithreadedDifferentNodes() throws Exception {
        final Collection<IgniteInternalFuture<?>> futs = new ConcurrentLinkedDeque<>();

        int threadNum = 20;

        GridTestUtils.runMultiThreaded(new Callable<Object>() {
            @Override public Object call() throws Exception {
                CacheConfiguration ccfg = new CacheConfiguration(DEFAULT_CACHE_NAME);

                ccfg.setName(DYNAMIC_CACHE_NAME);

                IgniteEx kernal = grid(ThreadLocalRandom.current().nextInt(nodeCount()));

                futs.add(kernal.context().cache().dynamicStartCache(ccfg,
                    ccfg.getName(),
                    null,
                    true,
                    true,
                    true));

                return null;
            }
        }, threadNum, "cache-starter");

        assertEquals(threadNum, futs.size());

        int succeeded = 0;
        int failed = 0;

        for (IgniteInternalFuture<?> fut : futs) {
            try {
                fut.get();

                info("Succeeded: " + System.identityHashCode(fut));

                succeeded++;
            }
            catch (IgniteCheckedException e) {
                info(e.getMessage());

                failed++;
            }
        }

        assertEquals(1, succeeded);
        assertEquals(threadNum - 1, failed);

        futs.clear();

        GridTestUtils.runMultiThreaded(new Callable<Object>() {
            @Override public Object call() throws Exception {
                IgniteEx kernal = grid(ThreadLocalRandom.current().nextInt(nodeCount()));

                futs.add(kernal.context().cache().dynamicDestroyCache(DYNAMIC_CACHE_NAME, false, true, false, null));

                return null;
            }
        }, threadNum, "cache-stopper");

        assertEquals(threadNum, futs.size());

        for (IgniteInternalFuture<?> fut : futs)
            fut.get();
    }

    /**
     * @throws Exception If failed.
     */
    @Test
    public void testStartStopCacheSimpleTransactional() throws Exception {
        checkStartStopCacheSimple(CacheAtomicityMode.TRANSACTIONAL);
    }

    /**
     * @throws Exception If failed.
     */
    @Test
    public void testStartStopCacheSimpleTransactionalMvcc() throws Exception {
        checkStartStopCacheSimple(CacheAtomicityMode.TRANSACTIONAL_SNAPSHOT);
    }

    /**
     * @throws Exception If failed.
     */
    @Test
    public void testStartStopCacheSimpleAtomic() throws Exception {
        checkStartStopCacheSimple(CacheAtomicityMode.ATOMIC);
    }

    /**
     * @throws Exception If failed.
     */
    @Test
    public void testStartStopCachesSimpleTransactional() throws Exception {
        checkStartStopCachesSimple(CacheAtomicityMode.TRANSACTIONAL);
    }

    /**
     * @throws Exception If failed.
     */
    @Test
    public void testStartStopCachesSimpleTransactionalMvcc() throws Exception {
        checkStartStopCachesSimple(CacheAtomicityMode.TRANSACTIONAL_SNAPSHOT);
    }

    /**
     * @throws Exception If failed.
     */
    @Test
    public void testStartStopCachesSimpleAtomic() throws Exception {
        checkStartStopCachesSimple(CacheAtomicityMode.ATOMIC);
    }

    /**
     * @param mode Cache atomicity mode.
     * @throws Exception If failed.
     */
    private void checkStartStopCacheSimple(CacheAtomicityMode mode) throws Exception {
        final IgniteEx kernal = grid(0);

        CacheConfiguration ccfg = new CacheConfiguration(DEFAULT_CACHE_NAME);
        ccfg.setWriteSynchronizationMode(CacheWriteSynchronizationMode.FULL_SYNC);
        ccfg.setAtomicityMode(mode);

        ccfg.setName(DYNAMIC_CACHE_NAME);

        kernal.createCache(ccfg);

        for (int g = 0; g < nodeCount(); g++) {
            IgniteEx kernal0 = grid(g);

            info("Getting cache for node: " + g);

            assertNotNull(grid(g).cache(DYNAMIC_CACHE_NAME));
        }

        grid(0).cache(DYNAMIC_CACHE_NAME).put("1", "1");

        for (int g = 0; g < nodeCount(); g++)
            assertEquals("1", grid(g).cache(DYNAMIC_CACHE_NAME).get("1"));

        // Grab caches before stop.
        final IgniteCache[] caches = new IgniteCache[nodeCount()];

        for (int g = 0; g < nodeCount(); g++)
            caches[g] = grid(g).cache(DYNAMIC_CACHE_NAME);

        kernal.destroyCache(DYNAMIC_CACHE_NAME);

        awaitPartitionMapExchange();

        for (int g = 0; g < nodeCount(); g++) {
            final IgniteKernal kernal0 = (IgniteKernal)grid(g);

            final int idx = g;

            assertNull(kernal0.cache(DYNAMIC_CACHE_NAME));

            GridTestUtils.assertThrows(log, new Callable<Object>() {
                @Override public Object call() throws Exception {
                    return caches[idx].get("1");
                }
            }, IllegalStateException.class, null);
        }
    }

    /**
     * @param mode Cache atomicity mode.
     * @throws Exception If failed.
     */
    private void checkStartStopCachesSimple(CacheAtomicityMode mode) throws Exception {
        final IgniteEx kernal = grid(0);
        final int cacheCnt = 3;

        List<CacheConfiguration> ccfgList = new ArrayList<>();

        for (int i = 0; i < cacheCnt; i++) {
            CacheConfiguration ccfg = new CacheConfiguration(DEFAULT_CACHE_NAME);
            ccfg.setWriteSynchronizationMode(CacheWriteSynchronizationMode.FULL_SYNC);
            ccfg.setAtomicityMode(mode);
            ccfg.setName(DYNAMIC_CACHE_NAME + Integer.toString(i));

            ccfgList.add(ccfg);
        }

        kernal.createCaches(ccfgList);

        for (int g = 0; g < nodeCount(); g++) {
            IgniteEx kernal0 = grid(g);

            info("Getting cache for node: " + g);

            for (int i = 0; i < cacheCnt; i++)
                assertNotNull(grid(g).cache(DYNAMIC_CACHE_NAME + Integer.toString(i)));
        }

        for (int i = 0; i < cacheCnt; i++)
            grid(0).cache(DYNAMIC_CACHE_NAME + Integer.toString(i)).put(Integer.toString(i), Integer.toString(i));

        for (int g = 0; g < nodeCount(); g++) {
            for (int i = 0; i < cacheCnt; i++) {
                assertEquals(
                    Integer.toString(i),
                    grid(g).cache(DYNAMIC_CACHE_NAME + Integer.toString(i)).get(Integer.toString(i))
                );
            }
        }

        // Grab caches before stop.
        final IgniteCache[] caches = new IgniteCache[nodeCount() * cacheCnt];

        for (int g = 0; g < nodeCount(); g++) {
            for (int i = 0; i < cacheCnt; i++)
                caches[g * nodeCount() + i] = grid(g).cache(DYNAMIC_CACHE_NAME + Integer.toString(i));
        }

        List<String> namesToDestroy = new ArrayList<>();

        for (int i = 0; i < cacheCnt; i++)
            namesToDestroy.add(DYNAMIC_CACHE_NAME + Integer.toString(i));

        kernal.destroyCaches(namesToDestroy);

        awaitPartitionMapExchange();

        for (int g = 0; g < nodeCount(); g++) {
            final IgniteKernal kernal0 = (IgniteKernal)grid(g);

            for (int i = 0; i < cacheCnt; i++) {
                final int idx = g * nodeCount() + i;
                final int expVal = i;

                assertNull(kernal0.cache(DYNAMIC_CACHE_NAME));

                GridTestUtils.assertThrows(log, new Callable<Object>() {
                    @Override public Object call() throws Exception {
                        return caches[idx].get(Integer.toString(expVal));
                    }
                }, IllegalStateException.class, null);
            }
        }
    }

    /**
     * @throws Exception If failed.
     */
    @Test
    public void testStartStopCacheAddNode() throws Exception {
        final IgniteEx kernal = grid(0);

        CacheConfiguration ccfg = new CacheConfiguration(DEFAULT_CACHE_NAME);
        ccfg.setCacheMode(CacheMode.REPLICATED);
        ccfg.setWriteSynchronizationMode(CacheWriteSynchronizationMode.FULL_SYNC);

        ccfg.setName(DYNAMIC_CACHE_NAME);

        kernal.createCache(ccfg);

        info(">>>>>>> Deployed dynamic cache");

        startGrid(nodeCount());

        try {
            // Check that cache got deployed on new node.
            IgniteCache<Object, Object> cache = ignite(nodeCount()).cache(DYNAMIC_CACHE_NAME);

            cache.put("1", "1");

            for (int g = 0; g < nodeCount() + 1; g++) {
                assertEquals("1", grid(g).cache(DYNAMIC_CACHE_NAME).get("1"));

                Collection<ClusterNode> nodes = grid(g).affinity(DYNAMIC_CACHE_NAME).mapKeyToPrimaryAndBackups(0);

                assertEquals(nodeCount() + 1, nodes.size());
            }

            // Undeploy cache.
            kernal.destroyCache(DYNAMIC_CACHE_NAME);

            startGrid(nodeCount() + 1);

            awaitPartitionMapExchange();

            // Check that cache is not deployed on new node after undeploy.
            for (int g = 0; g < nodeCount() + 2; g++) {
                final IgniteKernal kernal0 = (IgniteKernal)grid(g);

                assertNull(kernal0.cache(DYNAMIC_CACHE_NAME));
            }
        }
        finally {
            stopGrid(nodeCount() + 1);
            stopGrid(nodeCount());
        }
    }

    /**
     * @throws Exception If failed.
     */
    @Test
    public void testDeployFilter() throws Exception {
        try {
            testAttribute = false;

            startGrid(nodeCount());

            final IgniteEx kernal = grid(0);

            CacheConfiguration ccfg = new CacheConfiguration(DEFAULT_CACHE_NAME);
            ccfg.setWriteSynchronizationMode(CacheWriteSynchronizationMode.FULL_SYNC);

            ccfg.setName(DYNAMIC_CACHE_NAME);

            ccfg.setNodeFilter(NODE_FILTER);

            kernal.createCache(ccfg);

            startGrid(nodeCount() + 1);

            for (int i = 0; i < 100; i++)
                grid(0).cache(DYNAMIC_CACHE_NAME).put(i, i);

            for (int i = 0; i < 100; i++)
                assertEquals(i, grid(1).cache(DYNAMIC_CACHE_NAME).get(i));

            info("Affinity nodes: " + grid(0).affinity(DYNAMIC_CACHE_NAME).mapKeyToPrimaryAndBackups(0));

            for (int g = 0; g < nodeCount(); g++) {
                for (int i = 0; i < 100; i++) {
                    assertFalse(grid(g).affinity(DYNAMIC_CACHE_NAME).mapKeyToPrimaryAndBackups(i)
                        .contains(grid(nodeCount()).cluster().localNode()));

                    assertFalse(grid(g).affinity(DYNAMIC_CACHE_NAME).mapKeyToPrimaryAndBackups(i)
                        .contains(grid(nodeCount() + 1).cluster().localNode()));
                }
            }

            awaitPartitionMapExchange();

            // Check that cache is not deployed on new node after undeploy.
            for (int g = 0; g < nodeCount() + 2; g++) {
                final IgniteKernal kernal0 = (IgniteKernal)grid(g);

                if (g < nodeCount())
                    assertNotNull(grid(g).cache(DYNAMIC_CACHE_NAME));
                else
                    GridTestUtils.assertThrows(log, new Callable<Object>() {
                        @Override public Object call() throws Exception {
                            return kernal0.getCache(DYNAMIC_CACHE_NAME);
                        }
                    }, IllegalArgumentException.class, null);
            }

            kernal.destroyCache(DYNAMIC_CACHE_NAME);

            stopGrid(nodeCount() + 1);
            stopGrid(nodeCount());
        }
        finally {
            testAttribute = true;
        }
    }

    /**
     * @throws Exception If failed.
     */
    @Test
    public void testFailWhenConfiguredCacheExists() throws Exception {
        GridTestUtils.assertThrowsInherited(log, new Callable<Object>() {
            @Override public Object call() throws Exception {
                final Ignite kernal = grid(0);

                CacheConfiguration ccfg = new CacheConfiguration(DEFAULT_CACHE_NAME);
                ccfg.setWriteSynchronizationMode(CacheWriteSynchronizationMode.FULL_SYNC);

                // Cache is already configured, should fail.
                ccfg.setName(STATIC_CACHE_NAME);

                ccfg.setNodeFilter(NODE_FILTER);

                return kernal.createCache(ccfg);
            }
        }, CacheExistsException.class, null);
    }

    /**
     * @throws Exception If failed.
     */
    @Test
    public void testFailWhenOneOfConfiguredCacheExists() throws Exception {
        GridTestUtils.assertThrowsInherited(log, new Callable<Object>() {
            @Override public Object call() throws Exception {
                final Ignite kernal = grid(0);

                CacheConfiguration ccfgDynamic = new CacheConfiguration(DEFAULT_CACHE_NAME);
                ccfgDynamic.setWriteSynchronizationMode(CacheWriteSynchronizationMode.FULL_SYNC);

                ccfgDynamic.setName(DYNAMIC_CACHE_NAME);

                ccfgDynamic.setNodeFilter(NODE_FILTER);

                CacheConfiguration ccfgStatic = new CacheConfiguration(DEFAULT_CACHE_NAME);
                ccfgStatic.setWriteSynchronizationMode(CacheWriteSynchronizationMode.FULL_SYNC);

                // Cache is already configured, should fail.
                ccfgStatic.setName(STATIC_CACHE_NAME);

                ccfgStatic.setNodeFilter(NODE_FILTER);

                return kernal.createCaches(F.asList(ccfgDynamic, ccfgStatic));
            }
        }, CacheExistsException.class, null);

        assertNull(grid(0).cache(DYNAMIC_CACHE_NAME));
    }

    /**
     * @throws Exception If failed.
     */
    @Test
    public void testClientCache() throws Exception {
        try {
            testAttribute = false;

            startGrid(nodeCount());

            final IgniteEx kernal = grid(0);

            CacheConfiguration ccfg = new CacheConfiguration(DEFAULT_CACHE_NAME);
            ccfg.setWriteSynchronizationMode(CacheWriteSynchronizationMode.FULL_SYNC);

            ccfg.setName(DYNAMIC_CACHE_NAME);

            ccfg.setNodeFilter(NODE_FILTER);

            kernal.createCache(ccfg);

            GridTestUtils.assertThrows(log, new Callable<Object>() {
                @Override public Object call() throws Exception {
                    IgniteKernal ignite = (IgniteKernal)grid(nodeCount());

                    return ignite.getCache(DYNAMIC_CACHE_NAME);
                }
            }, IllegalArgumentException.class, null);

            // Should obtain client cache on new node.
            IgniteCache<Object, Object> clientCache = ignite(nodeCount()).cache(DYNAMIC_CACHE_NAME);

            clientCache.put("1", "1");

            for (int g = 0; g < nodeCount() + 1; g++)
                assertEquals("1", ignite(g).cache(DYNAMIC_CACHE_NAME).get("1"));

            kernal.destroyCache(DYNAMIC_CACHE_NAME);
        }
        finally {
            stopGrid(nodeCount());
        }
    }

    /**
     * @throws Exception If failed.
     */
    @Test
    public void testStartFromClientNode() throws Exception {
        try {
            testAttribute = false;

            startGrid(nodeCount());

            final IgniteEx kernal = grid(0);

            CacheConfiguration ccfg = new CacheConfiguration(DEFAULT_CACHE_NAME);
            ccfg.setWriteSynchronizationMode(CacheWriteSynchronizationMode.FULL_SYNC);

            ccfg.setName(DYNAMIC_CACHE_NAME);

            ccfg.setNodeFilter(NODE_FILTER);

            final IgniteKernal started = (IgniteKernal)grid(nodeCount());

            started.createCache(ccfg);

            GridCacheAdapter<Object, Object> cache = started.internalCache(DYNAMIC_CACHE_NAME);

            assertNotNull(cache);
            assertFalse(cache.context().affinityNode());

            // Should obtain client cache on new node.
            IgniteCache<Object, Object> clientCache = ignite(nodeCount()).cache(DYNAMIC_CACHE_NAME);

            clientCache.put("1", "1");

            for (int g = 0; g < nodeCount() + 1; g++)
                assertEquals("1", ignite(g).cache(DYNAMIC_CACHE_NAME).get("1"));

            kernal.destroyCache(DYNAMIC_CACHE_NAME);
        }
        finally {
            stopGrid(nodeCount());
        }
    }

    /**
     * @throws Exception If failed.
     */
    @Test
    public void testStartNearCacheFromClientNode() throws Exception {
        try {
            testAttribute = false;

            startGrid(nodeCount());

            final IgniteEx kernal = grid(0);

            CacheConfiguration ccfg = new CacheConfiguration(DEFAULT_CACHE_NAME);
            ccfg.setWriteSynchronizationMode(CacheWriteSynchronizationMode.FULL_SYNC);

            ccfg.setName(DYNAMIC_CACHE_NAME);

            ccfg.setNodeFilter(NODE_FILTER);

            final IgniteKernal started = (IgniteKernal)grid(nodeCount());

            NearCacheConfiguration nearCfg = new NearCacheConfiguration();

            started.createCache(ccfg, nearCfg);

            GridCacheAdapter<Object, Object> cache = started.internalCache(DYNAMIC_CACHE_NAME);

            assertNotNull(cache);
            assertFalse(cache.context().affinityNode());
            assertTrue(cache.context().isNear());

            // Should obtain client cache on new node.
            IgniteCache<Object, Object> clientCache = ignite(nodeCount()).cache(DYNAMIC_CACHE_NAME);

            clientCache.put("1", "1");

            for (int g = 0; g < nodeCount() + 1; g++)
                assertEquals("1", ignite(g).cache(DYNAMIC_CACHE_NAME).get("1"));

            kernal.destroyCache(DYNAMIC_CACHE_NAME);
        }
        finally {
            stopGrid(nodeCount());
        }
    }

    /**
     * @throws Exception If failed.
     */
    @Test
    public void testEvents() throws Exception {
        CacheConfiguration cfg = new CacheConfiguration(DEFAULT_CACHE_NAME);

        cfg.setName(DYNAMIC_CACHE_NAME);
        cfg.setCacheMode(CacheMode.REPLICATED);

        // This cache will not fire any cache events.
        CacheConfiguration cfgEvtsDisabled = new CacheConfiguration(cfg);

        cfgEvtsDisabled.setName("DynamicCacheEvtsDisabled");
        cfgEvtsDisabled.setEventsDisabled(true);

        final CountDownLatch[] starts = new CountDownLatch[nodeCount()];
        final CountDownLatch[] stops = new CountDownLatch[nodeCount()];

        IgnitePredicate[] lsnrs = new IgnitePredicate[nodeCount()];

        for (int i = 0; i < nodeCount(); i++) {
            final int idx = i;

            starts[i] = new CountDownLatch(1);
            stops[i] = new CountDownLatch(1);

            lsnrs[i] = new IgnitePredicate<CacheEvent>() {
                @Override public boolean apply(CacheEvent e) {
                    switch (e.type()) {
                        case EVT_CACHE_STARTED:
                            starts[idx].countDown();

                            break;

                        case EVT_CACHE_STOPPED:
                            stops[idx].countDown();

                            break;

                        default:
                            assert false;
                    }

                    assertEquals(DYNAMIC_CACHE_NAME, e.cacheName());

                    return true;
                }
            };

            ignite(i).events().localListen(lsnrs[i], EventType.EVTS_CACHE_LIFECYCLE);
        }

        IgniteCache<Object, Object> cacheEvtsDisabled = ignite(0).createCache(cfgEvtsDisabled);
        IgniteCache<Object, Object> cache = ignite(0).createCache(cfg);

        try {
            for (CountDownLatch start : starts)
                start.await();
        }
        finally {
            cacheEvtsDisabled.destroy();
            cache.destroy();
        }

        for (CountDownLatch stop : stops)
            stop.await();

        for (int i = 0; i < nodeCount(); i++)
            ignite(i).events().stopLocalListen(lsnrs[i]);
    }

    /** */
    @Test
    public void testRemoteListenShouldGetCacheEventFromEveryNode() throws Exception {
        CountDownLatch[] evts = new CountDownLatch[] {new CountDownLatch(nodeCount())};
        int[] evtType = new int[] {EVT_CACHE_STARTED};

        UUID lsnrId = ignite(0).events().remoteListen((uuid, evt) -> {
            assertEquals(DYNAMIC_CACHE_NAME, ((CacheEvent)evt).cacheName());
            assertEquals(evt.type(), evtType[0]);

            evts[0].countDown();

            return true;
        }, evt -> true, EventType.EVTS_CACHE_LIFECYCLE);

        try {
            IgniteCache<Object, Object> cache = ignite(0).createCache(DYNAMIC_CACHE_NAME);

            evts[0].await(10, TimeUnit.SECONDS);

            evts[0] = new CountDownLatch(nodeCount());
            evtType[0] = EVT_CACHE_STOPPED;

            cache.destroy();

            evts[0].await(10, TimeUnit.SECONDS);
        }
        finally {
            ignite(0).events().stopRemoteListen(lsnrId);

            if (ignite(0).cache(DYNAMIC_CACHE_NAME) != null)
                ignite(0).cache(DYNAMIC_CACHE_NAME).destroy();
        }
    }

    /**
     * @throws Exception If failed.
     */
    @Test
    public void testNearNodesCache() throws Exception {
        try {
            testAttribute = false;

            Ignite ig = startGrid(nodeCount());

            CacheConfiguration ccfg = new CacheConfiguration(DEFAULT_CACHE_NAME);

            ccfg.setName(DYNAMIC_CACHE_NAME);
            ccfg.setCacheMode(CacheMode.PARTITIONED);
            ccfg.setNodeFilter(NODE_FILTER);

            IgniteCache cache = ig.createCache(ccfg, new NearCacheConfiguration());
            assertNotNull(cache);

            GridCacheAdapter<Object, Object> cacheAdapter =
                ((IgniteKernal)ig).internalCache(DYNAMIC_CACHE_NAME);

            assertNotNull(cacheAdapter);
            assertFalse(cacheAdapter.context().affinityNode());
            assertTrue(cacheAdapter.context().isNear());

            try {
                IgniteEx grid = startGrid(nodeCount() + 1);

                // Check that new node sees near node.
                GridDiscoveryManager disco = grid.context().discovery();

                assertTrue(disco.cacheNearNode(disco.node(ig.cluster().localNode().id()),
                    DYNAMIC_CACHE_NAME));
            }
            finally {
                cache.destroy();

                stopGrid(nodeCount() + 1);
            }
        }
        finally {
            stopGrid(nodeCount());
        }
    }

    /** */
    @Test
    public void testGetOrCreate() throws Exception {
        try {
            final CacheConfiguration cfg = new CacheConfiguration(DEFAULT_CACHE_NAME);

            cfg.setName(DYNAMIC_CACHE_NAME);
            cfg.setNodeFilter(NODE_FILTER);

            grid(0).getOrCreateCache(cfg);
            grid(0).getOrCreateCache(cfg);

            GridTestUtils.assertThrows(log, new Callable<Object>() {
                @Override public Object call() throws Exception {
                    return grid(0).getOrCreateCache(cfg, new NearCacheConfiguration());
                }
            }, CacheException.class, null);

            GridTestUtils.assertThrows(log, new Callable<Object>() {
                @Override public Object call() throws Exception {
                    return grid(0).getOrCreateNearCache(DYNAMIC_CACHE_NAME, new NearCacheConfiguration());
                }
            }, CacheException.class, null);

            testAttribute = false;

            startGrid(nodeCount());
            startGrid(nodeCount() + 1);

            try {
                IgniteEx nearGrid = grid(nodeCount());

                nearGrid.getOrCreateCache(cfg, new NearCacheConfiguration());
                nearGrid.getOrCreateNearCache(DYNAMIC_CACHE_NAME, new NearCacheConfiguration());

                GridCacheContext<Object, Object> nCtx = ((IgniteKernal)nearGrid)
                    .internalCache(DYNAMIC_CACHE_NAME).context();

                assertTrue(nCtx.isNear());
                assertFalse(nCtx.affinityNode());

                IgniteEx clientGrid = grid(nodeCount() + 1);

                clientGrid.getOrCreateCache(cfg);
                clientGrid.getOrCreateCache(cfg);

                GridCacheContext<Object, Object> cCtx = ((IgniteKernal)clientGrid)
                    .internalCache(DYNAMIC_CACHE_NAME).context();

                assertFalse(cCtx.isNear());
                assertFalse(cCtx.affinityNode());
            }
            finally {
                stopGrid(nodeCount() + 1);
                stopGrid(nodeCount());
            }
        }
        finally {
            grid(0).destroyCache(DYNAMIC_CACHE_NAME);
        }
    }

    /** */
    @Test
    public void testGetOrCreateCollection() throws Exception {
        final int cacheCnt = 3;

        try {
            final Collection<CacheConfiguration> ccfgs = new ArrayList<>();

            for (int i = 0; i < cacheCnt; i++) {
                final CacheConfiguration cfg = new CacheConfiguration(DEFAULT_CACHE_NAME);

                cfg.setName(DYNAMIC_CACHE_NAME + Integer.toString(i));
                cfg.setNodeFilter(NODE_FILTER);

                ccfgs.add(cfg);

                grid(0).getOrCreateCaches(ccfgs);
            }

            for (int i = 0; i < cacheCnt; i++) {
                assertNotNull(grid(0).cache(DYNAMIC_CACHE_NAME + Integer.toString(i)));

                IgniteCache<Object, Object> jcache = grid(0).cache(DYNAMIC_CACHE_NAME + Integer.toString(i));

                jcache.put(Integer.toString(i), Integer.toString(i));

                assertEquals(jcache.get(Integer.toString(i)), Integer.toString(i));
            }
        }
        finally {
            for (int i = 0; i < cacheCnt; i++)
                grid(0).destroyCache(DYNAMIC_CACHE_NAME + Integer.toString(i));
        }
    }

    /**
     * @throws Exception If failed.
     */
    @Test
    public void testGetOrCreateMultiNode() throws Exception {
        try {
            final AtomicInteger cnt = new AtomicInteger();
            final AtomicReference<Throwable> err = new AtomicReference<>();

            GridTestUtils.runMultiThreaded(new Callable<Object>() {
                @Override public Object call() throws Exception {
                    int idx = cnt.getAndIncrement();

                    try {
                        CacheConfiguration cfg = new CacheConfiguration(DYNAMIC_CACHE_NAME);

                        ignite(idx).getOrCreateCache(cfg);
                    }
                    catch (Exception e) {
                        err.compareAndSet(null, e);
                    }

                    return null;
                }
            }, nodeCount(), "starter");

            assertNull(err.get());

            for (int i = 0; i < nodeCount(); i++) {
                GridCacheContext<Object, Object> ctx = ((IgniteKernal)ignite(i)).internalCache(DYNAMIC_CACHE_NAME)
                    .context();

                assertTrue(ctx.affinityNode());
                assertFalse(ctx.isNear());
            }

            lightCheckDynamicCache();
        }
        finally {
            ignite(0).destroyCache(DYNAMIC_CACHE_NAME);
        }
    }

    /**
     * @throws Exception If failed.
     */
    @Test
    public void testGetOrCreateMultiNodeTemplate() throws Exception {
        final AtomicInteger idx = new AtomicInteger();

        GridTestUtils.runMultiThreaded(new Callable<Object>() {
            @Override public Object call() throws Exception {
                int idx0 = idx.getAndIncrement();

                ignite(idx0 % nodeCount()).getOrCreateCache(DYNAMIC_CACHE_NAME);

                return null;
            }
        }, nodeCount() * 4, "runner");

        ignite(0).destroyCache(DYNAMIC_CACHE_NAME);
    }

    /**
     * @throws Exception If failed.
     */
    @Test
    public void testGetOrCreateNearOnlyMultiNode() throws Exception {
        checkGetOrCreateNear(true);
    }

    /**
     * @throws Exception If failed.
     */
    @Test
    public void testGetOrCreateNearMultiNode() throws Exception {
        checkGetOrCreateNear(false);
    }

    /**
     * @param nearOnly Near only flag.
     * @throws Exception If failed.
     */
    private void checkGetOrCreateNear(final boolean nearOnly) throws Exception {
        try {
            final AtomicInteger cnt = new AtomicInteger(nodeCount());
            final AtomicReference<Throwable> err = new AtomicReference<>();

            final int clientCnt = 2;

            try {
                testAttribute = false;

                for (int i = 0; i < clientCnt; i++)
                    startGrid(nodeCount() + i);

                cnt.set(nodeCount());

                final CacheConfiguration<Object, Object> cacheCfg = new CacheConfiguration<>(DYNAMIC_CACHE_NAME);
                cacheCfg.setNodeFilter(NODE_FILTER);

                if (nearOnly)
                    ignite(0).createCache(cacheCfg);

                GridTestUtils.runMultiThreaded(new Callable<Object>() {
                    @Override public Object call() throws Exception {
                        int idx = cnt.getAndIncrement();

                        try {
                            if (nearOnly)
                                ignite(idx).getOrCreateNearCache(DYNAMIC_CACHE_NAME, new NearCacheConfiguration<>());
                            else
                                ignite(idx).getOrCreateCache(cacheCfg, new NearCacheConfiguration<>());
                        }
                        catch (Exception ex) {
                            err.compareAndSet(null, ex);
                        }

                        return null;
                    }
                }, clientCnt, "starter");

                assertNull(err.get());

                for (int i = 0; i < nodeCount(); i++) {
                    GridCacheContext<Object, Object> ctx = ((IgniteKernal)ignite(i)).internalCache(DYNAMIC_CACHE_NAME)
                        .context();

                    assertTrue(ctx.affinityNode());
                    assertFalse(ctx.isNear());
                }

                for (int i = 0; i < clientCnt; i++) {
                    GridCacheContext<Object, Object> ctx = ((IgniteKernal)ignite(nodeCount() + i))
                        .internalCache(DYNAMIC_CACHE_NAME).context();

                    assertFalse(ctx.affinityNode());
                    assertTrue("Cache is not near for index: " + (nodeCount() + i), ctx.isNear());
                }

                lightCheckDynamicCache();
            }
            finally {
                for (int i = 0; i < clientCnt; i++)
                    stopGrid(nodeCount() + i);
            }
        }
        finally {
            ignite(0).destroyCache(DYNAMIC_CACHE_NAME);
        }
    }

    /**
     * @throws Exception If failed.
     */
    private void lightCheckDynamicCache() throws Exception {
        int nodes = F.size(G.allGrids());

        for (int i = 0; i < nodes; i++) {
            IgniteCache<Object, Object> jcache = ignite(i).cache(DYNAMIC_CACHE_NAME);

            for (int k = 0; k < 20; k++) {
                int key = i + k * nodes;

                jcache.put(key, key);
            }
        }

        for (int i = 0; i < nodes; i++) {
            IgniteCache<Object, Object> jcache = ignite(i).cache(DYNAMIC_CACHE_NAME);

            for (int k = 0; k < 20 * nodes; k++)
                assertEquals(k, jcache.get(k));
        }

        for (int i = 0; i < nodes; i++) {
            IgniteCache<Object, Object> jcache = ignite(i).cache(DYNAMIC_CACHE_NAME);

            for (int k = 0; k < 20; k++) {
                int key = i + k * nodes;

                assertEquals(key, jcache.getAndRemove(key));
            }
        }

        for (int i = 0; i < nodes; i++) {
            IgniteCache<Object, Object> jcache = ignite(i).cache(DYNAMIC_CACHE_NAME);

            for (int k = 0; k < 20 * nodes; k++)
                assertNull(jcache.get(k));
        }
    }

    /**
     * @throws Exception If failed.
     */
    @Test
    public void testServerNodesLeftEvent() throws Exception {
        testAttribute = false;

        startGrid(nodeCount());

        CacheConfiguration cfg = new CacheConfiguration(DYNAMIC_CACHE_NAME);

        cfg.setNodeFilter(F.not(NODE_FILTER));

        IgniteCache<Object, Object> cache = ignite(0).createCache(cfg);

        final CountDownLatch[] latches = new CountDownLatch[nodeCount()];

        IgnitePredicate[] lsnrs = new IgnitePredicate[nodeCount()];

        for (int i = 0; i < nodeCount(); i++) {
            final int idx = i;

            latches[i] = new CountDownLatch(1);
            lsnrs[i] = new IgnitePredicate<CacheEvent>() {
                @Override public boolean apply(CacheEvent e) {
                    switch (e.type()) {
                        case EventType.EVT_CACHE_NODES_LEFT:
                            latches[idx].countDown();

                            break;

                        default:
                            assert false;
                    }

                    assertEquals(DYNAMIC_CACHE_NAME, e.cacheName());

                    return true;
                }
            };

            ignite(i).events().localListen(lsnrs[i], EventType.EVTS_CACHE_LIFECYCLE);
        }

        stopGrid(nodeCount());

        for (CountDownLatch latch : latches)
            latch.await();

        for (int i = 0; i < nodeCount(); i++)
            ignite(i).events().stopLocalListen(lsnrs[i]);

        cache.destroy();
    }

    /**
     * @throws Exception If failed.
     */
    @Test
    public void testDaemonNode() throws Exception {
        daemon = true;

        Ignite dNode = startGrid(nodeCount());

        try {
            CacheConfiguration cfg = new CacheConfiguration(DYNAMIC_CACHE_NAME);

            IgniteCache cache = ignite(0).createCache(cfg);

            try {
                for (int i = 0; i < 100; i++) {
                    assertFalse(ignite(0).affinity(DYNAMIC_CACHE_NAME).mapKeyToPrimaryAndBackups(i)
                        .contains(dNode.cluster().localNode()));

                    cache.put(i, i);
                }
            }
            finally {
                cache.destroy();
            }
        }
        finally {
            stopGrid(nodeCount());

            daemon = false;
        }
    }

    /**
     * @throws Exception If failed.
     */
    @Test
    public void testAwaitPartitionMapExchange() throws Exception {
        IgniteCache cache = grid(0).getOrCreateCache(new CacheConfiguration(DYNAMIC_CACHE_NAME));

        awaitPartitionMapExchange();

        startGrid(nodeCount());

        awaitPartitionMapExchange();

        startGrid(nodeCount() + 1);

        awaitPartitionMapExchange();

        stopGrid(nodeCount() + 1);

        awaitPartitionMapExchange();

        stopGrid(nodeCount());

        cache.destroy();
    }

    /**
     * @throws Exception If failed.
     */
    @Test
    public void testStartStopWithClientJoin() throws Exception {
        Ignite ignite1 = ignite(1);

        final AtomicBoolean stop = new AtomicBoolean();

        IgniteInternalFuture<?> fut = GridTestUtils.runMultiThreadedAsync(new Callable<Object>() {
            @Override public Object call() throws Exception {
                int iter = 0;

                while (!stop.get()) {
                    if (iter % 10 == 0)
                        log.info("Client start/stop iteration: " + iter);

                    iter++;

                    try (Ignite ignite = startClientGrid(nodeCount())) {
                        assertTrue(ignite.configuration().isClientMode());
                    }
                }

                return null;
            }
        }, 1, "client-start-stop");

        try {
            long stopTime = U.currentTimeMillis() + 30_000;

            int iter = 0;

            while (System.currentTimeMillis() < stopTime) {
                if (iter % 10 == 0)
                    log.info("Cache start/stop iteration: " + iter);

                IgniteCache<Object, Object> cache = ignite1.getOrCreateCache("cache-" + iter);

                assertNotNull(cache);

                cache.destroy();

                iter++;
            }
        }
        finally {
            stop.set(true);
        }

        fut.get();
    }

    /**
     * @throws Exception If failed.
     */
    @Test
    public void testStartStopSameCacheMultinode() throws Exception {
        final AtomicInteger idx = new AtomicInteger();

        IgniteInternalFuture<?> fut = GridTestUtils.runMultiThreadedAsync(new Callable<Object>() {
            @Override public Object call() throws Exception {
                int node = idx.getAndIncrement();

                Ignite ignite = ignite(node);

                Thread.currentThread().setName("start-stop-" + ignite.name());

                CacheConfiguration ccfg = new CacheConfiguration(DEFAULT_CACHE_NAME);

                ccfg.setName("testStartStop");

                for (int i = 0; i < 1000; i++) {
                    log.info("Start cache: " + i);

                    try (IgniteCache<Object, Object> cache = ignite.getOrCreateCache(ccfg)) {
                        // No-op.
                    }

                    log.info("Stopped cache: " + i);
                }

                return null;
            }
        }, nodeCount(), "start-stop-cache");

        fut.get();
    }

    /**
     * @throws Exception If failed.
     */
    @Test
    public void testCacheRestartIsAllowedOnlyToItsInititator() throws Exception {
        IgniteEx kernal = grid(ThreadLocalRandom.current().nextInt(nodeCount()));

        CacheConfiguration ccfg = new CacheConfiguration("testCacheRestartIsAllowedOnlyToItsInititator");

        kernal.createCache(ccfg);

        IgniteUuid restartId = IgniteUuid.randomUuid();

        kernal.context().cache().dynamicDestroyCache(ccfg.getName(), false, true, true, restartId)
                .get(getTestTimeout(), TimeUnit.MILLISECONDS);

        try {
            kernal.createCache(ccfg);

            fail();
        }
        catch (Exception e) {
            assertTrue(X.hasCause(e, CacheExistsException.class));

            System.out.println("User couldn't start new cache with the same name");
        }

        try {
            kernal.context().cache().dynamicStartCache(ccfg, ccfg.getName(), null, true, false, true).get();

            fail();
        }
        catch (Exception e) {
            assertTrue(X.hasCause(e, CacheExistsException.class));

            System.out.println("We couldn't start new cache with private API");
        }

        StoredCacheData storedCacheData = new StoredCacheData(ccfg);

        try {
            kernal.context().cache().dynamicStartCachesByStoredConf(
                Collections.singleton(storedCacheData),
                true,
                true,
                false,
                IgniteUuid.randomUuid()
            ).get();

            fail();
        }
        catch (Exception e) {
            assertTrue(X.hasCause(e, CacheExistsException.class));

            System.out.println("We couldn't start new cache with wrong restart id.");
        }

        kernal.context().cache().dynamicStartCachesByStoredConf(Collections.singleton(storedCacheData), true, true, false, restartId).get();

        System.out.println("We successfully restarted cache with initial restartId.");

        kernal.destroyCache(ccfg.getName());
    }
}


text:
cask 'leanote' do
  version '2.1'
  sha256 '62feedb4b8ed2e6b2fefecdd8763c92ad394543d2ee27aa78f9b1251c00e4a9d'

  # sourceforge.net/leanote-desktop-app was verified as official when first introduced to the cask
  url "https://downloads.sourceforge.net/leanote-desktop-app/#{version}/leanote-desktop-mac-v#{version}.zip"
  appcast 'https://github.com/leanote/desktop-app/releases.atom',
          checkpoint: '19a1cc4cc1347a96093670e3fa3945b0a2f9cfbc5c806423e240a12645c97a8e'
  name 'Leanote'
  homepage 'http://leanote.org/'

  app 'Leanote.app'
end