text:
#include "SmartFactoryTestHelper.h"
#include "formatters/CSmartFactory.h"
#include "gtest/gtest.h"

namespace test {
namespace components {
namespace formatters {

TEST(CSmartFactoryTest, CreateSmartSchemaKey_ExpectCreated) {
  SmartSchemaKey<FunctionIdTest::eType, MessageTypeTest::eType> test_key(
      FunctionIdTest::Function1, MessageTypeTest::notification);
  EXPECT_EQ(test_key.functionId, FunctionIdTest::Function1);
  EXPECT_EQ(test_key.messageType, MessageTypeTest::notification);
}

TEST(CSmartFactoryTest, CreateSmartFactory_ExpectCreated) {
  CSmartFactoryTest test_factory;
  EXPECT_EQ(9u, test_factory.function_schemes().size());
  EXPECT_EQ(2u, test_factory.structs_schemes().size());
}

TEST(CSmartFactoryTest, CreateSmartObjWithSchema1_ExpectCreatedObjectToCorrespondSmSchema1) {
  CSmartFactoryTest test_factory;
  // Create SmartObject with attached SmartChmema
  SmartObject obj = test_factory.CreateSmartObject(FunctionIdTest::Function1,
                                                   MessageTypeTest::request);
  EXPECT_TRUE(SmartType::SmartType_Map == obj.getType());
  // Adding necessary fields
  obj[S_PARAMS][S_FUNCTION_ID] = FunctionIdTest::Function1;
  obj[S_PARAMS][S_MESSAGE_TYPE] = MessageTypeTest::request;
  obj[S_PARAMS][S_CORRELATION_ID] = 444;
  obj[S_PARAMS][S_PROTOCOL_VERSION] = 1;
  obj[S_PARAMS][S_PROTOCOL_TYPE] = 0;
  obj[S_MSG_PARAMS] = SmartObject(SmartType::SmartType_Map);
  std::set<std::string> keys = obj.enumerate();
  EXPECT_EQ(2u, keys.size());
  EXPECT_EQ(Errors::eType::OK, obj.validate());
  EXPECT_TRUE(obj.isValid());
}

TEST(CSmartFactoryTest, CreateSmartObjWithNotExistedSchema_ExpectCreatedObjectNotValid) {
  CSmartFactoryTest test_factory;
  // Create SmartObject with attached SmartChmema
  SmartObject obj = test_factory.CreateSmartObject(
      FunctionIdTest::Function1, MessageTypeTest::INVALID_ENUM);
  EXPECT_FALSE(SmartType::SmartType_Map == obj.getType());
  EXPECT_TRUE(SmartType::SmartType_Null == obj.getType());
  EXPECT_EQ(Errors::eType::OK, obj.validate());
  EXPECT_TRUE(obj.isValid());
}

TEST(CSmartFactoryTest, CreateSmartObjectWithSchema1_MissedOneField_ExpectCreatedNotCorrespondSmartSchema) {
  CSmartFactoryTest test_factory;
  // Create SmartObject with attached SmartChmema
  SmartObject obj = test_factory.CreateSmartObject(FunctionIdTest::Function1,
                                                   MessageTypeTest::request);
  EXPECT_TRUE(SmartType::SmartType_Map == obj.getType());
  // Adding necessary fields but one field is missed
  obj[S_PARAMS][S_FUNCTION_ID] = FunctionIdTest::Function1;
  obj[S_PARAMS][S_MESSAGE_TYPE] = MessageTypeTest::request;
  obj[S_PARAMS][S_PROTOCOL_VERSION] = 1;
  obj[S_PARAMS][S_PROTOCOL_TYPE] = 0;
  obj[S_MSG_PARAMS] = SmartObject(SmartType::SmartType_Map);
  std::set<std::string> keys = obj.enumerate();
  EXPECT_EQ(2u, keys.size());
  EXPECT_EQ(Errors::eType::MISSING_MANDATORY_PARAMETER, obj.validate());
  EXPECT_FALSE(obj.isValid());
}

TEST(CSmartFactoryTest, CreateSmartObjectWithSchema1_AddOutOfRangeValue_ExpectCreatedNotCorrespondSmartSchema) {
  CSmartFactoryTest test_factory;
  // Create SmartObject with attached SmartChmema
  SmartObject obj = test_factory.CreateSmartObject(FunctionIdTest::Function1,
                                                   MessageTypeTest::request);
  EXPECT_TRUE(SmartType::SmartType_Map == obj.getType());
  // Adding necessary fields but one field is missed
  obj[S_PARAMS][S_FUNCTION_ID] = FunctionIdTest::Function1;
  obj[S_PARAMS][S_MESSAGE_TYPE] = 5;
  obj[S_PARAMS][S_PROTOCOL_VERSION] = 1;
  obj[S_PARAMS][S_PROTOCOL_TYPE] = 0;
  obj[S_PARAMS][S_CORRELATION_ID] = 444;
  obj[S_MSG_PARAMS] = SmartObject(SmartType::SmartType_Map);
  std::set<std::string> keys = obj.enumerate();
  EXPECT_EQ(2u, keys.size());
  EXPECT_EQ(Errors::eType::OUT_OF_RANGE, obj.validate());
  EXPECT_FALSE(obj.isValid());
}

TEST(CSmartFactoryTest, CreateSmartObjectWithSchema1_AddInvalidValue_ExpectCreatedNotCorrespondSmartSchema) {
  CSmartFactoryTest test_factory;
  // Create SmartObject with attached SmartChmema
  SmartObject obj = test_factory.CreateSmartObject(FunctionIdTest::Function1,
                                                   MessageTypeTest::request);
  EXPECT_TRUE(SmartType::SmartType_Map == obj.getType());
  // Adding necessary fields but one field is missed
  obj[S_PARAMS][S_FUNCTION_ID] = FunctionIdTest::Function1;
  obj[S_PARAMS][S_MESSAGE_TYPE] = "return";
  obj[S_PARAMS][S_PROTOCOL_VERSION] = 1;
  obj[S_PARAMS][S_PROTOCOL_TYPE] = 0;
  obj[S_PARAMS][S_CORRELATION_ID] = 444;
  obj[S_MSG_PARAMS] = SmartObject(SmartType::SmartType_Map);
  std::set<std::string> keys = obj.enumerate();
  EXPECT_EQ(2u, keys.size());
  EXPECT_EQ(Errors::eType::INVALID_VALUE, obj.validate());
  EXPECT_FALSE(obj.isValid());
}

TEST(CSmartFactoryTest, CreateSmartObj_AttachSchema1_ExpectCreatedObjectCorrespondsSmSchema1) {
  CSmartFactoryTest test_factory;
  // Create empty SmartObject  without any schema
  SmartObject obj;
  // Adding fields necessary for schema to attach
  obj[S_PARAMS][S_FUNCTION_ID] = FunctionIdTest::Function1;
  obj[S_PARAMS][S_MESSAGE_TYPE] = MessageTypeTest::request;
  // Attach schema to object
  EXPECT_TRUE(test_factory.attachSchema(obj, false));
  EXPECT_TRUE(SmartType::SmartType_Map == obj.getType());
  // Adding necessary fileds to correspond schema
  obj[S_PARAMS][S_CORRELATION_ID] = 444;
  obj[S_PARAMS][S_PROTOCOL_VERSION] = 1;
  obj[S_PARAMS][S_PROTOCOL_TYPE] = 0;
  obj[S_MSG_PARAMS] = SmartObject(SmartType::SmartType_Map);
  std::set<std::string> keys = obj.enumerate();
  EXPECT_EQ(2u, keys.size());
  EXPECT_EQ(Errors::eType::OK, obj.validate());
  EXPECT_TRUE(obj.isValid());
}

TEST(CSmartFactoryTest, CreateSmartObj_AttachSchema1_MissOneField_ExpectCreatedObjectNotCorrespondsSmSchema1) {
  CSmartFactoryTest test_factory;
  // Create empty SmartObject  without any schema
  SmartObject obj;
  // Adding fields necessary for schema to attach
  obj[S_PARAMS][S_FUNCTION_ID] = FunctionIdTest::Function1;
  obj[S_PARAMS][S_MESSAGE_TYPE] = MessageTypeTest::request;
  // Attach schema to object
  EXPECT_TRUE(test_factory.attachSchema(obj, false));
  EXPECT_TRUE(SmartType::SmartType_Map == obj.getType());
  // Adding necessary fileds to correspond schema but 1 field is missing
  obj[S_PARAMS][S_PROTOCOL_VERSION] = 1;
  obj[S_PARAMS][S_PROTOCOL_TYPE] = 0;
  obj[S_MSG_PARAMS] = SmartObject(SmartType::SmartType_Map);
  std::set<std::string> keys = obj.enumerate();
  EXPECT_EQ(2u, keys.size());
  EXPECT_EQ(Errors::eType::MISSING_MANDATORY_PARAMETER, obj.validate());
  EXPECT_FALSE(obj.isValid());
}

TEST(CSmartFactoryTest, CreateSmartObj_AttachNotExistedSchema_ExpectSmSchemaNotAttached) {
  CSmartFactoryTest test_factory;
  // Create empty SmartObject  without any schema
  SmartObject obj;
  // Adding fields necessary for schema to attach but one value is invalid
  obj[S_PARAMS][S_FUNCTION_ID] = FunctionIdTest::Function1;
  obj[S_PARAMS][S_MESSAGE_TYPE] = 10;
  // Attach schema to object
  EXPECT_FALSE(test_factory.attachSchema(obj, false));
  EXPECT_TRUE(SmartType::SmartType_Map == obj.getType());
}

TEST(CSmartFactoryTest, CreateSmartObj_AttachSchema1_AddInvalidValue_ExpectCreatedObjectNotCorrespondsSmSchema1) {
  CSmartFactoryTest test_factory;
  // Create empty SmartObject  without any schema
  SmartObject obj;
  // Adding fields necessary for schema to attach
  obj[S_PARAMS][S_FUNCTION_ID] = FunctionIdTest::Function1;
  obj[S_PARAMS][S_MESSAGE_TYPE] = MessageTypeTest::request;
  // Attach schema to object
  EXPECT_TRUE(test_factory.attachSchema(obj, false));
  EXPECT_TRUE(SmartType::SmartType_Map == obj.getType());
  // Adding necessary fileds to correspond schema but 1 field is missing
  obj[S_PARAMS][S_PROTOCOL_VERSION] = "string";
  obj[S_PARAMS][S_PROTOCOL_TYPE] = 0;
  obj[S_PARAMS][S_CORRELATION_ID] = 444;
  obj[S_MSG_PARAMS] = SmartObject(SmartType::SmartType_Map);
  std::set<std::string> keys = obj.enumerate();
  EXPECT_EQ(2u, keys.size());
  EXPECT_EQ(Errors::eType::INVALID_VALUE, obj.validate());
  EXPECT_FALSE(obj.isValid());
}

TEST(CSmartFactoryTest, CreateSmartObj_AttachSchema1_ExpectCreatedObjectCorrespondsSmSchema) {
  CSmartFactoryTest test_factory;
  // Create empty SmartObject  without any schema
  SmartObject obj;
  // Attach schema to object
  EXPECT_TRUE(test_factory.AttachSchema(StructIdentifiersTest::Common_1, obj));
  obj["text"] = "test";
  obj["position"] = 200;
  std::set<std::string> keys = obj.enumerate();
  EXPECT_EQ(2u, keys.size());
  EXPECT_EQ(Errors::eType::OK, obj.validate());
  EXPECT_TRUE(obj.isValid());
}

TEST(CSmartFactoryTest, CreateSmartObj_AttachSchema1_OneMandatoryFieldMissed_ExpectCreatedObjectNotCorrespondsSmSchema) {
  CSmartFactoryTest test_factory;
  // Create empty SmartObject  without any schema
  SmartObject obj;
  // Attach schema to object
  EXPECT_TRUE(test_factory.AttachSchema(StructIdentifiersTest::Common_1, obj));
  obj["text"] = "test";
  std::set<std::string> keys = obj.enumerate();
  EXPECT_EQ(1u, keys.size());
  EXPECT_EQ(Errors::eType::MISSING_MANDATORY_PARAMETER, obj.validate());
  EXPECT_FALSE(obj.isValid());
}

TEST(CSmartFactoryTest, CreateSmartObj_AttachSchema2_ExpectCreatedObjectCorrespondsSmSchema) {
  CSmartFactoryTest test_factory;
  // Create empty SmartObject  without any schema
  SmartObject obj;
  // Attach schema to object
  EXPECT_TRUE(test_factory.AttachSchema(StructIdentifiersTest::Common_2, obj));
  obj["text"] = "test1";
  obj["position"] = 200;
  std::set<std::string> keys = obj.enumerate();
  EXPECT_EQ(2u, keys.size());
  EXPECT_EQ(Errors::eType::OK, obj.validate());
  EXPECT_TRUE(obj.isValid());
}

TEST(CSmartFactoryTest, CreateSmartObj_AttachSchema_ExpectCreatedObjectCorrespondsSmSchema) {
  CSmartFactoryTest test_factory;
  // Create empty SmartObject  without any schema
  SmartObject obj;
  // Attach schema to object
  EXPECT_TRUE(test_factory.AttachSchema(StructIdentifiersTest::Common_1, obj));
  obj["text"] = "test";
  obj["position"] = 200;
  obj["image"]["text"] = "test2";
  obj["image"]["position"] = 100;
  EXPECT_EQ(Errors::eType::OK, obj["image"].validate());
  std::set<std::string> keys = obj.enumerate();
  EXPECT_EQ(3u, keys.size());
  EXPECT_EQ(Errors::eType::OK, obj.validate());
  EXPECT_TRUE(obj.isValid());
}

TEST(CSmartFactoryTest, CreateSmartObj_WithSchemaFromStructId_ExpectCreatedObjectCorrespondsSmSchema) {
  CSmartFactoryTest test_factory;
  // Create empty SmartObject  with schema correspopnding StructId
  SmartObject obj = test_factory.CreateSmartObject(
      StructIdentifiersTest::Common_1);
  // Add fields
  obj["text"] = "test";
  obj["position"] = 200;
  obj["image"]["text"] = "test2";
  obj["image"]["position"] = 100;
  // Check object "image"
  EXPECT_EQ(Errors::eType::OK, obj["image"].validate());
  std::set<std::string> keys = obj.enumerate();
  EXPECT_EQ(3u, keys.size());
  // Check global object
  EXPECT_EQ(Errors::eType::OK, obj.validate());
  EXPECT_TRUE(obj.isValid());
}

TEST(CSmartFactoryTest, CreateSmartObj_WithSchemaFromStructId_MissedOneField_ExpectCreatedObjectNotCorrespondsSmSchema) {
  CSmartFactoryTest test_factory;
  // Create empty SmartObject  with schema correspopnding StructId
  SmartObject obj = test_factory.CreateSmartObject(
      StructIdentifiersTest::Common_1);
  // Add fields. One missed.
  obj["text"] = "test";
  obj["image"]["text"] = "test2";
  obj["image"]["position"] = 100;
  // Check object "image"
  EXPECT_EQ(Errors::eType::OK, obj["image"].validate());
  std::set<std::string> keys = obj.enumerate();
  EXPECT_EQ(2u, keys.size());
  // Check global object
  EXPECT_EQ(Errors::eType::MISSING_MANDATORY_PARAMETER, obj.validate());
  EXPECT_FALSE(obj.isValid());
}

TEST(CSmartFactoryTest, CreateSmartObj_WithSchemaFromStructId2_ExpectCreatedObjectCorrespondsSmSchema) {
  CSmartFactoryTest test_factory;
  // Create empty SmartObject  with schema correspopnding StructId
  SmartObject obj = test_factory.CreateSmartObject(
      StructIdentifiersTest::Common_2);
  // Add fields
  obj["text"] = "test";
  obj["position"] = 200;
  obj["image"]["text"] = "test2";
  obj["image"]["position"] = 100;
  // Check object "image"
  EXPECT_EQ(Errors::eType::OK, obj["image"].validate());
  std::set<std::string> keys = obj.enumerate();
  EXPECT_EQ(3u, keys.size());
  // Check global object
  EXPECT_EQ(Errors::eType::OK, obj.validate());
  EXPECT_TRUE(obj.isValid());
}

TEST(CSmartFactoryTest, CreateSmartObj_WithSchemaFromStructId2_MissedOneField_ExpectCreatedObjectNotCorrespondsSmSchema) {
  CSmartFactoryTest test_factory;
  // Create empty SmartObject  with schema correspopnding StructId
  SmartObject obj = test_factory.CreateSmartObject(
      StructIdentifiersTest::Common_2);
  // Add fields. One missed.
  obj["text"] = "test";
  obj["image"]["text"] = "test2";
  std::set<std::string> keys = obj.enumerate();
  EXPECT_EQ(2u, keys.size());
  // Check global object
  EXPECT_EQ(Errors::eType::MISSING_MANDATORY_PARAMETER, obj.validate());
  EXPECT_FALSE(obj.isValid());
}

TEST(CSmartFactoryTest, CreateSmartObj_WithSchemaFromStructId2_InvalidValueAdded_ExpectCreatedObjectNotCorrespondsSmSchema) {
  CSmartFactoryTest test_factory;
  // Create empty SmartObject  with schema correspopnding StructId
  SmartObject obj = test_factory.CreateSmartObject(
      StructIdentifiersTest::Common_2);
  // Add fields. One missed.
  obj["text"] = 111;
  obj["position"] = 200;
  obj["image"]["text"] = "test2";
  std::set<std::string> keys = obj.enumerate();
  EXPECT_EQ(3u, keys.size());
  // Check global object
  EXPECT_EQ(Errors::eType::INVALID_VALUE, obj.validate());
  EXPECT_FALSE(obj.isValid());
}

TEST(CSmartFactoryTest, GetSchemaWithSmartFactory_ExpectReceivedSchema) {
  CSmartFactoryTest test_factory;
  CSmartSchema schema;
  EXPECT_TRUE(
      test_factory.GetSchema(FunctionIdTest::Function1,
                             MessageTypeTest::request, schema));
}

TEST(CSmartFactoryTest, GetNotExistedSchemaWithSmartFactory_ExpectNotReceivedSchema) {
  CSmartFactoryTest test_factory;
  CSmartSchema schema;
  EXPECT_FALSE(
      test_factory.GetSchema(FunctionIdTest::Function1,
                             MessageTypeTest::INVALID_ENUM, schema));
}

TEST(CSmartFactoryTest, GetSchemaWithSmartFactoryWithStructId1_ExpectReceivedSchema) {
  CSmartFactoryTest test_factory;
  CSmartSchema schema;
  EXPECT_TRUE(test_factory.GetSchema(StructIdentifiersTest::Common_1, schema));
}

TEST(CSmartFactoryTest, GetSchemaWithSmartFactoryWithStructId2_ExpectReceivedSchema) {
  CSmartFactoryTest test_factory;
  CSmartSchema schema;
  EXPECT_TRUE(test_factory.GetSchema(StructIdentifiersTest::Common_2, schema));
}

TEST(CSmartFactoryTest, GetNotExistedSchemaWithSmartFactoryWithStructId_ExpectNotReceivedSchema) {
  CSmartFactoryTest test_factory;
  CSmartSchema schema;
  EXPECT_FALSE(
      test_factory.GetSchema(StructIdentifiersTest::INVALID_ENUM, schema));
}

}  // namespace formatters
}  // namespace components
}  // namespace test


