text:
package com.datastax.oss.driver.mapper;

import static com.datastax.oss.driver.assertions.Assertions.assertThat;

import com.datastax.oss.driver.api.core.CqlIdentifier;
import com.datastax.oss.driver.api.core.CqlSession;
import com.datastax.oss.driver.api.core.cql.BoundStatement;
import com.datastax.oss.driver.api.core.cql.BoundStatementBuilder;
import com.datastax.oss.driver.api.core.cql.PreparedStatement;
import com.datastax.oss.driver.api.core.cql.ResultSet;
import com.datastax.oss.driver.api.core.cql.SimpleStatement;
import com.datastax.oss.driver.api.mapper.annotations.Computed;
import com.datastax.oss.driver.api.mapper.annotations.CqlName;
import com.datastax.oss.driver.api.mapper.annotations.Dao;
import com.datastax.oss.driver.api.mapper.annotations.DaoFactory;
import com.datastax.oss.driver.api.mapper.annotations.DaoKeyspace;
import com.datastax.oss.driver.api.mapper.annotations.DaoTable;
import com.datastax.oss.driver.api.mapper.annotations.DefaultNullSavingStrategy;
import com.datastax.oss.driver.api.mapper.annotations.Delete;
import com.datastax.oss.driver.api.mapper.annotations.Entity;
import com.datastax.oss.driver.api.mapper.annotations.GetEntity;
import com.datastax.oss.driver.api.mapper.annotations.HierarchyScanStrategy;
import com.datastax.oss.driver.api.mapper.annotations.Insert;
import com.datastax.oss.driver.api.mapper.annotations.Mapper;
import com.datastax.oss.driver.api.mapper.annotations.PartitionKey;
import com.datastax.oss.driver.api.mapper.annotations.Query;
import com.datastax.oss.driver.api.mapper.annotations.Select;
import com.datastax.oss.driver.api.mapper.annotations.SetEntity;
import com.datastax.oss.driver.api.mapper.annotations.Transient;
import com.datastax.oss.driver.api.mapper.annotations.Update;
import com.datastax.oss.driver.api.mapper.entity.saving.NullSavingStrategy;
import com.datastax.oss.driver.api.testinfra.ccm.CcmRule;
import com.datastax.oss.driver.api.testinfra.session.SessionRule;
import com.datastax.oss.driver.categories.ParallelizableTests;
import com.datastax.oss.driver.shaded.guava.common.collect.ImmutableList;
import com.datastax.oss.driver.shaded.guava.common.collect.Sets;
import com.tngtech.java.junit.dataprovider.DataProvider;
import com.tngtech.java.junit.dataprovider.DataProviderRunner;
import com.tngtech.java.junit.dataprovider.UseDataProvider;
import java.util.Objects;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.function.Consumer;
import java.util.function.Function;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.rules.RuleChain;
import org.junit.rules.TestRule;
import org.junit.runner.RunWith;

@Category(ParallelizableTests.class)
@RunWith(DataProviderRunner.class)
public class EntityPolymorphismIT {
  private static final CcmRule CCM_RULE = CcmRule.getInstance();

  private static final SessionRule<CqlSession> SESSION_RULE = SessionRule.builder(CCM_RULE).build();

  @ClassRule
  public static final TestRule CHAIN = RuleChain.outerRule(CCM_RULE).around(SESSION_RULE);

  private static TestMapper mapper;

  @BeforeClass
  public static void setup() {
    CqlSession session = SESSION_RULE.session();
    for (String query :
        ImmutableList.of(
            "CREATE TYPE point2d (\"X\" int, \"Y\" int)",
            "CREATE TYPE point3d (\"X\" int, \"Y\" int, \"Z\" int)",
            "CREATE TABLE circles (circle_id uuid PRIMARY KEY, center2d frozen<point2d>, radius "
                + "double, tags set<text>)",
            "CREATE TABLE rectangles (rect_id uuid PRIMARY KEY, bottom_left frozen<point2d>, top_right frozen<point2d>, tags set<text>)",
            "CREATE TABLE squares (square_id uuid PRIMARY KEY, bottom_left frozen<point2d>, top_right frozen<point2d>, tags set<text>)",
            "CREATE TABLE spheres (sphere_id uuid PRIMARY KEY, center3d frozen<point3d>, radius "
                + "double, tags set<text>)",
            "CREATE TABLE devices (device_id uuid PRIMARY KEY, name text)",
            "CREATE TABLE tracked_devices (device_id uuid PRIMARY KEY, name text, location text)",
            "CREATE TABLE simple_devices (id uuid PRIMARY KEY, in_use boolean)")) {
      session.execute(
          SimpleStatement.builder(query).setExecutionProfile(SESSION_RULE.slowProfile()).build());
    }
    mapper = new EntityPolymorphismIT_TestMapperBuilder(session).build();
  }

  // define parent interface with dao methods.
  @DefaultNullSavingStrategy(NullSavingStrategy.SET_TO_NULL)
  interface BaseDao<T> {
    @Insert
    void save(T t);

    @Select
    T findById(UUID id);

    @Delete
    void delete(T t);

    @SetEntity
    void bind(T t, BoundStatementBuilder builder);

    @GetEntity
    T one(ResultSet result);

    @Update
    void update(T t);
  }

  // another parent interface with dao methods
  interface WriteTimeDao<Y extends WriteTimeProvider> extends BaseDao<Y> {
    @Insert(timestamp = ":writeTime")
    void saveWithTime(Y y, long writeTime);
  }

  @Dao
  interface RectangleDao extends BaseDao<Rectangle> {}

  // Define an intermediate interface with same type variable name to ensure
  // this doesn't cause any issue in code generation.
  interface ArbitraryInterface<Y extends Number> {
    default long increment(Y input) {
      return input.longValue() + 1;
    }
  }

  @Dao
  interface SquareDao extends WriteTimeDao<Square>, ArbitraryInterface<Float> {}

  @Dao
  interface CircleDao extends WriteTimeDao<Circle> {}

  @Dao
  interface SphereDao extends WriteTimeDao<Sphere> {}

  interface NamedDeviceDao<Y extends Device> extends BaseDao<Y> {
    @Query("UPDATE ${qualifiedTableId} SET name = :name WHERE device_id = :id")
    void updateName(String name, UUID id);

    @Query("SELECT * FROM ${qualifiedTableId} WHERE device_id = :id")
    CompletableFuture<Y> findByIdQueryAsync(UUID id);
  }

  @Dao
  interface DeviceDao extends NamedDeviceDao<Device> {}

  @Dao
  interface TrackedDeviceDao extends NamedDeviceDao<TrackedDevice> {}

  @Dao
  interface SimpleDeviceDao extends BaseDao<SimpleDevice> {}

  @Mapper
  public interface TestMapper {
    @DaoFactory
    CircleDao circleDao(@DaoKeyspace CqlIdentifier keyspace);

    @DaoFactory
    RectangleDao rectangleDao(@DaoKeyspace CqlIdentifier keyspace);

    @DaoFactory
    SquareDao squareDao(@DaoKeyspace CqlIdentifier keyspace);

    @DaoFactory
    SphereDao sphereDao(@DaoKeyspace CqlIdentifier keyspace);

    @DaoFactory
    DeviceDao deviceDao(@DaoKeyspace CqlIdentifier keyspace, @DaoTable CqlIdentifier table);

    @DaoFactory
    TrackedDeviceDao trackedDeviceDao(
        @DaoKeyspace CqlIdentifier keyspace, @DaoTable CqlIdentifier table);

    @DaoFactory
    SimpleDeviceDao simpleDeviceDao(@DaoKeyspace CqlIdentifier keyspace);
  }

  @DataProvider
  public static Object[][] setAndGetProvider() {
    Function<CqlIdentifier, CircleDao> circleDao = keyspace -> mapper.circleDao(keyspace);
    Function<CqlIdentifier, RectangleDao> rectangleDao = keyspace -> mapper.rectangleDao(keyspace);
    Function<CqlIdentifier, SquareDao> squareDao = keyspace -> mapper.squareDao(keyspace);
    Function<CqlIdentifier, SphereDao> sphereDao = keyspace -> mapper.sphereDao(keyspace);
    return new Object[][] {
      {
        new Rectangle(new Point2D(20, 30), new Point2D(50, 60)),
        rectangleDao,
        (Consumer<Rectangle>) (Rectangle r) -> r.setTopRight(new Point2D(21, 31)),
        SimpleStatement.newInstance(
            "insert into rectangles (rect_id, bottom_left, top_right, "
                + "tags) values (?, ?, ?, ?)"),
        SimpleStatement.newInstance("select * from rectangles where rect_id = :id limit 1")
      },
      {
        new Circle(new Point2D(11, 22), 12.34),
        circleDao,
        (Consumer<Circle>) (Circle c) -> c.setRadius(13.33),
        SimpleStatement.newInstance(
            "insert into circles (circle_id, center2d, radius, tags) " + "values (?, ?, ?, ?)"),
        SimpleStatement.newInstance(
            "select circle_id, center2d, radius, tags, writetime(radius) "
                + "as write_time from circles where circle_id = :id limit 1")
      },
      {
        new Square(new Point2D(20, 30), new Point2D(50, 60)),
        squareDao,
        (Consumer<Square>) (Square s) -> s.setBottomLeft(new Point2D(10, 20)),
        SimpleStatement.newInstance(
            "insert into squares (square_id, bottom_left, top_right, "
                + "tags) values (?, ?, ?, ?)"),
        SimpleStatement.newInstance(
            "select square_id, bottom_left, top_right, tags, writetime"
                + "(bottom_left) as write_time from squares where square_id = :id limit 1")
      },
      {
        new Sphere(new Point3D(11, 22, 33), 34.56),
        sphereDao,
        (Consumer<Sphere>) (Sphere s) -> s.setCenter(new Point3D(10, 20, 30)),
        SimpleStatement.newInstance(
            "insert into spheres (sphere_id, center3d, radius, tags) " + "values (?, ?, ?, ?)"),
        SimpleStatement.newInstance(
            "select sphere_id, center3d, radius, tags, writetime(radius) "
                + "as write_time from spheres where sphere_id = :id limit 1")
      },
    };
  }

