text:
package com.github.leanframeworks.propertiesframework.swing.property;

import javax.swing.JButton;

/**
 * Readable/writable property representing the text bean property of a {@link JButton}.
 *

 * It is possible to control the text of the button by setting the value of this property or by calling the {@link
 * JButton#setText(String)} method of that button.
 *

 * If the value of this property is set to null, the button will be emptied.
 *
 * @see JButton#getText()
 * @see JButton#setText(String)
 */
public class JButtonTextProperty extends AbstractComponentProperty<JButton, String> {

    /**
     * {@inheritDoc}
     */
    public JButtonTextProperty(JButton button) {
        super(button, "text");
    }

    /**
     * @see AbstractComponentProperty#getPropertyValueFromComponent()
     */
    @Override
    protected String getPropertyValueFromComponent() {
        return component.getText();
    }

    /**
     * @see AbstractComponentProperty#setPropertyValueToComponent(Object)
     */
    @Override
    protected void setPropertyValueToComponent(String value) {
        component.setText(value);
    }
}


text:
export * from './accordion-section';
export * from './accordion';

redpajama_set_name: RedPajamaGithub


text:
/**
 * Provides the classes for communicating with and implementing the master.
 *
 * @see master documentation
 */
package org.ros.master;


text:
package com.glaf.core.domain;

import java.io.Serializable;
import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.glaf.core.base.JSONable;
import com.glaf.core.base.Parameter;
import com.glaf.core.domain.util.SchedulerParamJsonFactory;

@Entity
@Table(name = "SYS_SCHEDULER_PARAMS")
public class SchedulerParam implements Serializable, Parameter, JSONable {
	private static final long serialVersionUID = 1L;

	@Id
	@Column(name = "ID", length = 50, nullable = false)
	protected String id;

	/**
	 * taskId
	 */
	@Column(name = "TASKID", length = 50)
	protected String taskId;

	/**
	 * type_cd
	 */
	@Column(name = "TYPE_CD", length = 20)
	protected String typeCd;

	/**
	 * key_name
	 */
	@Column(name = "KEY_NAME", length = 50)
	protected String keyName;

	@Column(name = "TITLE", length = 200)
	protected String title;

	/**
	 * string_val
	 */
	@Column(name = "STRING_VAL", length = 2000)
	protected String stringVal;

	@Lob
	@Column(name = "TEXT_VAL")
	protected String textVal;

	/**
	 * date_val
	 */
	@Temporal(TemporalType.TIMESTAMP)
	@Column(name = "DATE_VAL")
	protected Date dateVal;

	/**
	 * long_val
	 */
	@Column(name = "INT_VAL")
	protected Integer intVal;

	/**
	 * long_val
	 */
	@Column(name = "LONG_VAL")
	protected Long longVal;

	/**
	 * double_val
	 */
	@Column(name = "DOUBLE_VAL")
	protected Double doubleVal;

	@javax.persistence.Transient
	protected boolean autoTypeConvert;

	public SchedulerParam() {

	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		SchedulerParam other = (SchedulerParam) obj;
		if (id == null) {
			if (other.id != null)
				return false;
		} else if (!id.equals(other.id))
			return false;
		return true;
	}

	public Date getDateVal() {
		return this.dateVal;
	}

	public Double getDoubleVal() {
		return this.doubleVal;
	}

	public String getId() {
		return id;
	}

	public Integer getIntVal() {
		return intVal;
	}

	public String getKeyName() {
		return this.keyName;
	}

	public Long getLongVal() {
		return this.longVal;
	}

	public String getName() {
		return this.keyName;
	}

	public String getStringVal() {
		return this.stringVal;
	}

	public String getTaskId() {
		return this.taskId;
	}

	public String getTextVal() {
		return textVal;
	}

	public String getTitle() {
		return title;
	}

	public String getTypeCd() {
		return this.typeCd;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((id == null) ? 0 : id.hashCode());
		return result;
	}

	public boolean isAutoTypeConvert() {
		return autoTypeConvert;
	}

	public SchedulerParam jsonToObject(JSONObject jsonObject) {
		return SchedulerParamJsonFactory.jsonToObject(jsonObject);
	}

	public void setAutoTypeConvert(boolean autoTypeConvert) {
		this.autoTypeConvert = autoTypeConvert;
	}

	public void setDateVal(Date dateVal) {
		this.dateVal = dateVal;
	}

	public void setDoubleVal(Double doubleVal) {
		this.doubleVal = doubleVal;
	}

	public void setId(String id) {
		this.id = id;
	}

	public void setIntVal(Integer intVal) {
		this.intVal = intVal;
	}

	public void setKeyName(String keyName) {
		this.keyName = keyName;
	}

	public void setLongVal(Long longVal) {
		this.longVal = longVal;
	}

	public void setName(String keyName) {
		this.keyName = keyName;
	}

	public void setStringVal(String stringVal) {
		this.stringVal = stringVal;
	}

	public void setTaskId(String taskId) {
		this.taskId = taskId;
	}

	public void setTextVal(String textVal) {
		this.textVal = textVal;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public void setTypeCd(String typeCd) {
		this.typeCd = typeCd;
	}

	public JSONObject toJsonObject() {
		return SchedulerParamJsonFactory.toJsonObject(this);
	}

	public ObjectNode toObjectNode() {
		return SchedulerParamJsonFactory.toObjectNode(this);
	}

	public String toString() {
		return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE);
	}

}


text:
package com.google.cloud.dataflow.sdk.util;

import static com.google.common.base.Verify.verifyNotNull;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;

import com.google.api.client.googleapis.json.GoogleJsonError;
import com.google.api.client.googleapis.json.GoogleJsonError.ErrorInfo;
import com.google.api.client.googleapis.json.GoogleJsonErrorContainer;
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.client.http.LowLevelHttpResponse;
import com.google.api.client.json.GenericJson;
import com.google.api.client.json.Json;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.testing.http.MockHttpTransport;
import com.google.api.client.testing.http.MockLowLevelHttpRequest;
import com.google.api.client.util.BackOff;
import com.google.api.client.util.Sleeper;
import com.google.api.services.bigquery.Bigquery;
import com.google.api.services.bigquery.model.Table;
import com.google.api.services.bigquery.model.TableDataInsertAllResponse;
import com.google.api.services.bigquery.model.TableReference;
import com.google.api.services.bigquery.model.TableRow;
import com.google.cloud.dataflow.sdk.testing.ExpectedLogs;
import com.google.cloud.hadoop.util.RetryBoundedBackOff;
import com.google.common.collect.ImmutableList;

import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * Tests of {@link BigQueryTableInserter}.
 */
@RunWith(JUnit4.class)
public class BigQueryTableInserterTest {
  @Rule public ExpectedException thrown = ExpectedException.none();
  @Rule public ExpectedLogs expectedLogs = ExpectedLogs.none(BigQueryTableInserter.class);
  @Mock private LowLevelHttpResponse response;
  private Bigquery bigquery;

  @Before
  public void setUp() {
    MockitoAnnotations.initMocks(this);

    // A mock transport that lets us mock the API responses.
    MockHttpTransport transport =
        new MockHttpTransport.Builder()
            .setLowLevelHttpRequest(
                new MockLowLevelHttpRequest() {
                  @Override
                  public LowLevelHttpResponse execute() throws IOException {
                    return response;
                  }
                })
            .build();

    // A sample BigQuery API client that uses default JsonFactory and RetryHttpInitializer.
    bigquery =
        new Bigquery.Builder(
                transport, Transport.getJsonFactory(), new RetryHttpRequestInitializer())
            .build();
  }

  @After
  public void tearDown() throws IOException {
    // These three interactions happen for every request in the normal response parsing.
    verify(response, atLeastOnce()).getContentEncoding();
    verify(response, atLeastOnce()).getHeaderCount();
    verify(response, atLeastOnce()).getReasonPhrase();
    verifyNoMoreInteractions(response);
  }

  /** A helper to wrap a {@link GenericJson} object in a content stream. */
  private static InputStream toStream(GenericJson content) throws IOException {
    return new ByteArrayInputStream(JacksonFactory.getDefaultInstance().toByteArray(content));
  }

  /** A helper that generates the error JSON payload that Google APIs produce. */
  private static GoogleJsonErrorContainer errorWithReasonAndStatus(String reason, int status) {
    ErrorInfo info = new ErrorInfo();
    info.setReason(reason);
    info.setDomain("global");
    // GoogleJsonError contains one or more ErrorInfo objects; our utiities read the first one.
    GoogleJsonError error = new GoogleJsonError();
    error.setErrors(ImmutableList.of(info));
    error.setCode(status);
    // The actual JSON response is an error container.
    GoogleJsonErrorContainer container = new GoogleJsonErrorContainer();
    container.setError(error);
    return container;
  }

  /**
   * Tests that {@link BigQueryTableInserter} succeeds on the first try.
   */
  @Test
  public void testCreateTableSucceeds() throws IOException {
    Table testTable = new Table().setDescription("a table");

    when(response.getContentType()).thenReturn(Json.MEDIA_TYPE);
    when(response.getStatusCode()).thenReturn(200);
    when(response.getContent()).thenReturn(toStream(testTable));

    BigQueryTableInserter inserter = new BigQueryTableInserter(bigquery);
    Table ret =
        inserter.tryCreateTable(
            new Table(),
            "project",
            "dataset",
            new RetryBoundedBackOff(0, BackOff.ZERO_BACKOFF),
            Sleeper.DEFAULT);
    assertEquals(testTable, ret);
    verify(response, times(1)).getStatusCode();
    verify(response, times(1)).getContent();
    verify(response, times(1)).getContentType();
  }

  /**
   * Tests that {@link BigQueryTableInserter} succeeds when the table already exists.
   */
  @Test
  public void testCreateTableSucceedsAlreadyExists() throws IOException {
    when(response.getStatusCode()).thenReturn(409); // 409 means already exists

    BigQueryTableInserter inserter = new BigQueryTableInserter(bigquery);
    Table ret =
        inserter.tryCreateTable(
            new Table(),
            "project",
            "dataset",
            new RetryBoundedBackOff(0, BackOff.ZERO_BACKOFF),
            Sleeper.DEFAULT);

    assertNull(ret);
    verify(response, times(1)).getStatusCode();
    verify(response, times(1)).getContent();
    verify(response, times(1)).getContentType();
  }

  /**
   * Tests that {@link BigQueryTableInserter} retries quota rate limited attempts.
   */
  @Test
  public void testCreateTableRetry() throws IOException {
    TableReference ref =
        new TableReference().setProjectId("project").setDatasetId("dataset").setTableId("table");
    Table testTable = new Table().setTableReference(ref);

    // First response is 403 rate limited, second response has valid payload.
    when(response.getContentType()).thenReturn(Json.MEDIA_TYPE);
    when(response.getStatusCode()).thenReturn(403).thenReturn(200);
    when(response.getContent())
        .thenReturn(toStream(errorWithReasonAndStatus("rateLimitExceeded", 403)))
        .thenReturn(toStream(testTable));

    BigQueryTableInserter inserter = new BigQueryTableInserter(bigquery);
    Table ret =
        inserter.tryCreateTable(
            testTable,
            "project",
            "dataset",
            new RetryBoundedBackOff(3, BackOff.ZERO_BACKOFF),
            Sleeper.DEFAULT);
    assertEquals(testTable, ret);
    verify(response, times(2)).getStatusCode();
    verify(response, times(2)).getContent();
    verify(response, times(2)).getContentType();
    verifyNotNull(ret.getTableReference());
    expectedLogs.verifyInfo(
        "Quota limit reached when creating table project:dataset.table, "
            + "retrying up to 5.0 minutes");
  }

