text:
layout: post
title: "Rails url_for weaknesses"
description: "url_for is used by link_to which is used any Rails developer.
This method accepts a lot of types of arguments. And sometimes it can be slow. See how to use it with maximum performance."
categories: ruby
tags: [rails]
---

Rails helper `link_to` is the most famous and used any Rails developer. Usually the first argument is a link name and the second is a parameters which are used to build url. You are able to pass 4 types of these parameters: helper which is generated by routes, string, hash and since rails 3 - record. But when and which one to use for your task? This is an interesting question.

## url_for

Passed to `link_to` parameters go to the `url_for` method. This method builds known url which is eventually passed to the `href` attribute of generated link. So to answer on this question we should answer on question what and when to pass to the `url_for`.

As I've already said `url_for` accepts 4 types of parameters and see how it's possible to pass them there:

{% highlight ruby %}
url_for("/events/#{@event.id}") # string
url_for(event_path(@event)) # generated helper
url_for(controller: 'events', action: 'show', id: @event.id) # hash
url_for(@event) # polymorphic
{% endhighlight %}

All there calls of `url_for` generate the same result `/events/:id`, for example `/events/1`.

The most convenient seems the last call - you just pass `@event` record and that's it. There is no any brainstorming or surfing generated routes with `rake routes` task (this task shows all available routes for your Rails application, run it if you still hadn't done this yet). It really convenient not only that's why but it will be useful when you change controller or route which serves the event. You won't have to change all your entire code in Rails application where you used old route helpers or string urls, hashes and so on.

The most complicated seems the hash variant. It looks the biggest and there is no doubt that why it is silently deprecated by Rails community. Rails developers avoid to using it at all. The reason is not only in this reason but in one more which I will tell you in a few seconds.

There is no any rule which method of proposed to use and of course you are not restricted to use any of these call types.

But let's see what is their speed. I wrote the benchmarking test especially for this case:

{% highlight ruby %}
class EventsHelperTest < ActionView::TestCase
  def setup
    country = Country.create(name: 'Belarus')
    state = State.create(name: 'Minsk')
    @event = Event.create(country: country, state: state, name: 'Drinking bear')
  end

  def test_url_for
    n = 10000
    Benchmark.bmbm do |x|
      x.report('string') { n.times { url_for("/events/#{@event.id}") } }
      x.report('helper') { n.times { url_for(event_path(@event)) } }
      x.report('hash') { n.times { url_for(controller: 'events', action: 'show', id: @event.id) } }
      x.report('polymorphic') { n.times { url_for(@event) } }
    end
  end
end
{% endhighlight %}

And these are results of their running:

    rake test test/helpers/events_helper_test.rb
    Run options: --seed 23668

    # Running tests:

    Rehearsal -----------------------------------------------
    string        0.010000   0.000000   0.010000 (  0.019028)
    helper        0.480000   0.010000   0.490000 (  0.498942)
    hash          1.250000   0.000000   1.250000 (  1.253836)
    polymorphic   0.920000   0.010000   0.930000 (  0.924670)
    -------------------------------------- total: 2.680000sec

                      user     system      total        real
    string        0.010000   0.000000   0.010000 (  0.013747)
    helper        0.480000   0.000000   0.480000 (  0.478646)
    hash          1.200000   0.000000   1.200000 (  1.200571)
    polymorphic   0.890000   0.000000   0.890000 (  0.892464)
    .

    Finished tests in 5.542858s, 0.1804 tests/s, 0.0000 assertions/s.

    1 tests, 0 assertions, 0 failures, 0 errors, 0 skips

As you see the slowest here is a hash style. And then polymorphic generating goes. Helper style on the 3rd place and it's not surprise that string generating wins.

## Conclusion

For my opinion the most convenient style here is polymorphic. But it's 2x slower than helper style. String style is the fastest but we can't use it because if you change your routes your tests may not show you that there is an error in generating routes - string will be generated as before but helper method won't be presented and page will fail that's why.

So my conclusion is to use helper methods everywhere where it's possible. If you have some place in your application where you have to define which helper to use by record type or any other sign the polymorphic way is more preferable.

And the last conclusion - avoid using hash types of generating url at all.


text:
class File
  # Return `file_name`, changing the extension to `new_extension`.
  def self.change_extension(file_name, new_extension)
    if file_name =~ /^(.+)\.(.+)$/
      "#{$1}.#{new_extension}"
    else
      "#{file_name}.#{new_extension}"
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
Part of info application responsible for presentation of our apps

## Installation

    pod "AOAppsInfo", :git => 'https://github.com/alekoleg/AOAppsInfo.git'

Because it is private spec, they are not in cocoapods Spec. You must add following lines to your Podfile

    pod 'VZPolicCollectionView', :git => 'https://github.com/alekoleg/VZPolicCollectionView'
    pod 'AOInfoNetManager', :git => 'https://github.com/alekoleg/AOInfoNetManager'
    pod 'CLPLoading', :git => 'https://github.com/alekoleg/CLPLoading'

## Author

Oleg Alekseenko, alekoleg@gmail.com

## License


text:
package com.webcohesion.enunciate.javac.javadoc;

/**
 * Handler to be used to define logic to perform for tags in JavaDoc comments.
 *
 * @author Ryan Heaton
 */
public class JavaDocTagHandlerFactory {

  private static JavaDocTagHandler INSTANCE;
  private static boolean CHECKED;

  /**
   * The tag handler instance.
   *
   * @return The tag handler instance.
   */
  public static synchronized JavaDocTagHandler getTagHandler() {
    if (!CHECKED) {
      String handlerClassname = System.getProperty(JavaDocTagHandler.class.getName());
      if (handlerClassname != null) {
        try {
          INSTANCE = (JavaDocTagHandler) Class.forName(handlerClassname).newInstance();
          CHECKED = true;
        }
        catch (Exception e) {
          System.getProperties().remove(JavaDocTagHandler.class.getName());
          e.printStackTrace(System.err);
        }
      }
      else {
        INSTANCE = new DefaultJavaDocTagHandler();
        CHECKED = true;
      }
    }

    return INSTANCE;
  }

  /**
   * The tag handler instance.
   *
   * @param tagHandler The tag handler instance.
   */
  public static synchronized void setTagHandler(JavaDocTagHandler tagHandler) {
    INSTANCE = tagHandler;
    CHECKED = true;
  }

}


text:
void throwf(const char *format, ...);
void assertf(bool condition, const char *format, ...);

#endif