text:
package com.unipad.http;

import com.unipad.AppContext;
import com.unipad.singlebrain.home.bean.VersionBean;
import com.unipad.singlebrain.home.dao.NewsService;
import com.unipad.common.Constant;

import org.json.JSONObject;

/**
 * Created by gongkan on 2016/6/12.
 */
public class HitopNewsVersion extends HitopRequest<VersionBean>{

    public HitopNewsVersion(String path) {
        super(path);
    }
    public HitopNewsVersion() {
        super(HttpConstant.GET_NEWS_VERSION);

    }

    @Override
    public String buildRequestURL() {
        return null;
    }

    @Override
    public VersionBean handleJsonData(String json) {
        VersionBean versionBean = null;
        JSONObject jsObj = null;
        try {
            jsObj = new JSONObject(json);
            if (jsObj != null && jsObj.toString().length() != 0) {
                if (jsObj.getInt("ret_code") == 0) {
                    JSONObject data = new JSONObject(jsObj.getString("data"));
                    versionBean = new VersionBean();
                    versionBean.setVersion(data.getString("version"));
                    versionBean.setUpdateTime(data.getString("uploadDate"));
                    versionBean.setPath(HttpConstant.PATH_FILE_URL + data.getString("path"));
                    versionBean.setInfoDescription(data.getString("info"));
                }
            }
        }catch (Exception e) {
            return null;
        }
        ((NewsService)AppContext.instance().getService(Constant.NEWS_SERVICE)).noticeDataChange(HttpConstant.NOTIFY_DOWNLOAD_APK,versionBean);

        return null;
    }
}

redpajama_set_name: RedPajamaGithub


text:
export const MEDIA_SOURCE_LOCAL = 'local';
export const MEDIA_SOURCE_MJPEG = 'mjpeg';


text:
CREATE VIEW [dbo].[ApplicationUsers_V]
AS
SELECT dbo.Applications.ApplicationID, dbo.Applications.Name, dbo.Users.UserID, dbo.Users.FirstName, dbo.Users.LastName, dbo.Users.EmployeeID, dbo.Roles.Role,
               dbo.Permissions.Inactive, dbo.Permissions.PermissionID
FROM  dbo.Applications INNER JOIN
               dbo.Permissions ON dbo.Applications.ApplicationID = dbo.Permissions.ApplicationID INNER JOIN
               dbo.Users ON dbo.Permissions.UserID = dbo.Users.UserID INNER JOIN
               dbo.Roles ON dbo.Permissions.RoleID = dbo.Roles.RoleID
GO


text:
namespace Microsoft.Azure.Management.Compute.Models
{

    /// <summary>
    /// Defines values for PublicIPAddressSkuTier.
    /// </summary>
    public static class PublicIPAddressSkuTier
    {
        public const string Regional = "Regional";
        public const string Global = "Global";
    }
}


text:
<?php require_once("includes/functions.php"); ?>
<?php require_once("includes/session.php"); ?>
<?php require_once("includes/db_connection.php"); ?>
<?php function igdb_cover($title) {
	$title = urlencode($title);
	// determine Game ID
	// the id's of games should be stored locally, this would prevent the extra request
	$url  = "https://igdbcom-internet-game-database-v1.p.mashape.com/games/?search=";
  $url .= $title;

	$curl = curl_init($url);
	curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
	curl_setopt($curl, CURLOPT_HTTPHEADER, array('Accept: application/json','X-Mashape-Key: GoaKiXZhO2mshIteyk8g163yoUdup1Vbo91jsnTJo8PhLfcXWP'));
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
	$result = curl_exec ($curl);
	curl_close($curl);

	//converts the json array

		$game_set = json_decode($result, true);
		$id = $game_set[0]["id"];

		$image_url  = "https://igdbcom-internet-game-database-v1.p.mashape.com/games/";
		$image_url .= $id;
		$image_url .= "?fields=cover";

		$curl = curl_init($image_url);
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($curl, CURLOPT_HTTPHEADER, array('Accept: application/json','X-Mashape-Key: GoaKiXZhO2mshIteyk8g163yoUdup1Vbo91jsnTJo8PhLfcXWP'));
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
		$result = curl_exec ($curl);
		curl_close($curl);

		//converts the json array

			$image_set = json_decode($result, true);
			$image_location = $image_set[0]["cover"]["url"];

			return $image_location;
}
?>
<?php
$user_set = find_all_users();

//Displays images of each game on each user's list, very request-heavy on igdb

  while($user = mysqli_fetch_assoc($user_set)) {
	$list = find_list_by_user($user["id"]);
	if(!empty($list)) {
		$output  = "
". $user["username"]. "
";
		$output .= "
";

		while($game = mysqli_fetch_assoc($list)){
			//$output .= $game["title"]. "
";
			$output .= "";
		}
		$output .= "
";
		echo $output;
	}
}