  /**
   * Tests that {@link BigQueryTableInserter} does not retry non-rate-limited attempts.
   */
  @Test
  public void testCreateTableDoesNotRetry() throws IOException {
    Table testTable = new Table().setDescription("a table");

    // First response is 403 not-rate-limited, second response has valid payload but should not
    // be invoked.
    when(response.getContentType()).thenReturn(Json.MEDIA_TYPE);
    when(response.getStatusCode()).thenReturn(403).thenReturn(200);
    when(response.getContent())
        .thenReturn(toStream(errorWithReasonAndStatus("actually forbidden", 403)))
        .thenReturn(toStream(testTable));

    thrown.expect(GoogleJsonResponseException.class);
    thrown.expectMessage("actually forbidden");

    BigQueryTableInserter inserter = new BigQueryTableInserter(bigquery);
    try {
      inserter.tryCreateTable(
          new Table(),
          "project",
          "dataset",
          new RetryBoundedBackOff(3, BackOff.ZERO_BACKOFF),
          Sleeper.DEFAULT);
      fail();
    } catch (IOException e) {
      verify(response, times(1)).getStatusCode();
      verify(response, times(1)).getContent();
      verify(response, times(1)).getContentType();
      throw e;
    }
  }

  /**
   * Tests that {@link BigQueryTableInserter#insertAll} retries quota rate limited attempts.
   */
  @Test
  public void testInsertRetry() throws IOException {
    TableReference ref =
        new TableReference().setProjectId("project").setDatasetId("dataset").setTableId("table");
    List<TableRow> rows = new ArrayList<>();
    rows.add(new TableRow());

    // First response is 403 rate limited, second response has valid payload.
    when(response.getContentType()).thenReturn(Json.MEDIA_TYPE);
    when(response.getStatusCode()).thenReturn(403).thenReturn(200);
    when(response.getContent())
        .thenReturn(toStream(errorWithReasonAndStatus("rateLimitExceeded", 403)))
        .thenReturn(toStream(new TableDataInsertAllResponse()));

    BigQueryTableInserter inserter = new BigQueryTableInserter(bigquery);

    inserter.insertAll(ref, rows);
    verify(response, times(2)).getStatusCode();
    verify(response, times(2)).getContent();
    verify(response, times(2)).getContentType();
    expectedLogs.verifyInfo("BigQuery insertAll exceeded rate limit, retrying");
  }

  /**
   * Tests that {@link BigQueryTableInserter#insertAll} does not retry non-rate-limited attempts.
   */
  @Test
  public void testInsertDoesNotRetry() throws Throwable {
    TableReference ref =
        new TableReference().setProjectId("project").setDatasetId("dataset").setTableId("table");
    List<TableRow> rows = new ArrayList<>();
    rows.add(new TableRow());

    // First response is 403 not-rate-limited, second response has valid payload but should not
    // be invoked.
    when(response.getContentType()).thenReturn(Json.MEDIA_TYPE);
    when(response.getStatusCode()).thenReturn(403).thenReturn(200);
    when(response.getContent())
        .thenReturn(toStream(errorWithReasonAndStatus("actually forbidden", 403)))
        .thenReturn(toStream(new TableDataInsertAllResponse()));

    thrown.expect(GoogleJsonResponseException.class);
    thrown.expectMessage("actually forbidden");

    BigQueryTableInserter inserter = new BigQueryTableInserter(bigquery);

    try {
      inserter.insertAll(ref, rows);
      fail();
    } catch (RuntimeException e) {
      verify(response, times(1)).getStatusCode();
      verify(response, times(1)).getContent();
      verify(response, times(1)).getContentType();
      throw e.getCause();
    }
  }
}


text:
BigReactors
===========

What is this?
-------------

An upcoming mod for Minecraft, based on adding new and fun ways to generate power through big multi-block structures. Don't just plop blocks, design the machines yourself!

For near-future plans and development status, see the Roadmap file.