text:
namespace mediapipe {
namespace mediasequence {

// ***********************    METADATA    *************************************
// Context Keys:
// A unique identifier for each example.
const char kExampleIdKey[] = "example/id";
// The name of the data set, including the version.
const char kExampleDatasetNameKey[] = "example/dataset_name";
// String flags or attributes for this example within a data set.
const char kExampleDatasetFlagStringKey[] = "example/dataset/flag/string";

// The relative path to the data on disk from some root directory.
const char kClipDataPathKey[] = "clip/data_path";
// Any identifier for the media beyond the data path.
const char kClipMediaId[] = "clip/media_id";
// Yet another alternative identifier.
const char kClipAlternativeMediaId[] = "clip/alternative_media_id";
// The encoded bytes for storing media directly in the SequenceExample.
const char kClipEncodedMediaBytesKey[] = "clip/encoded_media_bytes";
// The start time for the encoded media if not preserved during encoding.
const char kClipEncodedMediaStartTimestampKey[] =
    "clip/encoded_media_start_timestamp";
// The start time, in microseconds, for the start of the clip in the media.
const char kClipStartTimestampKey[] = "clip/start/timestamp";
// The end time, in microseconds, for the end of the clip in the media.
const char kClipEndTimestampKey[] = "clip/end/timestamp";
// A list of label indices for this clip.
const char kClipLabelIndexKey[] = "clip/label/index";
// A list of label strings for this clip.
const char kClipLabelStringKey[] = "clip/label/string";
// A list of label confidences for this clip.
const char kClipLabelConfidenceKey[] = "clip/label/confidence";
// A list of label start timestamps for this clip.
const char kClipLabelStartTimestampKey[] = "clip/label/start/timestamp";
// A list of label end timestamps for this clip.
const char kClipLabelEndTimestampKey[] = "clip/label/end/timestamp";

BYTES_CONTEXT_FEATURE(ExampleId, kExampleIdKey);
BYTES_CONTEXT_FEATURE(ExampleDatasetName, kExampleDatasetNameKey);
VECTOR_BYTES_CONTEXT_FEATURE(ExampleDatasetFlagString,
                             kExampleDatasetFlagStringKey);

BYTES_CONTEXT_FEATURE(ClipDataPath, kClipDataPathKey);
BYTES_CONTEXT_FEATURE(ClipAlternativeMediaId, kClipAlternativeMediaId);
BYTES_CONTEXT_FEATURE(ClipMediaId, kClipMediaId);
BYTES_CONTEXT_FEATURE(ClipEncodedMediaBytes, kClipEncodedMediaBytesKey);
INT64_CONTEXT_FEATURE(ClipEncodedMediaStartTimestamp,
                      kClipEncodedMediaStartTimestampKey);
INT64_CONTEXT_FEATURE(ClipStartTimestamp, kClipStartTimestampKey);
INT64_CONTEXT_FEATURE(ClipEndTimestamp, kClipEndTimestampKey);
VECTOR_BYTES_CONTEXT_FEATURE(ClipLabelString, kClipLabelStringKey);
VECTOR_INT64_CONTEXT_FEATURE(ClipLabelIndex, kClipLabelIndexKey);
VECTOR_FLOAT_CONTEXT_FEATURE(ClipLabelConfidence, kClipLabelConfidenceKey);
VECTOR_INT64_CONTEXT_FEATURE(ClipLabelStartTimestamp,
                             kClipLabelStartTimestampKey);
VECTOR_INT64_CONTEXT_FEATURE(ClipLabelEndTimestamp, kClipLabelEndTimestampKey);

// ***********************    SEGMENTS    *************************************
// Context Keys:
// A list of segment start times in microseconds.
const char kSegmentStartTimestampKey[] = "segment/start/timestamp";
// A list of indices marking the first frame index >= the start time.
const char kSegmentStartIndexKey[] = "segment/start/index";
// A list of segment end times in microseconds.
const char kSegmentEndTimestampKey[] = "segment/end/timestamp";
// A list of indices marking the last frame index <= the end time.
const char kSegmentEndIndexKey[] = "segment/end/index";
// A list with the label index for each segment.
// Multiple labels for the same segment are encoded as repeated segments.
const char kSegmentLabelIndexKey[] = "segment/label/index";
// A list with the label string for each segment.
// Multiple labels for the same segment are encoded as repeated segments.
const char kSegmentLabelStringKey[] = "segment/label/string";
// A list with the label confidence for each segment.
// Multiple labels for the same segment are encoded as repeated segments.
const char kSegmentLabelConfidenceKey[] = "segment/label/confidence";

VECTOR_BYTES_CONTEXT_FEATURE(SegmentLabelString, kSegmentLabelStringKey);
VECTOR_INT64_CONTEXT_FEATURE(SegmentStartTimestamp, kSegmentStartTimestampKey);
VECTOR_INT64_CONTEXT_FEATURE(SegmentEndTimestamp, kSegmentEndTimestampKey);
VECTOR_INT64_CONTEXT_FEATURE(SegmentStartIndex, kSegmentStartIndexKey);
VECTOR_INT64_CONTEXT_FEATURE(SegmentEndIndex, kSegmentEndIndexKey);
VECTOR_INT64_CONTEXT_FEATURE(SegmentLabelIndex, kSegmentLabelIndexKey);
VECTOR_FLOAT_CONTEXT_FEATURE(SegmentLabelConfidence,
                             kSegmentLabelConfidenceKey);

// *****************    REGIONS / BOUNDING BOXES    ***************************
// Context keys:
// The dimensions of each embedding per region / bounding box.
const char kRegionEmbeddingDimensionsPerRegionKey[] =
    "region/embedding/dimensions_per_region";
// The format encoding embeddings as strings.
const char kRegionEmbeddingFormatKey[] = "region/embedding/format";
// The list of region parts expected in this example.
const char kRegionPartsKey[] = "region/parts";

// Feature list keys:
// The normalized coordinates of the bounding boxes are provided in four lists
// to avoid order ambiguity, but we provide additional accessors for complete
// bounding boxes below.
const char kRegionBBoxYMinKey[] = "region/bbox/ymin";
const char kRegionBBoxXMinKey[] = "region/bbox/xmin";
const char kRegionBBoxYMaxKey[] = "region/bbox/ymax";
const char kRegionBBoxXMaxKey[] = "region/bbox/xmax";
// The point and radius can denote keypoints.
const char kRegionPointXKey[] = "region/point/x";
const char kRegionPointYKey[] = "region/point/y";
const char kRegionRadiusKey[] = "region/radius";
// The 3d point can denote keypoints.
const char kRegion3dPointXKey[] = "region/3d_point/x";
const char kRegion3dPointYKey[] = "region/3d_point/y";
const char kRegion3dPointZKey[] = "region/3d_point/z";
// The number of regions at that timestep.
const char kRegionNumRegionsKey[] = "region/num_regions";
// Whether that timestep is annotated for bounding regions.
// (Distinguishes between multiple meanings of num_regions = 0.
const char kRegionIsAnnotatedKey[] = "region/is_annotated";
// A list indicating if each region is generated (1) or manually annotated (0).
const char kRegionIsGeneratedKey[] = "region/is_generated";
// A list indicating if each region is occluded (1) or visible (0).
const char kRegionIsOccludedKey[] = "region/is_occluded";
// Lists with a label for each region.
// Multiple labels for the same region require duplicating the region.
const char kRegionLabelIndexKey[] = "region/label/index";
const char kRegionLabelStringKey[] = "region/label/string";
const char kRegionLabelConfidenceKey[] = "region/label/confidence";
// Lists with a track identifier for each region.
const char kRegionTrackIndexKey[] = "region/track/index";
const char kRegionTrackStringKey[] = "region/track/string";
const char kRegionTrackConfidenceKey[] = "region/track/confidence";
// A list with a class for each region. In general, prefer to use the label
// fields. These class fields exist to distinguish tracks when different classes
// have overlapping track ids.
const char kRegionClassIndexKey[] = "region/class/index";
const char kRegionClassStringKey[] = "region/class/string";
const char kRegionClassConfidenceKey[] = "region/class/confidence";
// The timestamp of the region annotations in microseconds.
const char kRegionTimestampKey[] = "region/timestamp";
// An embedding for each region. The length of each list must be the product of
// the number of regions and the product of the embedding dimensions.
const char kRegionEmbeddingFloatKey[] = "region/embedding/float";
// A string encoded embedding for each region.
const char kRegionEmbeddingEncodedKey[] = "region/embedding/encoded";
// The confidence of the embedding.
const char kRegionEmbeddingConfidenceKey[] = "region/embedding/confidence";
// The original timestamp in microseconds for region annotations.
// ReconcileMetadata can align region annotations to image frames, and this
// field preserves the original timestamps.
const char kUnmodifiedRegionTimestampKey[] = "region/unmodified_timestamp";

// Functions:
// These functions get and set bounding boxes as MediaPipe::Location to avoid
// needing to get and set each box coordinate separately.
int GetBBoxSize(const std::string& prefix,
                const tensorflow::SequenceExample& sequence);
std::vector<::mediapipe::Location> GetBBoxAt(
    const std::string& prefix, const tensorflow::SequenceExample& sequence,
    int index);
void AddBBox(const std::string& prefix,
             const std::vector<::mediapipe::Location>& bboxes,
             tensorflow::SequenceExample* sequence);
void ClearBBox(const std::string& prefix,
               tensorflow::SequenceExample* sequence);

// The input and output format is a pair of <y, x> coordinates to match the
// order of bounding box coordinates.
int GetPointSize(const std::string& prefix,
                 const tensorflow::SequenceExample& sequence);
std::vector<std::pair<float, float>> GetPointAt(
    const std::string& prefix, const tensorflow::SequenceExample& sequence,
    int index);
void AddPoint(const std::string& prefix,
              const std::vector<std::pair<float, float>>& points,
              tensorflow::SequenceExample* sequence);
void ClearPoint(const std::string& prefix,
                tensorflow::SequenceExample* sequence);

// The input and output format is a pair of <y, x> coordinates to match the
// order of bounding box coordinates.
int Get3dPointSize(const std::string& prefix,
                   const tensorflow::SequenceExample& sequence);
std::vector<std::tuple<float, float, float>> Get3dPointAt(
    const std::string& prefix, const tensorflow::SequenceExample& sequence,
    int index);
void Add3dPoint(const std::string& prefix,
                const std::vector<std::tuple<float, float, float>>& points,
                tensorflow::SequenceExample* sequence);
void Clear3dPoint(const std::string& prefix,
                  tensorflow::SequenceExample* sequence);
#define FIXED_PREFIX_BBOX_ACCESSORS(identifier, prefix)                        \
  inline int CONCAT_STR3(Get, identifier,                                      \
                         Size)(const tensorflow::SequenceExample& sequence) {  \
    return GetBBoxSize(prefix, sequence);                                      \
  }                                                                            \
  inline std::vector<::mediapipe::Location> CONCAT_STR3(Get, identifier, At)(  \
      const tensorflow::SequenceExample& sequence, int index) {                \
    return GetBBoxAt(prefix, sequence, index);                                 \
  }                                                                            \
  inline void CONCAT_STR2(Add, identifier)(                                    \
      const std::vector<::mediapipe::Location>& bboxes,                        \
      tensorflow::SequenceExample* sequence) {                                 \
    return AddBBox(prefix, bboxes, sequence);                                  \
  }                                                                            \
  inline void CONCAT_STR2(                                                     \
      Clear, identifier)(tensorflow::SequenceExample * sequence) {             \
    return ClearBBox(prefix, sequence);                                        \
  }                                                                            \
  inline int CONCAT_STR3(Get, identifier, PointSize)(                          \
      const tensorflow::SequenceExample& sequence) {                           \
    return GetPointSize(prefix, sequence);                                     \
  }                                                                            \
  inline int CONCAT_STR3(Get, identifier, PointSize)(                          \
      const std::string& name, const tensorflow::SequenceExample& sequence) {  \
    return GetPointSize(name, sequence);                                       \
  }                                                                            \
  inline std::vector<std::pair<float, float>> CONCAT_STR3(                     \
      Get, identifier, PointAt)(const tensorflow::SequenceExample& sequence,   \
                                int index) {                                   \
    return GetPointAt(prefix, sequence, index);                                \
  }                                                                            \
  inline std::vector<std::pair<float, float>> CONCAT_STR3(                     \
      Get, identifier, PointAt)(const std::string& name,                       \
                                const tensorflow::SequenceExample& sequence,   \
                                int index) {                                   \
    return GetPointAt(name, sequence, index);                                  \
  }                                                                            \
  inline void CONCAT_STR3(Add, identifier, Point)(                             \
      const std::vector<std::pair<float, float>>& points,                      \
      tensorflow::SequenceExample* sequence) {                                 \
    return AddPoint(prefix, points, sequence);                                 \
  }                                                                            \
  inline void CONCAT_STR3(Add, identifier, Point)(                             \
      const std::string& name,                                                 \
      const std::vector<std::pair<float, float>>& points,                      \
      tensorflow::SequenceExample* sequence) {                                 \
    return AddPoint(name, points, sequence);                                   \
  }                                                                            \
  inline void CONCAT_STR3(Clear, identifier,                                   \
                          Point)(tensorflow::SequenceExample * sequence) {     \
    return ClearPoint(prefix, sequence);                                       \
  }                                                                            \
  inline void CONCAT_STR3(Clear, identifier, Point)(                           \
      std::string name, tensorflow::SequenceExample * sequence) {              \
    return ClearPoint(name, sequence);                                         \
  }                                                                            \
  inline int CONCAT_STR3(Get, identifier, 3dPointSize)(                        \
      const tensorflow::SequenceExample& sequence) {                           \
    return Get3dPointSize(prefix, sequence);                                   \
  }                                                                            \
  inline int CONCAT_STR3(Get, identifier, 3dPointSize)(                        \
      const std::string& name, const tensorflow::SequenceExample& sequence) {  \
    return Get3dPointSize(name, sequence);                                     \
  }                                                                            \
  inline std::vector<std::tuple<float, float, float>> CONCAT_STR3(             \
      Get, identifier, 3dPointAt)(const tensorflow::SequenceExample& sequence, \
                                  int index) {                                 \
    return Get3dPointAt(prefix, sequence, index);                              \
  }                                                                            \
  inline std::vector<std::tuple<float, float, float>> CONCAT_STR3(             \
      Get, identifier, 3dPointAt)(const std::string& name,                     \
                                  const tensorflow::SequenceExample& sequence, \
                                  int index) {                                 \
    return Get3dPointAt(name, sequence, index);                                \
  }                                                                            \
  inline void CONCAT_STR3(Add, identifier, 3dPoint)(                           \
      const std::vector<std::tuple<float, float, float>>& points,              \
      tensorflow::SequenceExample* sequence) {                                 \
    return Add3dPoint(prefix, points, sequence);                               \
  }                                                                            \
  inline void CONCAT_STR3(Add, identifier, 3dPoint)(                           \
      const std::string& name,                                                 \
      const std::vector<std::tuple<float, float, float>>& points,              \
      tensorflow::SequenceExample* sequence) {                                 \
    return Add3dPoint(name, points, sequence);                                 \
  }                                                                            \
  inline void CONCAT_STR3(Clear, identifier,                                   \
                          3dPoint)(tensorflow::SequenceExample * sequence) {   \
    return Clear3dPoint(prefix, sequence);                                     \
  }                                                                            \
  inline void CONCAT_STR3(Clear, identifier, 3dPoint)(                         \
      std::string name, tensorflow::SequenceExample * sequence) {              \
    return Clear3dPoint(name, sequence);                                       \
  }

#define PREFIXED_BBOX(identifier, prefix)                                      \
  FIXED_PREFIX_BBOX_ACCESSORS(identifier, prefix)                              \
  FIXED_PREFIX_VECTOR_BYTES_FEATURE_LIST(CONCAT_STR2(identifier, LabelString), \
                                         kRegionLabelStringKey, prefix)        \
  FIXED_PREFIX_VECTOR_BYTES_FEATURE_LIST(CONCAT_STR2(identifier, ClassString), \
                                         kRegionClassStringKey, prefix)        \
  FIXED_PREFIX_VECTOR_BYTES_FEATURE_LIST(CONCAT_STR2(identifier, TrackString), \
                                         kRegionTrackStringKey, prefix)        \
  FIXED_PREFIX_VECTOR_INT64_FEATURE_LIST(CONCAT_STR2(identifier, LabelIndex),  \
                                         kRegionLabelIndexKey, prefix)         \
  FIXED_PREFIX_VECTOR_INT64_FEATURE_LIST(CONCAT_STR2(identifier, ClassIndex),  \
                                         kRegionClassIndexKey, prefix)         \
  FIXED_PREFIX_VECTOR_INT64_FEATURE_LIST(CONCAT_STR2(identifier, TrackIndex),  \
                                         kRegionTrackIndexKey, prefix)         \
  FIXED_PREFIX_VECTOR_FLOAT_FEATURE_LIST(                                      \
      CONCAT_STR2(identifier, LabelConfidence), kRegionLabelConfidenceKey,     \
      prefix)                                                                  \
  FIXED_PREFIX_VECTOR_FLOAT_FEATURE_LIST(                                      \
      CONCAT_STR2(identifier, ClassConfidence), kRegionClassConfidenceKey,     \
      prefix)                                                                  \
  FIXED_PREFIX_VECTOR_FLOAT_FEATURE_LIST(                                      \
      CONCAT_STR2(identifier, TrackConfidence), kRegionTrackConfidenceKey,     \
      prefix)                                                                  \
  FIXED_PREFIX_VECTOR_INT64_FEATURE_LIST(CONCAT_STR2(identifier, IsGenerated), \
                                         kRegionIsGeneratedKey, prefix)        \
  FIXED_PREFIX_VECTOR_INT64_FEATURE_LIST(CONCAT_STR2(identifier, IsOccluded),  \
                                         kRegionIsOccludedKey, prefix)         \
  FIXED_PREFIX_INT64_FEATURE_LIST(CONCAT_STR2(identifier, NumRegions),         \
                                  kRegionNumRegionsKey, prefix)                \
  FIXED_PREFIX_INT64_FEATURE_LIST(CONCAT_STR2(identifier, IsAnnotated),        \
                                  kRegionIsAnnotatedKey, prefix)               \
  FIXED_PREFIX_VECTOR_FLOAT_FEATURE_LIST(CONCAT_STR2(identifier, YMin),        \
                                         kRegionBBoxYMinKey, prefix)           \
  FIXED_PREFIX_VECTOR_FLOAT_FEATURE_LIST(CONCAT_STR2(identifier, XMin),        \
                                         kRegionBBoxXMinKey, prefix)           \
  FIXED_PREFIX_VECTOR_FLOAT_FEATURE_LIST(CONCAT_STR2(identifier, YMax),        \
                                         kRegionBBoxYMaxKey, prefix)           \
  FIXED_PREFIX_VECTOR_FLOAT_FEATURE_LIST(CONCAT_STR2(identifier, XMax),        \
                                         kRegionBBoxXMaxKey, prefix)           \
  FIXED_PREFIX_VECTOR_FLOAT_FEATURE_LIST(CONCAT_STR2(identifier, PointX),      \
                                         kRegionPointXKey, prefix)             \
  FIXED_PREFIX_VECTOR_FLOAT_FEATURE_LIST(CONCAT_STR2(identifier, PointY),      \
                                         kRegionPointYKey, prefix)             \
  FIXED_PREFIX_VECTOR_FLOAT_FEATURE_LIST(CONCAT_STR2(identifier, Radius),      \
                                         kRegionRadiusKey, prefix)             \
  FIXED_PREFIX_VECTOR_FLOAT_FEATURE_LIST(CONCAT_STR2(identifier, 3dPointX),    \
                                         kRegion3dPointXKey, prefix)           \
  FIXED_PREFIX_VECTOR_FLOAT_FEATURE_LIST(CONCAT_STR2(identifier, 3dPointY),    \
                                         kRegion3dPointYKey, prefix)           \
  FIXED_PREFIX_VECTOR_FLOAT_FEATURE_LIST(CONCAT_STR2(identifier, 3dPointZ),    \
                                         kRegion3dPointZKey, prefix)           \
  FIXED_PREFIX_VECTOR_FLOAT_FEATURE_LIST(                                      \
      CONCAT_STR2(identifier, EmbeddingFloats), kRegionEmbeddingFloatKey,      \
      prefix)                                                                  \
  FIXED_PREFIX_VECTOR_BYTES_FEATURE_LIST(                                      \
      CONCAT_STR2(identifier, EmbeddingEncoded), kRegionEmbeddingEncodedKey,   \
      prefix)                                                                  \
  FIXED_PREFIX_VECTOR_FLOAT_FEATURE_LIST(                                      \
      CONCAT_STR2(identifier, EmbeddingConfidence),                            \
      kRegionEmbeddingConfidenceKey, prefix)                                   \
  FIXED_PREFIX_VECTOR_INT64_CONTEXT_FEATURE(                                   \
      CONCAT_STR2(identifier, EmbeddingDimensionsPerRegion),                   \
      kRegionEmbeddingDimensionsPerRegionKey, prefix)                          \
  FIXED_PREFIX_BYTES_CONTEXT_FEATURE(CONCAT_STR2(identifier, EmbeddingFormat), \
                                     kRegionEmbeddingFormatKey, prefix)        \
  FIXED_PREFIX_VECTOR_BYTES_CONTEXT_FEATURE(CONCAT_STR2(identifier, Parts),    \
                                            kRegionPartsKey, prefix)           \
  FIXED_PREFIX_INT64_FEATURE_LIST(CONCAT_STR2(identifier, Timestamp),          \
                                  kRegionTimestampKey, prefix)                 \
  FIXED_PREFIX_INT64_FEATURE_LIST(                                             \
      CONCAT_STR3(Unmodified, identifier, Timestamp),                          \
      kUnmodifiedRegionTimestampKey, prefix)

// Provides suites of functions for working with bounding boxes and predicted
// bounding boxes such as
// GetBBoxNumBoxes, GetBBoxSize, GetBBoxAt, GetBBoxLabelIndexAt, etc., and
// GetPredictedBBoxNumBoxes, GetPredictedBBoxSize, GetPredictedBBoxAt, etc.
const char kPredictedPrefix[] = "PREDICTED";
PREFIXED_BBOX(BBox, "");
PREFIXED_BBOX(PredictedBBox, kPredictedPrefix);

// ************************    IMAGES    **************************************
// Context keys:
// The format the images are encoded as (e.g. "JPEG", "PNG")
const char kImageFormatKey[] = "image/format";
// The number of channels in the image.
const char kImageChannelsKey[] = "image/channels";
// The colorspace of the image.
const char kImageColorspaceKey[] = "image/colorspace";
// The height of the image in pixels.
const char kImageHeightKey[] = "image/height";
// The width of the image in pixels.
const char kImageWidthKey[] = "image/width";
// The frame rate in images/second of media.
const char kImageFrameRateKey[] = "image/frame_rate";
// The maximum value if the images were saturated and normalized for encoding.
const char kImageSaturationKey[] = "image/saturation";
// The listing from discrete image values (as indices) to class indices.
const char kImageClassLabelIndexKey[] = "image/class/label/index";
// The listing from discrete image values (as indices) to class strings.
const char kImageClassLabelStringKey[] = "image/class/label/string";
// The listing from discrete instance indices to class indices they embody.
const char kImageObjectClassIndexKey[] = "image/object/class/index";
// The path of the image file if it did not come from a media clip.
const char kImageDataPathKey[] = "image/data_path";

// Feature list keys:
// The encoded image frame.
const char kImageEncodedKey[] = "image/encoded";
// Multiple images for the same timestep (e.g. multiview video).
const char kImageMultiEncodedKey[] = "image/multi_encoded";
// The timestamp of the frame in microseconds.
const char kImageTimestampKey[] = "image/timestamp";
// A per image label if specific frames have labels.
// If time spans have labels, segments are preferred to allow changing rates.
const char kImageLabelIndexKey[] = "image/label/index";
const char kImageLabelStringKey[] = "image/label/string";
const char kImageLabelConfidenceKey[] = "image/label/confidence";

#define PREFIXED_IMAGE(identifier, prefix)                                     \
  FIXED_PREFIX_INT64_CONTEXT_FEATURE(CONCAT_STR2(identifier, Height),          \
                                     kImageHeightKey, prefix)                  \
  FIXED_PREFIX_INT64_CONTEXT_FEATURE(CONCAT_STR2(identifier, Width),           \
                                     kImageWidthKey, prefix)                   \
  FIXED_PREFIX_INT64_CONTEXT_FEATURE(CONCAT_STR2(identifier, Channels),        \
                                     kImageChannelsKey, prefix)                \
  FIXED_PREFIX_BYTES_CONTEXT_FEATURE(CONCAT_STR2(identifier, Format),          \
                                     kImageFormatKey, prefix)                  \
  FIXED_PREFIX_BYTES_CONTEXT_FEATURE(CONCAT_STR2(identifier, Colorspace),      \
                                     kImageColorspaceKey, prefix)              \
  FIXED_PREFIX_FLOAT_CONTEXT_FEATURE(CONCAT_STR2(identifier, FrameRate),       \
                                     kImageFrameRateKey, prefix)               \
  FIXED_PREFIX_FLOAT_CONTEXT_FEATURE(CONCAT_STR2(identifier, Saturation),      \
                                     kImageSaturationKey, prefix)              \
  FIXED_PREFIX_BYTES_CONTEXT_FEATURE(CONCAT_STR2(identifier, DataPath),        \
                                     kImageDataPathKey, prefix)                \
  FIXED_PREFIX_VECTOR_INT64_CONTEXT_FEATURE(                                   \
      CONCAT_STR2(identifier, ClassLabelIndex), kImageClassLabelIndexKey,      \
      prefix)                                                                  \
  FIXED_PREFIX_VECTOR_BYTES_CONTEXT_FEATURE(                                   \
      CONCAT_STR2(identifier, ClassLabelString), kImageClassLabelStringKey,    \
      prefix)                                                                  \
  FIXED_PREFIX_VECTOR_INT64_CONTEXT_FEATURE(                                   \
      CONCAT_STR2(identifier, ObjectClassIndex), kImageObjectClassIndexKey,    \
      prefix)                                                                  \
  FIXED_PREFIX_BYTES_FEATURE_LIST(CONCAT_STR2(identifier, Encoded),            \
                                  kImageEncodedKey, prefix)                    \
  FIXED_PREFIX_VECTOR_BYTES_FEATURE_LIST(                                      \
      CONCAT_STR2(identifier, MultiEncoded), kImageMultiEncodedKey, prefix)    \
  FIXED_PREFIX_INT64_FEATURE_LIST(CONCAT_STR2(identifier, Timestamp),          \
                                  kImageTimestampKey, prefix)                  \
  FIXED_PREFIX_VECTOR_INT64_FEATURE_LIST(CONCAT_STR2(identifier, LabelIndex),  \
                                         kImageLabelIndexKey, prefix)          \
  FIXED_PREFIX_VECTOR_BYTES_FEATURE_LIST(CONCAT_STR2(identifier, LabelString), \
                                         kImageLabelStringKey, prefix)         \
  FIXED_PREFIX_VECTOR_FLOAT_FEATURE_LIST(                                      \
      CONCAT_STR2(identifier, LabelConfidence), kImageLabelConfidenceKey,      \
      prefix)

// Provides suites of functions for working with images and data encoded in
// images such as
// AddImageEncoded, GetImageEncodedAt, AddImageTimestamp, GetImageHeight, etc.,
// AddForwardFlowEncoded, GetForwardFlowEncodedAt, AddForwardFlowTimestamp, etc.
// AddClassSegmentationEncoded, GetClassSegmentationEncodedAt, etc., and
// AddInstanceSegmentationEncoded, GetInstanceSegmentationEncodedAt, etc.
const char kForwardFlowPrefix[] = "FORWARD_FLOW";
const char kClassSegmentationPrefix[] = "CLASS_SEGMENTATION";
const char kInstanceSegmentationPrefix[] = "INSTANCE_SEGMENTATION";
PREFIXED_IMAGE(Image, "");
PREFIXED_IMAGE(ForwardFlow, kForwardFlowPrefix);
PREFIXED_IMAGE(ClassSegmentation, kClassSegmentationPrefix);
PREFIXED_IMAGE(InstanceSegmentation, kInstanceSegmentationPrefix);

// **************************   TEXT   ****************************************
// Context keys:
// Which language text tokens are likely to be in.
const char kTextLanguageKey[] = "text/language";
// A large block of text that applies to the media.
const char kTextContextContentKey[] = "text/context/content";

// Feature list keys:
// The text contents for a given time.
const char kTextContentKey[] = "text/content";
// The start time for the text becoming relevant.
const char kTextTimestampKey[] = "text/timestamp";
// The duration where the text is relevant.
const char kTextDurationKey[] = "text/duration";
// The confidence that this is the correct text.
const char kTextConfidenceKey[] = "text/confidence";
// A floating point embedding corresponding to the text.
const char kTextEmbeddingKey[] = "text/embedding";
// An integer id corresponding to the text.
const char kTextTokenIdKey[] = "text/token/id";

BYTES_CONTEXT_FEATURE(TextLanguage, kTextLanguageKey);
BYTES_CONTEXT_FEATURE(TextContextContent, kTextContextContentKey);
BYTES_FEATURE_LIST(TextContent, kTextContentKey);
INT64_FEATURE_LIST(TextTimestamp, kTextTimestampKey);
INT64_FEATURE_LIST(TextDuration, kTextDurationKey);
FLOAT_FEATURE_LIST(TextConfidence, kTextConfidenceKey);
VECTOR_FLOAT_FEATURE_LIST(TextEmbedding, kTextEmbeddingKey);
INT64_FEATURE_LIST(TextTokenId, kTextTokenIdKey);

// ***********************    FEATURES    *************************************
// Context keys:
// The dimensions of the feature.
const char kFeatureDimensionsKey[] = "feature/dimensions";
// The rate the features are extracted per second of media.
const char kFeatureRateKey[] = "feature/rate";
// The encoding format if any for the feature.
const char kFeatureBytesFormatKey[] = "feature/bytes/format";
// For audio, the rate the samples are extracted per second of media.
const char kFeatureSampleRateKey[] = "feature/sample_rate";
// For audio, the number of channels per extracted feature.
const char kFeatureNumChannelsKey[] = "feature/num_channels";
// For audio, the number of samples per extracted feature.
const char kFeatureNumSamplesKey[] = "feature/num_samples";
// For audio, the rate the features are extracted per second of media.
const char kFeaturePacketRateKey[] = "feature/packet_rate";
// For audio, the original audio sampling rate the feature is derived from.
const char kFeatureAudioSampleRateKey[] = "feature/audio_sample_rate";
// The feature as a list of floats.
const char kContextFeatureFloatsKey[] = "context_feature/floats";
// The feature as a list of floats.
const char kContextFeatureBytesKey[] = "context_feature/bytes";
// The feature as a list of floats.
const char kContextFeatureIntsKey[] = "context_feature/ints";

// Feature list keys:
// The feature as a list of floats.
const char kFeatureFloatsKey[] = "feature/floats";
// The feature as a list of bytes. May be encoded.
const char kFeatureBytesKey[] = "feature/bytes";
// The feature as a list of ints.
const char kFeatureIntsKey[] = "feature/ints";
// The timestamp, in microseconds, of the feature.
const char kFeatureTimestampKey[] = "feature/timestamp";

// It is occasionally useful to indicate that a feature applies to a given
// range. This should be used for features only and annotations should be
// provided as segments.
const char kFeatureDurationKey[] = "feature/duration";
// Encodes an optional confidence score for generated features.
const char kFeatureConfidenceKey[] = "feature/confidence";

// Functions:

// Returns/sets a MediaPipe::Matrix for the stream with that prefix.
std::unique_ptr<mediapipe::Matrix> GetAudioFromFeatureAt(
    const std::string& prefix, const tensorflow::SequenceExample& sequence,
    int index);
void AddAudioAsFeature(const std::string& prefix,
                       const mediapipe::Matrix& audio,
                       tensorflow::SequenceExample* sequence);

PREFIXED_VECTOR_INT64_CONTEXT_FEATURE(FeatureDimensions, kFeatureDimensionsKey);
PREFIXED_FLOAT_CONTEXT_FEATURE(FeatureRate, kFeatureRateKey);
PREFIXED_VECTOR_FLOAT_CONTEXT_FEATURE(ContextFeatureFloats,
                                      kContextFeatureFloatsKey);
PREFIXED_VECTOR_BYTES_CONTEXT_FEATURE(ContextFeatureBytes,
                                      kContextFeatureBytesKey);
PREFIXED_VECTOR_INT64_CONTEXT_FEATURE(ContextFeatureInts,
                                      kContextFeatureIntsKey);
PREFIXED_BYTES_CONTEXT_FEATURE(FeatureBytesFormat, kFeatureBytesFormatKey);
PREFIXED_VECTOR_FLOAT_FEATURE_LIST(FeatureFloats, kFeatureFloatsKey);
PREFIXED_VECTOR_BYTES_FEATURE_LIST(FeatureBytes, kFeatureBytesKey);
PREFIXED_VECTOR_INT64_FEATURE_LIST(FeatureInts, kFeatureIntsKey);
PREFIXED_INT64_FEATURE_LIST(FeatureTimestamp, kFeatureTimestampKey);
PREFIXED_VECTOR_INT64_FEATURE_LIST(FeatureDuration, kFeatureDurationKey);
PREFIXED_VECTOR_FLOAT_FEATURE_LIST(FeatureConfidence, kFeatureConfidenceKey);

PREFIXED_FLOAT_CONTEXT_FEATURE(FeatureSampleRate, kFeatureSampleRateKey);
PREFIXED_INT64_CONTEXT_FEATURE(FeatureNumChannels, kFeatureNumChannelsKey);
PREFIXED_INT64_CONTEXT_FEATURE(FeatureNumSamples, kFeatureNumSamplesKey);
PREFIXED_FLOAT_CONTEXT_FEATURE(FeaturePacketRate, kFeaturePacketRateKey);
PREFIXED_FLOAT_CONTEXT_FEATURE(FeatureAudioSampleRate,
                               kFeatureAudioSampleRateKey);

// Modifies the context features to match the metadata of the features in the
// sequences. Specifically, it sets the frame indices corresponding to the
// timestamps in the label meta data based on the image timestamps. For
// encoded images, encoded optical flow, and encoded human pose puppets the
// image format, height, width, channels, and frame rate are written as
// metadata. For float feature lists, the frame rate and dimensions are
// calculated. If the float feature dimensions are already present, then the
// code verifies the number of elements matches the dimensions.
// Reconciling bounding box annotations is optional because will remove
// annotations if the sequence rate is lower than the annotation rate.
absl::Status ReconcileMetadata(bool reconcile_bbox_annotations,
                               bool reconcile_region_annotations,
                               tensorflow::SequenceExample* sequence);
}  // namespace mediasequence
}  // namespace mediapipe