  @UseDataProvider("setAndGetProvider")
  @Test
  public <T extends Shape> void should_set_and_get_entity_then_update_then_delete(
      T t,
      Function<CqlIdentifier, BaseDao<T>> daoProvider,
      Consumer<T> updater,
      SimpleStatement insertStatement,
      SimpleStatement selectStatement) {
    BaseDao<T> dao = daoProvider.apply(SESSION_RULE.keyspace());
    CqlSession session = SESSION_RULE.session();
    PreparedStatement prepared = session.prepare(insertStatement);

    BoundStatementBuilder bs = prepared.boundStatementBuilder();
    dao.bind(t, bs);

    session.execute(bs.build());

    PreparedStatement selectPrepared = session.prepare(selectStatement);
    BoundStatement selectBs = selectPrepared.bind(t.getId());
    T retrieved = dao.one(session.execute(selectBs));
    assertThat(retrieved).isEqualTo(t);

    // update value
    updater.accept(t);
    dao.update(t);

    // retrieve value to ensure update worked correctly.
    assertThat(dao.one(session.execute(selectBs))).isEqualTo(t);

    // delete value and ensure it's gone
    dao.delete(t);
    assertThat(dao.one(session.execute(selectBs))).isNull();
  }

  @Test
  public void should_save_and_retrieve_circle() {
    // verifies the inheritance behavior around Circle.
    // * CqlName("circle_id") on getId renames id property to circle_id
    // * annotations, but these are primarily used for
    //   verifying inheritance behavior in Sphere.
    // * verifies writeTime is set.
    CircleDao dao = mapper.circleDao(SESSION_RULE.keyspace());

    long writeTime = System.currentTimeMillis() - 1000;
    Circle circle = new Circle(new Point2D(11, 22), 12.34);
    dao.saveWithTime(circle, writeTime);

    Circle retrievedCircle = dao.findById(circle.getId());
    assertThat(retrievedCircle).isEqualTo(circle);
    assertThat(retrievedCircle.getWriteTime()).isEqualTo(writeTime);
  }

  @Test
  public void should_save_and_retrieve_rectangle() {
    // verifies the inheritance behavior around Rectangle:
    // * CqlName("rect_id") on getId renames id property to rect_id
    // * annotations work, but these are primarily used for
    //   verifying inheritance behavior in Square.
    RectangleDao dao = mapper.rectangleDao(SESSION_RULE.keyspace());

    Rectangle rectangle = new Rectangle(new Point2D(20, 30), new Point2D(50, 60));
    dao.save(rectangle);

    assertThat(dao.findById(rectangle.getId())).isEqualTo(rectangle);
  }

  @Test
  public void should_save_and_retrieve_square() {
    // verifies the inheritance behavior around Square:
    // * CqlName("square_id") on getId renames id property to square_id
    // * height remains transient even though we define field/getter/setter
    // * getBottomLeft() retains CqlName from parent.
    // * verifies writeTime is set.
    SquareDao dao = mapper.squareDao(SESSION_RULE.keyspace());

    long writeTime = System.currentTimeMillis() - 1000;
    Square square = new Square(new Point2D(20, 30), new Point2D(50, 60));
    dao.saveWithTime(square, writeTime);

    Square retrievedSquare = dao.findById(square.getId());
    assertThat(retrievedSquare).isEqualTo(square);
    assertThat(retrievedSquare.getWriteTime()).isEqualTo(writeTime);
  }

  @Test
  public void should_save_and_retrieve_sphere() {
    // verifies the inheritance behavior around Circle:
    // * @CqlName("sphere_id") on getId renames id property to sphere_id
    // * @CqlName("center3d") on getCenter renames center property from center2d
    //   which was renamed on the parent field for Circle
    // * That getCenter returns Point3D influences get/set behavior to use Point3D
    // * Override setRadius to return Sphere causes no issues.
    // * Interface method getVolume() is skipped because no field exists.
    // * WriteTime is inherited, so queried and set.
    SphereDao dao = mapper.sphereDao(SESSION_RULE.keyspace());

    long writeTime = System.currentTimeMillis() - 1000;
    Sphere sphere = new Sphere(new Point3D(11, 22, 33), 34.56);
    dao.saveWithTime(sphere, writeTime);

    Sphere retrievedSphere = dao.findById(sphere.getId());
    assertThat(retrievedSphere).isEqualTo(sphere);
    assertThat(retrievedSphere.getWriteTime()).isEqualTo(writeTime);
  }

  @Test
  public void should_save_and_retrieve_device() throws Exception {
    // verifies the hierarchy scanner behavior around Device:
    // * by virtue of Assert setting highestAncestor to Asset.class, location property from
    //   LocatableItem should not be included
    DeviceDao dao = mapper.deviceDao(SESSION_RULE.keyspace(), CqlIdentifier.fromCql("devices"));

    // save should be successful as location property omitted.
    Device device = new Device("my device", "New York");
    dao.save(device);

    Device retrievedDevice = dao.findById(device.getId());
    assertThat(retrievedDevice.getId()).isEqualTo(device.getId());
    assertThat(retrievedDevice.getName()).isEqualTo(device.getName());
    // location should be null.
    assertThat(retrievedDevice.getLocation()).isNull();

    // should be able to use @Query with update
    String name = "my new name";
    dao.updateName(name, device.getId());

    // should be able to use @Query returning Entity and name should be applied.
    retrievedDevice = dao.findByIdQueryAsync(device.getId()).get();
    assertThat(retrievedDevice.getName()).isEqualTo(name);
  }

  @Test
  public void should_save_and_retrieve_tracked_device() throws Exception {
    // verifies the hierarchy scanner behavior around TrackedDevice:
    // * Since TrackedDevice defines a default @HierarchyScanStrategy it should
    //   include LocatableItem's location property, even though Asset defines
    //   a strategy that excludes it.
    TrackedDeviceDao dao =
        mapper.trackedDeviceDao(SESSION_RULE.keyspace(), CqlIdentifier.fromCql("tracked_devices"));

    TrackedDevice device = new TrackedDevice("my device", "New York");
    dao.save(device);

    // location property should be present, thus should equal saved item.
    TrackedDevice retrievedDevice = dao.findById(device.getId());
    assertThat(retrievedDevice).isEqualTo(device);

    // should be able to use @Query with update
    String name = "my new name";
    dao.updateName(name, device.getId());

    // should be able to use @Query returning Entity and name should be applied.
    retrievedDevice = dao.findByIdQueryAsync(device.getId()).get();
    assertThat(retrievedDevice.getName()).isEqualTo(name);
  }

  @Test
  public void should_save_and_retrieve_simple_device() {
    // verifies the hierarchy scanner behavior around SimpleDevice:
    // * Since SimpleDevice defines a @HierarchyScanStrategy that prevents
    //   scanning of ancestors, only its properties (id, inUse) should be included.
    SimpleDeviceDao dao = mapper.simpleDeviceDao(SESSION_RULE.keyspace());

    SimpleDevice device = new SimpleDevice(true);
    dao.save(device);

    SimpleDevice retrievedDevice = dao.findById(device.getId());
    assertThat(retrievedDevice.getId()).isEqualTo(device.getId());
    assertThat(retrievedDevice.getInUse()).isEqualTo(device.getInUse());
    // location and name should be null
    assertThat(retrievedDevice.getLocation()).isNull();
    assertThat(retrievedDevice.getName()).isNull();
  }

  @Entity
  static class Point2D {
    private int x;
    private int y;

    public Point2D() {}

    public Point2D(int x, int y) {
      this.x = x;
      this.y = y;
    }

    @CqlName("\"X\"")
    public int getX() {
      return x;
    }

    public void setX(int x) {
      this.x = x;
    }

    @CqlName("\"Y\"")
    public int getY() {
      return y;
    }

    public void setY(int y) {
      this.y = y;
    }

    @Override
    public boolean equals(Object other) {
      if (this == other) return true;
      else if (other instanceof Point2D) {
        Point2D that = (Point2D) other;
        return this.x == that.x && this.y == that.y;
      } else {
        return false;
      }
    }

    @Override
    public int hashCode() {
      return Objects.hash(x, y);
    }
  }