/*
while($user = mysqli_fetch_assoc($user_set)) {
	$completion_set = find_completed_games($user["id"]);
	if( mysqli_num_rows($completion_set) != 0) {
		echo "
{$user["username"]}
";
		echo mysqli_num_rows($completion_set). ' Games Completed';
		echo '
';
		while ($completion = mysqli_fetch_assoc($completion_set)) {
			$game = find_game_by_id($completion["game_id"]);
			echo '
'. $game["title"]. '
';
		}
		echo '
';
	}
}

*/
?>


text:
package com.spotify.styx.model;

import static com.spotify.styx.serialization.Json.OBJECT_MAPPER;
import static com.spotify.styx.testdata.TestData.DAILY_WORKFLOW_CONFIGURATION;
import static com.spotify.styx.testdata.TestData.HOURLY_WORKFLOW_CONFIGURATION;
import static com.spotify.styx.testdata.TestData.HOURLY_WORKFLOW_CONFIGURATION_WITH_VALID_OFFSET;
import static com.spotify.styx.testdata.TestData.MONTHLY_WORKFLOW_CONFIGURATION;
import static com.spotify.styx.testdata.TestData.WEEKLY_WORKFLOW_CONFIGURATION;
import static com.spotify.styx.testdata.TestData.YEARLY_WORKFLOW_CONFIGURATION;
import static java.time.temporal.ChronoUnit.DAYS;
import static java.time.temporal.ChronoUnit.HOURS;
import static java.time.temporal.ChronoUnit.MINUTES;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;

import com.fasterxml.jackson.core.JsonProcessingException;
import java.time.Duration;
import java.time.Instant;
import java.util.Arrays;
import java.util.Collections;
import junitparams.JUnitParamsRunner;
import junitparams.Parameters;
import junitparams.naming.TestCaseName;
import org.junit.Test;
import org.junit.runner.RunWith;

@RunWith(JUnitParamsRunner.class)
public class WorkflowConfigurationTest {

  private static final Instant NOW = Instant.now();

  @Test
  public void shouldAddOffset() {
    assertThat(HOURLY_WORKFLOW_CONFIGURATION_WITH_VALID_OFFSET.addOffset(NOW),
        is(NOW.plus(30, DAYS).plus(30, MINUTES)));
  }

  @Test
  public void shouldAddDefaultOffset() {
    assertThat(HOURLY_WORKFLOW_CONFIGURATION.addOffset(NOW),
        is(NOW.plus(1, HOURS)));
  }

  @Test
  public void shouldSubtractOffset() {
    assertThat(HOURLY_WORKFLOW_CONFIGURATION_WITH_VALID_OFFSET.subtractOffset(NOW),
        is(NOW.minus(30, DAYS).minus(30, MINUTES)));
  }

  @Test
  public void shouldSubtractDefaultOffset() {
    assertThat(HOURLY_WORKFLOW_CONFIGURATION.subtractOffset(NOW),
        is(NOW.minus(1, HOURS)));
  }

  @Test
  public void shouldReturnDefaultOffset() {
    assertThat(HOURLY_WORKFLOW_CONFIGURATION.defaultOffset(), is("PT1H"));
    assertThat(DAILY_WORKFLOW_CONFIGURATION.defaultOffset(), is("P1D"));
    assertThat(WEEKLY_WORKFLOW_CONFIGURATION.defaultOffset(), is("P1W"));
    assertThat(MONTHLY_WORKFLOW_CONFIGURATION.defaultOffset(), is("P1M"));
    assertThat(YEARLY_WORKFLOW_CONFIGURATION.defaultOffset(), is("P1Y"));
    assertThat(WorkflowConfigurationBuilder.from(HOURLY_WORKFLOW_CONFIGURATION)
            .schedule(Schedule.parse("45 23 * * 6"))
            .build()
            .defaultOffset(),
        is("PT0S"));
  }

  @Test
  @TestCaseName("{method}: {0}")
  @Parameters(source = ParseJsonArgsProvider.class)
  public void shouldParseFromJson(String testCase, String json, WorkflowConfiguration expected)
      throws JsonProcessingException {
    final var conf = OBJECT_MAPPER.readValue(json, WorkflowConfiguration.class);

    assertThat(conf, is(expected));
  }

  public static class ParseJsonArgsProvider {

    private ParseJsonArgsProvider(){
      // Prevents instantiation
    }

    @SuppressWarnings("unused")
    public static Object[] provideDockerConf() {
      return new Object[] {
          "Original docker centred conf",
          buildJson(
              "\"docker_image\":\"gcr.io/some-bucket/some-image\","
              + "\"docker_args\":[\"1\",\"2\",\"3\"],"
              + "\"docker_termination_logging\":true"),
          configurationBuilder()
              .dockerImage("gcr.io/some-bucket/some-image")
              .dockerArgs(Arrays.asList("1", "2", "3"))
              .dockerTerminationLogging(true)
              .build()
      };
    }

    @SuppressWarnings("unused")
    public static Object[] provideFlyteExecConf() {
      return new Object[] {
          "Flyte exec conf",
          buildJson(
              "\"flyte_exec_conf\":{"
              + "  \"reference_id\":{"
              + "    \"resource_type\":\"launch-plan\","
              + "    \"domain\":\"production\","
              + "    \"project\":\"flyte-test\","
              + "    \"name\":\"TestWorkflow\","
              + "    \"version\":\"1.0\""
              + "  },"
              + "  \"input_fields\":{\"foo\": \"bar\"}"
              + "}"),
          configurationBuilder()
              .flyteExecConf(FlyteExecConf.builder()
                  .referenceId(FlyteIdentifier.builder()
                      .resourceType("launch-plan")
                      .domain("production")
                      .project("flyte-test")
                      .name("TestWorkflow")
                      .version("1.0")
                      .build())
                  .inputFields("foo", "bar")
                  .build())
              .build()
      };
    }

    @SuppressWarnings("unused")
    public static Object[] provideDeploymentSource() {
      return new Object[] {
          "Original docker centred conf",
          buildJson(
              "\"docker_image\":\"gcr.io/some-bucket/some-image\","
              + "\"docker_args\":[\"1\",\"2\",\"3\"],"
              + "\"docker_termination_logging\":true,"
              + "\"deployment_source\":{\"repository\":\"some-organisation/some-path-to-repositry\", \"source\":\"some-tool-name/some/path/to/file\" }"
          ),
          configurationBuilder()
              .dockerImage("gcr.io/some-bucket/some-image")
              .dockerArgs(Arrays.asList("1", "2", "3"))
              .dockerTerminationLogging(true)
              .deploymentSource(
                  DeploymentSource.builder()
                      .repository("some-organisation/some-path-to-repositry")
                      .source("some-tool-name/some/path/to/file")
                      .build())
              .build()
      };
    }

    @SuppressWarnings("unused")
    public static Object[] providePartialDeploymentSource() {
      return new Object[] {
          "Original docker centred conf",
          buildJson(
              "\"docker_image\":\"gcr.io/some-bucket/some-image\","
              + "\"docker_args\":[\"1\",\"2\",\"3\"],"
              + "\"docker_termination_logging\":true,"
              + "\"deployment_source\":{\"source\":\"some-tool-name/some/path/to/file\" }"
          ),
          configurationBuilder()
              .dockerImage("gcr.io/some-bucket/some-image")
              .dockerArgs(Arrays.asList("1", "2", "3"))
              .dockerTerminationLogging(true)
              .deploymentSource(
                  DeploymentSource.builder()
                      .source("some-tool-name/some/path/to/file")
                      .build())
              .build()
      };
    }

    private static WorkflowConfigurationBuilder configurationBuilder() {
      return WorkflowConfiguration.builder()
          .id("id")
          .schedule(Schedule.DAYS)
          .offset("P1D")
          .commitSha("817cdc3f95382c4e4e11232e3a2de484de8a2bea")
          .serviceAccount("foo@project.com")
          .resources(Collections.singletonList("resource"))
          .env(Collections.singletonMap("STYX_FOO", "bar"))
          .runningTimeout(Duration.ofHours(3))
          .retryCondition("true");
    }

    public static String buildJson(String execConf) {
      return "{"
             + "\"id\":\"id\","
             + "\"schedule\":\"days\","
             + "\"offset\":\"P1D\","
             + "\"commit_sha\":\"817cdc3f95382c4e4e11232e3a2de484de8a2bea\","
             + "\"service_account\":\"foo@project.com\","
             + "\"resources\":[\"resource\"],"
             + "\"env\":{\"STYX_FOO\":\"bar\"},"
             + "\"running_timeout\":10800.000000000,"
             + "\"retry_condition\":\"true\","
             + execConf
             + "}";
    }
  }
}


text:
using System;

namespace Umbraco.Cms.Core.Services.Changes
{
    [Flags]
    public enum TreeChangeTypes : byte
    {
        None = 0,

        // all items have been refreshed
        RefreshAll = 1,

        // an item node has been refreshed
        // with only local impact
        RefreshNode = 2,

        // an item node has been refreshed
        // with branch impact
        RefreshBranch = 4,

        // an item node has been removed
        // never to return
        Remove = 8,
    }
}


text:
import sys
import re

class ByLineBaseFilter:
    def __init__(self):
        self.output = ''

    def write(self, data):
        self.output += data
        k = self.output.rfind('\n')
        if k != -1:
            data_to_flush = self.output[:k]
            for line in data_to_flush.splitlines():
                self.process_line(line)
            self.output = self.output[k+1:]

    def flush(self):
        # only works by line, so ignore any flush
        pass

    def process_line(self, line):
        pass

class IncludeFilter(ByLineBaseFilter):
    def __init__(self, regex, stdout):
        self.regex = re.compile(regex)
        self.stdout = stdout
        super(IncludeFilter, self).__init__()

    def process_line(self, line):
        if self.regex.search(line):
            self.stdout.write(line + '\n')

class ExcludeFilter(ByLineBaseFilter):
    def __init__(self, regex, stdout):
        self.regex = re.compile(regex)
        self.stdout = stdout
        super(ExcludeFilter, self).__init__()

    def process_line(self, line):
        if not self.regex.search(line):
            self.stdout.write(line + '\n')

class RedirectStdout:
    ''' Create a context manager for redirecting sys.stdout
        to another file.
    '''
    def __init__(self, new_target):
        self.new_target = new_target
        self.olt_target = None

    def __enter__(self):
        self.old_target = sys.stdout
        sys.stdout = self.new_target
        return self

    def __exit__(self, exctype, excinst, exctb):
        sys.stdout = self.old_target

class FilterFactory:
    def create_include_filter(self, reg_ex, output):
        return IncludeFilter(reg_ex, output)

    def create_exclude_filter(self, reg_ex, output):
        return ExcludeFilter(reg_ex, output)


text:
using System;
using NUnit.Framework;
using System.Threading.Tasks;
using Nito.AsyncEx;
using System.Linq;
using System.Threading;
using System.Diagnostics.CodeAnalysis;
using System.Linq.Expressions;
using System.ComponentModel;

namespace Tests
{
    [TestFixture]
    public class TaskCompletionNotifierUnitTests_NET40
    {
        [Test]
        public void Notifier_TaskCompletesSuccessfully_NotifiesProperties()
        {
            var tcs = new TaskCompletionSource();
            var notifier = NotifyTaskCompletion.Create(tcs.Task);
            var taskNotification = PropertyNotified(notifier, n => n.Task);
            var statusNotification = PropertyNotified(notifier, n => n.Status);
            var isCompletedNotification = PropertyNotified(notifier, n => n.IsCompleted);
            var isSuccessfullyCompletedNotification = PropertyNotified(notifier, n => n.IsSuccessfullyCompleted);
            var isCanceledNotification = PropertyNotified(notifier, n => n.IsCanceled);
            var isFaultedNotification = PropertyNotified(notifier, n => n.IsFaulted);
            var exceptionNotification = PropertyNotified(notifier, n => n.Exception);
            var innerExceptionNotification = PropertyNotified(notifier, n => n.InnerException);
            var errorMessageNotification = PropertyNotified(notifier, n => n.ErrorMessage);

            tcs.SetResult();

            Assert.IsFalse(taskNotification());
            Assert.IsTrue(statusNotification());
            Assert.IsTrue(isCompletedNotification());
            Assert.IsTrue(isSuccessfullyCompletedNotification());
            Assert.IsFalse(isCanceledNotification());
            Assert.IsFalse(isFaultedNotification());
            Assert.IsFalse(exceptionNotification());
            Assert.IsFalse(innerExceptionNotification());
            Assert.IsFalse(errorMessageNotification());
        }