#endif  // MEDIAPIPE_TENSORFLOW_SEQUENCE_MEDIA_SEQUENCE_H_


text:
<bill session="115" type="s" number="981" updated="2017-09-11T02:59:56Z">
  <state datetime="2017-04-27">REFERRED</state>
  <status>
    <introduced datetime="2017-04-27"/>
  </status>
  <introduced datetime="2017-04-27"/>
  <titles>
    <title type="official" as="introduced">A bill to require the Secretary of Energy to establish an energy efficiency materials pilot program.</title>
    <title type="display">A bill to require the Secretary of Energy to establish an energy efficiency materials pilot program.</title>
  </titles>
  <sponsor bioguide_id="K000367"/>
  <cosponsors>
    <cosponsor bioguide_id="C001070" joined="2017-07-17"/>
    <cosponsor bioguide_id="E000295" joined="2017-05-25"/>
    <cosponsor bioguide_id="H001061" joined="2017-04-27"/>
    <cosponsor bioguide_id="S000770" joined="2017-06-15"/>
  </cosponsors>
  <actions>
    <action datetime="2017-04-27">
      <text>Introduced in Senate</text>
    </action>
    <action datetime="2017-04-27" state="REFERRED">
      <text>Read twice and referred to the Committee on Energy and Natural Resources.</text>
    </action>
  </actions>
  <committees>
    <committee subcommittee="" code="SSEG" name="Senate Energy and Natural Resources" activity="Referral"/>
  </committees>
  <relatedbills>
    <bill type="h" session="115" relation="identical" number="2197"/>
  </relatedbills>
  <subjects>
    <term name="Energy"/>
    <term name="Building construction"/>
    <term name="Educational facilities and institutions"/>
    <term name="Energy efficiency and conservation"/>
    <term name="Health facilities and institutions"/>
    <term name="Materials"/>
    <term name="Social work, volunteer service, charitable organizations"/>
    <term name="Tax-exempt organizations"/>
  </subjects>
  <amendments/>
  <committee-reports/>