  @Entity
  static class Point3D extends Point2D {
    private int z;

    public Point3D() {}

    public Point3D(int x, int y, int z) {
      super(x, y);
      this.z = z;
    }

    @CqlName("\"Z\"")
    public int getZ() {
      return z;
    }

    public void setZ(int z) {
      this.z = z;
    }

    @Override
    public boolean equals(Object other) {
      if (this == other) {
        return true;
      } else if (other instanceof Point3D) {
        Point3D that = (Point3D) other;
        return super.equals(that) && this.z == that.z;
      } else {
        return false;
      }
    }

    @Override
    public int hashCode() {
      return Objects.hash(super.hashCode(), z);
    }
  }

  interface Shape2D {
    Set<String> getTags();

    // test annotation on interface method, should get inherited everywhere
    @Transient
    double getArea();
  }

  interface Shape3D {
    double getVolume();
  }

  abstract static class Shape implements Shape2D {

    @PartitionKey // annotated field on superclass; annotation will get inherited in all subclasses
    protected UUID id;

    protected Set<String> tags;

    protected String location;

    public Shape() {
      this.id = UUID.randomUUID();
      this.tags = Sets.newHashSet("cool", "awesome");
    }

    @CqlName("wrong")
    public abstract UUID getId();

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

    @Override
    public Set<String> getTags() {
      return tags;
    }

    public void setTags(Set<String> tags) {
      this.tags = tags;
    }

    @Override
    public boolean equals(Object other) {
      if (this == other) {
        return true;
      } else if (other instanceof Shape) {
        Shape that = (Shape) other;
        return Objects.equals(id, that.id) && Objects.equals(tags, that.tags);
      } else {
        return false;
      }
    }

    @Override
    public int hashCode() {
      return Objects.hash(id, tags);
    }
  }

  interface WriteTimeProvider {
    long getWriteTime();
  }

  @CqlName("circles")
  @Entity
  static class Circle extends Shape implements WriteTimeProvider {

    @CqlName("center2d")
    protected Point2D center;

    protected double radius;

    private long writeTime;

    public Circle() {}

    public Circle(Point2D center, double radius) {
      super();
      this.center = center;
      this.radius = radius;
    }

    @Override
    @CqlName("circle_id")
    public UUID getId() {
      return id;
    }

    @Override
    public double getArea() {
      return Math.PI * Math.pow(getRadius(), 2);
    }

    public double getRadius() {
      return this.radius;
    }

    public Circle setRadius(double radius) {
      this.radius = radius;
      return this;
    }

    @Computed("writetime(radius)")
    @Override
    public long getWriteTime() {
      return writeTime;
    }

    public void setWriteTime(long writeTime) {
      this.writeTime = writeTime;
    }

    public Point2D getCenter() {
      return center;
    }

    public void setCenter(Point2D center) {
      this.center = center;
    }

    @Override
    public boolean equals(Object other) {
      if (this == other) {
        return true;
      } else if (other instanceof Circle) {
        Circle that = (Circle) other;
        return super.equals(that)
            && Double.compare(that.radius, radius) == 0
            && center.equals(that.center);
      } else {
        return false;
      }
    }

    @Override
    public int hashCode() {
      return Objects.hash(super.hashCode(), center, radius);
    }
  }

  @CqlName("rectangles")
  @Entity
  static class Rectangle extends Shape {
    private Point2D bottomLeft;
    private Point2D topRight;

    public Rectangle() {}

    public Rectangle(Point2D bottomLeft, Point2D topRight) {
      super();
      this.bottomLeft = bottomLeft;
      this.topRight = topRight;
    }

    @CqlName("rect_id")
    @Override
    public UUID getId() {
      return id;
    }

    @CqlName("bottom_left")
    public Point2D getBottomLeft() {
      return bottomLeft;
    }

    public void setBottomLeft(Point2D bottomLeft) {
      this.bottomLeft = bottomLeft;
    }

    @CqlName("top_right")
    public Point2D getTopRight() {
      return topRight;
    }

    public void setTopRight(Point2D topRight) {
      this.topRight = topRight;
    }

    // test annotation in class method
    @Transient
    public double getWidth() {
      return Math.abs(topRight.getX() - bottomLeft.getX());
    }

    @Transient
    public double getHeight() {
      return Math.abs(topRight.getY() - bottomLeft.getY());
    }

    @Override
    public double getArea() {
      return getWidth() * getHeight();
    }

    @Override
    public boolean equals(Object other) {
      if (this == other) {
        return true;
      } else if (other instanceof Rectangle) {
        Rectangle that = (Rectangle) other;
        return super.equals(that)
            && bottomLeft.equals(that.bottomLeft)
            && topRight.equals(that.topRight);
      } else {
        return false;
      }
    }

    @Override
    public int hashCode() {
      return Objects.hash(super.hashCode(), bottomLeft, topRight);
    }
  }

  @CqlName("squares")
  @Entity
  static class Square extends Rectangle implements WriteTimeProvider {

    @Computed("writetime(bottom_left)")
    private long writeTime;

    public Square() {}

    public Square(Point2D bottomLeft, Point2D topRight) {
      super(bottomLeft, topRight);
      assert getHeight() == getWidth();
    }

    @CqlName("square_id")
    @Override
    public UUID getId() {
      return id;
    }

    @Override
    // inherits @CqlName
    public Point2D getBottomLeft() {
      return super.getBottomLeft();
    }

    @Override
    // inherits @Transient
    public double getHeight() {
      return getWidth();
    }

    public void setHeight(Point2D height) {
      throw new IllegalArgumentException("This method should never be called");
    }

    @Override
    public long getWriteTime() {
      return writeTime;
    }

    public void setWriteTime(long writeTime) {
      this.writeTime = writeTime;
    }
  }

  @CqlName("spheres")
  @Entity
  static class Sphere extends Circle implements Shape3D {

    // ignored field
    private long writeTime;

    public Sphere() {}

    public Sphere(Point3D center, double radius) {
      super(center, radius);
    }

    @CqlName("sphere_id")
    @Override
    public UUID getId() {
      return id;
    }

    // overrides field annotation in Circle,
    // note that the property type is narrowed down to Point3D
    @CqlName("center3d")
    @Override
    public Point3D getCenter() {
      return (Point3D) center;
    }

    @Override
    public void setCenter(Point2D center) {
      assert center instanceof Point3D;
      this.center = center;
    }

    // overridden builder-style setter
    @Override
    public Sphere setRadius(double radius) {
      super.setRadius(radius);
      return this;
    }

    @Override
    public double getVolume() {
      return 4d / 3d * Math.PI * Math.pow(getRadius(), 3);
    }

    @Override
    public boolean equals(Object other) {
      if (this == other) {
        return true;
      } else if (other instanceof Sphere) {
        Sphere that = (Sphere) other;
        return super.equals(that) && writeTime == that.writeTime;
      } else {
        return false;
      }
    }

    @Override
    public int hashCode() {
      return Objects.hash(super.hashCode(), writeTime);
    }
  }

  abstract static class LocatableItem {

    protected String location;

    LocatableItem() {}

    LocatableItem(String location) {
      this.location = location;
    }

    public String getLocation() {
      return location;
    }

    public void setLocation(String location) {
      this.location = location;
    }

    @Override
    public boolean equals(Object other) {
      if (this == other) {
        return true;
      } else if (other instanceof LocatableItem) {
        LocatableItem that = (LocatableItem) other;
        return Objects.equals(this.location, that.location);
      } else {
        return false;
      }
    }

    @Override
    public int hashCode() {
      return Objects.hash(location);
    }
  }

  // define strategy that stops scanning at Asset, meaning LocatableItem's location will
  // not be considered a property.
  @HierarchyScanStrategy(highestAncestor = Asset.class, includeHighestAncestor = true)
  abstract static class Asset extends LocatableItem {
    protected String name;

    Asset() {}

    Asset(String name, String location) {
      super(location);
      this.name = name;
    }

    public String getName() {
      return name;
    }

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

    @Override
    public boolean equals(Object other) {
      if (this == other) {
        return true;
      } else if (other instanceof Asset) {
        Asset that = (Asset) other;
        return super.equals(that) && Objects.equals(this.name, that.name);
      } else {
        return false;
      }
    }

    @Override
    public int hashCode() {
      return Objects.hash(super.hashCode(), name);
    }
  }

  // should inherit scan strategy from Asset, thus location will not be present.
  @Entity
  @CqlName("devices")
  static class Device extends Asset {

    @PartitionKey protected UUID id;

    Device() {}

    Device(String name, String location) {
      super(name, location);
      this.id = UUID.randomUUID();
    }

    // rename to device_id, if Device not included in scanning, this won't be used.
    @CqlName("device_id")
    public UUID getId() {
      return id;
    }

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

    @Override
    public boolean equals(Object other) {
      if (this == other) {
        return true;
      } else if (other instanceof Device) {
        Device that = (Device) other;
        return super.equals(that) && this.id.equals(that.id);
      } else {
        return false;
      }
    }

    @Override
    public int hashCode() {
      return Objects.hash(super.hashCode(), id);
    }
  }

  // use default strategy, which should override Assert's strategy, and thus location
  // should be considered a property.
  @HierarchyScanStrategy
  @Entity
  @CqlName("tracked_devices")
  static class TrackedDevice extends Device {
    TrackedDevice() {}