        [Test]
        public void Notifier_TaskCanceled_NotifiesProperties()
        {
            var tcs = new TaskCompletionSource();
            var notifier = NotifyTaskCompletion.Create(tcs.Task);
            var taskNotification = PropertyNotified(notifier, n => n.Task);
            var statusNotification = PropertyNotified(notifier, n => n.Status);
            var isCompletedNotification = PropertyNotified(notifier, n => n.IsCompleted);
            var isSuccessfullyCompletedNotification = PropertyNotified(notifier, n => n.IsSuccessfullyCompleted);
            var isCanceledNotification = PropertyNotified(notifier, n => n.IsCanceled);
            var isFaultedNotification = PropertyNotified(notifier, n => n.IsFaulted);
            var exceptionNotification = PropertyNotified(notifier, n => n.Exception);
            var innerExceptionNotification = PropertyNotified(notifier, n => n.InnerException);
            var errorMessageNotification = PropertyNotified(notifier, n => n.ErrorMessage);

            tcs.SetCanceled();

            Assert.IsFalse(taskNotification());
            Assert.IsTrue(statusNotification());
            Assert.IsTrue(isCompletedNotification());
            Assert.IsFalse(isSuccessfullyCompletedNotification());
            Assert.IsTrue(isCanceledNotification());
            Assert.IsFalse(isFaultedNotification());
            Assert.IsFalse(exceptionNotification());
            Assert.IsFalse(innerExceptionNotification());
            Assert.IsFalse(errorMessageNotification());
        }

        [Test]
        public void Notifier_TaskFaulted_NotifiesProperties()
        {
            var tcs = new TaskCompletionSource();
            var notifier = NotifyTaskCompletion.Create(tcs.Task);
            var taskNotification = PropertyNotified(notifier, n => n.Task);
            var statusNotification = PropertyNotified(notifier, n => n.Status);
            var isCompletedNotification = PropertyNotified(notifier, n => n.IsCompleted);
            var isSuccessfullyCompletedNotification = PropertyNotified(notifier, n => n.IsSuccessfullyCompleted);
            var isCanceledNotification = PropertyNotified(notifier, n => n.IsCanceled);
            var isFaultedNotification = PropertyNotified(notifier, n => n.IsFaulted);
            var exceptionNotification = PropertyNotified(notifier, n => n.Exception);
            var innerExceptionNotification = PropertyNotified(notifier, n => n.InnerException);
            var errorMessageNotification = PropertyNotified(notifier, n => n.ErrorMessage);

            tcs.SetException(new NotImplementedException());

            Assert.IsFalse(taskNotification());
            Assert.IsTrue(statusNotification());
            Assert.IsTrue(isCompletedNotification());
            Assert.IsFalse(isSuccessfullyCompletedNotification());
            Assert.IsFalse(isCanceledNotification());
            Assert.IsTrue(isFaultedNotification());
            Assert.IsTrue(exceptionNotification());
            Assert.IsTrue(innerExceptionNotification());
            Assert.IsTrue(errorMessageNotification());
        }

        [Test]
        public void NotifierT_TaskCompletesSuccessfully_NotifiesProperties()
        {
            var tcs = new TaskCompletionSource<object>();
            var notifier = NotifyTaskCompletion.Create(tcs.Task);
            var taskNotification = PropertyNotified(notifier, n => n.Task);
            var statusNotification = PropertyNotified(notifier, n => n.Status);
            var isCompletedNotification = PropertyNotified(notifier, n => n.IsCompleted);
            var isSuccessfullyCompletedNotification = PropertyNotified(notifier, n => n.IsSuccessfullyCompleted);
            var isCanceledNotification = PropertyNotified(notifier, n => n.IsCanceled);
            var isFaultedNotification = PropertyNotified(notifier, n => n.IsFaulted);
            var exceptionNotification = PropertyNotified(notifier, n => n.Exception);
            var innerExceptionNotification = PropertyNotified(notifier, n => n.InnerException);
            var errorMessageNotification = PropertyNotified(notifier, n => n.ErrorMessage);
            var resultNotification = PropertyNotified(notifier, n => n.Result);

            tcs.SetResult(null);

            Assert.IsFalse(taskNotification());
            Assert.IsTrue(statusNotification());
            Assert.IsTrue(isCompletedNotification());
            Assert.IsTrue(isSuccessfullyCompletedNotification());
            Assert.IsFalse(isCanceledNotification());
            Assert.IsFalse(isFaultedNotification());
            Assert.IsFalse(exceptionNotification());
            Assert.IsFalse(innerExceptionNotification());
            Assert.IsFalse(errorMessageNotification());
            Assert.IsTrue(resultNotification());
        }

        [Test]
        public void NotifierT_TaskCanceled_NotifiesProperties()
        {
            var tcs = new TaskCompletionSource<object>();
            var notifier = NotifyTaskCompletion.Create(tcs.Task);
            var taskNotification = PropertyNotified(notifier, n => n.Task);
            var statusNotification = PropertyNotified(notifier, n => n.Status);
            var isCompletedNotification = PropertyNotified(notifier, n => n.IsCompleted);
            var isSuccessfullyCompletedNotification = PropertyNotified(notifier, n => n.IsSuccessfullyCompleted);
            var isCanceledNotification = PropertyNotified(notifier, n => n.IsCanceled);
            var isFaultedNotification = PropertyNotified(notifier, n => n.IsFaulted);
            var exceptionNotification = PropertyNotified(notifier, n => n.Exception);
            var innerExceptionNotification = PropertyNotified(notifier, n => n.InnerException);
            var errorMessageNotification = PropertyNotified(notifier, n => n.ErrorMessage);
            var resultNotification = PropertyNotified(notifier, n => n.Result);

            tcs.SetCanceled();

            Assert.IsFalse(taskNotification());
            Assert.IsTrue(statusNotification());
            Assert.IsTrue(isCompletedNotification());
            Assert.IsFalse(isSuccessfullyCompletedNotification());
            Assert.IsTrue(isCanceledNotification());
            Assert.IsFalse(isFaultedNotification());
            Assert.IsFalse(exceptionNotification());
            Assert.IsFalse(innerExceptionNotification());
            Assert.IsFalse(errorMessageNotification());
            Assert.IsFalse(resultNotification());
        }

        [Test]
        public void NotifierT_TaskFaulted_NotifiesProperties()
        {
            var tcs = new TaskCompletionSource<object>();
            var notifier = NotifyTaskCompletion.Create(tcs.Task);
            var taskNotification = PropertyNotified(notifier, n => n.Task);
            var statusNotification = PropertyNotified(notifier, n => n.Status);
            var isCompletedNotification = PropertyNotified(notifier, n => n.IsCompleted);
            var isSuccessfullyCompletedNotification = PropertyNotified(notifier, n => n.IsSuccessfullyCompleted);
            var isCanceledNotification = PropertyNotified(notifier, n => n.IsCanceled);
            var isFaultedNotification = PropertyNotified(notifier, n => n.IsFaulted);
            var exceptionNotification = PropertyNotified(notifier, n => n.Exception);
            var innerExceptionNotification = PropertyNotified(notifier, n => n.InnerException);
            var errorMessageNotification = PropertyNotified(notifier, n => n.ErrorMessage);
            var resultNotification = PropertyNotified(notifier, n => n.Result);

            tcs.SetException(new NotImplementedException());

            Assert.IsFalse(taskNotification());
            Assert.IsTrue(statusNotification());
            Assert.IsTrue(isCompletedNotification());
            Assert.IsFalse(isSuccessfullyCompletedNotification());
            Assert.IsFalse(isCanceledNotification());
            Assert.IsTrue(isFaultedNotification());
            Assert.IsTrue(exceptionNotification());
            Assert.IsTrue(innerExceptionNotification());
            Assert.IsTrue(errorMessageNotification());
            Assert.IsFalse(resultNotification());
        }

        private static Func<bool> PropertyNotified<T, P>(T obj, Expression<Func<T, P>> prop) where T : INotifyPropertyChanged
        {
            var expression = (MemberExpression)prop.Body;
            string name = expression.Member.Name;

            bool invoked = false;
            obj.PropertyChanged += (_, e) =>
            {
                if (e.PropertyName == name)
                    invoked = true;
            };

            return () => invoked;
        }
    }
}


text:
.class public interface abstract Landroid/hardware/camera2/legacy/CameraDeviceState$CameraDeviceStateListener;
.super Ljava/lang/Object;
.source "CameraDeviceState.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/hardware/camera2/legacy/CameraDeviceState;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x609
    name = "CameraDeviceStateListener"
.end annotation

# virtual methods
.method public abstract onBusy()V
.end method

.method public abstract onCaptureResult(Landroid/hardware/camera2/impl/CameraMetadataNative;Landroid/hardware/camera2/legacy/RequestHolder;)V
.end method

.method public abstract onCaptureStarted(Landroid/hardware/camera2/legacy/RequestHolder;J)V
.end method

.method public abstract onConfiguring()V
.end method

.method public abstract onError(ILandroid/hardware/camera2/legacy/RequestHolder;)V
.end method

.method public abstract onIdle()V
.end method


text:
<?php

require_once dirname(__FILE__) . '/../../../tools/helpers/bookstore/BookstoreEmptyTestBase.php';

/**
 * Test class for PropelOnDemandFormatter.
 *
 * @author     Francois Zaninotto
 * @version    $Id: PropelOnDemandFormatterTest.php 1374 2009-12-26 23:21:37Z francois $
 * @package    runtime.formatter
 */
class PropelOnDemandFormatterTest extends BookstoreEmptyTestBase
{

    public function testFormatNoCriteria()
    {
        $con = Propel::getConnection(BookPeer::DATABASE_NAME);

        $stmt = $con->query('SELECT * FROM book');
        $formatter = new PropelOnDemandFormatter();
        try {
            $books = $formatter->format($stmt);
            $this->fail('PropelOnDemandFormatter::format() trows an exception when called with no valid criteria');
        } catch (PropelException $e) {
            $this->assertTrue(true,'PropelOnDemandFormatter::format() trows an exception when called with no valid criteria');
        }
    }

    public function testFormatManyResults()
    {
        $con = Propel::getConnection(BookPeer::DATABASE_NAME);
        BookstoreDataPopulator::populate($con);

        $stmt = $con->query('SELECT * FROM book');
        $formatter = new PropelOnDemandFormatter();
        $formatter->init(new ModelCriteria('bookstore', 'Book'));
        $books = $formatter->format($stmt);

        $this->assertTrue($books instanceof PropelOnDemandCollection, 'PropelOnDemandFormatter::format() returns a PropelOnDemandCollection');
        $this->assertEquals(4, count($books), 'PropelOnDemandFormatter::format() returns a collection that counts as many rows as the results in the query');
        foreach ($books as $book) {
            $this->assertTrue($book instanceof Book, 'PropelOnDemandFormatter::format() returns an traversable collection of Model objects');
        }
    }

    /**
     * @expectedException PropelException
     */
    public function testFormatManyResultsIteratedTwice()
    {
        $con = Propel::getConnection(BookPeer::DATABASE_NAME);
        BookstoreDataPopulator::populate($con);

        $stmt = $con->query('SELECT * FROM book');
        $formatter = new PropelOnDemandFormatter();
        $formatter->init(new ModelCriteria('bookstore', 'Book'));
        $books = $formatter->format($stmt);

        foreach ($books as $book) {
            // do nothing
        }
        foreach ($books as $book) {
            // this should throw a PropelException since we're iterating a second time over a stream
        }
    }

    public function testFormatALotOfResults()
    {
        $nbBooks = 50;
        $con = Propel::getConnection(BookPeer::DATABASE_NAME);
        Propel::disableInstancePooling();
        $book = new Book();
        for ($i=0; $i < $nbBooks; $i++) {
            $book->clear();
            $book->setTitle('BookTest' . $i);
            $book->save($con);
        }

        $stmt = $con->query('SELECT * FROM book');
        $formatter = new PropelOnDemandFormatter();
        $formatter->init(new ModelCriteria('bookstore', 'Book'));
        $books = $formatter->format($stmt);

        $this->assertTrue($books instanceof PropelOnDemandCollection, 'PropelOnDemandFormatter::format() returns a PropelOnDemandCollection');
        $this->assertEquals($nbBooks, count($books), 'PropelOnDemandFormatter::format() returns a collection that counts as many rows as the results in the query');
        $i = 0;
        foreach ($books as $book) {
            $this->assertTrue($book instanceof Book, 'PropelOnDemandFormatter::format() returns a collection of Model objects');
            $this->assertEquals('BookTest' . $i, $book->getTitle(), 'PropelOnDemandFormatter::format() returns the model objects matching the query');
            $i++;
        }
        Propel::enableInstancePooling();
    }