</bill>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Serenity.Net
{
    public enum ConnectionListenerState
    {
        Faulted = -1,
        Stopped = 0,
        Stopping = 1,
        Initializing = 2,
        Initialized = 3,
        Starting = 4,
        Started = 5,
    }
}


text:
/* jshint undef: true, unused: true */
/*global angular */
(function () {
	'use strict';

	angular.module('todoFocus', [])

	/**
	 * Directive that places focus on the element it is applied to when the expression it binds to evaluates to true
	 */
	.directive('todoFocus', function ($timeout) {
		return function (scope, elem, attrs) {
			scope.$watch(attrs.todoFocus, function (newVal) {
				if (newVal) {
					$timeout(function () {
						elem[0].focus();
					}, 0, false);
				}
			});
		};
	});
})();


text:
package com.example.sp2014f_testpro2;

public class MainTest {

}


text:
using System;
using Nalarium;

namespace NetInterop.Routing.Core
{
    public struct TypeOrLength : IHeader, IReversable
    {
        public byte Segment1;
        public byte Segment2;

        #region IReversable Members

        public byte[] GetBytes()
        {
            return GetBytes(this);
        }

        #endregion

        public static TypeOrLength From(byte[] array)
        {
            if (array == null)
            {
                return new TypeOrLength();
            }
            return new TypeOrLength
                   {
                       Segment1 = array[0],
                       Segment2 = array[1]
                   };
        }