    TrackedDevice(String name, String location) {
      super(name, location);
    }
  }

  // do not scan ancestors, so only id and inUse should be considered properties.
  @HierarchyScanStrategy(scanAncestors = false)
  @Entity
  @CqlName("simple_devices")
  static class SimpleDevice extends Device {
    boolean inUse;

    // suppress error prone warning as we are doing this with intent
    @SuppressWarnings("HidingField")
    @PartitionKey
    private UUID id;

    SimpleDevice() {}

    SimpleDevice(boolean inUse) {
      super(null, null);
      this.id = UUID.randomUUID();
      this.inUse = inUse;
    }

    public boolean getInUse() {
      return inUse;
    }

    public void setInUse(boolean inUse) {
      this.inUse = inUse;
    }

    @Override
    public UUID getId() {
      return id;
    }

    @Override
    public void setId(UUID id) {
      this.id = id;
    }

    @Override
    public boolean equals(Object other) {
      if (this == other) {
        return true;
      } else if (other instanceof SimpleDevice) {
        SimpleDevice that = (SimpleDevice) other;
        return super.equals(that) && this.inUse == that.inUse && this.id.equals(that.id);
      } else {
        return false;
      }
    }

    @Override
    public int hashCode() {
      return Objects.hash(super.hashCode(), inUse, id);
    }
  }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>yirui</artifactId>
        <groupId>com.yirui</groupId>
        <version>1.0-SNAPSHOT</version>
        <relativePath>../pom.xml</relativePath>
    </parent>

    <modelVersion>4.0.0</modelVersion>
    <artifactId>yirui-admin</artifactId>
    <packaging>war</packaging>
    <name>yirui-admin</name>
    <url>https://github.com/yorkchow/yirui/yirui-admin</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>com.yirui</groupId>
            <artifactId>yirui-common</artifactId>
            <version>${project.version}</version>
        </dependency>

        <dependency>
            <groupId>com.yirui</groupId>
            <artifactId>yirui-paginator</artifactId>
            <version>${project.version}</version>
        </dependency>
        <!-- begin spring library -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-oxm</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
        </dependency>
        <!-- end spring -->

        <!-- begin aspectj library -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
        </dependency>
        <!-- end aspectj -->

        <!-- begin jdbc library -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
        </dependency>

        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
        </dependency>

        <dependency>
            <groupId>org.mybatis.caches</groupId>
            <artifactId>mybatis-ehcache</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
        </dependency>
        <!-- end jdbc -->