    public function testFormatOneResult()
    {
        $con = Propel::getConnection(BookPeer::DATABASE_NAME);
        BookstoreDataPopulator::populate($con);

        $stmt = $con->query('SELECT * FROM book WHERE book.TITLE = "Quicksilver"');
        $formatter = new PropelOnDemandFormatter();
        $formatter->init(new ModelCriteria('bookstore', 'Book'));
        $books = $formatter->format($stmt);

        $this->assertTrue($books instanceof PropelOnDemandCollection, 'PropelOnDemandFormatter::format() returns a PropelOnDemandCollection');
        $this->assertEquals(1, count($books), 'PropelOnDemandFormatter::format() returns a collection that counts as many rows as the results in the query');
        foreach ($books as $book) {
            $this->assertTrue($book instanceof Book, 'PropelOnDemandFormatter::format() returns a collection of Model objects');
            $this->assertEquals('Quicksilver', $book->getTitle(), 'PropelOnDemandFormatter::format() returns the model objects matching the query');
        }
    }

    public function testFormatNoResult()
    {
        $con = Propel::getConnection(BookPeer::DATABASE_NAME);

        $stmt = $con->query('SELECT * FROM book WHERE book.TITLE = "foo"');
        $formatter = new PropelOnDemandFormatter();
        $formatter->init(new ModelCriteria('bookstore', 'Book'));
        $books = $formatter->format($stmt);

        $this->assertTrue($books instanceof PropelOnDemandCollection, 'PropelOnDemandFormatter::format() returns a PropelCollection');
        $this->assertEquals(0, count($books), 'PropelOnDemandFormatter::format() returns an empty collection when no record match the query');
        foreach ($books as $book) {
            $this->fail('PropelOnDemandFormatter returns an empty iterator when no record match the query');
        }
    }

    public function testFormatOneManyResults()
    {
        $con = Propel::getConnection(BookPeer::DATABASE_NAME);
        BookstoreDataPopulator::populate($con);

        $stmt = $con->query('SELECT * FROM book');
        $formatter = new PropelOnDemandFormatter();
        $formatter->init(new ModelCriteria('bookstore', 'Book'));
        $book = $formatter->formatOne($stmt);

        $this->assertTrue($book instanceof Book, 'PropelOnDemandFormatter::formatOne() returns a model object');
    }

    public function testFormatSingleTableInheritanceManyResults()
    {
        $con = Propel::getConnection(BookPeer::DATABASE_NAME);
        BookstoreDataPopulator::populate($con);

        $stmt = $con->query('SELECT * FROM bookstore_employee');
        $formatter = new PropelOnDemandFormatter();
        $formatter->init(new ModelCriteria('bookstore', 'BookstoreEmployee'));

        $employees = $formatter->format($stmt);

        foreach ($employees as $employee) {
            $row = array();
            $row[1] = $employee->getClassKey();

            $omClass = BookstoreEmployeePeer::getOMClass($row, 0, false);
            $actualClass = get_class($employee);

            $this->assertEquals($omClass, $actualClass, 'PropelOnDemandFormatter::format() should handle single table inheritance');
        }
    }
}


text:
shopt -s -o pipefail
set -e 		# Exit on error

PKG_NAME="perl"
PKG_VERSION="5.26.0"

TARBALL="${PKG_NAME}-${PKG_VERSION}.tar.xz"
SRC_DIR="${PKG_NAME}-${PKG_VERSION}"

function showHelp() {
    echo -e "--------------------------------------------------------------------------------------------------------------"
    echo -e "Description: The Perl package contains the Practical Extraction and Report Language."
    echo -e "--------------------------------------------------------------------------------------------------------------"
    echo -e ""
}

function prepare() {
    ln -sv /sources/${TARBALL} ${TARBALL}
}

function unpack() {
    tar xf ${TARBALL}
}

function build() {
    sed -i "s@/usr/include@${HOST_TDIR}/include@g" ext/Errno/Errno_pm.PL

    ./configure.gnu --prefix=${HOST_TDIR} \
                    -Dcc="gcc"

    make ${MAKE_PARALLEL}
}

function instal() {
    make ${MAKE_PARALLEL} install
    ln -sfv ${HOST_TDIR}/bin/perl /usr/bin
}

function clean() {
    rm -rf ${SRC_DIR} ${TARBALL}
}

# Run the installation procedure
time { showHelp;clean;prepare;unpack;pushd ${SRC_DIR};build;instal;popd;clean; }
# Verify installation
if [ -f /usr/bin/perl ]; then
    touch ${DONE_DIR_BUILD_SYSTEM}/$(basename $(pwd))
fi


text:
import type {Fiber} from './ReactInternalTypes';
import type {Container, SuspenseInstance} from './ReactFiberHostConfig';
import type {SuspenseState} from './ReactFiberSuspenseComponent.old';

import invariant from 'shared/invariant';

import {get as getInstance} from 'shared/ReactInstanceMap';
import ReactSharedInternals from 'shared/ReactSharedInternals';
import getComponentName from 'shared/getComponentName';
import {
  ClassComponent,
  HostComponent,
  HostRoot,
  HostPortal,
  HostText,
  SuspenseComponent,
} from './ReactWorkTags';
import {NoFlags, Placement, Hydrating} from './ReactFiberFlags';

const ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner;

export function getNearestMountedFiber(fiber: Fiber): null | Fiber {
  let node = fiber;
  let nearestMounted = fiber;
  if (!fiber.alternate) {
    // If there is no alternate, this might be a new tree that isn't inserted
    // yet. If it is, then it will have a pending insertion effect on it.
    let nextNode = node;
    do {
      node = nextNode;
      if ((node.flags & (Placement | Hydrating)) !== NoFlags) {
        // This is an insertion or in-progress hydration. The nearest possible
        // mounted fiber is the parent but we need to continue to figure out
        // if that one is still mounted.
        nearestMounted = node.return;
      }
      nextNode = node.return;
    } while (nextNode);
  } else {
    while (node.return) {
      node = node.return;
    }
  }
  if (node.tag === HostRoot) {
    // TODO: Check if this was a nested HostRoot when used with
    // renderContainerIntoSubtree.
    return nearestMounted;
  }
  // If we didn't hit the root, that means that we're in an disconnected tree
  // that has been unmounted.
  return null;
}

export function getSuspenseInstanceFromFiber(
  fiber: Fiber,
): null | SuspenseInstance {
  if (fiber.tag === SuspenseComponent) {
    let suspenseState: SuspenseState | null = fiber.memoizedState;
    if (suspenseState === null) {
      const current = fiber.alternate;
      if (current !== null) {
        suspenseState = current.memoizedState;
      }
    }
    if (suspenseState !== null) {
      return suspenseState.dehydrated;
    }
  }
  return null;
}

export function getContainerFromFiber(fiber: Fiber): null | Container {
  return fiber.tag === HostRoot
    ? (fiber.stateNode.containerInfo: Container)
    : null;
}

export function isFiberMounted(fiber: Fiber): boolean {
  return getNearestMountedFiber(fiber) === fiber;
}

export function isMounted(component: React$Component<any, any>): boolean {
  if (__DEV__) {
    const owner = (ReactCurrentOwner.current: any);
    if (owner !== null && owner.tag === ClassComponent) {
      const ownerFiber: Fiber = owner;
      const instance = ownerFiber.stateNode;
      if (!instance._warnedAboutRefsInRender) {
        console.error(
          '%s is accessing isMounted inside its render() function. ' +
            'render() should be a pure function of props and state. It should ' +
            'never access something that requires stale data from the previous ' +
            'render, such as refs. Move this logic to componentDidMount and ' +
            'componentDidUpdate instead.',
          getComponentName(ownerFiber.type) || 'A component',
        );
      }
      instance._warnedAboutRefsInRender = true;
    }
  }

  const fiber: ?Fiber = getInstance(component);
  if (!fiber) {
    return false;
  }
  return getNearestMountedFiber(fiber) === fiber;
}

function assertIsMounted(fiber) {
  invariant(
    getNearestMountedFiber(fiber) === fiber,
    'Unable to find node on an unmounted component.',
  );
}

export function findCurrentFiberUsingSlowPath(fiber: Fiber): Fiber | null {
  const alternate = fiber.alternate;
  if (!alternate) {
    // If there is no alternate, then we only need to check if it is mounted.
    const nearestMounted = getNearestMountedFiber(fiber);
    invariant(
      nearestMounted !== null,
      'Unable to find node on an unmounted component.',
    );
    if (nearestMounted !== fiber) {
      return null;
    }
    return fiber;
  }
  // If we have two possible branches, we'll walk backwards up to the root
  // to see what path the root points to. On the way we may hit one of the
  // special cases and we'll deal with them.
  let a: Fiber = fiber;
  let b: Fiber = alternate;
  while (true) {
    const parentA = a.return;
    if (parentA === null) {
      // We're at the root.
      break;
    }
    const parentB = parentA.alternate;
    if (parentB === null) {
      // There is no alternate. This is an unusual case. Currently, it only
      // happens when a Suspense component is hidden. An extra fragment fiber
      // is inserted in between the Suspense fiber and its children. Skip
      // over this extra fragment fiber and proceed to the next parent.
      const nextParent = parentA.return;
      if (nextParent !== null) {
        a = b = nextParent;
        continue;
      }
      // If there's no parent, we're at the root.
      break;
    }

    // If both copies of the parent fiber point to the same child, we can
    // assume that the child is current. This happens when we bailout on low
    // priority: the bailed out fiber's child reuses the current child.
    if (parentA.child === parentB.child) {
      let child = parentA.child;
      while (child) {
        if (child === a) {
          // We've determined that A is the current branch.
          assertIsMounted(parentA);
          return fiber;
        }
        if (child === b) {
          // We've determined that B is the current branch.
          assertIsMounted(parentA);
          return alternate;
        }
        child = child.sibling;
      }
      // We should never have an alternate for any mounting node. So the only
      // way this could possibly happen is if this was unmounted, if at all.
      invariant(false, 'Unable to find node on an unmounted component.');
    }

    if (a.return !== b.return) {
      // The return pointer of A and the return pointer of B point to different
      // fibers. We assume that return pointers never criss-cross, so A must
      // belong to the child set of A.return, and B must belong to the child
      // set of B.return.
      a = parentA;
      b = parentB;
    } else {
      // The return pointers point to the same fiber. We'll have to use the
      // default, slow path: scan the child sets of each parent alternate to see
      // which child belongs to which set.
      //
      // Search parent A's child set
      let didFindChild = false;
      let child = parentA.child;
      while (child) {
        if (child === a) {
          didFindChild = true;
          a = parentA;
          b = parentB;
          break;
        }
        if (child === b) {
          didFindChild = true;
          b = parentA;
          a = parentB;
          break;
        }
        child = child.sibling;
      }
      if (!didFindChild) {
        // Search parent B's child set
        child = parentB.child;
        while (child) {
          if (child === a) {
            didFindChild = true;
            a = parentB;
            b = parentA;
            break;
          }
          if (child === b) {
            didFindChild = true;
            b = parentB;
            a = parentA;
            break;
          }
          child = child.sibling;
        }
        invariant(
          didFindChild,
          'Child was not found in either parent set. This indicates a bug ' +
            'in React related to the return pointer. Please file an issue.',
        );
      }
    }

    invariant(
      a.alternate === b,
      "Return fibers should always be each others' alternates. " +
        'This error is likely caused by a bug in React. Please file an issue.',
    );
  }
  // If the root is not a host container, we're in a disconnected tree. I.e.
  // unmounted.
  invariant(
    a.tag === HostRoot,
    'Unable to find node on an unmounted component.',
  );
  if (a.stateNode.current === a) {
    // We've determined that A is the current branch.
    return fiber;
  }
  // Otherwise B has to be current branch.
  return alternate;
}