        public static byte[] GetBytes(TypeOrLength typeOrLength)
        {
            var array = new byte[2];
            array[0] = typeOrLength.Segment1;
            array[1] = typeOrLength.Segment2;
            return array;
        }

        public override String ToString()
        {
            return PairAndSeriesBuilder.CreateSeries(this);
        }
    }
}


text:
package twoverse.gui;

import processing.core.PApplet;
import processing.core.PFont;
import twoverse.util.Point;

/**
 * Rectangular implementation of Button.
 *
 * @author Christopher Peplin (chris.peplin@rhubarbtech.com)
 * @version 1.0, Copyright 2009 under Apache License
 */
public class RectButton extends Button {
    private int mWidth;
    private int mHeight;
    private PFont mFont;

    private void setFont(PFont font) {
        mFont = font;
    }

    private void drawNormal() {
        mParentApplet.pushMatrix();
        mParentApplet.translate(-mParentApplet.width / 2,
                -mParentApplet.height / 2);
        mParentApplet.stroke(0);
        mParentApplet.fill(getBaseColor());
        mParentApplet.rect((float) getCorner().getX(),
                (float) getCorner().getY(),
                getWidth(),
                getHeight());
        label();
        mParentApplet.popMatrix();
    }

    private void drawHighlight() {
        if(isVisible()) {
            mParentApplet.pushMatrix();
            mParentApplet.translate(-mParentApplet.width / 2,
                    -mParentApplet.height / 2);
            mParentApplet.stroke(0);
            mParentApplet.fill(getHighlightColor());
            mParentApplet.rect((float) getCorner().getX(),
                    (float) getCorner().getY(),
                    getWidth(),
                    getHeight());
            label();
            mParentApplet.popMatrix();
        }
    }