Big Reactors has an official website at [www.big-reactors.com](http://www.big-reactors.com)

Alpha
--------

Big Reactors is in an alpha state. The major features exist, and there are no _known_ serious bugs. However, it's not fully balanced. I'm only one guy - I can't totally break all the combinations you crazy folks will discover. The internal radiation/power production simulation is very complicated.

You can download the latest alpha from [the big-reactors.com download page](http://www.big-reactors.com/#/download).

_You will need other mods_ to play with Big Reactors. This is just a power-generation mod, so you will need a mod that supports the Redstone Flux (RF) power system. I personally recommend [Thermal Expansion](http://teamcofh.com/thermal-expansion).

License
-------

Licensing for Minecraft mods is silly. If you want to use my mod on your server, in your modpack, whatever, do it, have fun! If you want to use, copy or fork my code, go for it, have fun!

For the pedantic, copied from LICENSE.txt:

The MIT License (MIT)

Copyright (c) 2013, 2014 "Erogenous Beef"

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.


text:
<datasources>
  <datasource jndi-name="java:jboss/datasources/ExampleDS" pool-name="ExampleDS" enabled="true" use-java-context="true">
    <connection-url>jdbc:h2:mem:test;DB_CLOSE_DELAY=-1</connection-url>
    <driver>h2</driver>
    <security>
      <user-name>sa</user-name>
      <password>sa</password>
    </security>
  </datasource>
  <xa-datasource jndi-name="java:jboss/datasources/ProcessEngine" enabled="true" use-ccm="true"
                 pool-name="ProcessEngine">
    <xa-datasource-property name="URL">${database.url}</xa-datasource-property>
    <driver>h2</driver>
    <transaction-isolation>TRANSACTION_READ_COMMITTED</transaction-isolation>
    <xa-datasource-property name="User">${database.username}</xa-datasource-property>
    <xa-datasource-property name="password">${database.password}</xa-datasource-property>
  </xa-datasource>
</datasources>


text:
macro_rules! mac1 {
    ($eval:expr) => {
        let mut $eval = ();
        //~^ ERROR `mut` must be followed by a named binding
    };
}

macro_rules! mac2 {
    ($eval:pat) => {
        let mut $eval = ();
        //~^ ERROR `mut` must be followed by a named binding
        //~| ERROR expected identifier, found `does_not_exist!()`
    };
}

fn foo() {
    mac1! { does_not_exist!() }
    //~^ ERROR cannot find macro `does_not_exist` in this scope
    mac2! { does_not_exist!() }
    //~^ ERROR cannot find macro `does_not_exist` in this scope
}

fn main() {}


text:
namespace EntertainmentSystem.Web.Areas.Forum.Controllers
{
    using System.Linq;
    using System.Web.Mvc;
    using Common.Constants;
    using Services.Contracts.Forum;

    public class PostCategoryController : PostsBaseController
    {
        private readonly IForumCategoryService categoryService;

        public PostCategoryController(IForumPostService postService, IForumCategoryService categoryService)
            : base(postService)
        {
            this.categoryService = categoryService;
        }

        [HttpGet]
        public ActionResult Index(
            int page = GlobalConstants.ForumStartPage,
            string search = GlobalConstants.StringEmpty,
            string name = GlobalConstants.StringEmpty)
        {
            this.ViewBag.Title = "Category \"" + name + "\"";

            var result = this.ConditionalActionResult(
                () => this.GetPostsPage(
                    this.PostServise.GetAll()
                    .Where(p => p.PostCategory.Name == name),
                    page,
                    search,
                    name),
                (content) => this.View(content));

            return result;
        }

        [Authorize]
        [HttpGet]
        public JsonResult GetCategories()
        {
            var categories = this.categoryService.GetAll().ToList();
            var result = this.Json(categories, JsonRequestBehavior.AllowGet);

            return result;
        }
    }
}


text:
"use strict";
app.controller("singleOrgCtrl", ["$http", "$state", "$stateParams","lodash","ngNotify", function($http, $state, $stateParams, _, ngNotify){
  const self = this;
  ngNotify.config({
    theme: 'pure',
    position: 'bottom',
    duration: 5000,
    type: 'info',
    sticky: false,
    button: true,
    html: false
  });
  self.orgAbrev = $stateParams.abrev;
  self.orgId = $stateParams.orgId;
  $http.get(`/api/${self.orgId}/practice`)
  .then((data) =>{
    self.currentPractices = data.data;
  });

  self.setSelectedPractice = (practice) => {
    console.log(practice);
    self.selectedPractice = practice;
  };

  self.deletePractice = ()=>{
    const remainingPractices =[];
    $http({
      url: "/api/practice",
      method: "DELETE",
      headers: {delparams: JSON.stringify(self.selectedPractice)}
    })
    .then(()=>{
      ngNotify.set("Deleted practice successfully");
      self.currentPractices.map((item)=>{
        if(item.title !== self.selectedPractice.title){
          remainingPractices.push(item);
        }
      });
      self.currentPractices = remainingPractices;
    });
  };

}]);


text:
function sensorPlotColor(sensor,type)
% Plot sensor cross-correlations
%
% Synopsis
%  sensorColorPlot(sa,[type=RB'])
%
% Description
%  This routine analyzes the scene color properties, usually color
%  balancing. The routine produces a graph that includes the
%  cross-corrrelation and indicates the expected distribution assuming
%  various different color temperatures of the ambient illumination.
%
% Example:
%   sensor = vcGetObject('ISA');
%   sensorPlotColor(sensor,'rg')
%
% Copyright ImagEval Consultants, LLC, 2005.

if ieNotDefined('sa'),   sensor = ieGetObject('sensor'); end
if ieNotDefined('type'), type = 'rg'; end

labels = {'Red sensor','Green sensor','Blue sensor'};

% Demosiac the (R,B) values.
wave       = sensorGet(sensor,'wave');
spectralQE = sensorGet(sensor,'spectral QE');

% We need a default, target display to do the demosaic'ing
ip = ipCreate;
ip = ipSet(ip,'input',sensorGet(sensor,'volts'));
demosaicedImage = Demosaic(ip,sensor);

ieNewGraphWin;

switch lower(type)
    case 'rg'
        dList = [1,2];
    case 'rb'
        dList = [1,3];
    otherwise
        error('Unknown plot type.');
end

% Make the scatter plot after demosaicing the sensor data
d1 = demosaicedImage(:,:,dList(1));
d2 = demosaicedImage(:,:,dList(2));
d = sqrt(d1.^2 + d2.^2);
d = max(d(:));

% We should probably check to see that d1,d2 aren't too big.  If they are
% randomly sample.
plot(d1(:),d2(:),'.'); axis equal
xlabel(labels{dList(1)}); ylabel(labels{dList(2)});

% Estimate the slope for white surfaces at these color temperatures
cTemp = [2500,3000,3500,4000,4500,5500,6500,8000,10500];

for ii=1:length(cTemp)
    spec = Energy2Quanta(wave,blackbody(wave, cTemp(ii) ));
    rgb = spectralQE'*spec;
    rgb = 0.9*d*(rgb/sqrt(sum(rgb(dList).^2)));
    txt = sprintf('%.1fK',round(cTemp(ii)/100)/10);
    hold on; plot(rgb(dList(1)),rgb(dList(2)),'k.');
    text(rgb(dList(1))+0.02,rgb(dList(2)),txt)
end
hold off

set(gca,'xlim',[0 d], 'ylim', [0,d])
title('Sensor Color Balance');
grid on;

uData.name = 'sensorColorPlot';
uData.d1 = d1;
uData.d2 = d2;
uData.rgb = rgb;
set(gcf,'userdata',uData);

end


text:
<?php

namespace Postmark\Tests;

require_once __DIR__ . "/PostmarkClientBaseTest.php";

use Postmark\Tests\PostmarkClientBaseTest as PostmarkClientBaseTest;
use \Postmark\PostmarkClient;

class PostmarkClickClientStatisticsTest extends PostmarkClientBaseTest {

	function testClientCanGetClickOverviewStatistics() {
		$tk = parent::$testKeys;
		$client = new PostmarkClient($tk->READ_LINK_TRACKING_TEST_SERVER_TOKEN, $tk->TEST_TIMEOUT);

		$stats = $client->getOutboundClickStatistics();

		$this->assertNotNull($stats);
	}

	function testClientCanGetClickBrowserFamilies() {
		$tk = parent::$testKeys;
		$client = new PostmarkClient($tk->READ_LINK_TRACKING_TEST_SERVER_TOKEN, $tk->TEST_TIMEOUT);

		$stats = $client->getOutboundClickBrowserFamilyStatistics();

		$this->assertNotNull($stats);
	}

	function testClientCanGetClickBrowserPlatformStatistics() {
		$tk = parent::$testKeys;
		$client = new PostmarkClient($tk->READ_LINK_TRACKING_TEST_SERVER_TOKEN, $tk->TEST_TIMEOUT);

		$stats = $client->getOutboundClickBrowserPlatformStatistics();

		$this->assertNotEmpty($stats);
	}

	function testClientCanGetClickLocationStatistics() {
		$tk = parent::$testKeys;
		$client = new PostmarkClient($tk->READ_LINK_TRACKING_TEST_SERVER_TOKEN, $tk->TEST_TIMEOUT);

		$stats = $client->getOutboundClickLocationStatistics();

		$this->assertNotNull($stats);
	}
}

?>


text:
source ./env.sh

cd $GAE_ROOTDIR
go test ./src/sample1/...


text:
<?php

namespace Backend\Modules\Locale\Engine;

use Symfony\Component\Filesystem\Filesystem;

/**
 * In this file, the locale cache is build
 */
class CacheBuilder
{
    /**
     * @var \SpoonDatabase
     */
    protected $database;

    /**
     * @var array
     */
    protected $locale;

    /**
     * @param \SpoonDatabase $database
     */
    public function __construct(\SpoonDatabase $database)
    {
        $this->database = $database;
    }

    /**
     * @param string $language
     * @param string $application Backend or Frontend
     */
    public function buildCache(string $language, string $application): void
    {
        $this->locale = $this->getLocale($language, $application);
        $this->dumpJsonCache($language, $application);
    }

    /**
     * Fetches locale for a certain language application combo
     *
     * @param string $language
     * @param string $application
     *
     * @return array
     */
    protected function getLocale(string $language, string $application): array
    {
        return (array) $this->database->getRecords(
            'SELECT type, module, name, value
             FROM locale
             WHERE language = ? AND application = ?
             ORDER BY type ASC, name ASC, module ASC',
            [$language, $application]
        );
    }

    /**
     * Builds the array that will be put in cache
     *
     * @param string $language
     * @param string $application
     *
     * @return array
     */
    protected function buildJsonCache(string $language, string $application): array
    {
        // init var
        $json = [];
        foreach (Model::TYPES as $type) {
            // loop locale
            foreach ($this->locale as $i => $item) {
                // types match
                if ($item['type'] == $type) {
                    if ($application == 'Backend') {
                        $json[$type][$item['module']][$item['name']] = $item['value'];
                    } else {
                        $json[$type][$item['name']] = $item['value'];
                    }
                }
            }
        }

        $this->addSpoonLocale($json, $language);

        return $json;
    }

    /**
     * Adds months and days from spoonLocale to the json
     *
     * @param array  $json
     * @param string $language
     */
    protected function addSpoonLocale(array &$json, string $language): void
    {
        // get months
        $monthsLong = \SpoonLocale::getMonths($language, false);
        $monthsShort = \SpoonLocale::getMonths($language, true);

        // get days
        $daysLong = \SpoonLocale::getWeekDays($language, false, 'sunday');
        $daysShort = \SpoonLocale::getWeekDays($language, true, 'sunday');

        // build labels
        foreach ($monthsLong as $key => $value) {
            $json['loc']['MonthLong' . \SpoonFilter::ucfirst($key)] = $value;
        }
        foreach ($monthsShort as $key => $value) {
            $json['loc']['MonthShort' . \SpoonFilter::ucfirst($key)] = $value;
        }
        foreach ($daysLong as $key => $value) {
            $json['loc']['DayLong' . \SpoonFilter::ucfirst($key)] = $value;
        }
        foreach ($daysShort as $key => $value) {
            $json['loc']['DayShort' . \SpoonFilter::ucfirst($key)] = $value;
        }
    }

    /**
     * dumps the locale in cache as a json object
     *
     * @param string $language
     * @param string $application
     */
    protected function dumpJsonCache(string $language, string $application): void
    {
        $filesystem = new Filesystem();
        $filesystem->dumpFile(
            constant(mb_strtoupper($application) . '_CACHE_PATH') . '/Locale/' . $language . '.json',
            json_encode($this->buildJsonCache($language, $application))
        );
    }
}


text:
var keystone = require('keystone'),
	async = require('async');

exports = module.exports = function(req, res) {

	if (req.user) {
		return res.redirect(req.cookies.target || '/me');
	}

	var view = new keystone.View(req, res),
		locals = res.locals;

	locals.section = 'session';
	locals.form = req.body;

	view.on('post', { action: 'join' }, function(next) {

		async.series([

			function(cb) {

				if (!req.body.firstname || !req.body.lastname || !req.body.email || !req.body.password) {
					req.flash('error', 'Please enter a name, email and password.');
					return cb(true);
				}

				return cb();

			},

			function(cb) {

				keystone.list('User').model.findOne({ email: req.body.email }, function(err, user) {

					if (err || user) {
						req.flash('error', 'User already exists with that email address.');
						return cb(true);
					}

					return cb();

				});

			},

			function(cb) {

				var userData = {
					name: {
						first: req.body.firstname,
						last: req.body.lastname,
					},
					email: req.body.email,
					password: req.body.password,

					website: req.body.website
				};

				var User = keystone.list('User').model,
					newUser = new User(userData);

				newUser.save(function(err) {
					return cb(err);
				});

			}

		], function(err){

			if (err) return next();

			var onSuccess = function() {
				if (req.body.target && !/join|signin/.test(req.body.target)) {
					console.log('[join] - Set target as [' + req.body.target + '].');
					res.redirect(req.body.target);
				} else {
					res.redirect('/me');
				}
			}

			var onFail = function(e) {
				req.flash('error', 'There was a problem signing you in, please try again.');
				return next();
			}

			keystone.session.signin({ email: req.body.email, password: req.body.password }, req, res, onSuccess, onFail);

		});

	});

	view.render(keystone.lang + '/session/join');

}


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>
Uses of Package org.apache.hadoop.mapred.gridmix.emulators.resourceusage (Apache Hadoop Gridmix 2.3.0 API)
</TITLE>

<META NAME="date" CONTENT="2015-03-06">

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

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Package
org.apache.hadoop.mapred.gridmix.emulators.resourceusage

Packages that use org.apache.hadoop.mapred.gridmix.emulators.resourceusage

org.apache.hadoop.mapred.gridmix.emulators.resourceusage

Classes in org.apache.hadoop.mapred.gridmix.emulators.resourceusage used by org.apache.hadoop.mapred.gridmix.emulators.resourceusage

CumulativeCpuUsageEmulatorPlugin.CpuUsageEmulatorCore

          This is the core CPU usage emulation algorithm.

ResourceUsageEmulatorPlugin

          Each resource to be emulated should have a corresponding implementation
 class that implements ResourceUsageEmulatorPlugin.

TotalHeapUsageEmulatorPlugin.HeapUsageEmulatorCore

          Defines the core heap usage emulation algorithm.

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Copyright © 2015 Apache Software Foundation. All Rights Reserved.


text:
<ui:UiBinder xmlns:ui="urn:ui:com.google.gwt.uibinder"
             xmlns:b="urn:import:org.gwtbootstrap3.client.ui"
             xmlns:b.html="urn:import:org.gwtbootstrap3.client.ui.html"
             xmlns:b3="urn:import:org.gwtbootstrap3.extras.slider.client.ui"
             xmlns:d="urn:import:org.gwtbootstrap3.demo.client.ui">

    <ui:style>
        .danger {
            background-color: #fcf2f2;
            border-color: #dFb5b4;
        }

        .margin-fix {
            margin-top: 0 !important;
        }

        .spacing {
            margin-left: 5px;
        }
    </ui:style>

                Original Library Link:
                Bootstrap
                    Slider

                Current Version Supported: 1.4.3

                    To use Slider, you must first add the extras module to your project. In Maven:

                <d:PrettyPre addStyleNames="lang-xml">
                    <dependency>\n
                    \s\s\s\s<groupId>org.gwtbootstrap3</groupId>\n
                    \s\s\s\s<artifactId>gwtbootstrap3-extras</artifactId>\n
                    \s\s\s\s<version>VERSION</version>\n
                    \s\s\s\s<scope>provided</scope>\n
                    </dependency>
                </d:PrettyPre>

                    Then you need to inherit the following GWT Module
                    additionally
                    to any GwtBootstrap3
                    module into your *.gwt.xml of your project:

                <d:PrettyPre addStyleNames="lang-xml">
                    <inherits name="org.gwtbootstrap3.extras.slider.Slider"/>
                </d:PrettyPre>

                    Last but not least must add this namespace to your *.ui.xml (don't have to name it b3):

                <d:PrettyPre addStyleNames="lang-xml">
                    xmlns:b3="urn:import:org.gwtbootstrap3.extras.slider.client.ui"
                </d:PrettyPre>

                    <b3:Slider/>

                    <d:PrettyPre addStyleNames="lang-xml">
                        <b3:Slider/>\n
                    </d:PrettyPre>

                    <b3:Slider ui:field="customSlider" value="250.0" min="-150.0" max="500.0" step="5.0"
                               handle="SQUARE"/>

                    <d:PrettyPre addStyleNames="lang-xml">
                        <b3:Slider ui:field="customSlider" value="250.0" min="-150.0" max="500.0" step="5.0"
                        handle="SQUARE"/>\n
                    </d:PrettyPre>
                    <d:PrettyPre addStyleNames="lang-java">
                        customSlider.setFormatter(new FormatterCallback() {\n
                        \s@Override\n
                        \s\spublic String toolTipMsg(double value) {\n
                        \s\s\sint b = (int) (value * 10);\n
                        \s\s\sreturn b + " blocks";\n
                        \s\s}\n
                        \s});\n
                    </d:PrettyPre>

                    <b3:Slider orientation="VERTICAL"/>

                    <d:PrettyPre addStyleNames="lang-xml">
                        <b3:Slider orientation="VERTICAL"/>\n
                    </d:PrettyPre>

</ui:UiBinder>


text:
LIB_JAVA=${SWAC_HOME}/lib/java

function usage() {
cat << EOF
Usage: `basename $0` scenario_name base_date forecast_fiscal_year [classifier] [-u] [[-f|--files] file_name data_class [...]]
       `basename $0` -h
    Creates the necessary files and directories to run a given scenario.

    scenario_name - The name to give to the created scenario.
    base_date - The base date for the scenario (yyyyMMdd).
    forecast_fiscal_year - The forecast fiscal year for the scenario (yyyy).

    classifier - The scenario classifier.

    -f|--files: Override following scenario files
        (
            file_name: The name or the fileglob filter to identify the file(s).
                       Any valid input to the ls command.
            data_class: The Java class which will be used to read in the
                        contents of the file.
        )
    -u: Update scenario
        Allows the user to modify an existing scenario. The base dates, forecast
        fiscal years, classifiers, or overridden files may be changed. NOTE:
        Any previously overridden files will be reverted to the default unless
        the override is specified again.
    -h: help
        outputs this usage statement.
EOF
    exit $1
}

function file_substitution() {
    TMP="$NEW_SCENARIO_DIR/temp/tmp.txt"

    sed s:"$2":"$3":g "$1" > "$TMP"

    errno="$?"

    if [[ $errno != 0 ]]; then
        echo "FATAL: Error creating scenario file: "${1}". sed exited with errno: ${errno}."
        swac-delete-scenario "$SCENARIO_NAME" 2>/dev/null
        exit $errno
    fi

    mv "$TMP" "$1"

    errno="$?"

    if [[ $errno != 0 ]]; then
        echo "FATAL: Error creating scenario file: "${1}". mv exited with errno: ${errno}."
        swac-delete-scenario "$SCENARIO_NAME" 2>/dev/null
        exit $errno
    fi
}

################################################
# START SCRIPT EXECUTION
################################################
#$1 - Scenario Name
#$2 - Base Date (yyyyMMdd)
#$3 - Forecast Fiscal Year
#$4 - Classifier

if [[ $# < 3 ]]
then
    usage 1
fi

SCENARIO_NAME="$1"
BASE_DATES="$2"
FORECAST_FISCAL_YEARS="$3"
CLASSIFIERS="base"
F_OPTIONS=""

shift 3

if [[ $# > 0 && $4 != -* ]]; then
    CLASSIFIERS=$1
    shift 1
fi

update_only=false

while getopts "hf:u:-:" OPTION; do
    case $OPTION in
        f)
            shift 1

            F_OPTIONS=$@
            echo "f options ${F_OPTIONS}"
            ;;
        u)
            update_only=true
            ;;
        -)
        	shift 1

        	F_OPTIONS=$@
            echo "f options ${F_OPTIONS}"
            ;;
        h)
            usage 0
            ;;
        *)
            usage 1
            ;;
    esac
done

NEW_SCENARIO_DIR="$SWAC_WORK/scenarios/$SCENARIO_NAME"
NEW_SCENARIO_XML_FILE="$NEW_SCENARIO_DIR/$SCENARIO_NAME.xml"
NEW_SCENARIO_PROPERTIES_FILE="$NEW_SCENARIO_DIR/$SCENARIO_NAME.properties"

if [[ $update_only == true && (-d "$NEW_SCENARIO_DIR") ]]; then
    rm "$NEW_SCENARIO_PROPERTIES_FILE"

    errno=$?

    if [[ $errno != 0 ]]; then
        echo "ERROR: Update to properties file failed! rm exited with status ${errno}"
        exit $errno
    fi

    cp "$SWAC_WORK/scenarios/scenario/scenario.properties" "$NEW_SCENARIO_PROPERTIES_FILE"

    errno=$?

    if [[ $errno != 0 ]]; then
        echo "ERROR: Update to properties file failed! cp exited with status ${errno}"
        exit $errno
    fi
else
    swac-copy-scenario scenario "$SCENARIO_NAME"

    errno=$?

    if [[ $errno != 0 ]]; then
        # At this point, swac-copy-scenario will have already logged the error message:
        # "FATAL: Scenario name is already in use"
        echo "	To delete the existing scenario, run \"swac -x $SCENARIO_NAME\""
        exit $errno
    fi

    echo "INFO: Scenario XML file: ${NEW_SCENARIO_XML_FILE} created."
fi

file_substitution "$NEW_SCENARIO_PROPERTIES_FILE" "BASE_DATE=BASE_DATE" "BASE_DATE=${BASE_DATES}"
file_substitution "$NEW_SCENARIO_PROPERTIES_FILE" "FORECAST_FISCAL_YEAR=FORECAST_FISCAL_YEAR" "FORECAST_FISCAL_YEAR=${FORECAST_FISCAL_YEARS}"
file_substitution "$NEW_SCENARIO_PROPERTIES_FILE" "CLASSIFIER=CLASSIFIER" "CLASSIFIER=${CLASSIFIERS}"

echo "INFO: Scenario properties file: ${NEW_SCENARIO_PROPERTIES_FILE} created."

java -Dswac.work.dir="$SWAC_WORK" -cp "${LIB_JAVA}/"\* gov.faa.ang.swac.controller.ScenarioImportsFileGenerator $SCENARIO_NAME $BASE_DATES $FORECAST_FISCAL_YEARS $CLASSIFIERS $F_OPTIONS

echo "INFO: Finished creating scenario ${SCENARIO_NAME}";


text:
package com.inversoft.passport.domain.api;

import com.inversoft.json.JacksonConstructor;
import com.inversoft.passport.domain.UserComment;

/**
 * @author Seth Musselman
 */
public class UserCommentRequest {
  public UserComment userComment;

  @JacksonConstructor
  public UserCommentRequest() {
  }

  public UserCommentRequest(UserComment userComment) {
    this.userComment = userComment;
  }
}


text:
package executor

import (
	"sync"
	"time"

	log "github.com/golang/glog"
)

type (
	// filter registration events, return false to abort further processing of the event
	watchFilter func(pod *PodEvent) (accept bool)

	watchExpiration struct {
		// timeout closes when the handler has expired; it delivers at most one Time.
		timeout <-chan time.Time

		// onEvent is an optional callback that is invoked if/when the expired chan
		// closes
		onEvent func(taskID string)
	}

	watchHandler struct {
		// prevent callbacks from being invoked simultaneously
		sync.Mutex

		// handle registration events, return true to indicate the handler should be
		// de-registered upon completion. If pod is nil then the associated handler
		// has expired.
		onEvent func(pod *PodEvent) (done bool, err error)

		// expiration is an optional configuration that indicates when a handler should
		// be considered to have expired, and what action to take upon such
		expiration watchExpiration
	}

	// watcher observes PodEvent events and conditionally executes handlers that
	// have been associated with the taskID of the PodEvent.
	watcher struct {
		updates  <-chan *PodEvent
		rw       sync.RWMutex
		handlers map[string]watchHandler
		filters  []watchFilter
		runOnce  chan struct{}
	}
)

func newWatcher(updates <-chan *PodEvent) *watcher {
	return &watcher{
		updates:  updates,
		handlers: make(map[string]watchHandler),
		runOnce:  make(chan struct{}),
	}
}

func (pw *watcher) run() {
	select {
	case <-pw.runOnce:
		log.Error("run() has already been invoked for this pod-watcher")
		return
	default:
		close(pw.runOnce)
	}
updateLoop:
	for u := range pw.updates {
		log.V(2).Info("filtering " + u.FormatShort())
		for _, f := range pw.filters {
			if !f(u) {
				continue updateLoop
			}
		}
		log.V(1).Info("handling " + u.FormatShort())
		h, ok := func() (h watchHandler, ok bool) {
			pw.rw.RLock()
			defer pw.rw.RUnlock()
			h, ok = pw.handlers[u.taskID]
			return
		}()
		if ok {
			log.V(1).Info("executing action for " + u.FormatShort())
			done, err := func() (bool, error) {
				h.Lock()
				defer h.Unlock()
				return h.onEvent(u)
			}()
			if err != nil {
				log.Error(err)
			}
			if done {
				// de-register handler upon successful completion of action
				log.V(1).Info("de-registering handler for " + u.FormatShort())
				func() {
					pw.rw.Lock()
					delete(pw.handlers, u.taskID)
					pw.rw.Unlock()
				}()
			}
		}
	}
}

func (pw *watcher) addFilter(f watchFilter) {
	select {
	case <-pw.runOnce:
		log.Errorf("failed to add filter because pod-watcher is already running")
	default:
		pw.filters = append(pw.filters, f)
	}
}

// forTask associates a handler `h` with the given taskID.
func (pw *watcher) forTask(taskID string, h watchHandler) {
	pw.rw.Lock()
	pw.handlers[taskID] = h
	pw.rw.Unlock()

	if exp := h.expiration; exp.timeout != nil {
		go func() {
			<-exp.timeout
			log.V(1).Infof("expiring handler for task %v", taskID)

			// de-register handler upon expiration
			pw.rw.Lock()
			delete(pw.handlers, taskID)
			pw.rw.Unlock()

			if exp.onEvent != nil {
				h.Lock()
				defer h.Unlock()
				exp.onEvent(taskID)
			}
		}()
	}
}


text:
package com.ripplargames.meshio.vertices;

public enum VertexType {
    Position_X,
    Position_Y,
    Position_Z,
    Normal_X,
    Normal_Y,
    Normal_Z,
    Color_R,
    Color_G,
    Color_B,
    Color_A,
    ImageCoord_X,
    ImageCoord_Y;
}


text:
from threading import Thread as thread

from plyer.facades import Notification
from plyer.platforms.win.libs.balloontip import balloon_tip

class WindowsNotification(Notification):
    def _notify(self, **kwargs):
        thread(target=balloon_tip, kwargs=kwargs).start()

def instance():
    return WindowsNotification()


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
                      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

    <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
    <title>Introduction - Zend Framework Manual</title>

                    Zend_View

Zend_View

                        Programmer's Reference Guide

Scripts de contrôleur

Introduction

        Zend_View est une classe qui permet de travailler avec la
        partie "Vue" du motif de conception Modèle-Vue-Contrôleur. Elle existe pour aider à garder
        la vue séparée du modèle et des scripts du contrôleur. Elle fournie un système d'aide, de
        filtres d'affichage, et d'échappement de variables.

        Zend_View est un système de template agnostique ; vous pouvez
        utiliser <acronym class="acronym">PHP</acronym> comme langage de template, ou créer des instances d'autres systèmes de
        templates, et les manipuler à travers les scripts de vue.

        L'utilisation de Zend_View se déroule en deux étapes
        principales : 1. Votre script de contrôleur crée une instance de
        Zend_View et assigne des variables à cette instance. 2. Le contrôleur
        dit à Zend_View d'effectuer le rendu d'une vue particulière, et de ce
        fait va donner le contrôle au script de vue, qui va générer l'affichage.

Script du Contrôleur

            Comme exemple simple, imaginons que votre contrôleur aie une liste de données sur
            des livres qu'il veut afficher en passant par une vue. Le contrôleur pourrait alors
            ressembler à ceci :

// utilise un modèle pour obtenir les données sur les livres :

// auteurs et titres

$data = array(

    array(

        'auteur' => 'Hernando de Soto',

        'titre' => 'Le mystère du capitalisme'

    ),

    array(

        'auteur' => 'Henry Hazlitt',

        'titre' => 'Les sciences économique en un cours'

    ),

    array(

        'auteur' => 'Milton Friedman',

        'titre' => 'Libre de choisir'

    )

);

// assigniation des données du livre à une instance Zend_View

Zend_Loader::loadClass('Zend_View');

$view = new Zend_View();

$view->books = $data;

// et appel du script de rendu d'affichage appelé "booklist.php"

echo $view->render('booklist.php');

Script de vue

            Maintenant, nous avons besoin d'associer le script de vue
            "<var class="filename">booklist.php</var>". C'est un script <acronym class="acronym">PHP</acronym> comme les autres, à une
            exception près : il s'exécute dans la portée de l'instance
            Zend_View, ce qui veut dire que les référence à
            <var class="varname">$this</var> pointent vers les attributs et les méthodes de
            Zend_View. (Les variables assignées à l'instance par le
            contrôleur sont des propriétés publiques de l'instance
            Zend_View). Ainsi un script de vue de base pourrait ressembler à
            ceci :

<?php if ($this->books): ?>

    <!-- La table des livres -->

    <table>

        <tr>

            <th>Auteur</th>

            <th>Titre</th>

        </tr>

        <?php foreach ($this->books as $key => $val): ?>

        <tr>

            <td><?php echo $this->escape($val['auteur']) ?></td>

            <td><?php echo $this->escape($val['titre']) ?></td>

        </tr>

        <?php endforeach; ?>

    </table>

<?php else: ?>

    <p>Aucun livre à afficher</p>

<?php endif; ?>

            Notez l'utilisation de la méthode escape pour échapper les variables
            à afficher.

Options

            Zend_View possède plusieurs options qui peuvent être
            réglées pour changer le comportement de vos scripts de vues.

                    basePath : indique le chemin de base où peuvent être trouvés
                    les dossiers de scripts, d'aides et de filtres. Il considère une structure de
                    dossiers de ce type :

chemin/vers/

    helpers/

    filters/

    scripts/

                    Ceci peut être paramétré via les méthodes  setBasePath(),
                     addBasePath(), ou l'option basePath du
                    constructeur.

                    encoding : indique l'encodage de caractère à utiliser avec
                     htmlentities(),  htmlspecialchars(), et tout autre
                    opération. La valeur par défaut est ISO-8859-1 (latin1). Il peut être paramétré
                    avec la méthode  setEncoding() ou l'option encoding du
                    constructeur.

                    escape : indique le callback que doit utiliser
                     escape(). Ceci pet être paramétré avec la méthode
                     setEscape() ou l'option escape du constructeur.

                    filter : indique un filtre à utiliser avant d'effectuer le
                    rendu d'un script de vue. Ceci peut être paramétré avec les méthodes
                     setFilter(),  addFilter(), ou l'option
                    filter du constructeur.

                    strictVars : force Zend_View à émettre
                    des "notices" et des "warnings" quand des variables non initialisées sont lues.
                    Ceci peut être activé en appelant  strictVars(true) ou en passant
                    l'option strictVars au constructeur.

Balises courtes dans les scripts de vue

            Dans nos exemples et notre documentation, nous utilisons les balises longues <acronym class="acronym">PHP</acronym> :
            <?php. De plus, nous utilisons parfois » la syntaxe
            alternative des structures de contrôle. Ce sont des éléments pratiques à
            utiliser lors de la rédaction de vos scripts de vue, car elles rendent les constructions
            plus laconiques, maintiennent les instructions sur des lignes uniques et éliminent la chasse aux
            accolades à l'intérieur de l'HTML.

            Dans les versions précédentes, nous recommandions souvent l'utilisation des balises
            courtes (<? et <?=), car elles rendent
            les scripts de vues moins verbeux. Cependant, la valeur par défaut du fichier
            <var class="filename">php.ini</var> pour le réglage <tt>short_open_tag</tt> est
            désactivé par défaut en production ou en hébergement mutualisé ; rendant ainsi
            vos scripts peu portables. De plus, si vous modélisez du <acronym class="acronym">XML</acronym> dans
            vos scripts, la présence des balises courtes entrainera l'échec de la validation.
            Enfin, si vous utilisez les balises courtes et que <tt>short_open_tag</tt>
            est désactivé, le script retournera soit des erreurs, soit votre code PHP à
            l'utilisateur.

            Ceci étant dit, de nombreux développeurs préfère utiliser la forme complète pour
            des questions de validation ou de portabilité. Par exemple, short_open_tag
            est désactivé dans le php.ini.recommended, et si vous avez du <acronym class="acronym">XML</acronym>
            dans vos scripts de vue, alors les balises courtes entraîneront un échec de validation
            du modèle.

            De plus, si vous utilisez les balises courtes avec un réglage du paramètre à
            "off", alors les scripts de vue vont soit entraîner des erreurs, soit simplement
            afficher le code à l'utilisateur.

            Si malgré ces avertissements, vous souhaitez utiliser les balises courtes mais
            qu'elles sont désactivées, vous avez deux options :

Activer les dans votre fichier .htaccess :

php_value "short_open_tag" "on"

                    Ceci est seulement possible si vous êtes autorisé à créer et utiliser les
                    fichiers .htaccess. Cette directive peut aussi être ajoutée à votre
                    fichier httpd.conf.

                    Activer une enveloppe de flux ("stream wrapper") optionnelle pour
                    convertir les balises courtes en balises longues à la volée :

$view->setUseStreamWrapper(true);

                    Ceci enregistre Zend_View_Stream en tant que
                    enveloppe de flux pour les scripts de vue, et permet de s'assurer que votre code
                    continue à fonctionner comme si les balises courtes étaient activées.

Warning

Les enveloppes de flux de vue dégradent les performances

                L'utilisation d'enveloppe de flux dégradera les
                performances de votre application, bien que les tests de performance réels sont
                indisponibles pour quantifier le niveau de dégradation. Nous recommandons donc soit
                d'activer les balises courtes, soit de convertir vos scripts pour utiliser la forme
                longue, ou d'avoir une bonne stratégie de mise en cache partielle ou totale du
                contenu de vos pages.

Accesseurs utiles

            Typiquement, vous ne devriez seulement avoir besoin d'appeler les méthodes
             assign(),  render(), ou une des méthodes pour le
            paramétrage/l'ajout de chemins de filtre, d'aide et de script de vues. Cependant, si
            vous souhaitez étendre Zend_View vous-même, ou avez besoin
            d'accéder à quelques unes de ces méthodes internes, un certain nombre d'accesseurs
            existent :

 getVars() retournera toutes les variables assignées.

                     clearVars() effacera toutes les variables assignées ; utile
                    si vous souhaitez ré-utiliser un objet de vue, ou contrôler les variables qui
                    sont disponibles.

                     getScriptPath($script) récupérera le chemin résolu vers un
                    script donné..

                     getScriptPaths() récupérera tous les chemins vers les scripts
                    de vues enregistrés.

                     getHelperPath($helper) récupérera le chemin résolu vers une
                    classe d'aide nommée.

                     getHelperPaths() récupérera tous les chemins vers les aides
                    enregistrés.

                     getFilterPath($filter) récupérera le chemin résolu vers une
                    classe de filtre nommée.

                     getFilterPaths() récupérera tous les chemins vers les filtres
                    enregistrés.

                    Zend_View

Zend_View

                        Programmer's Reference Guide

Scripts de contrôleur

Programmer's Reference Guide

Programmer's Reference Guide

Zend Framework Reference

Zend_View

Introduction

Scripts de contrôleur

Scripts de vue

Aides de vue

Zend_View_Abstract


text:
package org.hisp.dhis.dataexchange.aggregate;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.nullable;
import static org.mockito.Mockito.when;

import java.util.Date;
import java.util.List;

import org.hisp.dhis.analytics.AnalyticsService;
import org.hisp.dhis.analytics.DataQueryParams;
import org.hisp.dhis.analytics.DataQueryService;
import org.hisp.dhis.common.BaseDimensionalObject;
import org.hisp.dhis.common.DimensionType;
import org.hisp.dhis.common.DimensionalObject;
import org.hisp.dhis.common.IdScheme;
import org.hisp.dhis.dataexchange.client.Dhis2Client;
import org.hisp.dhis.dxf2.common.ImportOptions;
import org.hisp.dhis.dxf2.datavalueset.DataValueSet;
import org.hisp.dhis.dxf2.datavalueset.DataValueSetService;
import org.hisp.dhis.dxf2.importsummary.ImportStatus;
import org.hisp.dhis.dxf2.importsummary.ImportSummaries;
import org.hisp.dhis.dxf2.importsummary.ImportSummary;
import org.hisp.dhis.scheduling.NoopJobProgress;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;

@ExtendWith( MockitoExtension.class )
class AggregateDataExchangeServiceTest
{
    @Mock
    private AnalyticsService analyticsService;

    @Mock
    private AggregateDataExchangeStore aggregateDataExchangeStore;

    @Mock
    private DataQueryService dataQueryService;

    @Mock
    private DataValueSetService dataValueSetService;

    @InjectMocks
    private AggregateDataExchangeService service;

    @Test
    @SuppressWarnings( "unchecked" )
    void testExchangeData()
    {
        when( analyticsService.getAggregatedDataValueSet( any( DataQueryParams.class ) ) )
            .thenReturn( new DataValueSet() );
        when( dataQueryService.getDimension( eq( DimensionalObject.DATA_X_DIM_ID ), any(), any( Date.class ),
            nullable( List.class ), anyBoolean(), nullable( IdScheme.class ) ) )
                .thenReturn( new BaseDimensionalObject(
                    DimensionalObject.DATA_X_DIM_ID, DimensionType.DATA_X, List.of() ) );
        when( dataQueryService.getDimension( eq( DimensionalObject.PERIOD_DIM_ID ), any(), any( Date.class ),
            nullable( List.class ), anyBoolean(), nullable( IdScheme.class ) ) )
                .thenReturn( new BaseDimensionalObject(
                    DimensionalObject.PERIOD_DIM_ID, DimensionType.PERIOD, List.of() ) );
        when( dataQueryService.getDimension( eq( DimensionalObject.ORGUNIT_DIM_ID ), any(), any( Date.class ),
            nullable( List.class ), anyBoolean(), nullable( IdScheme.class ) ) )
                .thenReturn( new BaseDimensionalObject(
                    DimensionalObject.ORGUNIT_DIM_ID, DimensionType.ORGANISATION_UNIT, List.of() ) );
        when( dataValueSetService.importDataValueSet( any( DataValueSet.class ), any( ImportOptions.class ) ) )
            .thenReturn( new ImportSummary( ImportStatus.SUCCESS ) );

        SourceRequest sourceRequest = new SourceRequest()
            .setName( "SourceRequestA" )
            .setDx( List.of( "Vz0C3i4Wy3M", "ToaOToReol6" ) )
            .setPe( List.of( "202101", "202102" ) )
            .setOu( List.of( "lGgJFgRkZui", "pvINfKxtqyN" ) );
        Source source = new Source()
            .setRequests( List.of( sourceRequest ) );
        TargetRequest request = new TargetRequest()
            .setDataElementIdScheme( "code" )
            .setOrgUnitIdScheme( "code" )
            .setIdScheme( "uid" );
        Target target = new Target()
            .setType( TargetType.INTERNAL )
            .setApi( new Api() )
            .setRequest( request );
        AggregateDataExchange exchange = new AggregateDataExchange()
            .setSource( source )
            .setTarget( target );

        ImportSummaries summaries = service.exchangeData( exchange, NoopJobProgress.INSTANCE );

        assertNotNull( summaries );
        assertEquals( 1, summaries.getImportSummaries().size() );

        ImportSummary summary = summaries.getImportSummaries().get( 0 );

        assertNotNull( summary );
        assertEquals( ImportStatus.SUCCESS, summary.getStatus() );
    }

    @Test
    @SuppressWarnings( "unchecked" )
    void testToDataQueryParams()
    {
        when( dataQueryService.getDimension( eq( DimensionalObject.DATA_X_DIM_ID ), any(), any( Date.class ),
            nullable( List.class ), anyBoolean(), nullable( IdScheme.class ) ) )
                .thenReturn( new BaseDimensionalObject(
                    DimensionalObject.DATA_X_DIM_ID, DimensionType.DATA_X, List.of() ) );
        when( dataQueryService.getDimension( eq( DimensionalObject.PERIOD_DIM_ID ), any(), any( Date.class ),
            nullable( List.class ), anyBoolean(), nullable( IdScheme.class ) ) )
                .thenReturn( new BaseDimensionalObject(
                    DimensionalObject.PERIOD_DIM_ID, DimensionType.PERIOD, List.of() ) );
        when( dataQueryService.getDimension( eq( DimensionalObject.ORGUNIT_DIM_ID ), any(), any( Date.class ),
            nullable( List.class ), anyBoolean(), nullable( IdScheme.class ) ) )
                .thenReturn( new BaseDimensionalObject(
                    DimensionalObject.ORGUNIT_DIM_ID, DimensionType.ORGANISATION_UNIT, List.of() ) );

        SourceRequest sourceRequest = new SourceRequest()
            .setName( "SourceRequestA" )
            .setDx( List.of( "Vz0C3i4Wy3M", "ToaOToReol6" ) )
            .setPe( List.of( "202101", "202102" ) )
            .setOu( List.of( "lGgJFgRkZui", "pvINfKxtqyN", "VOyqQ54TehY" ) )
            .setOutputDataElementIdScheme( IdScheme.UID.name() )
            .setOutputOrgUnitIdScheme( IdScheme.CODE.name() )
            .setOutputIdScheme( IdScheme.CODE.name() );

        DataQueryParams query = service.toDataQueryParams( sourceRequest );

        assertTrue( query.hasDimension( DimensionalObject.DATA_X_DIM_ID ) );
        assertTrue( query.hasDimension( DimensionalObject.PERIOD_DIM_ID ) );
        assertTrue( query.hasDimension( DimensionalObject.ORGUNIT_DIM_ID ) );
        assertEquals( IdScheme.UID, query.getOutputDataElementIdScheme() );
        assertEquals( IdScheme.CODE, query.getOutputOrgUnitIdScheme() );
        assertEquals( IdScheme.CODE, query.getOutputIdScheme() );
    }

    @Test
    void testToImportOptionsA()
    {
        TargetRequest request = new TargetRequest()
            .setDataElementIdScheme( "code" )
            .setOrgUnitIdScheme( "code" )
            .setIdScheme( "uid" );
        Target target = new Target()
            .setType( TargetType.EXTERNAL )
            .setApi( new Api() )
            .setRequest( request );
        AggregateDataExchange exchange = new AggregateDataExchange()
            .setTarget( target );

        ImportOptions options = service.toImportOptions( exchange );

        assertEquals( IdScheme.CODE, options.getIdSchemes().getDataElementIdScheme() );
        assertEquals( IdScheme.CODE, options.getIdSchemes().getOrgUnitIdScheme() );
        assertEquals( IdScheme.UID, options.getIdSchemes().getCategoryOptionComboIdScheme() );
        assertEquals( IdScheme.UID, options.getIdSchemes().getCategoryOptionIdScheme() );
        assertEquals( IdScheme.UID, options.getIdSchemes().getIdScheme() );
    }

    @Test
    void testToImportOptionsB()
    {
        TargetRequest request = new TargetRequest()
            .setDataElementIdScheme( "uid" )
            .setOrgUnitIdScheme( "code" );
        Target target = new Target()
            .setType( TargetType.EXTERNAL )
            .setApi( new Api() )
            .setRequest( request );
        AggregateDataExchange exchange = new AggregateDataExchange()
            .setTarget( target );

        ImportOptions options = service.toImportOptions( exchange );

        assertEquals( IdScheme.UID, options.getIdSchemes().getDataElementIdScheme() );
        assertEquals( IdScheme.CODE, options.getIdSchemes().getOrgUnitIdScheme() );
        assertEquals( IdScheme.UID, options.getIdSchemes().getCategoryOptionComboIdScheme() );
        assertEquals( IdScheme.UID, options.getIdSchemes().getCategoryOptionIdScheme() );
        assertEquals( IdScheme.UID, options.getIdSchemes().getIdScheme() );
    }

    @Test
    void testToIdScheme()
    {
        assertEquals( IdScheme.CODE, service.toIdScheme( "code" ) );
        assertEquals( IdScheme.UID, service.toIdScheme( "UID" ) );
        assertEquals( IdScheme.UID, service.toIdScheme( "uid" ) );
        assertNull( service.toIdScheme( null ) );
    }

    @Test
    void testToIdSchemeOrDefault()
    {
        assertEquals( IdScheme.CODE, service.toIdSchemeOrDefault( "code" ) );
        assertEquals( IdScheme.UID, service.toIdSchemeOrDefault( "UID" ) );
        assertEquals( IdScheme.UID, service.toIdSchemeOrDefault( "uid" ) );
        assertEquals( IdScheme.UID, service.toIdSchemeOrDefault( null ) );
    }

    @Test
    void testGetDhis2Client()
    {
        Api api = new Api()
            .setUrl( "https://play.dhis2.org/demo" )
            .setUsername( "admin" )
            .setPassword( "district" );

        Target target = new Target()
            .setType( TargetType.EXTERNAL )
            .setApi( api );

        AggregateDataExchange exchange = new AggregateDataExchange()
            .setTarget( target );

        Dhis2Client client = service.getDhis2Client( exchange );

        assertEquals( "https://play.dhis2.org/demo", client.getUrl() );
    }

    @Test
    void testGetDhis2ClientIllegalState()
    {
        Api api = new Api()
            .setUrl( "https://play.dhis2.org/demo" );

        Target target = new Target()
            .setType( TargetType.EXTERNAL )
            .setApi( api );

        AggregateDataExchange exchange = new AggregateDataExchange()
            .setTarget( target );

        assertThrows( IllegalStateException.class, () -> service.getDhis2Client( exchange ) );
    }

    @Test
    void testIsPersisted()
    {
        AggregateDataExchange adeA = new AggregateDataExchange();
        adeA.setId( 1 );
        adeA.setAutoFields();
        adeA.setName( "DataExchangeA" );

        AggregateDataExchange adeB = new AggregateDataExchange();
        adeB.setAutoFields();
        adeB.setName( "DataExchangeB" );

        assertTrue( service.isPersisted( adeA ) );
        assertFalse( service.isPersisted( adeB ) );
    }
}


text:
package ast;

/**
 * @author GAO RISHENG
 * This class is the combination of all statements that can be presented within 1 lines
 * e.g return/continue/break/label/expression/create variable/goto etc
 */
public class ASTSimpleStatement extends ASTStatement{
	private static final String NODE_TYPE = "Simple Statement";
	public ASTSimpleStatement(){
		super();
	}
	public String toSyntax(){
		this.result = "\n";
		return this.result;
	}
	public String typeof(){
		return super.typeof()+"->"+NODE_TYPE;
	}
}


text:
package validate

import (
	"bytes"
	"encoding/json"
	"fmt"
	"sort"
	"strings"
)

type ValidationError error

type validationError struct {
	template string
	args     []interface{}
}

func (e validationError) Template() string {
	return e.template
}

func (e validationError) Args() []interface{} {
	return e.args
}

func (e validationError) Error() string {
	return fmt.Sprintf(e.template, e.args...)
}

func (e validationError) MarshalJSON() ([]byte, error) {
	return json.Marshal(e.Error())
}

func (e *validationError) UnmarshalJSON(data []byte) error {
	return json.Unmarshal(data, &e.template)
}

func NewValidationError(template string, args ...interface{}) ValidationError {
	return &validationError{
		template: template,
		args:     args,
	}
}

var (
	// errOmitEmpty is the error returned when variable has a empty value
	errOmitEmpty = NewValidationError("omitempty")

	// ErrRequired is the error returned when variable has a empty value
	ErrRequired = NewValidationError("required")

	// ErrEmpty is the error returned when variable has a empty value
	ErrEmpty = NewValidationError("value is empty")

	// ErrMin is the error returned when variable is less than mininum
	// value specified
	ErrMin = NewValidationError("less than min")

	// ErrMax is the error returned when variable is more than
	// maximum specified
	ErrMax = NewValidationError("greater than max")

	// ErrLen is the error returned when length is not equal to
	// param specified
	ErrLen = NewValidationError("invalid length")

	// ErrBetween is the error returned when variable is less than
	// minimum or more than maximum specified
	ErrBetween = NewValidationError("not between")

	// ErrAround is the error returned when variable is more than
	// minimum and less then maximum specified
	ErrAround = NewValidationError("not around")

	// ErrRegexp is the error returned when the value does not
	// match the provided regular expression parameter
	ErrRegexp = NewValidationError("regular expression mismatch")

	// ErrIdentifier is the error returned when the value does not match the
	// identifier pattern
	ErrIdentifier = NewValidationError("invalid id format")

	// ErrAlpha is the error returned when the value does contains
	// other characters than alphas
	ErrAlpha = NewValidationError("alpha dash mismatch")

	// ErrAlphaNumeric is the error returned when the value does contains
	// other characters than alphas or numerics
	ErrAlphaNumeric = NewValidationError("alpha dash mismatch")

	// ErrAlphaDash is the error returned when the value does contains
	// other characters than alphas or dashes
	ErrAlphaDash = NewValidationError("alpha dash mismatch")

	// ErrAlphaDashDot is the error returned when the value does contains
	// other characters than alpha's, dashes or dots
	ErrAlphaDashDot = NewValidationError("alpha dash dot mismatch")

	// ErrEmail is the error returned when the value does not match
	// a valid email pattern
	ErrEmail = NewValidationError("invalid email")

	// ErrURL is the error returned when the value does not match
	// a valid url pattern
	ErrURL = NewValidationError("invalid url")

	// ErrInclude is the error returned when the value is not found
	// in the set values that in the include list
	ErrInclude = NewValidationError("value not found in set")

	// ErrExclude is the error returned when the value is  found
	// in the set values to exclude
	ErrExclude = NewValidationError("value matches one exluded value")

	// ErrUnsupported is the error error returned when a validation rule
	// is used with an unsupported variable type
	ErrUnsupported = NewValidationError("unsupported type")

	// ErrBadParameter is the error returned when an invalid parameter
	// is provided to a validation rule (e.g. a string where an int was
	// expected (max(foo),len=(bar))
	ErrBadParameter = NewValidationError("bad parameter")

	// ErrInvalidParameterCount is the error returned when there are not enough or
	// to many parameters provided to the validation rule.
	ErrInvalidParameterCount = NewValidationError("invalid parameter count")

	// ErrSyntax is the error who is returned when a invalid syntax is detected
	// while parsing the structure validatorTag
	ErrSyntax = NewValidationError("syntax error")

	// ErrUnknownTag is the error returned when an unknown validatorTag is found
	ErrUnknownTag = NewValidationError("unknown validatorTag")

	// ErrInvalid is the error returned when variable is invalid
	// (normally a nil pointer)
	ErrInvalid = NewValidationError("invalid value")

	// ErrNumber is the error returned when value is not a number
	ErrNumber = NewValidationError("value not a number")

	// ErrNumeric is the error returned when value is not in numeric format
	ErrNumeric = NewValidationError("value not numeric")

	// ErrUUID is the error returned when value is not in UUID format
	ErrUUID = NewValidationError("invalid UUID")

	// ErrUUID3 is the error returned when value is not in UUID format
	ErrUUID3 = NewValidationError("invalid UUID3")

	// ErrUUID4 is the error returned when value is not in UUID format
	ErrUUID4 = NewValidationError("invalid UUID4")

	// ErrUUID5 is the error returned when value is not in UUID format
	ErrUUID5 = NewValidationError("invalid UUID5")

	// ErrBase64 is the error returned when value is not a valid base64 encoded
	ErrBase64 = NewValidationError("invalid base64 encoded")

	// ErrBEnum is the error returned when value is not in a set of enum values
	ErrEnum = NewValidationError("invalid value")
)

type ErrorList []error

func (e ErrorList) Error() string {
	errs := make([]string, len(e))
	for i, err := range e {
		errs[i] = err.Error()
	}
	return strings.Join(errs, ", ")
}

func (e ErrorList) MarshalJSON() ([]byte, error) {
	var buf bytes.Buffer
	buf.WriteByte('[')

	//stringify errors
	for i, es := range e {
		if i != 0 {
			buf.WriteByte(',')
		}
		val, err := json.Marshal(es.Error())
		if err != nil {
			return nil, err
		}
		buf.Write(val)
	}
	buf.WriteByte(']')

	return buf.Bytes(), nil
}

type Errors map[string][]error

func (e Errors) Error() string {
	names := make([]string, 0, len(e))
	for name := range e {
		names = append(names, name)
	}
	sort.Strings(names)

	stringErrors := make([]string, len(e))
	for ei, name := range names {
		errs := make([]string, len(e[name]))
		for ie, err := range e[name] {
			errs[ie] = err.Error()
		}
		stringErrors[ei] = fmt.Sprintf("%s: [%s]", name, strings.Join(errs, ", "))
	}
	return strings.Join(stringErrors, ", ")
}

func (e *Errors) Add(field string, errors ...error) {
	if *e == nil {
		*e = make(Errors, 1)
	}

	(*e)[field] = append((*e)[field], errors...)
}

func (e *Errors) Merge(errors error) {
	switch verr := errors.(type) {
	case Errors:
		for field, errs := range verr {
			e.Add(field, errs...)
		}
	default:
		e.Add("_", errors)
	}
}

func (e *Errors) MergePrefix(prefix string, errors error) {
	switch verr := errors.(type) {
	case Errors:
		for field, errs := range verr {
			e.Add(prefix+field, errs...)
		}
		//case Error:
		//	e.Add(prefix+verr.Field(), verr.Errors()...)
	default:
		e.Add(prefix+"_", errors)
	}
}

func (e Errors) MarshalJSON() ([]byte, error) {
	//order alphabetic field/namess
	names := make([]string, 0, len(e))
	for name := range e {
		names = append(names, name)
	}
	sort.Strings(names)

	var buf bytes.Buffer
	buf.WriteByte('{')
	for i, name := range names {
		if i != 0 {
			buf.WriteByte(',')
		}

		//name/field who contains errors
		key, err := json.Marshal(name)
		if err != nil {
			return nil, err
		}
		buf.Write(key)

		buf.WriteString(":[")

		//stringify errors
		for esi, es := range e[name] {
			if esi != 0 {
				buf.WriteByte(',')
			}
			val, err := json.Marshal(es.Error())
			if err != nil {
				return nil, err
			}
			buf.Write(val)
		}
		buf.WriteByte(']')

	}
	buf.WriteString("}")
	return buf.Bytes(), nil
}

func (e *Errors) UnmarshalJSON(data []byte) error {
	errs := map[string][]validationError{}
	err := json.Unmarshal(data, &errs)
	if err != nil {
		return err
	}

	*e = make(map[string][]error, len(errs))
	for k, v := range errs {
		(*e)[k] = make([]error, len(v))
		for i, err := range v {
			(*e)[k][i] = error(err)
		}
	}
	return nil
}


text:
<?php
if (droits() == 1 || droits() == 2)
{
	$db->exec("DELETE FROM articles WHERE id=".$id_article);

	require('./views/article.phtml');
}
else {
	require('./views/home.phtml');
}
?>


text:
<?php

if (!defined('_ECRIRE_INC_VERSION')) return;

include_spip('inc/headers');

// acces aux documents joints securise
// verifie soit que le demandeur est authentifie
// soit que le document est publie, c'est-a-dire
// joint a au moins 1 article, breve ou rubrique publie

// http://doc.spip.org/@action_acceder_document_dist
function action_acceder_document_dist() {
	include_spip('inc/documents');

	// $file exige pour eviter le scan id_document par id_document
	$f = rawurldecode(_request('file'));
	$file = get_spip_doc($f);
	$arg = rawurldecode(_request('arg'));

	$status = $dcc = false;
	if (strpos($f,'../') !== false
	OR preg_match(',^\w+://,', $f)) {
		$status = 403;
	}
	else if (!file_exists($file) OR !is_readable($file)) {
		$status = 404;
	} else {
		$where = "documents.fichier=".sql_quote(set_spip_doc($file))
		. ($arg ? " AND documents.id_document=".intval($arg): '');

		$doc = sql_fetsel("documents.id_document, documents.titre, documents.fichier, types.mime_type, types.inclus, documents.extension", "spip_documents AS documents LEFT JOIN spip_types_documents AS types ON documents.extension=types.extension",$where);
		if (!$doc) {
			$status = 404;
		} else {

			// ETag pour gerer le status 304
			$ETag = md5($file . ': '. filemtime($file));
			if (isset($_SERVER['HTTP_IF_NONE_MATCH'])
			AND $_SERVER['HTTP_IF_NONE_MATCH'] == $ETag) {
				http_status(304); // Not modified
				exit;
			} else {
				header('ETag: '.$ETag);
			}

			//
			// Verifier les droits de lecture du document
			// en controlant la cle passee en argument
			//
			include_spip('inc/securiser_action');
			$cle = _request('cle');
			if (!verifier_cle_action($doc['id_document'].','.$f, $cle)) {
				spip_log("acces interdit $cle erronee");
				$status = 403;
			}
		}
	}

	switch($status) {

	case 403:
		include_spip('inc/minipres');
		echo minipres();
		break;

	case 404:
		http_status(404);
		include_spip('inc/minipres');
		echo minipres(_T('erreur').' 404',
			_T('info_document_indisponible'));
		break;

	default:
		header("Content-Type: ". $doc['mime_type']);

		// pour les images ne pas passer en attachment
		// sinon, lorsqu'on pointe directement sur leur adresse,
		// le navigateur les downloade au lieu de les afficher

		if ($doc['inclus']=='non') {

		  // Si le fichier a un titre avec extension,
		  // ou si c'est un nom bien connu d'Unix, le prendre
		  // sinon l'ignorer car certains navigateurs pataugent

			$f = basename($file);
			if (isset($doc['titre'])
				AND (preg_match('/^\w+[.]\w+$/', $doc['titre']) OR $doc['titre'] == 'Makefile'))
				$f = $doc['titre'];

			// ce content-type est necessaire pour eviter des corruptions de zip dans ie6
			header('Content-Type: application/octet-stream');

			header("Content-Disposition: attachment; filename=\"$f\";");
			header("Content-Transfer-Encoding: binary");

			// fix for IE catching or PHP bug issue
			header("Pragma: public");
			header("Expires: 0"); // set expiration time
			header("Cache-Control: must-revalidate, post-check=0, pre-check=0");

		}

		if ($cl = filesize($file))
			header("Content-Length: ". $cl);

		readfile($file);
		break;
	}

}

?>


text:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[MealCalc_CalcDayMenuGoodSpendWriteOff_BeforeInsert]
	@ID int OUTPUT,
	@CalcDayMenuGoodSpendID int OUTPUT,
	@GoodIncomeID int OUTPUT,
	@Quantity decimal(18, 3) OUTPUT,
	@ErrorMessages XML OUTPUT
AS
SET NOCOUNT ON

DECLARE @ErrorList TABLE
(
	Message VARCHAR(2000),
	AttributeName VARCHAR(128) NULL,
	AttributeFriendlyName VARCHAR(200) NULL,
	Severity INT
)

IF
	(
		SELECT
			dbo.MealCalc_CalcDayMenu.CalcDayMenuStatusID
		FROM dbo.MealCalc_CalcDayMenuGoodSpendWriteOff
			INNER JOIN dbo.MealCalc_CalcDayMenuGoodSpend ON dbo.MealCalc_CalcDayMenuGoodSpendWriteOff.CalcDayMenuGoodSpendID = dbo.MealCalc_CalcDayMenuGoodSpend.ID
			INNER JOIN dbo.MealCalc_CalcDayMenu ON dbo.MealCalc_CalcDayMenuGoodSpend.CalcDayMenuID = dbo.MealCalc_CalcDayMenu.ID
		WHERE dbo.MealCalc_CalcDayMenuGoodSpendWriteOff.ID = @ID
	)
	!= 1
BEGIN
	RAISERROR ('Èçìåíåíèå ìåíþ íåâîçìîæíî, ïîñêîëüêî êàëüêóëÿöèÿ óæå óòâåðæäåíà', 11, 1)
	RETURN -1
END

IF (SELECT dbo.MealCalc_GoodIncome.Deleted FROM dbo.MealCalc_GoodIncome WHERE dbo.MealCalc_GoodIncome.ID = @GoodIncomeID) = 1
BEGIN
	INSERT INTO @ErrorList (Message, AttributeName, AttributeFriendlyName, Severity)
	SELECT
		'Óêàçàííàÿ ïðèõîäíàÿ ïîçèöèÿ óäàëåíà',
		NULL,
		NULL,
		2
END

IF ISNULL
(
	(
		SELECT dbo.MealCalc_GoodIncome.Quantity - dbo.MealCalc_GoodIncome.QuantityWrittenOff - dbo.MealCalc_GoodIncome.QuantityWrittenOff
		FROM dbo.MealCalc_GoodIncome
		WHERE dbo.MealCalc_GoodIncome.ID = @GoodIncomeID
	),
	0
) < @Quantity
BEGIN
	INSERT INTO @ErrorList (Message, AttributeName, AttributeFriendlyName, Severity)
	SELECT
		'Óêàçàííàÿ ïîçèöèÿ ñîäåðæèò íåäîñòàòî÷íîå êîëè÷åñòâî òîâàðà äëÿ ñïèñàíèÿ',
		NULL,
		NULL,
		2
END

SET @ErrorMessages =
(
	SELECT Message, AttributeName, AttributeFriendlyName, Severity
	FROM @ErrorList AS EL
	ORDER BY EL.Severity DESC, EL.AttributeName
	FOR XML RAW('row'), ROOT ('root')
)
GO


text:
// This file is automatically generated.

package adila.db;

/*
 * Samsung Galaxy S5 Google Play Edition
 *
 * DEVICE: kgedlte
 * MODEL: SM-G900FG
 */
final class kgedlte {
    public static final String DATA = "Samsung|Galaxy S5 Google Play Edition|Galaxy S";
}


text:
extern bool acpi_atcs_functions_supported(void *device,
							uint32_t index);
extern int acpi_pcie_perf_request(void *device,
						uint8_t perf_req,
						bool advertise);
extern bool acpi_atcs_notify_pcie_device_ready(void *device);


text:
<?php

/**
 * Recurring profile collection
 *
 * @category    Mage
 * @package     Mage_Sales
 * @author      Magento Core Team <core@magentocommerce.com>
 */
class Mage_Sales_Model_Resource_Recurring_Profile_Collection extends Mage_Core_Model_Resource_Db_Collection_Abstract
{
    /**
     * Event prefix
     *
     * @var string
     */
    protected $_eventPrefix    = 'sales_recurring_profile_collection';

    /**
     * Event object
     *
     * @var string
     */
    protected $_eventObject    = 'recurring_profile_collection';

    /**
     * Entity initialization
     *
     */
    protected function _construct()
    {
        $this->_init('sales/recurring_profile');
    }
}


text:
Spring Security的Java配置并不暴露已配置的每个对象的每个参数。这会简化绝大部分用户的配置。毕竟如果每个参数都暴露了,那么用户可能就会使用标准的bean配置了。

尽管不直接暴露每个参数的有很多好处,但用户仍然可能需要一些更高级的配置选项。Spring Security展示了 `ObjectPostProcessor` 的概念,它可以用来更改或替换许多由Java配置创建的对象实例。例如,如果你想要配置 `filterSecurityPublishAuthorizationSuccess` 参数到 `FilterSecurityInterceptor` 中,你可以像下面这样:

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http
			.authorizeRequests()
				.anyRequest().authenticated()
				.withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() {
					public <O extends FilterSecurityInterceptor> O postProcess(
							O fsi) {
						fsi.setPublishAuthorizationSuccess(true);
						return fsi;
					}
				});
	}


text:
@extends('layouts.master')

@section('page-header', 'Destroy Buildings')

@section('content')
    <form action="{{ route('dominion.destroy') }}" method="post" role="form">
        {!! csrf_field() !!}

 Destroy Buildings

                    <colgroup>
                        <col>
                        <col width="100">
                        <col width="100">
                    </colgroup>

                    @foreach ($buildingHelper->getBuildingTypesByLandType($selectedDominion->race) as $landType => $buildingTypes)

                        @if (empty($buildingTypes))
                            @continue
                        @endif

                                {{ ucfirst($landType) }} (Barren: {{ number_format($landCalculator->getTotalBarrenLandByLandType($landType)) }})

                                Building
                                Owned
                                Destroy

                            @foreach ($buildingTypes as $buildingType)

                                        {{ ucwords(str_replace('_', ' ', $buildingType)) }}
                                        {!! $buildingHelper->getBuildingImplementedString($buildingType) !!}

                                        {{ $selectedDominion->{'building_' . $buildingType} }}

                                            ({{ number_format((($selectedDominion->{'building_' . $buildingType} / $landCalculator->getTotalLand()) * 100), 1) }}%)

                                        <input type="number" name="destroy[{{ $buildingType }}]" class="form-control text-center" placeholder="0" min="0" max="{{ $selectedDominion->{'building_' . $buildingType} }}" value="{{ old('destroy.' . $buildingType) }}" {{ $selectedDominion->isLocked() ? 'disabled' : null }}>

                            @endforeach

                    @endforeach

                <button type="submit" class="btn btn-danger" {{ $selectedDominion->isLocked() ? 'disabled' : null }}>Destroy</button>

    </form>
@endsection


text:
.PHONY: test folproof

all: folproof test

folproof:
	node ./node_modules/jison/lib/cli.js src/parser/folproof-parser.jison src/parser/folproof-parser.jisonlex
	./node_modules/.bin/browserify --standalone folproof src/verifier.js > folproof-verifier.js

test:
	./node_modules/nodeunit/bin/nodeunit tests/*.js


text:
"""
Copyright 2014 Novartis Institutes for Biomedical Research

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

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

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

import time
import os
from yap_printer import *
from yap_check import *
import yap_workflow_dict as wd
def print_info():
    file_split_struct = []
    # Set default values for workflow
    f_summary_file =  wd.workflow_output_path + "/" + wd.workflow_name + "_workflow_summary.txt"
    f_summary = open(f_summary_file, 'wb')
    number_of_samples = len(wd.inp_files_list)
    if os.path.exists(wd.usage_log):
        f_usage = open(wd.usage_log, 'a')
        if wd.job_id != '':
            f_usage.write(
                wd.yap_version +
                "\t" +
                wd.username +
                "\t" +
                time.strftime(
                    "%Y/%m/%d %H:%M:%S",
                    time.localtime()) +
                "\t" +
                str(number_of_samples) +
                "\t" +
                str(wd.nprocs) +
                "\t" +
                str(wd.job_id) +
                "\t" +
                "START" +
                "\n")
        else:
            f_usage.write(
                wd.yap_version +
                "\t" +
                wd.username +
                "\t" +
                time.strftime(
                    "%Y/%m/%d %H:%M:%S",
                    time.localtime()) +
                "\t" +
                str(number_of_samples) +
                "\t" +
                str(wd.nprocs) +
                "\t" +
                str(wd.random_id) +
                "\t" +
                "START" +
                "\n")

        f_usage.close()
    else:
        "Warning: YAP usage log not found"
    # print information on screen and file
    print_list(wd.check_results, f_summary)
    # close the summary file
    f_summary.close()
#-------------------------------------------------------------------------

def print_usage():
    print "Options : "
    print " To print help : ", " yap --help or yap -h"
    print " To do configuration file format check : ", " yap --check [workflow_configuration_filename], ", "\"eg: yap --check workflow_configuration.cfg \""
    print " To run YAP: ", " yap -n [number of processors] [workflow_configuration_filename], ", "\"eg: yap -n 2 workflow_configuration.cfg \"", "(yap run with 2 processors)"
    print "exiting the program"


text:
title: Software Life Cycle
name: software-life-cycle
id: en-software-life-cycle
permalink: /en/lifecycle/
layout: page
type: pages
lang: en
share: false
version: 1
---
This document describes the life-cycle of the Bitcoin Core software package released by the Bitcoin Core project. It is in line with standard maintenance policy across commercial software.

We aim to make a major release every 6-7 months, These will be numbered 0.11, 0.12 etc.

We will provide maintenance "minor releases" that fix bugs within the major releases. We may add minor features to point releases where necessary, for example when back-porting consensus rule changes such as soft forks. Minor releases will be numbered 0.11.1, 0.11.2, 0.12.1, 0.12.2 etc.

We maintain the major versions until their "Maintenance End". We generally maintain the current and previous major release. So if the current release is 0.12, then 0.11 is also considered maintained. Once 0.13 is released, then 0.11 would be considered at it's "Maintenance End". The older the major release, the more critical issues have to be to get backported to it, and the more to warrant a new minor release. Once software has reached the "Maintenance End" period it will only receive critical security fixes until the EOL date. After EOL, users must upgrade to a later version to receive security updates.

Please note that minor versions get bugfixes, translation updates, and soft forks. Translation on [Transifex][bitcoin-transifex-link] is only open for the last two major releases.

For example, major version 0.9 was released on 2014-03-19 and we provided maintenance fixes (point releases) until 2015-02-16. Critical security issues would still be continue to be fixed until the End-Of-Life "EOL" date of 2016-02-31. However, to take advantage of bug fixes, you would have to upgrade to a later major version.

Once EOL is reached, you will need to upgrade to a newer version.

| Version | Release Date | Maintenance End | End of Life |
|---------|--------------|-----------------|-------------|
{% include posts/_maintenance-table.md %}

\* _We aim to make a major release every 6-7 months_

_TBA: to be announced_

[bitcoin-transifex-link]: https://www.transifex.com/bitcoin/bitcoin/


text:
namespace Implementation
{
    using Orleans;
    using System;
    using System.Runtime.InteropServices;
    using System.Runtime.Serialization;

}
#pragma warning restore 162
#pragma warning restore 219
#pragma warning restore 414
#pragma warning restore 649
#pragma warning restore 693
#pragma warning restore 1591
#pragma warning restore 1998
#endif


text:
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Runtime.CompilerServices;
using Xunit;

namespace System
{
    public static partial class PlatformDetection
    {
        //
        // Do not use the " { get; } = <expression> " pattern here. Having all the initialization happen in the type initializer
        // means that one exception anywhere means all tests using PlatformDetection fail. If you feel a value is worth latching,
        // do it in a way that failures don't cascade.
        //

        public static bool HasWindowsShell => IsWindows && IsNotWindowsServerCore && IsNotWindowsNanoServer && IsNotWindowsIoTCore;
        public static bool IsUap => IsInAppContainer || IsNetNative;
        public static bool IsFullFramework => RuntimeInformation.FrameworkDescription.StartsWith(".NET Framework", StringComparison.OrdinalIgnoreCase);
        public static bool IsNetNative => RuntimeInformation.FrameworkDescription.StartsWith(".NET Native", StringComparison.OrdinalIgnoreCase);
        public static bool IsNetCore => RuntimeInformation.FrameworkDescription.StartsWith(".NET Core", StringComparison.OrdinalIgnoreCase);
        public static bool IsOSX => RuntimeInformation.IsOSPlatform(OSPlatform.OSX);
        public static bool IsFreeBSD => RuntimeInformation.IsOSPlatform(OSPlatform.Create("FREEBSD"));
        public static bool IsNetBSD => RuntimeInformation.IsOSPlatform(OSPlatform.Create("NETBSD"));
        public static bool IsNotWindows8x => !IsWindows8x;
        public static bool IsNotWindowsNanoServer => !IsWindowsNanoServer;
        public static bool IsNotWindowsServerCore => !IsWindowsServerCore;
        public static bool IsNotWindowsIoTCore => !IsWindowsIoTCore;
        public static bool IsNotWindowsHomeEdition => !IsWindowsHomeEdition;
        public static bool IsDrawingSupported => (IsNotWindowsNanoServer && IsNotWindowsIoTCore);
        public static bool IsArmProcess => RuntimeInformation.ProcessArchitecture == Architecture.Arm;
        public static bool IsNotArmProcess => !IsArmProcess;

        public static bool IsNotInAppContainer => !IsInAppContainer;
        public static bool IsWinRTSupported => IsWindows && !IsWindows7;
        public static bool IsNotWinRTSupported => !IsWinRTSupported;
        public static bool IsNotMacOsHighSierraOrHigher => !IsMacOsHighSierraOrHigher;

        public static bool IsDomainJoinedMachine => !Environment.MachineName.Equals(Environment.UserDomainName, StringComparison.OrdinalIgnoreCase);

        public static bool IsNotNetNative => !IsNetNative;

        // Windows - Schannel supports alpn from win8.1/2012 R2 and higher.
        // Linux - OpenSsl supports alpn from openssl 1.0.2 and higher.
        // OSX - SecureTransport doesn't expose alpn APIs. #30492
        public static bool SupportsAlpn => (IsWindows && !IsWindows7) ||
            (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) &&
            (OpenSslVersion.Major >= 1 && (OpenSslVersion.Minor >= 1 || OpenSslVersion.Build >= 2)));
        public static bool SupportsClientAlpn => SupportsAlpn ||
            (RuntimeInformation.IsOSPlatform(OSPlatform.OSX) && PlatformDetection.OSXVersion > new Version(10, 12));

        // Officially, .Net Native only supports processes running in an AppContainer. However, the majority of tests still work fine
        // in a normal Win32 process and we often do so as running in an AppContainer imposes a substantial tax in debuggability
        // and investigatability. This predicate is used in ConditionalFacts to disable the specific tests that really need to be
        // running in AppContainer when running on .NetNative.
        public static bool IsNotNetNativeRunningAsConsoleApp => !(IsNetNative && !IsInAppContainer);

        private static Lazy<bool> m_isWindowsSubsystemForLinux = new Lazy<bool>(GetIsWindowsSubsystemForLinux);

        public static bool IsWindowsSubsystemForLinux => m_isWindowsSubsystemForLinux.Value;
        public static bool IsNotWindowsSubsystemForLinux => !IsWindowsSubsystemForLinux;

        private static bool GetIsWindowsSubsystemForLinux()
        {
            // https://github.com/Microsoft/BashOnWindows/issues/423#issuecomment-221627364

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                const string versionFile = "/proc/version";
                if (File.Exists(versionFile))
                {
                    string s = File.ReadAllText(versionFile);

                    if (s.Contains("Microsoft") || s.Contains("WSL"))
                    {
                        return true;
                    }
                }
            }

            return false;
        }

        private static Lazy<bool> s_largeArrayIsNotSupported = new Lazy<bool>(IsLargeArrayNotSupported);

        [MethodImpl(MethodImplOptions.NoOptimization)]
        private static bool IsLargeArrayNotSupported()
        {
            try
            {
                var tmp = new byte[int.MaxValue];
                return tmp == null;
            }
            catch (OutOfMemoryException)
            {
                return true;
            }
        }

        public static bool IsNotIntMaxValueArrayIndexSupported => s_largeArrayIsNotSupported.Value;

        public static bool IsNonZeroLowerBoundArraySupported
        {
            get
            {
                if (s_lazyNonZeroLowerBoundArraySupported == null)
                {
                    bool nonZeroLowerBoundArraysSupported = false;
                    try
                    {
                        Array.CreateInstance(typeof(int), new int[] { 5 }, new int[] { 5 });
                        nonZeroLowerBoundArraysSupported = true;
                    }
                    catch (PlatformNotSupportedException)
                    {
                    }
                    s_lazyNonZeroLowerBoundArraySupported = Tuple.Create<bool>(nonZeroLowerBoundArraysSupported);
                }
                return s_lazyNonZeroLowerBoundArraySupported.Item1;
            }
        }

        private static volatile Tuple<bool> s_lazyNonZeroLowerBoundArraySupported;

        public static bool IsReflectionEmitSupported = !PlatformDetection.IsNetNative;

        // Tracked in: https://github.com/dotnet/corert/issues/3643 in case we change our mind about this.
        public static bool IsInvokingStaticConstructorsSupported => !PlatformDetection.IsNetNative;

        // System.Security.Cryptography.Xml.XmlDsigXsltTransform.GetOutput() relies on XslCompiledTransform which relies
        // heavily on Reflection.Emit
        public static bool IsXmlDsigXsltTransformSupported => !PlatformDetection.IsUap;
    }
}