export function findCurrentHostFiber(parent: Fiber): Fiber | null {
  const currentParent = findCurrentFiberUsingSlowPath(parent);
  return currentParent !== null
    ? findCurrentHostFiberImpl(currentParent)
    : null;
}

function findCurrentHostFiberImpl(node: Fiber) {
  // Next we'll drill down this component to find the first HostComponent/Text.
  if (node.tag === HostComponent || node.tag === HostText) {
    return node;
  }

  let child = node.child;
  while (child !== null) {
    const match = findCurrentHostFiberImpl(child);
    if (match !== null) {
      return match;
    }
    child = child.sibling;
  }

  return null;
}

export function findCurrentHostFiberWithNoPortals(parent: Fiber): Fiber | null {
  const currentParent = findCurrentFiberUsingSlowPath(parent);
  return currentParent !== null
    ? findCurrentHostFiberWithNoPortalsImpl(currentParent)
    : null;
}

function findCurrentHostFiberWithNoPortalsImpl(node: Fiber) {
  // Next we'll drill down this component to find the first HostComponent/Text.
  if (node.tag === HostComponent || node.tag === HostText) {
    return node;
  }

  let child = node.child;
  while (child !== null) {
    if (child.tag !== HostPortal) {
      const match = findCurrentHostFiberWithNoPortalsImpl(child);
      if (match !== null) {
        return match;
      }
    }
    child = child.sibling;
  }

  return null;
}

export function isFiberSuspenseAndTimedOut(fiber: Fiber): boolean {
  const memoizedState = fiber.memoizedState;
  return (
    fiber.tag === SuspenseComponent &&
    memoizedState !== null &&
    memoizedState.dehydrated === null
  );
}

export function doesFiberContain(
  parentFiber: Fiber,
  childFiber: Fiber,
): boolean {
  let node = childFiber;
  const parentFiberAlternate = parentFiber.alternate;
  while (node !== null) {
    if (node === parentFiber || node === parentFiberAlternate) {
      return true;
    }
    node = node.return;
  }
  return false;
}


text:
package com.google.sps.servlets;

// See more information here: https://developers.google.com/calendar/v3/reference/calendars/insert

/** Add a new calendar to the user's list of calendars */
public class NewCalendar {
    private String summary = null;

    public NewCalendar(String summary) {
        this.summary = summary;
    }

    public String createNewCalendarURL(String accessToken) {
        return new StringBuilder("https://www.googleapis.com/calendar/v3/calendars?access_token=").append(accessToken).toString();
    }
}


text:
title: Edison User Guide
tags: "open-hardware"
published: true
img: ic-edison.png
permalink: /en/open-hardware/edison-user-guide.html
---

Thing+ Integration Guide for Edison

1. [Environment Setting](#id-setting)
2. [Install ThingPlus Package](#id-package)
3. [Set Hostname](#id-hostname)
4. [Gateway Registration](#id-register)

---

#### 1. Environment Setting

0) [Grove starter sensor kit](http://www.seeedstudio.com/depot/Grove-Starter-Kit-for-Arduino-p-1855.html)

1) Assemble your board

- [Reference](https://software.intel.com/en-us/articles/assemble-intel-edison-on-the-arduino-board)
- Plug in the power supply.
- Plug in 2 micro-USB cable to the USB connector on the expansion board. (Plug the other end of the USB cable in to your computer.)
  ![connection](/assets/edison_connect.png)

- Find the microswitch in between the USB ports on the expansion board. Switch the microswitch down towards the micro-USB ports, if it isn't already.
  ![switch](/assets/edison_ext.png)

2) Connect with Grove base shield.

![Edison + Grove kit](/assets/edison_base.png)

3) Connect with Sensors.

 LED Polarity

![LED Polarity](/assets/led.png)

![Edison + Grove Starter kit](/assets/edison_sensor.png)

4) Update firmware of Edison.

- In case of old version, connecing of WiFi is unstable.
- [Install "Firmware Installer"](https://software.intel.com/en-us/iot/software/installers)
  ![installer](/assets/intel_installer.png)
  ![installer](/assets/intel_installer2.png)

5) Connect to Edison by using USB.

- If you are a Mac or Linux user, please use the default terminal utility.
- If you are a Windows user, we recommend that you use the "Putty" client.
- [Install Putty](http://the.earth.li/~sgtatham/putty/latest/x86/putty.exe)

 For Mac OSX and Linux

- In case of Linux, you should be install "screen".
  - apt-get install screen

  ```
  screen -L /dev/cu.usbserial_XXXXXX 115200 (MAC)
  ```

- if you can't find "/dev/cb.usbserial_XXXX", then reboot device.
- When Termianl screen is changed, Press `Enter`.
- account : root, Password is none.

 For windows

- Select to `Serial` then set to `serial line` and `speed`. speed set to `115200`.
![putty](/assets/putty.png)

- `Serial line` is COM port for Edison , `COMXX`.
- account : root, Password is none.

6) Set To Password.

``` bash
configure_edison --password
```

7) Connect to WiFi

```
configure_edison --wifi
```

- Your board will scan for Wi-Fi networks for approximately 10 seconds. When it is finished, a list of available networks will be displayed. If you don't see any networks, enter 0 to rescan.
- Choose the network you would like to connect to, type the corresponding number from the list, and press Enter. To confirm your entry, type Y and press Enter.
- When you see a Done message, your board is connected to a Wi-Fi network.
- Note the IP Address. This is your board's IP Address

---

#### 2. Install ThingPlus Package

1) Make folder to be install Thing+ Embedded Package and move that folder.

```bash
edison:~/# mkdir /opt/thingplus
edison:~/# cd /opt/thingplus
```

2) Download a install script file. ([Install wget](/en/help/faq.html#install_wget))

```
wget http://support.thingplus.net/download/install/thingplus_embedded_sdk_edison_install.sh
```

3) Grant a run permission to the script you downloaded and Install the Thing+ Embedded Package.

- It can take few minutes to install the Thing+ Embedded Package.

  ```bash
  edison:/opt/thingplus# chmod 755 thingplus_embedded_sdk_edison_install.sh
  edison:/opt/thingplus# ./thingplus_embedded_sdk_edison_install.sh
  ```

---

#### 3. Set Host name

1) Change the hostname of your Edison for identifying it.

> Remark: You can't move the cursor on the Terminal and/or Putty with your mouse. please use your keyboard to move it.

- Modify `/etc/hostname`

  ```bash
  edison:~/# vi /etc/hostname
  ```

- Change the `Edison' in the file to your own name(letter, number and hyphen(-) allowed only) like the below image.
  ![Modify hostname](/assets/vi_hostname.png)

  - When you complete the edit task, press `CTRL-O`and `Enter` for saving the updates. Press `CTRL-X` to close the nano editor.

2) To apply your modification, please reboot your Edison.

```
edison:~/# reboot
```

---

#### 4. Gateway Registration

- Please Refer[Gateway Registration](/en/user-guide/registration.html#id-gateway)


text:
#include "cocos2d.h"
#include "cocos-ext.h"

class PlayerController : public cocos2d::extension::CCComController
{
protected:
    PlayerController(void);
    virtual ~PlayerController(void);

public:
    virtual void ccTouchesEnded(cocos2d::CCSet *pTouches, cocos2d::CCEvent *pEvent);

public:
    virtual bool init();
    virtual void onEnter();
    virtual void onExit();
    virtual void update(float delta);

   static PlayerController* create(void);
};

#endif  // __FUNDATION__CCCOMPONENT_H__


text:
using System.Linq;

namespace SharedKernel
{
    public abstract class ValueObject<T> where T : ValueObject<T>
    {
        private readonly IdentityFinder identityFinder = new IdentityFinder();
        private readonly TypeMemberInvoker valueInvoker = new TypeMemberInvoker();

        public override bool Equals(object obj)
        {
            if (obj == null || GetType() != obj.GetType())
            {
                return false;
            }

            return HasTheSameIdentity(obj);
        }

        public override int GetHashCode()
        {
            var members = identityFinder.FindIdentitiesIncludingInherited(GetType());
            var values = members.Select(member => valueInvoker.InvokeMemberOf(this, member))
                                .Where(value => value != null);

            return HashCoder.HashCode(values.ToArray());
        }

        public static bool operator ==(ValueObject<T> obj1, ValueObject<T> obj2)
        {
            if (((object)obj1) == null) //this cast prevents recursive call of == operator
            {
                return false;
            }
            return obj1.Equals(obj2);
        }

        public static bool operator !=(ValueObject<T> obj1, ValueObject<T> obj2)
        {
            return !(obj1 == obj2);
        }

        private bool HasTheSameIdentity(object obj)
        {
            foreach (var member in identityFinder.FindIdentitiesIncludingInherited(GetType()))
            {
                var value1 = valueInvoker.InvokeMemberOf(this, member);
                var value2 = valueInvoker.InvokeMemberOf(obj, member);
                if (value1 == null || !value1.Equals(value2))
                    return false;
            }

            return true;
        }
    }
}


text: console.log('base.js', 'loaded');


text:
This gem encapsulates the common logic for publishing and subscribing to events from services via AWS SNS and SQS.

It relies on https://github.com/pedro/cb2 and hence redis to circuit break in case of problems with AWS.

## Installation

You will need Ruby 2.2.2 or higher.

Add this line to your application's Gemfile:

```ruby
gem 'pub_sub', github: 'westfield/pub_sub'

```

And then execute:

```sh
$ bundle
```

## Usage

### Configuration
Configuration is handled with an initializer as below.

```ruby
# config/initializers/pub_sub.rb
PubSub.configure do |config|
  # The name of this service. Topics and queues will be named foo-service-[env].
  config.service 'foo'

  # Listen for the specified messages from one or more services
  config.subscribe_to 'barbaz', messages: ['bar_update', 'baz_update']
  config.subscribe_to 'wibble', messages: ['wibble_update']

  # Add senders to whitelist
  config.add_to_whitelist 'foobar_sender'
  config.add_to_whitelist 'barfoo_sender'

  # Credentials and region for Amazon AWS (for SNS/SQS)
  config.aws(
    key: 'mykey',
    secret: 'my_secret',
    regions: ['us-east-1', 'us-west-1']
  )
end
```
If you use standard AWS environment variables (`AWS_ACCESS_KEY_ID` and `AWS_SECRET_ACCESS_KEY`), then you do not need to specify them here.

Similarly, if you want to subscribe in all available regions, then omit the `regions` parameter as well.

### Logging
If running under Rails, this will log to Rails.logger. In other environments, you can set the logger like `PubSub.config.logger = MyLogger` or similar.
You also can set the log_level like `PubSub.config.log_level = :info` for published, received and processed messages, valid options are: `:debug`, `:info`, `:warn`, `:error`, `:fatal` and `:unknown`, `:debug` is the default value.

### Wiring up subscriptions
To connect queues to topics, and put the above config file into practice, you should run `bundle exec rake pub_sub:subscribe`. Verify this has worked as expected by running `bundle exec rake pub_sub:debug:subscriptions`.
Note that the subscribe task will be run automatically before the poll task, so it's probably not needed to run the subscribe task on production or staging. Checking that the subscriptions are correct after a deploy would be prudent, of course.

### Subscriber workers
You can set the number of worker threads for the subscribers with the ENV variable 'PUB_SUB_WORKER_CONCURRENCY'. By default it's two; testing with Standard 1X dynos on heroku suggests around 10-20 is reasonable, depending on the application.

### Unsubscribing
This functionality is not implemented yet.

### Receiving a message

When PubSub receives a message, it performs a couple of checks before processing:

* If the message originates from a known service, but the message type is not in the list of accepted types for that service, a `PubSub::MessageTypeUnknown` exception will be logged & raised.

If the message passes those validations, it will `classify` the message type and run its `process` method. Data from the message is available inside the message handler via the `data` variable.

```ruby
# app/events/foo_update.rb
require 'open-uri'

class FooUpdate
  include PubSub::MessageHandler

  # Recieve & process an foo_update message
  def self.process(data)
    foo = Foo.find_or_initialize_by(id: data['id'])
    foo_name = JSON.parse(open(data['uri']).read)['data']['name']
    foo.update(name: foo_name)
  end