    private void label() {
        mParentApplet.textFont(mFont, 24);
        mParentApplet.fill(255);
        mParentApplet.text(getName(),
                (float) getCorner().getX(),
                (float) getCorner().getY() - 5);
    }

    /**
     * Construct a new RectangleButton.
     *
     * @param width
     *            width of the rectangle
     * @param height
     *            height of the rectangle
     * @param font
     *            font to use for display text
     */
    public RectButton(PApplet parentApplet, Point center, int baseColor,
            int highlightColor, String name, int width, int height, PFont font) {
        super(parentApplet, center, baseColor, highlightColor, name);
        setWidth(width);
        setHeight(height);
        setFont(font);
    }

    @Override
    public boolean isPressed(Point cursor) {
        return overRect(cursor, getCorner(), mWidth, mHeight) && isVisible();
    }

    /**
     * Displays the button on the screen if it is marked as visible.
     *
     * If locked or pressed, uses the highlight color. Otherwise uses the normal
     * color.
     *
     * @param cursor
     *            position of cursor, to check if the button is pressed
     */
    public void display(Point cursor) {
        if(isVisible()) {
            if(isPressed(cursor) || isLocked()) {
                drawHighlight();
            } else {
                drawNormal();
            }
        }
    }

    public void setWidth(int width) {
        mWidth = width;
    }