        <dependency>
            <groupId>org.javassist</groupId>
            <artifactId>javassist</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>commons-logging</groupId>
                    <artifactId>commons-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <!-- begin shiro library -->
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-core</artifactId>
            <version>${shiro.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-web</artifactId>
            <version>${shiro.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-aspectj</artifactId>
            <version>${shiro.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-ehcache</artifactId>
            <version>${shiro.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-spring</artifactId>
            <version>${shiro.version}</version>
        </dependency>
        <!-- end shiro -->

        <dependency>
            <groupId>net.sf.ehcache</groupId>
            <artifactId>ehcache-core</artifactId>
            <scope>compile</scope>
            <exclusions>
                <exclusion>
                    <artifactId>slf4j-api</artifactId>
                    <groupId>org.slf4j</groupId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
        </dependency>

        <!-- begin log library -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <scope>compile</scope>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-ext</artifactId>
            <scope>compile</scope>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>jul-to-slf4j</artifactId>
            <scope>compile</scope>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>jcl-over-slf4j</artifactId>
            <scope>compile</scope>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>log4j-over-slf4j</artifactId>
            <scope>compile</scope>
        </dependency>

        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-core</artifactId>
            <scope>compile</scope>
        </dependency>

        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <scope>compile</scope>
        </dependency>

        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-access</artifactId>
            <scope>compile</scope>
        </dependency>

        <dependency>
            <groupId>org.codehaus.janino</groupId>
            <artifactId>janino</artifactId>
            <scope>runtime</scope>
        </dependency>
        <!-- end log -->

        <!-- begin web library -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>taglibs</groupId>
            <artifactId>standard</artifactId>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>
        <!-- end web -->

        <!-- begin utils library -->
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
        </dependency>

        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
        </dependency>

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
        </dependency>

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-collections4</artifactId>
        </dependency>

        <dependency>
            <groupId>joda-time</groupId>
            <artifactId>joda-time</artifactId>
        </dependency>
        <!-- end utils -->

        <!-- begin testing library -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <artifactId>hamcrest-core</artifactId>
                    <groupId>org.hamcrest</groupId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>org.hamcrest</groupId>
            <artifactId>hamcrest-all</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-all</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <artifactId>hamcrest-core</artifactId>
                    <groupId>org.hamcrest</groupId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <!--<scope>test</scope>-->
        </dependency>
        <!-- end testing -->
    </dependencies>

    <build>
        <finalName>${project.artifactId}</finalName>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.*</include>
                </includes>
                <filtering>true</filtering>
            </resource>
        </resources>
        <testResources>
            <testResource>
                <directory>src/test/resources</directory>
                <includes>
                    <include>resources.properties</include>
                </includes>
                <filtering>true</filtering>
            </testResource>
            <testResource>
                <directory>src/test/resources</directory>
                <excludes>
                    <exclude>resources.properties</exclude>
                </excludes>
                <filtering>false</filtering>
            </testResource>
        </testResources>

        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-clean-plugin</artifactId>
                <version>2.5</version>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-source-plugin</artifactId>
                <version>2.4</version>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.2</version>
                <configuration>
                    <source>${java_source_version}</source>
                    <target>${java_target_version}</target>
                    <encoding>${project.build.sourceEncoding}</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-install-plugin</artifactId>
                <version>2.4</version>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <version>2.4</version>
                <configuration>
                    <archive>
                        <manifest>
                            <addDefaultImplementationEntries>true</addDefaultImplementationEntries>
                        </manifest>
                    </archive>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.4</version>
                <configuration>
                    <warName>${project.artifactId}</warName>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-enforcer-plugin</artifactId>
                <version>1.3.1</version>
                <executions>
                    <execution>
                        <id>enforce-versions</id>
                        <goals>
                            <goal>enforce</goal>
                        </goals>
                        <configuration>
                            <rules>
                                <requireJavaVersion>
                                    <version>${jdk.version}</version>
                                </requireJavaVersion>
                            </rules>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

redpajama_set_name: RedPajamaGithub


text:
A datatheme is a class of [Tabular Datapackage](http://dataprotocols.org/tabular-data-package/). Essentially a Class from which you can base your Tabular Datapackage from. The intent is to have one place to define and version the data model using the [JSON Table Schema](http://dataprotocols.org/json-table-schema/).

You build the Datatheme into a base ``datapackage.json`` file which you can extend for your purpose.

#### Dependencies

* [NodeJS](https://nodejs.org/en/)
* [AWS CLI](https://aws.amazon.com/cli/)
* [jq](https://stedolan.github.io/jq/manual/)
* [jsonlint](https://github.com/zaach/jsonlint)

#### Building

```
$ brew install jq
$ npm install tesera/bawlk -g
$ make
```

#### Testing

```
$ npm install jsonlint -g
$ make test
```

#### Publishing

```
$ pip install awscli
$ export AWS_REGION=ca-central-1; export AWS_profile=datastream; make publish
```
#### Creating a new datatheme

1. Create a datatheme.json file with the format from the example below. Fill in your own data for your datatheme. Datatheme names should be unique per namespace i.e. mackenzie.

````json
{
    "name": "mackenzie.air",
    "version": "1.0.1",
    "repository": "http://github.com/gordonfn/datatheme-mackenzie-pmd.git",
    "author": "Gordon Foundation",
    "description": "Datatheme for Mackenzie Basin PMD data.",
    "schemas": []
}
````

2. Create a schemas folder with one JSON Table Schema file per model/table and name the file wit the name of the schema. i.e. pmd.json.

3. Copy an existing Makefile from an existing datatheme.

4. (Optional) Copy and configure a circle.ci CI/CD configuration file for your datatheme.


text:
package github.users.eirikma.iteratorgenerators;

/**
 * Lambda type to use for generators: loops outputting (possibly infinite sequences of) values that should be iterated over.
 *
 * A Generator is called whenever someone wants to consume objects they produce. If the Generator
 * doesn't yield any values, the stream is considered ended. An Iterator delivering the values
 * yielded by the Generator will then reply with 'false' on the next call to 'hasNext()'.
 *
 * This Generator gets a Yield that can hold some state between calls,
 * in order to facilitate code more similar to scala's for-comprehensions.
 */
public interface GeneratorWithState<T, S> extends Generator<T, StatefulYield<S, T>> {

    /**
         * Produce new value(s) for the iterator to iterate over.
         * This method gets called when ever someone calls the surrounding Iterator's next() or hasNext() methods,
         * and all the previously yielded values have been consumed.
         * If no values are yielded, the Iterators hasNext()-method will return false and the
         * generator is finished. More than one value may be yielded. These will be kept in memory
         * until they are consumed by the iterator.
         *
         * All code executes in the same thread as the surrounding iterator calling this method.
         * Infinite generators must can not loop forever, but must return now and then.
         * They will be called again in order to proceed, once the previously yielded elements are consumed.
         *
         * @param yieldTarget - the target containing the yield(t) method that must be called to yield values.
         */
    @Override
    void yieldNextValues(StatefulYield<S, T> yieldTarget);

}


text:
Super Rentalsでは、各賃貸物件の場所を示す地図を表示できるようにしたいと考えています。 この機能を実装するために、いくつかのEmberの概念を利用します。

  1. Google Maps APIから地図を作成するためのユーティリティ関数
  2. 描画された地図のキャッシュをアプリケーションのさまざまな場所で使用するための service (サービス)
  3. それぞれの賃貸物件の地図を表示するcomponent (コンポーネント)

### Googleマップを利用できるようにする

地図ユーティリティを実装する前に、EmberアプリケーションでサードパーティマップAPIを利用できるようにする必要があります。 Emberにサードパーティライブラリを含めるにはいくつかの方法があります。 サードパーティライブラリを追加する方法は、[依存関係を管理する](../../addons-and-dependencies/managing-dependencies/)のガイドを参照してください。

The [Google Maps API](https://developers.google.com/maps/documentation/javascript/tutorial) requires us to reference its library from a script tag. We can add custom script references to our application by updating the main HTML page at `app/index.html`.

```app/index.html{+22}
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>SuperRentals</title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    {{content-for "head"}}

    <link rel="stylesheet" href="{{rootURL}}assets/vendor.css">
    <link rel="stylesheet" href="{{rootURL}}assets/super-rentals.css">

    {{content-for "head-footer"}}
  </head>
  <body>
    {{content-for "body"}}

    <script src="{{rootURL}}assets/vendor.js"></script>
    <script src="{{rootURL}}assets/super-rentals.js"></script>
    <script src="https://maps.googleapis.com/maps/api/js?v=3.22"></script>

    {{content-for "body-footer"}}
  </body>
</html>

```

### ユーティリティを使ってGoogle Maps APIにアクセスする

Ember utilities are reusable code that can be accessed from various parts of the application. For Super Rentals, we'll use a utility to access the Google Maps API. The utility will abstract the Google API away from our Maps service, which will allow for future reuse of the maps API within the application, easier refactoring to alternate maps implementations, and easier testing of code that depends on it.

Now that we have the maps API available to the application, we can create our map utility. Utility files can be generated using Ember CLI.

```shell
ember g util google-maps
```

The CLI `generate util` command will create a utility file and a unit test. We'll delete the unit test since we don't want to test Google code.

Our app needs a single function, `createMap`, which makes use of `google.maps.Map` to create our map element, `google.maps.Geocoder` to lookup the coordinates of our location, and `google.maps.Marker` to pin our map based on the resolved location.

import Ember from 'ember';

const google = window.google;

export default Ember.Object.extend({

  init() {
    this.set('geocoder', new google.maps.Geocoder());
  },

  createMap(element, location) {
    let map = new google.maps.Map(element, { scrollwheel: false, zoom: 10 });
    this.pinLocation(location, map);
    return map;
  },

  pinLocation(location, map) {
    this.get('geocoder').geocode({address: location}, (result, status) => {
      if (status === google.maps.GeocoderStatus.OK) {
        let geometry = result[0].geometry.location;
        let position = { lat: geometry.lat(), lng: geometry.lng() };
        map.setCenter(position);
        new google.maps.Marker({ position, map, title: location });
      }
    });
  }

});

### サービスを使って地図を取得する

Now that we are able to generate a map element, we will implement a maps service that will keep a reference to the Map object we create, and attach the map to an element in our application

Accessing our maps API through a [service](../../applications/services) will give us several benefits

* サービスは[service locator](https://en.wikipedia.org/wiki/Service_locator_pattern)を使って注入されます。そして、地図APIをコードから抽象化することで、リファクタリングとメンテナンスを容易にします。
* サービスは遅延ロードされているため、最初に呼び出されるまで初期化されません。 場合によっては、これによってアプリのプロセッサ負荷とメモリ消費量を減少できる可能性があります。
* サービスはシングルトンです。つまり、ブラウザー内でそのサービスのインスタンスはただ一つです。 これによって、ユーザーがアプリ内を巡回している間に地図データを保持でき、ページに戻っても地図を再読み込みする必要はありません。

Let's get started creating our service by generating it through Ember CLI, which will create the service file, as well as a unit test for it.

```shell
ember g service maps
```

Now implement the service as follows. Note that we check if a map already exists for the given location and use that one, otherwise we call a Google Maps utility to create one.

```app/services/maps.js
import Ember from 'ember';
import MapUtil from '../utils/google-maps';

export default Ember.Service.extend({

  init() {
    if (!this.get('cachedMaps')) {
      this.set('cachedMaps', Ember.Object.create());
    }
    if (!this.get('mapUtil')) {
      this.set('mapUtil', MapUtil.create());
    }
  },

  getMapElement(location) {
    let camelizedLocation = location.camelize();
    let element = this.get(`cachedMaps.${camelizedLocation}`);
    if (!element) {
      element = this.createMapElement();
      this.get('mapUtil').createMap(element, location);
      this.set(`cachedMaps.${camelizedLocation}`, element);
    }
    return element;
  },

  createMapElement() {
    let element = document.createElement('div');
    element.className = 'map';
    return element;
  }

});
```

### コンポーネントで地図を表示する

With a service and utility that render a map to a web page element, we'll connect it to our application using a component.

Generate the map component using Ember CLI.

```shell
ember g component location-map
```

Running this command generates three files: a component JavaScript file, a template, and a test file.

Let's start by adding a `div` element to the component template. This `div` will act as a place for the 3rd party map API to render the map to.

<div class="map-container"></div>

Next, update the component to append the map output to the `div` element we created.

We provide the maps service into our component by initializing a property of our component, called `maps`. Services are commonly made available in components and other Ember objects by ["service injection"](../../applications/services/#toc_accessing-services). When you initialize a property with `Ember.inject.service()`, Ember tries to set that property with a service matching its name.

With our `maps` service, our component will call the `getMapElement` function with the provided location. We append the map element we get back from the service by implementing `didInsertElement`, which is a [component lifecycle hook](../../components/the-component-lifecycle/#toc_integrating-with-third-party-libraries-with-code-didinsertelement-code). This function runs during the component render, after the component's markup gets inserted into the page.

import Ember from 'ember';

export default Ember.Component.extend({
  maps: Ember.inject.service(),

  didInsertElement() {
    this._super(...arguments);
    let location = this.get('location');
    let mapElement = this.get('maps').getMapElement(location);
    this.$('.map-container').append(mapElement);
  }
});

You may have noticed that `this.get('location')` refers to a property location we haven't defined. This property will be passed in to the component by its parent template below.

Finally open the template file for our `rental-listing` component and add the new `location-map` component.

<article class="listing">
  <a {{action 'toggleImageSize'}} class="image {{if isWide "wide"}}">
    <img src="{{rental.image}}" alt="">
    <small>View Larger</small>
  </a>
  <h3>{{rental.title}}</h3>
  <div class="detail owner">
    <span>Owner:</span> {{rental.owner}}
  </div>
  <div class="detail type">
    <span>Type:</span> {{rental-property-type rental.type}} - {{rental.type}}
  </div>
  <div class="detail location">
    <span>Location:</span> {{rental.city}}
  </div>
  <div class="detail bedrooms">
    <span>Number of bedrooms:</span> {{rental.bedrooms}}
  </div>
  {{location-map location=rental.city}}
</article>

After starting the server we should now see some end to end maps functionality show up on our front page!

![super rentals homepage with maps](../../images/service/style-super-rentals-maps.png)

You may now either move onto the [next feature](../subroutes/), or continue here to test the maps feature we just added.

### サービスのユニットテスト

We'll use a unit test to validate the service. Unit tests are more isolated than integration tests and acceptance tests, and are intended for testing specific logic within a class.

For our service unit test, we'll want to verify that locations that have been previously loaded are fetched from cache, while new locations are created using the utility. We will isolate our tests from actually calling Google Maps by stubbing our map utility. On line 6 of `maps-test.js` below we create an Ember object to simulate the behavior of the utility, but instead of creating a google map, we return an empty JavaScript object.

Unit tests use the function called `this.subject` to instantiate the object to test, and lets the test pass in initial values as arguments. In our case we are passing in our fake map utility object in the first test, and passing a cache object for the second test.

import { moduleFor, test } from 'ember-qunit';
import Ember from 'ember';

const DUMMY_ELEMENT = {};

let MapUtilStub = Ember.Object.extend({
  createMap(element, location) {
    this.assert.ok(element, 'createMap called with element');
    this.assert.ok(location, 'createMap called with location');
    return DUMMY_ELEMENT;
  }
});

moduleFor('service:maps', 'Unit | Service | maps');

test('should create a new map if one isnt cached for location', function (assert) {
  assert.expect(4);
  let stubMapUtil = MapUtilStub.create({ assert });
  let mapService = this.subject({ mapUtil: stubMapUtil });
  let element = mapService.getMapElement('San Francisco');
  assert.ok(element, 'element exists');
  assert.equal(element.className, 'map', 'element has class name of map');
});

test('should use existing map if one is cached for location', function (assert) {
  assert.expect(1);
  let stubCachedMaps = Ember.Object.create({
    sanFrancisco: DUMMY_ELEMENT
  });
  let mapService = this.subject({ cachedMaps: stubCachedMaps });
  let element = mapService.getMapElement('San Francisco');
  assert.equal(element, DUMMY_ELEMENT, 'element fetched from cache');
});

When the service calls `createMap` on our fake utility, we will run asserts to validate that it is called. In our first test notice that we expect four asserts to be run in line 17. Two of the asserts run in the test function, while the other two are run when `createMap` is called.

In the second test, only one assert is expected (line 26), since the map element is fetched from cache and does not use the utility.

Also, note that the second test uses a dummy object as the returned map element (defined on line 4). Our map element can be substituted with any object because we are only asserting that the cache has been accessed (see line 32).

The location in the cache has been [`camelized`](http://emberjs.com/api/classes/Ember.String.html#method_camelize) (line 30), so that it may be used as a key to look up our element. This matches the behavior in `getMapElement` when city has not yet been cached.

### 地図コンポーネントの結合テスト

Now let's test that the map component is relying on our service to provide map elements.

To limit the test to validating only its own behavior and not the service, we'll take advantage of the registration API to register a stub maps service. That way when Ember injects the map service into the component, it uses our fake service instead of the real one.

A stub stands in place of the real object in your application and simulates its behavior. In the stub service, define a method that will fetch the map based on location, called `getMapElement`.

import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';
import Ember from 'ember';

let StubMapsService = Ember.Service.extend({
  getMapElement(location) {
    this.set('calledWithLocation', location);
    // We create a div here to simulate our maps service,
    // which will create and then cache the map element
    return document.createElement('div');
  }
});

moduleForComponent('location-map', 'Integration | Component | location map', {
  integration: true,
  beforeEach() {
    this.register('service:maps', StubMapsService);
    this.inject.service('maps', { as: 'mapsService' });
  }
});

test('should append map element to container element', function(assert) {
  this.set('myLocation', 'New York');
  this.render(hbs`{{location-map location=myLocation}}`);
  assert.equal(this.$('.map-container').children().length, 1, 'the map element should be put onscreen');
  assert.equal(this.get('mapsService.calledWithLocation'), 'New York', 'a map of New York should be requested');
});

In the `beforeEach` function that runs before each test, we use the built-in function `this.register` to [register](../../applications/dependency-injection/#toc_factory-registrations) our stub service in place of the maps service. Registration makes an object available to your Ember application for things like loading components from templates and injecting services in this case.

The call to the function `this.inject.service` [injects](../../applications/dependency-injection/#toc_ad-hoc-injections) the service we just registered into the context of the tests, so each test may access it through `this.get('mapsService')`. In the example we assert that `calledWithLocation` in our stub is set to the location we passed to the component.

### 受入テストにおけるスタブサービス

Finally, we want to update our acceptance tests to account for our new service. While it would be great to verify that a map is displaying, we don't want to hammer the Google Maps API every time we run our acceptance test. For this tutorial we'll rely on our component integration tests to ensure that the map DOM is being attached to our screen. To avoid hitting our Maps request limit, we'll stub out our Maps service in our acceptance tests.

Often, services connect to third party APIs that are not desirable to include in automated tests. To stub these services we simply have to register a stub service that implements the same API, but does not have the dependencies that are problematic for the test suite.

Add the following code after the imports to our acceptance test:

import { test } from 'qunit';
import moduleForAcceptance from 'super-rentals/tests/helpers/module-for-acceptance';
import Ember from 'ember';

let StubMapsService = Ember.Service.extend({
  getMapElement() {
    return document.createElement('div');
  }
});

moduleForAcceptance('Acceptance | list-rentals');
moduleForAcceptance('Acceptance | list rentals', {
  beforeEach() {
    this.application.register('service:stubMaps', StubMapsService);
    this.application.inject('component:location-map', 'maps', 'service:stubMaps');
  }
});

What's happening here is we are adding our own stub maps service that simply creates an empty div. Then we are putting it in Ember's [registry](../../applications/dependency-injection#toc_factory-registrations), and injecting it into the `location-map` component that uses it. That way every time that component is created, our stub map service gets injected over the Google maps service. Now when we run our acceptance tests, you'll notice that maps do not get rendered as the test runs.

![acceptance tests without maps](../../images/service/acceptance-without-maps.png)


text:
package com.test.myapplication;

import com.test.myapplication.model.CharacterModel;

import java.util.List;

/**
 * Created by Indigo on 2/28/17.
 */

public class CharactersResponseModel {

    public final int count;
    public final String next;
    public final String previous;
    public final List<CharacterModel> results;

    public CharactersResponseModel(int count, String next, String previous, List<CharacterModel> results) {
        this.count = count;
        this.next = next;
        this.previous = previous;
        this.results = results;
    }
}


text:
const storage = require('../../storage/gcs')
const plan = require('../../plan/garbage')
describe.only('Unit Test for gcs.js.', () => {
  describe('#save()', () => {
    it('should backup file to google cloud storage', done => {
      plan.backup(null, (err, file) => {
        if (err) throw err
        let option = {
          keyFilename: 'keyFilename',
          bucket: 'bucket'
        }
        storage.save(file, option, (err, response) => {
          if (err) throw err
          done()
        })
      })
    })
  })
})


text:
package microtools.anyops

import org.scalatest.{MustMatchers, WordSpec}
import microtools.anyops.AutoAnyValNumeric._
import scala.math.Numeric.Implicits._
import scala.math.Fractional.Implicits._

case class Bauer(value: Int)    extends AnyVal
case class Ralph(value: Double) extends AnyVal

class AnuValNumericOperationsSpec extends WordSpec with MustMatchers {
  "AnyVal operations spec" should {
    "apply operators on anyval" in {
      Bauer(2) + Bauer(3) must equal(Bauer(5))
      Bauer(2) - Bauer(3) must equal(Bauer(-1))
      Bauer(2) * Bauer(3) must equal(Bauer(6))
      Ralph(10.0) / Ralph(2.0d) must equal(Ralph(5.0d))

      Bauer(2).toInt must equal(2)
      Bauer(2).toDouble must equal(2.0d)
      Bauer(2).toFloat must equal(2.0f)
      Bauer(2).toLong must equal(2L)

      -Bauer(2) must equal(Bauer(-2))
      Bauer(2) must be <= Bauer(3)
      Bauer(3) must be >= Bauer(2)
      Bauer(2) must be < Bauer(3)
      Bauer(3) must be > Bauer(2)

    }
  }
}


text:
namespace {

template <typename Encoding>
using encode = sal_test::with_type<Encoding>;

using transform_types = testing::Types<
  sal::hex_string,
  sal::base64
>;

struct transform_names
{
  template <typename T>
  static std::string GetName (int i)
  {
    (void)i;
    if constexpr (std::is_same_v<T, sal::hex_string>)
    {
      return "hex";
    }
    else if constexpr (std::is_same_v<T, sal::base64>)
    {
      return "base64";
    }
    else
    {
      return std::to_string(i);
    }
  }
};

TYPED_TEST_CASE(encode, transform_types, transform_names);

using encode_data = std::vector<std::pair<std::string, std::string>>;

template <typename Encoding> const encode_data test_data{};
template <typename Encoding> const std::string invalid_data{};
template <typename Encoding> const std::string invalid_length_data{};

template <> const encode_data test_data<sal::hex_string> =
{
  { "", "" },
  { "hex_string", "6865785f737472696e67" },
  { "HEX_STRING", "4845585f535452494e47" },
  { "hex\nstring", "6865780a737472696e67" },
  { "hello, world", "68656c6c6f2c20776f726c64" },
};

template <> const std::string invalid_data<sal::hex_string> = "xy";
template <> const std::string invalid_length_data<sal::hex_string> = "A";

// https://tools.ietf.org/html/rfc4648 (10)
template <> const encode_data test_data<sal::base64> =
{
  { "", "" },
  { "f", "Zg==" },
  { "fo", "Zm8=" },
  { "foo", "Zm9v" },
  { "foob", "Zm9vYg==" },
  { "fooba", "Zm9vYmE=" },
  { "foobar", "Zm9vYmFy" },
};

template <> const std::string invalid_data<sal::base64> = "====";
template <> const std::string invalid_length_data<sal::base64> = "A";

TYPED_TEST(encode, max_encoded_size_range)
{
  for (auto &data: test_data<TypeParam>)
  {
    auto &[decoded, encoded] = data;
    EXPECT_LE(
      encoded.size(),
      sal::max_encoded_size<TypeParam>(decoded.begin(), decoded.end())
    ) << "Data: " << decoded;
  }
}

TYPED_TEST(encode, max_encoded_size_buffer)
{
  for (auto &data: test_data<TypeParam>)
  {
    auto &[decoded, encoded] = data;
    EXPECT_LE(
      encoded.size(),
      sal::max_encoded_size<TypeParam>(decoded)
    ) << "Data: " << decoded;
  }
}

TYPED_TEST(encode, encode_range_into_range)
{
  for (auto &data: test_data<TypeParam>)
  {
    auto &[decoded, encoded] = data;

    char buf[4096];
    auto result = std::string(buf,
      sal::encode<TypeParam>(decoded.begin(), decoded.end(), buf)
    );

    EXPECT_EQ(encoded, result) << "Data: " << decoded;
  }
}

TYPED_TEST(encode, encode_buffer_into_range)
{
  for (auto &data: test_data<TypeParam>)
  {
    auto &[decoded, encoded] = data;

    char buf[4096];
    auto result = std::string(buf, sal::encode<TypeParam>(decoded, buf));

    EXPECT_EQ(encoded, result) << "Data: " << decoded;
  }
}

TYPED_TEST(encode, encode_range_into_string)
{
  for (auto &data: test_data<TypeParam>)
  {
    auto &[decoded, encoded] = data;
    EXPECT_EQ(encoded, sal::encode<TypeParam>(decoded.begin(), decoded.end()))
      << "Data: " << decoded;
  }
}

TYPED_TEST(encode, encode_buffer_into_string)
{
  for (auto &data: test_data<TypeParam>)
  {
    auto &[decoded, encoded] = data;
    EXPECT_EQ(encoded, sal::encode<TypeParam>(decoded)) << "Data: " << decoded;
  }
}

TYPED_TEST(encode, max_decoded_size_range)
{
  for (auto &data: test_data<TypeParam>)
  {
    auto &[decoded, encoded] = data;
    std::error_code error;
    auto size = sal::max_decoded_size<TypeParam>(
      encoded.begin(),
      encoded.end(),
      error
    );
    EXPECT_LE(decoded.size(), size) << "Data: " << decoded;
    EXPECT_TRUE(!error);

    EXPECT_NO_THROW(
      sal::max_decoded_size<TypeParam>(encoded.begin(), encoded.end())
    );
  }
}

TYPED_TEST(encode, max_decoded_size_buffer)
{
  for (auto &data: test_data<TypeParam>)
  {
    auto &[decoded, encoded] = data;
    std::error_code error;
    auto size = sal::max_decoded_size<TypeParam>(encoded, error);
    EXPECT_LE(decoded.size(), size) << "Data: " << decoded;
    EXPECT_TRUE(!error);

    EXPECT_NO_THROW(sal::max_decoded_size<TypeParam>(encoded));
  }
}

TYPED_TEST(encode, max_decoded_size_range_invalid)
{
  for (auto data: test_data<TypeParam>)
  {
    auto [decoded, encoded] = data;
    encoded += invalid_length_data<TypeParam>;

    std::error_code error;
    sal::max_decoded_size<TypeParam>(encoded.begin(), encoded.end(), error);
    EXPECT_EQ(std::errc::message_size, error) << "Data: " << decoded;

    EXPECT_THROW(
      sal::max_decoded_size<TypeParam>(encoded.begin(), encoded.end()),
      std::system_error
    ) << "Data: " << decoded;
  }
}

TYPED_TEST(encode, max_decoded_size_buffer_invalid)
{
  for (auto data: test_data<TypeParam>)
  {
    auto [decoded, encoded] = data;
    encoded += invalid_length_data<TypeParam>;

    std::error_code error;
    sal::max_decoded_size<TypeParam>(encoded, error);
    EXPECT_EQ(std::errc::message_size, error) << "Data: " << decoded;

    EXPECT_THROW(sal::max_decoded_size<TypeParam>(encoded), std::system_error)
      << "Data: " << decoded;
  }
}

TYPED_TEST(encode, decode_range_into_range)
{
  for (auto &data: test_data<TypeParam>)
  {
    auto &[decoded, encoded] = data;

    char buf[4096];
    std::error_code error;
    auto result = std::string(buf,
      sal::decode<TypeParam>(encoded.begin(), encoded.end(), buf, error)
    );

    EXPECT_TRUE(!error);
    EXPECT_EQ(decoded, result) << "Data: " << decoded;

    EXPECT_NO_THROW(
      sal::decode<TypeParam>(encoded.begin(), encoded.end(), buf)
    );
  }
}

TYPED_TEST(encode, decode_range_into_range_invalid_length)
{
  for (auto &data: test_data<TypeParam>)
  {
    auto encoded = data.second + invalid_length_data<TypeParam>;

    char buf[4096];
    std::error_code error;
    auto result = std::string(buf,
      sal::decode<TypeParam>(encoded.begin(), encoded.end(), buf, error)
    );

    EXPECT_EQ(std::errc::message_size, error) << error.message();
    EXPECT_TRUE(result.empty());

    EXPECT_THROW(
      sal::decode<TypeParam>(encoded.begin(), encoded.end(), buf),
      std::system_error
    );
  }
}

TYPED_TEST(encode, decode_range_into_range_invalid_data_in_front)
{
  for (auto &data: test_data<TypeParam>)
  {
    auto encoded = invalid_data<TypeParam> + data.second;

    char buf[4096];
    std::error_code error;
    auto result = std::string(buf,
      sal::decode<TypeParam>(encoded.begin(), encoded.end(), buf, error)
    );

    EXPECT_EQ(std::errc::illegal_byte_sequence, error) << error.message();
    EXPECT_TRUE(result.empty());

    EXPECT_THROW(
      sal::decode<TypeParam>(encoded.begin(), encoded.end(), buf),
      std::system_error
    );
  }
}

TYPED_TEST(encode, decode_range_into_range_invalid_data_in_back)
{
  for (auto &data: test_data<TypeParam>)
  {
    auto encoded = data.second + invalid_data<TypeParam>;

    char buf[4096];
    std::error_code error;
    auto result = std::string(buf,
      sal::decode<TypeParam>(encoded.begin(), encoded.end(), buf, error)
    );
    EXPECT_EQ(std::errc::illegal_byte_sequence, error) << error.message();

    EXPECT_THROW(
      sal::decode<TypeParam>(encoded.begin(), encoded.end(), buf),
      std::system_error
    );
  }
}

TYPED_TEST(encode, decode_buffer_into_range)
{
  for (auto &data: test_data<TypeParam>)
  {
    auto &[decoded, encoded] = data;

    char buf[4096];
    std::error_code error;
    auto result = std::string(buf, sal::decode<TypeParam>(encoded, buf, error));

    EXPECT_TRUE(!error);
    EXPECT_EQ(decoded, result) << "Data: " << decoded;

    EXPECT_NO_THROW(sal::decode<TypeParam>(encoded, buf));
  }
}

TYPED_TEST(encode, decode_buffer_into_range_invalid_length)
{
  for (auto &data: test_data<TypeParam>)
  {
    auto encoded = data.second + invalid_length_data<TypeParam>;

    char buf[4096];
    std::error_code error;
    auto result = std::string(buf, sal::decode<TypeParam>(encoded, buf, error));

    EXPECT_EQ(std::errc::message_size, error) << error.message();
    EXPECT_TRUE(result.empty());

    EXPECT_THROW(
      sal::decode<TypeParam>(encoded, buf),
      std::system_error
    );
  }
}

TYPED_TEST(encode, decode_buffer_into_range_invalid_data_in_front)
{
  for (auto &data: test_data<TypeParam>)
  {
    auto encoded = invalid_data<TypeParam> + data.second;

    char buf[4096];
    std::error_code error;
    auto result = std::string(buf, sal::decode<TypeParam>(encoded, buf, error));

    EXPECT_EQ(std::errc::illegal_byte_sequence, error) << error.message();
    EXPECT_TRUE(result.empty());

    EXPECT_THROW(
      sal::decode<TypeParam>(encoded, buf),
      std::system_error
    );
  }
}

TYPED_TEST(encode, decode_buffer_into_range_invalid_data_in_back)
{
  for (auto &data: test_data<TypeParam>)
  {
    auto encoded = data.second + invalid_data<TypeParam>;

    char buf[4096];
    std::error_code error;
    auto result = std::string(buf, sal::decode<TypeParam>(encoded, buf, error));
    EXPECT_EQ(std::errc::illegal_byte_sequence, error) << error.message();

    EXPECT_THROW(
      sal::decode<TypeParam>(encoded, buf),
      std::system_error
    );
  }
}

inline auto to_string (const std::vector<uint8_t> &in)
{
  return std::string(in.begin(), in.end());
}

TYPED_TEST(encode, decode_range_into_vector)
{
  for (auto &data: test_data<TypeParam>)
  {
    auto &[decoded, encoded] = data;

    std::error_code error;
    auto result = sal::decode<TypeParam>(encoded.begin(), encoded.end(), error);

    EXPECT_TRUE(!error);
    EXPECT_EQ(decoded, to_string(result)) << "Data: " << decoded;

    EXPECT_NO_THROW(sal::decode<TypeParam>(encoded.begin(), encoded.end()));
  }
}

TYPED_TEST(encode, decode_range_into_vector_invalid_length)
{
  for (auto &data: test_data<TypeParam>)
  {
    auto encoded = data.second + invalid_length_data<TypeParam>;

    std::error_code error;
    auto result = sal::decode<TypeParam>(encoded.begin(), encoded.end(), error);

    EXPECT_EQ(std::errc::message_size, error) << error.message();
    EXPECT_TRUE(result.empty());

    EXPECT_THROW(
      sal::decode<TypeParam>(encoded.begin(), encoded.end()),
      std::system_error
    );
  }
}

TYPED_TEST(encode, decode_range_into_vector_invalid_data_in_front)
{
  for (auto &data: test_data<TypeParam>)
  {
    auto encoded = invalid_data<TypeParam> + data.second;

    std::error_code error;
    auto result = sal::decode<TypeParam>(encoded.begin(), encoded.end(), error);

    EXPECT_EQ(std::errc::illegal_byte_sequence, error) << error.message();
    EXPECT_TRUE(result.empty());

    EXPECT_THROW(
      sal::decode<TypeParam>(encoded.begin(), encoded.end()),
      std::system_error
    );
  }
}

TYPED_TEST(encode, decode_range_into_vector_invalid_data_in_back)
{
  for (auto &data: test_data<TypeParam>)
  {
    auto encoded = data.second + invalid_data<TypeParam>;

    std::error_code error;
    auto result = sal::decode<TypeParam>(encoded.begin(), encoded.end(), error);
    EXPECT_EQ(std::errc::illegal_byte_sequence, error) << error.message();

    EXPECT_THROW(
      sal::decode<TypeParam>(encoded.begin(), encoded.end()),
      std::system_error
    );
  }
}

TYPED_TEST(encode, decode_buffer_into_vector)
{
  for (auto &data: test_data<TypeParam>)
  {
    auto &[decoded, encoded] = data;

    std::error_code error;
    auto result = sal::decode<TypeParam>(encoded, error);

    EXPECT_TRUE(!error);
    EXPECT_EQ(decoded, to_string(result)) << "Data: " << decoded;

    EXPECT_NO_THROW(sal::decode<TypeParam>(encoded));
  }
}

TYPED_TEST(encode, decode_buffer_into_vector_invalid_length)
{
  for (auto &data: test_data<TypeParam>)
  {
    auto encoded = data.second + invalid_length_data<TypeParam>;

    std::error_code error;
    auto result = sal::decode<TypeParam>(encoded, error);

    EXPECT_EQ(std::errc::message_size, error) << error.message();
    EXPECT_TRUE(result.empty());

    EXPECT_THROW(
      sal::decode<TypeParam>(encoded),
      std::system_error
    );
  }
}

TYPED_TEST(encode, decode_buffer_into_vector_invalid_data_in_front)
{
  for (auto &data: test_data<TypeParam>)
  {
    auto encoded = invalid_data<TypeParam> + data.second;

    std::error_code error;
    auto result = sal::decode<TypeParam>(encoded, error);

    EXPECT_EQ(std::errc::illegal_byte_sequence, error) << error.message();
    EXPECT_TRUE(result.empty());

    EXPECT_THROW(
      sal::decode<TypeParam>(encoded),
      std::system_error
    );
  }
}

TYPED_TEST(encode, decode_buffer_into_vector_invalid_data_in_back)
{
  for (auto &data: test_data<TypeParam>)
  {
    auto encoded = data.second + invalid_data<TypeParam>;

    std::error_code error;
    auto result = sal::decode<TypeParam>(encoded, error);
    EXPECT_EQ(std::errc::illegal_byte_sequence, error) << error.message();

    EXPECT_THROW(
      sal::decode<TypeParam>(encoded),
      std::system_error
    );
  }
}

} // namespace


text:
<?php

error_reporting(E_ALL);

if (function_exists('date_default_timezone_set') && function_exists('date_default_timezone_get')) {
    date_default_timezone_set(@date_default_timezone_get());
}

require_once __DIR__ . '/TestSuite.php';
require_once __DIR__ . '/../src/Arrays.php';


text:
import pandas as pd
from slayer import constants, file_utils

class BaseConverter(object):
    def __init__(self, **kwargs):
        pass

    def convert_data(self, **kwargs):

        raise NotImplementedError

    @staticmethod
    def convert_dates(raw_data, start_date_column, end_date_column=None,
                      date_format=None, dataset_time_zone=None):
        start_slices = convert_date_column(raw_data[start_date_column],
                                           date_format, dataset_time_zone)
        raw_data[constants.start_date_column] = start_slices

        if end_date_column:
            end_slices = convert_date_column(raw_data[end_date_column],
                                             date_format, dataset_time_zone)
            raw_data[constants.end_date_column] = end_slices
        else:
            raw_data[constants.end_date_column] = start_slices

        return raw_data

    @staticmethod
    def convert_categories(raw_data, categories):
        renamed_columns = {category: constants.category_column_prefix + category
                           for category in categories}
        raw_data.rename(columns=renamed_columns, inplace=True)
        return raw_data

    @staticmethod
    def convert_spatial(raw_data, lat_column, lon_column):
        renamed_columns = {lat_column: constants.lat_column,
                           lon_column: constants.lon_column}
        raw_data.rename(columns=renamed_columns, inplace=True)
        return raw_data

    @staticmethod
    def add_default_category(raw_data):
        raw_data[constants.default_category] = constants.default_option
        return raw_data, [constants.default_category]

    @staticmethod
    def add_default_weight(raw_data):
        raw_data[constants.weight_column] = 1.0
        return raw_data

    @staticmethod
    def convert_weight(raw_data, weight_column):
        if weight_column:
            renamed_columns = {weight_column: constants.weight_column}
            raw_data.rename(columns=renamed_columns, inplace=True)
        else:
            raw_data = BaseConverter.add_default_weight(raw_data)
        return raw_data

def convert_date_column(date_column, date_format, dataset_time_zone=None):
    source_date_format = file_utils.detect_dateformat(date_column)
    if source_date_format == constants.DateFormat.timestamp:
        return pd.to_datetime(date_column, unit='s',
                              infer_datetime_format=True, utc=True)
    elif source_date_format == constants.DateFormat.timestamp_ms:
        return pd.to_datetime(date_column, unit='ms',
                              infer_datetime_format=True, utc=True)

    if dataset_time_zone:
        return pd.to_datetime(date_column,
                              format=date_format,
                              infer_datetime_format=True, utc=True
                              ).dt.tz_localize(dataset_time_zone, ambiguous='infer')\
                               .dt.tz_convert('UTC')\
                               .dt.tz_convert(None)

    return pd.to_datetime(date_column, format=date_format,
                          infer_datetime_format=True, utc=True)


text:
/****************************************************************************************
 Support portable address conversion.

 *****************************************************************************************/

#include "pminternal.h"

inline void * p_addr(void *md, void *addr) {
	struct mdesc *mdp = (struct mdesc *) md;
	return NULL == addr ? NULL : addr - (size_t) (mdp->mempoolbase);
}

inline void * e_addr(void *md, void *addr) {
	struct mdesc *mdp = (struct mdesc *) md;
	return NULL == addr ? NULL : (size_t) addr + mdp->mempoolbase;
}

inline void * b_addr(void *md) {
	struct mdesc *mdp = (struct mdesc *) md;
	return mdp->mempoolbase;
}


text:
import PriceAnalyzer from './priceAnalyzer';
import MailSender from './mailSender';
import ConsoleSender from './consoleSender';

const fs = require('fs');

const CONFIG_FILE = 'config.json';

function updateConfig(config) {
    fs.writeFile(CONFIG_FILE, JSON.stringify(config, null, 4));
}

fs.readFile(CONFIG_FILE, 'utf8', (err, data) => {
    if (err) throw err;
    const config = JSON.parse(data);
    const mailSender = new MailSender(config);
    const consoleSender = new ConsoleSender();
    const priceAnalyzer = new PriceAnalyzer(mailSender, config, updateConfig);
    //const priceAnalyzer = new PriceAnalyzer(consoleSender, config, updateConfig);
    priceAnalyzer.start();
});


text:
<?php

namespace Transitive\Utils;

class Country extends Model implements \JsonSerializable
{
    use Named;

    /**
     * @var int
     */
    private $code;

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

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

    public function __construct(string $name, int $code = null, string $alpha2 = null, string $alpha3 = null)
    {
        parent::__construct();

        $this->_initNamed($name ?? '');

        $this->setCode($code);
        $this->setAlpha2($alpha2);
        $this->setAlpha3($alpha3);
    }

    public function getCode(): ?int
    {
        return $this->code;
    }

    public function getAlpha2(): ?string
    {
        return $this->alpha2;
    }

    public function getAlpha3(): ?string
    {
        return $this->alpha3;
    }

    public function setCode(int $code = null): void
    {
        $this->code = $code;
    }

    public function setAlpha2(string $alpha2 = null): void
    {
        $this->alpha2 = $alpha2;
    }

    public function setAlpha3(string $alpha3 = null): void
    {
        $this->alpha3 = $alpha3;
    }

    public function __toString()
    {
        $str = '';
        $str .= $this->getName();
        $str .= '';

        return $str;
    }

    public function jsonSerialize()
    {
        return parent::jsonSerialize()
        + $this->_namedJsonSerialize()
        + [
            'code' => htmlentities($this->getCode()),
            'alpha2' => htmlentities($this->getAlpha2()),
            'alpha3' => htmlentities($this->getAlpha3()),
        ];
    }
}