end

```

### Publishing a message

A message publisher requires two things - an include of `PubSub::MessagePublisher` and a `message_data` method.

Note: If `message_data` is not defined in your publisher, a `NotImplementedError` will be raised.

```ruby
# app/events/foo_update.rb
class FooUpdate
  include PubSub::MessagePublisher

  def initialize(foo)
    @foo = foo
  end

  def message_data
    { url: foo_url, id: @foo.id }
  end

  def foo_url
    "https://example.com/foos/#{@foo.id}"
  end
end
```

### Combined Publisher / Receiver

A service can publish & consume the same kind of message. This can be used to offload heavy processing from the web tier, like resque or activejob.

```ruby
# app/events/foo_update.rb
require 'open-uri'

class FooUpdate
  include PubSub::MessagePublisher
  include PubSub::MessageHandler

  # Recieve & process an foo_update message
  def self.process(data)
    foo = Foo.find_or_initialize_by(id: data['id'])
    foo_name = JSON.parse(open(data['uri']).read)['data']['name']
    foo.update(name: foo_name)
  end

  def initialize(foo)
    @foo = foo
  end

  def message_data
    { url: foo_url, id: @foo.id }
  end

  def foo_url
    "https://example.com/foos/#{@foo.id}"
  end
end
```

### Async
`MessagePublisher.publish` has an optional parameter `async` which will send the message in a separate thread. This avoids blocking when communicating with the Amazon SNS service which generally adds a delay of around 0.5-2 seconds. This can cause slow response times for `POST` and `PUT` requests.

The trade-off is that if a message fails to send for some reason, it won't fail the parent transaction and you won't be notified. For this reason `async` is off by default, but you can use it where it makes sense to.

It is not recommended to use async functionality - it is deprecated and liekly to be removed soon. Instead, consider using futures from git@github.com:ruby-concurrency/concurrent-ruby.git .

```ruby
# Example of using a message publisher with async
FooUpdate.new(Foo.first).publish(async: true)
```

### ActiveRecord integration

To automatically publish a message when its data changes, add the following to your model definition:

```ruby
class Retailer < ActiveRecord::Base
  publish_changes_with :retailer_update