    public int getWidth() {
        return mWidth;
    }

    public void setHeight(int height) {
        mHeight = height;
    }

    public int getHeight() {
        return mHeight;
    }
}


text:
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
/**
 * @author mortent
 */
@ExportPackage
@PublicApi
package com.yahoo.container.jdisc.athenz;

import com.yahoo.api.annotations.PublicApi;
import com.yahoo.osgi.annotation.ExportPackage;


text:
package ssa

// tighten moves Values closer to the Blocks in which they are used.
// This can reduce the amount of register spilling required,
// if it doesn't also create more live values.
// A Value can be moved to any block that
// dominates all blocks in which it is used.
func tighten(f *Func) {
	canMove := make([]bool, f.NumValues())
	for _, b := range f.Blocks {
		for _, v := range b.Values {
			switch v.Op {
			case OpPhi, OpGetClosurePtr, OpArg, OpSelect0, OpSelect1:
				// Phis need to stay in their block.
				// GetClosurePtr & Arg must stay in the entry block.
				// Tuple selectors must stay with the tuple generator.
				continue
			}
			if len(v.Args) > 0 && v.Args[len(v.Args)-1].Type.IsMemory() {
				// We can't move values which have a memory arg - it might
				// make two memory values live across a block boundary.
				continue
			}
			// Count arguments which will need a register.
			narg := 0
			for _, a := range v.Args {
				switch a.Op {
				case OpConst8, OpConst16, OpConst32, OpConst64, OpAddr:
					// Probably foldable into v, don't count as an argument needing a register.
					// TODO: move tighten to a machine-dependent phase and use v.rematerializeable()?
				default:
					narg++
				}
			}
			if narg >= 2 && !v.Type.IsBoolean() {
				// Don't move values with more than one input, as that may
				// increase register pressure.
				// We make an exception for boolean-typed values, as they will
				// likely be converted to flags, and we want flag generators
				// moved next to uses (because we only have 1 flag register).
				continue
			}
			canMove[v.ID] = true
		}
	}

	// Build data structure for fast least-common-ancestor queries.
	lca := makeLCArange(f)

	// For each moveable value, record the block that dominates all uses found so far.
	target := make([]*Block, f.NumValues())

	// Grab loop information.
	// We use this to make sure we don't tighten a value into a (deeper) loop.
	idom := f.Idom()
	loops := f.loopnest()
	loops.calculateDepths()

	changed := true
	for changed {
		changed = false

		// Reset target
		for i := range target {
			target[i] = nil
		}

		// Compute target locations (for moveable values only).
		// target location = the least common ancestor of all uses in the dominator tree.
		for _, b := range f.Blocks {
			for _, v := range b.Values {
				for i, a := range v.Args {
					if !canMove[a.ID] {
						continue
					}
					use := b
					if v.Op == OpPhi {
						use = b.Preds[i].b
					}
					if target[a.ID] == nil {
						target[a.ID] = use
					} else {
						target[a.ID] = lca.find(target[a.ID], use)
					}
				}
			}
			if c := b.Control; c != nil {
				if !canMove[c.ID] {
					continue
				}
				if target[c.ID] == nil {
					target[c.ID] = b
				} else {
					target[c.ID] = lca.find(target[c.ID], b)
				}
			}
		}

		// If the target location is inside a loop,
		// move the target location up to just before the loop head.
		for _, b := range f.Blocks {
			origloop := loops.b2l[b.ID]
			for _, v := range b.Values {
				t := target[v.ID]
				if t == nil {
					continue
				}
				targetloop := loops.b2l[t.ID]
				for targetloop != nil && (origloop == nil || targetloop.depth > origloop.depth) {
					t = idom[targetloop.header.ID]
					target[v.ID] = t
					targetloop = loops.b2l[t.ID]
				}
			}
		}

		// Move values to target locations.
		for _, b := range f.Blocks {
			for i := 0; i < len(b.Values); i++ {
				v := b.Values[i]
				t := target[v.ID]
				if t == nil || t == b {
					// v is not moveable, or is already in correct place.
					continue
				}
				// Move v to the block which dominates its uses.
				t.Values = append(t.Values, v)
				v.Block = t
				last := len(b.Values) - 1
				b.Values[i] = b.Values[last]
				b.Values[last] = nil
				b.Values = b.Values[:last]
				changed = true
				i--
			}
		}
	}
}

// phiTighten moves constants closer to phi users.
// This pass avoids having lots of constants live for lots of the program.
// See issue 16407.
func phiTighten(f *Func) {
	for _, b := range f.Blocks {
		for _, v := range b.Values {
			if v.Op != OpPhi {
				continue
			}
			for i, a := range v.Args {
				if !a.rematerializeable() {
					continue // not a constant we can move around
				}
				if a.Block == b.Preds[i].b {
					continue // already in the right place
				}
				// Make a copy of a, put in predecessor block.
				v.SetArg(i, a.copyInto(b.Preds[i].b))
			}
		}
	}
}


text:
<?php

namespace Jad\Tests;

use Jad\Database\Manager;
use PHPUnit\Framework\TestCase as PHPUnitTestCase;
use Jad\Configure;

class TestCase extends PHPUnitTestCase
{
    /**
     * @throws \Doctrine\Common\Persistence\Mapping\MappingException
     */
    protected function setUp(): void
    {
        parent::setUp();
        Configure::getInstance()->setConfig('test_mode', true);
        Configure::getInstance()->setConfig('strict', true);

        Manager::getInstance()->getEm()->clear();
        $_GET = [];
        $_SERVER['REQUEST_URI']  = '';
        $_SERVER['REQUEST_METHOD']  = 'GET';
    }

    /**
     * @before
     */
    public function setupTestDatabase()
    {
        system('cp tests/fixtures/test_db_origin.sqlite tests/fixtures/test_db.sqlite ');
    }

    /**
     * @param $className
     * @param $methodName
     * @return \ReflectionMethod
     * @throws \ReflectionException
     */
    protected static function getMethod($className, $methodName) {
        $class = new \ReflectionClass($className);
        $method = $class->getMethod($methodName);
        $method->setAccessible(true);
        return $method;
    }

    /**
     * @param $className
     * @param array $options
     * @return \PHPUnit_Framework_MockObject_MockObject
     */
    protected function getClassMock($className, array $options = [])
    {
        $mock = $this->getMockBuilder($className)
            ->setMethods(array_keys($options))
            ->getMock();

        foreach($options as $method => $value) {
            $mock->expects($this->any())
                ->method($method)
                ->will($this->returnValue($value));
        }

        return $mock;
    }

    /**
     * @param $className
     * @param $property
     * @param $value
     * @throws \ReflectionException
     */
    public function setProtectedProperty($className, $property, $value)
    {
        $reflection = new \ReflectionClass($className);
        $reflection_property = $reflection->getProperty($property);
        $reflection_property->setAccessible(true);
        $reflection_property->setValue($className, $value);
    }
}