end
```

### Rake tasks

There are a few rake tasks made available for working with the message queues and subscriptions.

* `rake pub_sub:subscribe` - will subscribe the service to the message queues specified in the config. You must run this at least once as it registers your service with the queue.
* `rake pub_sub:poll` - starts receiving messages from the queue(s) and dispatching them to the appropriate handler(s) if available. It is multi-threaded with 2 threads by default, but this can be changed by setting the `PUB_SUB_WORKER_CONCURRENCY` environment variable. This can't be run until after `pub_sub:subscribe` has been run.
* `rake pub_sub:debug:all` - prints out information about the state of queues, topics & subscriptions.
* `rake pub_sub:debug:queues` - prints out information about the state of queues including the approximate number of messages in the queue.
* `rake pub_sub:debug:subscriptions` - prints out information about the state of subscriptions.
* `rake pub_sub:debug:topics` - prints out information about the state of topics.

If hosting on Heroku your `Procfile` ought to include a line like

```
worker: bundle exec rake pub_sub:poll
```

Note you don't need this line to publish, only to subscribe.

### Errors

There is a custom exception which may be raised during processing:

* `PubSub::MessageTypeUnknown` will be raised if a message arrives from a configured service, but is *not* in the list of acceptable messages.

### Region failover

In case of problems in one AWS region, this gem will attempt to failover across regions. By default, the regions selected are us-east-1, then us-west-1, then eu-west-1, then ap-southeast-1. An assumption is made that if SNS is encountering problems in a region, it's probable that SQS will as well, so errors in a region from either service will contribute to the failover circuit breaking logic.

The subscriber will "region hop" periodically if it's queue is empty even in the abscence of errors. This is because if an application doesn't publish, it will never know that SNS is having problems. By effectively receiving messages on _any_ region, we avoid this failure mode.

### Developing with pub_sub

Run `rake pub_sub:poll` to start receiving messages from your own queues. The services suffix their `service_identifier` with a local identifier (your system username) so your development and test messages don't pollute the production or UAT services.

To see how the subscriptions look without necessarily sending events through them, you can `rake pub_sub:subscribe` once to register your personal version of the service's queues with the topics. This may be useful for understanding how messages will flow, in conjunction with `rake pub_sub:debug:subscriptions`.

### Message design and SQS constraints

Generally it's recommended to provide the absolute minimum of data in a published message - a URI and/or ID for each event should be plenty.

The main reason for this is that SQS guarantees that every message will be received at least once. And that's _it_. You cannot rely on the order of messages, or that the same message won't be delivered n times. By relying on an API call based on ID or provided URI, which shouldn't change, we can make sure that an application gets the canonical, most up-to-date data based on a message.

It's possible to enforce ordering in application logic (eg, have a message counter that always increases, and compare counts to detect ordering issues and/or duplicates), but this gem does not implement such logic.

## Ruby Support

* 2.2.1+
* JRuby 9.0.0.0+


text:
// Copyright 2009 the Sputnik authors.  All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.

/*---
info: Appearing of continue without an IterationStatement leads to syntax error
es5id: 12.7_A1_T2
description: >
    Checking if single "continue" with Label but without any
    IterationStatement fails
negative: SyntaxError
---*/

LABEL : x=3.14;

//////////////////////////////////////////////////////////////////////////////
//CHECK#1
var x=1;
continue LABEL;
var y=2;
//
//////////////////////////////////////////////////////////////////////////////


text:
package el.fg;
import static el.phys.FloatMath.*;

import java.util.StringTokenizer;

import el.Model;
import el.phys.Intersection;

/**
 * Object with a position delta, facing angle and facing delta.
 */
public abstract class MovingObject extends FgObject  {

	/**
	 * Max velocity
	 */
	protected float maxv = 0f;
	/**
	 * X wind resistance (0=max 1=none)
	 */
	protected float xres = 1f;
	/**
	 * Y wind resistance
	 */
	protected float yres = 1f;
	/**
	 * Rotation resistance
	 */
	protected float rotres = 1f;

	/** movement vector in pixels/sec */
	protected float vx, vy;

	/** rotation vector in radians/sec */
	protected float fd;

	/** facing angle */
	protected float f;

	/**
	 * Should reflect on collision (requires collide=true)
	 */
	protected boolean reflect = true;

	/**
	 * Should detect collisions with background
	 */
	protected boolean collideBackground = true;

	/**
	 * Number of times collided
	 */
	protected int hit;

	/**
	 * players team (must be >= 1)
	 */
	protected int freq;

	public MovingObject() {
		//
	}

	public void setFreq(int freq) {
		this.freq = freq;
	}

	public int getFreq() {
		return freq;
	}

	@Override
	protected void readImpl(StringTokenizer tokens) {
		super.readImpl(tokens);
		// should really validate freq changes
		freq = Integer.parseInt(tokens.nextToken());
		vx = Float.parseFloat(tokens.nextToken());
		vy = Float.parseFloat(tokens.nextToken());
		fd = Float.parseFloat(tokens.nextToken());
		f = Float.parseFloat(tokens.nextToken());
	}

	@Override
	protected StringBuilder writeImpl(StringBuilder sb) {
		super.writeImpl(sb);
		sb.append(freq).append(" ");
		sb.append(vx).append(" ");
		sb.append(vy).append(" ");
		sb.append(fd).append(" ");
		sb.append(f).append(" ");
		return sb;
	}

	/**
	 * Accelerate (vx/vy) in facing direction (f) in pixels/sec
	 */
	protected void accel(float d) {
		vx += d * sin(f);
		vy -= d * cos(f);

		if (maxv > 0f && velocity() > maxv) {
			float a = atan2(vx,vy);
			vx = sin(a)*maxv;
			vy = cos(a)*maxv;
		}
	}

	/**
	 * Update location, check for collision, reflect or stop
	 */
	@Override
	public void update(float floatTime, float floatTimeDelta) {
		float dx = vx * floatTimeDelta;
		float dy = vy * floatTimeDelta;
		Intersection r;

		if (collideBackground && (r = model.backgroundCollision(this, dx, dy)) != null) {
			if (reflect) {
				// reflected position
				x += r.rtx;
				y += r.rty;
				// change velocity direction
				vx *= r.vx;
				vy *= r.vy;

			} else {
				// hit position
				x += r.itx;
				y += r.ity;
				// zero velocity
				vx = 0f;
				vy = 0f;
			}

			hit++;
			collision();

		} else {
			// just update the position
			x += dx;
			y += dy;
		}

		if (x < 0 || x > Model.maxx || y < 0 || y > Model.maxx) {
			throw new RuntimeException("object out of bounds");
		}

		// erode velocity
		f = (f + fd * floatTimeDelta) % twopi;
		if (xres != 1f)
			vx *= pow(xres, floatTimeDelta);
		if (yres != 1f)
			vy *= pow(yres, floatTimeDelta);
		if (rotres != 1f)
			fd *= pow(rotres, floatTimeDelta);
	}

	/**
	 * get x position of an object emerging from this object at the given translation from origin
	 */
	protected float getTransX(float tx, float ty) {
		return x + cos(f) * tx - sin(f) * ty;
	}

	/**
	 * get y position of an object emerging from this object at the given translation from origin
	 */
	protected float getTransY(float tx, float ty) {
		return y + sin(f) * tx + cos(f) * ty;
	}

	/**
	 * get x velocity of an object emerging from this object at the given angle and velocity in pixels per second
	 */
	protected float getTransDX(float tf, float tv) {
		return sin(f + tf) * tv + vx;
	}

	/**
	 * get y velocity of an object emerging from this object at the given angle and speed
	 */
	protected float getTransDY(float tf, float tv) {
		return -cos(f + tf) * tv + vy;
	}

	/**
	 * Called on collision.
	 * Subclasses might care, e.g. if a bomb can only bounce n times.
	 */
	protected void collision() {
		//
	}

	/**
	 * Returns the current velocity
	 */
	protected float velocity() {
		return hypot(vx, vy);
	}

	/**
	 * Returns the current velocity angle (not the facing angle!)
	 */
	protected float angle() {
		return atan2(vx, -vy);
	}

	@Override
	public String toString() {
		return String.format("Moving[d=%.1f,%.1f fa=%.1f va=%.1f v=%.1f]",
				vx, vy, deg(f), deg(angle()), velocity()) + super.toString();
	}

}


text:
package ch.bfh.sinep.service.impl;

import ch.bfh.sinep.model.Group;
import ch.bfh.sinep.model.User;
import ch.bfh.sinep.repository.GroupRepository;
import ch.bfh.sinep.repository.UserRepository;
import ch.bfh.sinep.service.UserService;
import ch.bfh.sinep.service.dto.GroupDTO;
import ch.bfh.sinep.service.dto.UserDTO;
import ch.bfh.sinep.service.dto.UserWithGroupsDTO;
import org.modelmapper.ModelMapper;
import org.modelmapper.TypeToken;

import javax.inject.Inject;
import javax.inject.Named;
import java.lang.reflect.Type;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

/**
 * Service class (Implementation) for the user crud (create, read, update, delete) operations.
 *
 * @author holzer
 * @since 17.11.2015
 */
@Named
public class DefaultUserService implements UserService {

    @Inject
    private UserRepository userRepository;
    @Inject
    private GroupRepository groupRepository;

    private final ModelMapper mapper = new ModelMapper();

    /**
     * create userWithGroupsDTO
     *
     * @param userWithGroupsDTO
     * @return
     */

    /**
     * Creates the given user in the database. Adds also references from groups to the created user.
     *
     * @param userWithGroupsDTO User to create/save in the database.
     * @return A mapped persistedGroup instance to a UserWithGroupsDTO.
     */
    public UserWithGroupsDTO create(UserWithGroupsDTO userWithGroupsDTO) {
        if (userWithGroupsDTO.getId() != null) {
            throw new RuntimeException("Can not create element with id");
        }
        if(userWithGroupsDTO.getGroups() == null || userWithGroupsDTO.getGroups().size() == 0){
            throw new RuntimeException("User must have at least one group assigned");
        }

        User user = mapper.map(userWithGroupsDTO, User.class);
        User updatedUser = userRepository.save(user);

        //Add user to groups (bidirectional association)
        Set<Group> addedGroups = new HashSet<Group>();
        for (Group group : updatedUser.getGroups()) {
            Group groupToSave = groupRepository.findOne(group.getId());
            addedGroups.add(groupToSave);
            groupToSave.addUser(user);
            groupRepository.save(groupToSave);
        }

        updatedUser.setGroups(addedGroups);
        return mapper.map(updatedUser, UserWithGroupsDTO.class);
    }

    /**
     * Reads the user with the given id from the database. Returns a {@link UserWithGroupsDTO}-object of the
     * read user. This object contains also a set of the groups which the user belongs to.
     *
     * @param id Id of the user to read from the database.
     * @return The read user.
     */
    public UserWithGroupsDTO read(Long id) {
        User user = userRepository.findOne(id);
        if (user == null) return null;
        return mapper.map(user, UserWithGroupsDTO.class);
    }

    /**
     * Reads all users from the database. Returns a collection of {@link UserWithGroupsDTO}-objects.
     * Every object in the collection contains also a set of the groups which the user belongs to.
     *
     * @return A collection of all read users.
     */
    public Collection<UserWithGroupsDTO> list() {
        Iterable<User> users = userRepository.findAll();
        Type listType = new TypeToken<Collection<UserWithGroupsDTO>>() {
        }.getType();
        Collection<UserWithGroupsDTO> userList = mapper.map(users, listType);
        return userList;
    }

    /**
     * Updates the given user in the database.
     * Also updates the references from the group to the user (if the updated user belongs to new groups).
     *
     * @param userWithGroupsDTO User to update in the database.
     * @return Updated user.
     */
    public UserWithGroupsDTO update(UserWithGroupsDTO userWithGroupsDTO) {
        if (userWithGroupsDTO.getId() == null) {
            throw new RuntimeException("Can not update new element");
        }
        if(userWithGroupsDTO.getGroups() == null){
            throw new RuntimeException("User must have at least one group assigned");
        }

        User userBeforeUpdate = userRepository.findOne(userWithGroupsDTO.getId());
        User user = mapper.map(userWithGroupsDTO, User.class);

        //remove old references from groups to user
        for (Group group : userBeforeUpdate.getGroups()) {
            group.removeUser(user);
            groupRepository.save(group);
        }

        User updatedUser = userRepository.save(user);

        //adds the references from groups to user (bidirectional association)
        for (Group group : updatedUser.getGroups()) {
            Group groupToSave = groupRepository.findOne(group.getId());
            groupToSave.addUser(user);
            groupRepository.save(groupToSave);
        }
        return mapper.map(updatedUser, UserWithGroupsDTO.class);
    }

    /**
     * Deletes the given user from the database.
     * Also removes the user from his groups.
     *
     * @param userDTO User to delete from the database.
     */
    public void delete(UserDTO userDTO) {
        User user = userRepository.findOne(userDTO.getId());

        //remove user from his groups
        for (Group group : user.getGroups()) {
            group.removeUser(user);
            groupRepository.save(group);
        }
        userRepository.delete(user);
    }
}


text:
"""
Created on Tue Feb 26 07:57:27 2019

@author: BallBlueMeercat

open propert, sampler from errorvssize runs and compare properties of resulting parmater distributions
"""

import matplotlib.pyplot as plt
import time
from pathlib import Path
import tools
import os.path
import pickle

import matplotlib as mpl
#mpl.style.use('default') # has to be switched on to set figure size
mpl.style.use('fivethirtyeight')
plt.rcParams['axes.facecolor'] = 'white'
plt.rcParams['figure.facecolor'] = 'white'
plt.rcParams['grid.color'] = 'white'

# Script timer.
timet0 = time.time()

#Model, errors on data and dataset sizes to iterate through:
test_keys = [None
#            ,'rainbow'
#            ,'kanangra'
#            ,'waterfall'
#            ,'stepfall'
#            ,'exotic'
#            ,'late_intxde'
#            ,'heaviside_late_int'
#            ,'heaviside_sudden'
#            ,'late_int'
#            ,'expgamma'
#            ,'txgamma'         # doesn't converge
#            ,'zxgamma'
#            ,'gamma_over_z'    # doesn't converge
#            ,'zxxgamma'        # gamma forced positive in firstderivs
#            ,'gammaxxz'        # gamma forced positive in firstderivs
#            ,'rdecay_m'
#            ,'rdecay_de'
#            ,'rdecay_mxde'
#            ,'rdecay'
#            ,'interacting'
            ,'LCDM'
#            ,'rLCDM'
            ]

sd_list = []
mean_list = []
vc_list = []

sigma_list = []
npoints_list = []
sampler_list = []

sigma_options = None, 0.01#, 0.07, 0.14, 0.2  #0.14, 0.2 #0.0001, 0.005, 0.007
npoints_options = 1048, 10480, 104800, 1048000

#N = len(sigma_options) * (len(npoints_options)) # Can't have None in options
N = len(npoints_options) # Ca't have None in options

for test_key in test_keys:
    if test_key:
        # parameter names and values used as input
        names, values = tools.names_values(test_key)
        # Relative path to folder for saving output.
        save_path = os.path.join('results_error_vs_data_plots',test_key)
        if not os.path.exists(save_path):
            os.makedirs(save_path)
        for sigma in sigma_options:
            if sigma:
                pass
            else:
                continue
            for npoints in npoints_options:
                if npoints:
                    pass
                else:
                    continue
                #retrieving results from errovsdatasize runs
                file_path = f'results_error_vs_data/{test_key}/sigma{sigma}_npoints{npoints}.p'
                my_file = Path(file_path)
                if my_file.is_file():
                    # results of emcee runs
                    with open(file_path,'rb') as rfp: propert, sampler = pickle.load(rfp)
                    file_open_indicator = 1
#                    print(f'{file_path} opened successfully')
                else:
                    print(f'{file_path} failed to open')
                    file_open_indicator = 0
                # assert ensures only sampler from intended file_path is used
                assert file_open_indicator > 0, "file_open_indicator failed"
                for key in propert:
                    if 'sd' in key:
                        sd = propert.get(key,0)
                        sd_list.append([key, sd])
                    elif 'mean' in key:
                        mean = propert.get(key,0)
                        mean_list.append([key, mean])
                        if mean != 0:
                            vc = sd/mean * 100
                            vc_list.append([key[0]+'_vc', vc])

                sigma_list.append(sigma)
                npoints_list.append(npoints)
                sampler_list.append(sampler)

        for j in range(len(values)):
            sd = []
            mean = []
            vc = []
            for i in range(N):
                index = i*len(values)+j

                sd_name = sd_list[index][0]
                sd_initial = sd_name[0]
                sd.append(sd_list[index][1])

                mean_name = mean_list[index][0]
                mean_initial = mean_name[0]
                mean.append(mean_list[index][1])

                vc_name = vc_list[index][0]
                vc_initial = vc_name[0]
                vc.append(vc_list[index][1])

                i+=1

            fig, ax = plt.subplots()
            ax.scatter(npoints_list, sd, c="C{}".format(0))

            # Plotting sd vs dataset size.
            for i, txt in enumerate(sigma_list):
                txt = str(txt) # noise on data
                ax.annotate(txt, (npoints_list[i], sd[i]))

            plt.xlabel('Dataset size')
            plt.ylabel('$\sigma$')
            plt.title(sd_name+' vs dataset size'+
                      '\n s.d. of noise labeled, model '+test_key)
            stamp = str(int(time.time()))
            filename = str(stamp)+'_sd_of_'+sd_initial+'_.png'
            filename = os.path.join(save_path, filename)
            plt.savefig(filename)

            # Plotting mean vs dataset size.
            fig, ax = plt.subplots()
            ax.scatter(npoints_list, mean, c="C{}".format(1))
            for i, txt in enumerate(sigma_list):
                txt = str(txt) # noise on data
                ax.annotate(txt, (npoints_list[i], mean[i]))

            plt.xlabel('Dataset size')
            plt.ylabel('$\mu$')
            plt.title(mean_name+' vs dataset size'+
                      '\n s.d. of noise labeled, model '+test_key)
            stamp = str(int(time.time()))
            filename = str(stamp)+'_mean_of_'+mean_initial+'_.png'
            filename = os.path.join(save_path, filename)
            plt.savefig(filename)

            # Plotting variance coefficient vs dataset size.
            if len(vc) == N:
                fig, ax = plt.subplots()
                ax.scatter(npoints_list, vc, c="C{}".format(2))
                for i, txt in enumerate(sigma_list):
                    txt = str(txt)
#                    ax.annotate(txt, (npoints_list[i], vc[i]))

                plt.xlabel('Dataset size')
                plt.ylabel(r'$\sigma/ \mu \times 100$')
                plt.title(vc_name+' vs dataset size'+
                          '\n s.d. of noise labeled, model '+test_key)
                stamp = str(int(time.time()))
                filename = str(stamp)+'_vc_of_'+vc_initial+'_.png'
                filename = os.path.join(save_path, filename)
                plt.savefig(filename)

                j+=1

        plt.show()

        # Saving results to directory.
        import results
        results.save(save_path, 'vc_list', vc_list)
        results.save(save_path, 'sd_list', sd_list)
        results.save(save_path, 'mean_list', mean_list)

        results.save(save_path, 'sigma_list', sigma_list)
        results.save(save_path, 'npoints_list', npoints_list)
        results.save(save_path, 'sampler_list', sampler_list)

#        import plots
#        plots.precise_runs(key, names, values, 9, 1.2)

# Time taken by script.
timet1=time.time()
tools.timer('errorvsdatasize_distribs', timet0, timet1)


text:
<?php

require("../lib/error.php");

mysql_start();

if($d) {
   $event_name = getEventName($d);
   echo '
'.$event_name.'

'.
   'Name	Age	Gender	Phones	Special Needs (if any)
';

   $query = "select * from attendance where event_code =\"$d\";";
   mysql_start();
   $results = mysql_query($query);
   while($attending = mysql_fetch_object($results)) {
      if($attending->paid == "Y"){
            $user_info = getUser("$attending->user_code");
            echo "
".$user_info["first_name"]."  ";
            echo $user_info["last_name"]."	";
            echo "".$user_info["age"]."	";
            echo "".$user_info["gender"]."	";
            echo "H:". $user_info["phone"]."
";
            echo "W: ".$user_info["workphone"]."
";
            echo "E: ".$user_info["911phone"]."	";
            echo "".$user_info["special_needs"]."
";
       }
   }
   echo '
';

}
else{
 mysql_start();
//$result = mysql_query("select * from conferences;");
 $result = getEvents();
 printheader($a);
 echo "
 Click Event Name to print roster" .
 		"
" .
 		"
Event
";

 //while($conferences = mysql_fetch_object($result)){
 foreach($result as $conferences) {
  mysql_start();
    $query_attendance = "select count(*) from attendance where event_code = \"$conferences->event_code\";";
    $attendance_results = mysql_query($query_attendance) or die(errorconsole(mysql_error()));
    $attend_total = mysql_fetch_array($attendance_results);
     errorconsole($attend_total);
     if($attend_total[0] > 0 ){
//     if(1){
       if($date != $conferences->date) {
		echo "

Week of $conferences->date
";
	}
       $date = $conferences->date;
     echo "
wwwsite/stats/index.php?z=roster&d=$conferences->event_code\">$conferences->title $conferences->date $conferences->time
";

     }
 }
}
// mysql_stop();
echo "
wwwsite/stats/index.php?z=roster>Back to Rosters";
?>


text:
layout: comune
title: Cento (Emilia Romagna)
---

La pagina ufficiale dell'albo pretorio del **Comune di Cento** è questa: [http://goo.gl/4o3lvG](http://goo.gl/4o3lvG)

Adesso puoi seguire le nuove pubblicazioni in albo in due modi dedicati:

* su un canale **Telegram** [https://telegram.me/AlboPret100FE](https://telegram.me/AlboPret100FE).
* iscrivendoti a un **feed RSS**: [https://goo.gl/khF4B4](https://goo.gl/khF4B4).

**Autore**: [Matteo Fortini](https://twitter.com/matt_fortini), [Servizio Sistemi Informativi](http://www.comune.cento.fe.it/ilcomune/ufficicomunali/-llpp-territorio/pagina22.html)