text:
import numpy as np

def gradient(mzs, intensities, **opt_args):
    function_args = {'max_output': -1, 'weighted_bins': 1, 'min_intensity': 1e-5,'grad_type':'gradient'}
    for key, val in opt_args.iteritems():
        if key in function_args.keys():
            function_args[key] = val
        else:
            print 'possible arguments:'
            for i in function_args.keys():
                print i
            raise NameError('gradient does not take argument: %s' % (key))
    mzMaxNum = function_args['max_output']
    weighted_bins = function_args['weighted_bins']
    min_intensity = function_args['min_intensity']
    gradient_type=function_args['grad_type']
    assert mzMaxNum < len(mzs)
    assert len(mzs)==len(intensities)
    assert weighted_bins < len(mzs)/2.
    # calc first&sectond differential
    if gradient_type == 'gradient':
        MZgrad = np.gradient(intensities)
        MZgrad2 = np.gradient(MZgrad)[0:-1]
    elif gradient_type == 'diff':
        MZgrad = np.concatenate((np.diff(intensities),[1]))
        MZgrad2 = np.diff(MZgrad)
    else:
        raise ValueError('gradient type {} not known'.format(gradient_type))
    # detect crossing points
    cPoint = MZgrad[0:-1] * MZgrad[1:] <= 0
    mPoint = MZgrad2<0
    indices = cPoint & mPoint
    # bool->list of indices
    # Could check left/right of crossing point
    indices_list_l = np.transpose(np.where(indices==True))
    indices_list_r = indices_list_l+1
    intensites_list_l=intensities[indices_list_l]
    intensites_list_r=intensities[indices_list_r]
    indices_list = np.zeros((len(intensites_list_l),1),dtype=int)
    for ii in range(0,len(intensites_list_l)):
        if intensites_list_l[ii] > intensites_list_r[ii]:
            indices_list[ii] = indices_list_l[ii]
        else:
            indices_list[ii] = indices_list_r[ii]
    indices_list=np.unique(np.asarray(indices_list))
    # Remove any 'peaks' that aren't real
    indices_list = indices_list[intensities[indices_list] > min_intensity]
    # Select the peaks
    intensities_list = intensities[indices_list]
    mzs_list = mzs[indices_list]
    # Tidy up if required
    if mzMaxNum > 0:
        if len(mzs_list) > mzMaxNum:
            sort_idx = np.argsort(intensities_list)
            intensities_list = intensities_list[sort_idx[-mzMaxNum:]]
            mzs_list = mzs_list[sort_idx[-mzMaxNum:]]
            indices_list = indices_list[sort_idx[-mzMaxNum:]]
        elif len(mzs) < mzMaxNum:
            lengthDiff = mzMaxNum - len(indices_list)
            mzs_list = np.concatenate((mzs_list, np.zeros((lengthDiff, 1))))
            intensities_list = np.concatenate((intensities_list, np.zeros((lengthDiff, 1))))
            indices_list = np.concatenate((indices_list, np.zeros((lengthDiff, 1))))
    if weighted_bins > 0:
        # check no peaks within bin width of spectrum edge
        good_idx = (indices_list > weighted_bins) & (indices_list < (len(mzs) - weighted_bins))
        mzs_list = mzs_list[good_idx]
        intensities_list = intensities_list[good_idx]
        indices_list = indices_list[good_idx]
        bin_shift = range(-weighted_bins, weighted_bins + 1)
        for ii in range(0, len(mzs_list)):
            bin_idx = bin_shift + indices_list[ii]
            mzs_list[ii] = np.average(mzs[bin_idx], weights=intensities[bin_idx])
            indices_list[ii] = indices_list[ii] + np.argmax(intensities[bin_idx]) - (1+weighted_bins)/2
            intensities_list[ii] = intensities[indices_list[ii]]
            # mzs_list[ii] = np.mean(mzs[bin_idx])
    return (mzs_list, intensities_list, indices_list)


text:
namespace ash {

namespace wm {
// Returns the window-modal transient child of |window|, or NULL if |window|
// does not have any window-modal transient children.
ASH_EXPORT aura::Window* GetWindowModalTransient(aura::Window* window);
}

namespace internal {

// WindowModalityController is an event filter that consumes events sent to
// windows that are the transient parents of window-modal windows. This filter
// must be added to the RootWindowEventFilter so that activation works properly.
class WindowModalityController : public aura::EventFilter {
 public:
  WindowModalityController();
  virtual ~WindowModalityController();

  // Overridden from aura::EventFilter:
  virtual bool PreHandleKeyEvent(aura::Window* target,
                                 aura::KeyEvent* event) OVERRIDE;
  virtual bool PreHandleMouseEvent(aura::Window* target,
                                   aura::MouseEvent* event) OVERRIDE;
  virtual ui::TouchStatus PreHandleTouchEvent(aura::Window* target,
                                              aura::TouchEvent* event) OVERRIDE;
  virtual ui::GestureStatus PreHandleGestureEvent(
      aura::Window* target,
      aura::GestureEvent* event) OVERRIDE;

 private:
  DISALLOW_COPY_AND_ASSIGN(WindowModalityController);
};

}  // namespace internal
}  // namespace ash

#endif  // ASH_WM_WINDOW_MODALITY_CONTROLLER_H_

redpajama_set_name: RedPajamaGithub


text:
PACKAGE_NAME="serf"
PACKAGE_VERSION=${1:-v0.9.5}
PACKAGE_URL="https://github.com/hashicorp/serf.git"

#need to start your container as

docker run -itd --name serf --privileged --network host registry.access.redhat.com/ubi8/ubi:8.5 /sbin/init

#Then run below commands

yum install -y git wget gcc make syslog
systemctl start rsyslog

GO_VERSION=1.14
wget https://golang.org/dl/go$GO_VERSION.linux-ppc64le.tar.gz
tar -C /bin -xf go$GO_VERSION.linux-ppc64le.tar.gz
rm -f go$GO_VERSION.linux-ppc64le.tar.gz
export PATH=$PATH:/bin/go/bin
export GOPATH=/home/tester/go
export PATH=$GOPATH/bin:$PATH
export GO111MODULE=on

mkdir -p /home/tester/go/src/github.com
cd /home/tester/go/src/github.com
git clone $PACKAGE_URL
cd serf/

git checkout $PACKAGE_VERSION
go get gotest.tools/gotestsum@latest
gotestsum --format=short-verbose --junitfile ../gotestsum-report.xml -- ./...

#Build and Test pass
#This should be the output of the test in case of success:

#PASS serf.TestSnapshotter_slowDiskNotBlockingEventCh (0.11s)
#PASS serf.TestSnapshotter_blockedUpstreamNotBlockingMemberlist (0.03s)
#PASS serf.TestBroadcastFinished_nilNotify (0.00s)
#PASS serf.TestBroadcastFinished (0.00s)
#PASS serf
#EMPTY version
#DONE 255 tests in 43.843s


text:
package tmdb

import (
	. "gopkg.in/check.v1"
)

const columbiaID int = 5

func (s *TmdbSuite) TestGetCompanyInfo(c *C) {
	company, err := s.tmdb.GetCompanyInfo(columbiaID, nil)
	s.baseTest(&company, err, c)
	c.Assert(company.ID, Equals, columbiaID)
	c.Assert(company.Name, Equals, "Columbia Pictures")
	c.Assert(company.Movies, Not(NotNil))

	var options = make(map[string]string)
	options["append_to_response"] = "movies"
	companyMovies, err := s.tmdb.GetCompanyInfo(columbiaID, options)
	s.baseTest(&companyMovies, err, c)
	c.Assert(companyMovies.ID, Equals, columbiaID)
	c.Assert(companyMovies.Name, Equals, "Columbia Pictures")
	c.Assert(companyMovies.Movies, NotNil)
}

func (s *TmdbSuite) TestGetCompanyMovies(c *C) {
	movies, err := s.tmdb.GetCompanyMovies(columbiaID, nil)
	s.baseTest(&movies, err, c)
	c.Assert(movies.ID, Equals, columbiaID)
	c.Assert(movies.Page, Equals, 1)
	c.Assert(movies.TotalPages > 20, Equals, true)
	c.Assert(movies.TotalResults > 400, Equals, true)
	c.Assert(movies.Results, NotNil)
	c.Assert(movies.Results, Not(HasLen), 0)

	var options = make(map[string]string)
	options["page"] = "2"
	moviesPage2, err := s.tmdb.GetCompanyMovies(columbiaID, options)
	s.baseTest(&moviesPage2, err, c)
	c.Assert(moviesPage2.ID, Equals, columbiaID)
	c.Assert(moviesPage2.Page, Equals, 2)
	c.Assert(moviesPage2.TotalPages > 20, Equals, true)
	c.Assert(moviesPage2.TotalResults > 400, Equals, true)
	c.Assert(moviesPage2.Results, NotNil)
	c.Assert(moviesPage2.Results, Not(HasLen), 0)
}


text: from cassandra.datastax.graph import *


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Portfolio - Katherine Choi</title>

    <link rel="stylesheet" href="css/bootstrap.min.css" type="text/css">

    <link href='http://fonts.googleapis.com/css?family=Lato:100,300' rel='stylesheet' type='text/css'>
    <link rel="stylesheet" href="font-awesome/css/font-awesome.min.css" type="text/css">

    <link rel="stylesheet" href="css/animate.min.css" type="text/css">

    <link rel="stylesheet" href="css/creative.css" type="text/css">

                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation

                </button>
                cv \\ portfolio

                        Greenlight Discharge Dashboard

                        Agent

                    Hospital Course Timeline

                    Pilots

                    Proposals

                    Web

                    Photography

                        Contact

Katherine Choi, BS

Clinical Informatics Product Manager Intern, Penn Medicine Center for Health Care Innovation
MD, Perelman School of Medicine at the University of Pennsylvania
BS, Massachusetts Institute of Technology

 CV

                                    Ux Design

                                    Greenlight Discharge Dashboard

                                    Product Management

                                    Agent

                                    Product Management

                                    Pilots

                                    Ux Design

                                    Hospital Course Timeline

                                    Proposals

                                    mHealth Center of Excellence

                                    Web/HTML

                                    Front-end Development

                                    Photography

                                    Travel+Engagement

Contact

 kathchoi at upenn dot edu

Please request CV by email.


text:
<link rel="import" href="../polymer/polymer.html">
<link rel="import" href="../expandjs/expandjs.html">
<link rel="import" href="../iron-flex-layout/iron-flex-layout.html">
<link rel="import" href="mat-paper-behavior.html">
<link rel="import" href="mat-paper-styles.html">
<link rel="import" href="mat-shadow.html">
<link rel="import" href="mat-spacing.html">
<link rel="import" href="mat-header.html">

<dom-module id="mat-header-panel">

    <template strip-whitespace>

                            <slot></slot>

                    <slot name="header"></slot>

                <slot name="footer"></slot>

    </template>

</dom-module>


text:
package com.google.android.apps.forscience.whistlepunk;

import static com.google.android.apps.forscience.whistlepunk.audio.SoundUtils.HALF_STEP_FREQUENCY_RATIO;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Typeface;
import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;
import androidx.appcompat.widget.AppCompatImageView;
import android.util.DisplayMetrics;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import com.google.android.apps.forscience.whistlepunk.audio.SoundUtils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;

/** Implements sensor animation behavior for the pitch sensor. */
class PitchSensorAnimationBehavior implements SensorAnimationBehavior {
  private static final double ANGLE_TOP = Math.PI / 2;

  private static final float ELLIPSE_RADIUS_RATIO = 0.44f;
  private static final float SHADE_RADIUS_RATIO = 0.38f;
  private static final float DOT_RADIUS_RATIO = 0.05f;
  private static final float NOTE_TEXT_SIZE_RATIO = 0.48f;
  private static final float NOTE_X_RATIO = 0.42f;
  private static final float NOTE_Y_RATIO = 0.62f;
  private static final float SIGN_TEXT_SIZE_RATIO = 0.25f;
  private static final float SIGN_X_RATIO = 0.68f;
  private static final float SIGN_Y_RATIO = 0.43f;
  private static final float OCTAVE_TEXT_SIZE_RATIO = 0.2f;
  private static final float OCTAVE_X_RATIO = 0.71f;
  private static final float OCTAVE_Y_RATIO = 0.71f;
  private static final float HALF_PIXEL = 0.5f;

  private static final int SHADE_LOW_RED = 0x71;
  private static final int SHADE_LOW_GREEN = 0xCA;
  private static final int SHADE_LOW_BLUE = 0xF8;
  private static final int SHADE_LOW = Color.rgb(SHADE_LOW_RED, SHADE_LOW_GREEN, SHADE_LOW_BLUE);
  private static final int SHADE_HIGH_RED = 0x0D;
  private static final int SHADE_HIGH_GREEN = 0x61;
  private static final int SHADE_HIGH_BLUE = 0xAF;
  private static final int SHADE_HIGH =
      Color.rgb(SHADE_HIGH_RED, SHADE_HIGH_GREEN, SHADE_HIGH_BLUE);
  private static final int COLOR_NOTE_LEFT = 0xFFEEEEEE;
  private static final int COLOR_NOTE_RIGHT = 0xFFDCDCDC;
  private static final int COLOR_SIGN = 0xFFDCDCDC;
  private static final int COLOR_OCTAVE = 0xFFDCDCDC;

  // These shadow values are from Konina.
  private static final int SHADOW_RADIUS = 4;
  private static final int SHADOW_DX = 1;
  private static final int SHADOW_DY = 2;
  private static final int SHADOW_COLOR = 0x3D000000;

  private static final String NATURAL = "";
  private static final String FLAT = "\u266D";
  private static final String SHARP = "\u266F";

  private static class MusicalNote {
    final String letter;
    final String sign;
    final String octave;

    MusicalNote(String letter, String sign, String octave) {
      this.letter = letter;
      this.sign = sign;
      this.octave = octave;
    }

    boolean isNotePlacedAtCenter() {
      // "-" and "+" are placed at the center.
      return letter.equals("-") || letter.equals("+");
    }
  }

  /**
   * noteFrequencies contains the frequencies of notes of a piano at indices 1-88. The value at
   * index 0 is a half step less than the value at index 1. The value at index 89 is a half step
   * more than the value at index 88.
   */
  @VisibleForTesting static final List<Double> noteFrequencies = new ArrayList<>();

  private static final List<MusicalNote> musicalNotes = new ArrayList<>();

  private final Paint paintForDot;
  private final Paint paintForShade;
  private final Paint paintForNoteLeft;
  private final Paint paintForNoteRight;
  private final Paint paintForSign;
  private final Paint paintForOctave;

  PitchSensorAnimationBehavior() {
    paintForDot = new Paint();
    paintForDot.setColor(Color.RED);

    paintForShade = new Paint();
    paintForShade.setColor(makeShadeColor(0));

    Typeface sansSerifBold = Typeface.create(Typeface.SANS_SERIF, Typeface.BOLD);

    paintForNoteLeft = new Paint(Paint.LINEAR_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);
    paintForNoteLeft.setTextAlign(Paint.Align.CENTER);
    paintForNoteLeft.setColor(COLOR_NOTE_LEFT);
    paintForNoteLeft.setTypeface(sansSerifBold);

    paintForNoteRight = new Paint(Paint.LINEAR_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);
    paintForNoteRight.setTextAlign(Paint.Align.CENTER);
    paintForNoteRight.setColor(COLOR_NOTE_RIGHT);
    paintForNoteRight.setTypeface(sansSerifBold);

    paintForSign = new Paint(Paint.LINEAR_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);
    paintForSign.setTextAlign(Paint.Align.CENTER);
    paintForSign.setColor(COLOR_SIGN);
    paintForSign.setTypeface(sansSerifBold);

    paintForOctave = new Paint(Paint.LINEAR_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);
    paintForOctave.setTextAlign(Paint.Align.CENTER);
    paintForOctave.setColor(COLOR_OCTAVE);
    paintForOctave.setTypeface(sansSerifBold);
  }

  private ImageViewCanvas getImageViewCanvas(RelativeLayout layout) {
    return (ImageViewCanvas) layout.getChildAt(0);
  }

  private class ImageViewCanvas extends AppCompatImageView {
    private float iconCenterX;
    private float iconCenterY;
    private float dotRadius;
    private float ellipseRadius;
    private float shadeRadius;
    private float noteX;
    private float noteY;
    private float signX;
    private float signY;
    private float octaveX;
    private float octaveY;
    private Rect noteBounds = new Rect();

    /**
     * The angle of the dot indicating how close the detected pitch is to the nearest musical note.
     * A value of 0 positions the dot at the far right. A value of PI/2 positions the dot at the
     * top. A value of PI positions the dot at the far left. Initialize so that the dot is displayed
     * at the top.
     */
    private double angleOfDot = ANGLE_TOP;

    private int level = 0;

    ImageViewCanvas(Context context) {
      super(context);
      // Without setting the layr type to software, the octave numbers 6 and 3 are cut off on
      // the right edge.
      setLayerType(LAYER_TYPE_SOFTWARE, null);
    }

    private void setPitch(double detectedPitch) {
      int level = pitchToLevel(detectedPitch);
      if (level != this.level) {
        this.level = level;
        paintForShade.setColor(makeShadeColor(level));
      }
      double difference = calculateDifference(detectedPitch, level);
      angleOfDot = (1 - 2 * difference) * (Math.PI / 2);
      setContentDescription(makeContentDescription(getContext(), level, difference));
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldW, int oldH) {
      iconCenterX = w / 2.0f;
      iconCenterY = h / 2.0f;
      ellipseRadius = w * ELLIPSE_RADIUS_RATIO;
      dotRadius = w * DOT_RADIUS_RATIO;
      shadeRadius = w * SHADE_RADIUS_RATIO;

      noteX = w * NOTE_X_RATIO;
      noteY = h * NOTE_Y_RATIO;
      signX = w * SIGN_X_RATIO;
      signY = h * SIGN_Y_RATIO;
      octaveX = w * OCTAVE_X_RATIO;
      octaveY = h * OCTAVE_Y_RATIO;

      paintForNoteLeft.setTextSize(h * NOTE_TEXT_SIZE_RATIO);
      paintForNoteRight.setTextSize(h * NOTE_TEXT_SIZE_RATIO);
      paintForSign.setTextSize(h * SIGN_TEXT_SIZE_RATIO);
      paintForOctave.setTextSize(h * OCTAVE_TEXT_SIZE_RATIO);
      DisplayMetrics metrics = getContext().getResources().getDisplayMetrics();
      int shadowRadius = SHADOW_RADIUS;
      int shadowDx = SHADOW_DX;
      int shadowDy = SHADOW_DY;
      if (metrics.densityDpi > DisplayMetrics.DENSITY_HIGH) {
        shadowRadius *= 2;
        shadowDx *= 2;
        shadowDy *= 2;
      }
      paintForNoteLeft.setShadowLayer(shadowRadius, shadowDx, shadowDy, SHADOW_COLOR);
      paintForNoteRight.setShadowLayer(shadowRadius, shadowDx, shadowDy, SHADOW_COLOR);
      paintForOctave.setShadowLayer(shadowRadius, shadowDx, shadowDy, SHADOW_COLOR);
      paintForSign.setShadowLayer(shadowRadius, shadowDx, shadowDy, SHADOW_COLOR);

      if (musicalNotes.isEmpty()) {
        fillNoteLists();
      }
    }

    @Override
    protected void onDraw(Canvas canvas) {
      super.onDraw(canvas);

      if (musicalNotes.isEmpty()) {
        // This shouldn't happen because onSize should have been called before onDraw, but
        // just in case it does happen, we'll just show the base icon, which is a - sign.
        return;
      }

      canvas.drawCircle(iconCenterX, iconCenterY, shadeRadius, paintForShade);

      MusicalNote musicalNote = musicalNotes.get(level);
      float noteX = this.noteX;
      float noteY = this.noteY;
      if (musicalNote.isNotePlacedAtCenter()) {
        // "-" and "+" are placed at the center.
        noteX = iconCenterX;
        paintForNoteLeft.getTextBounds(
            musicalNote.letter, 0, musicalNote.letter.length(), noteBounds);
        noteY = iconCenterY - (noteBounds.top + noteBounds.bottom) / 2;
      }
      canvas.save();
      canvas.clipRect(0, 0, noteX, getHeight());
      canvas.drawText(musicalNote.letter, noteX, noteY, paintForNoteLeft);
      canvas.restore();
      canvas.save();
      canvas.clipRect(noteX, 0, getWidth(), getHeight());
      canvas.drawText(musicalNote.letter, noteX, noteY, paintForNoteRight);
      canvas.restore();
      if (musicalNote.sign != null && !musicalNote.sign.isEmpty()) {
        // We need to draw the sharp or flat sign.
        canvas.drawText(musicalNote.sign, signX, signY, paintForSign);
      }
      if (musicalNote.octave != null && !musicalNote.octave.isEmpty()) {
        canvas.drawText(musicalNote.octave, octaveX, octaveY, paintForOctave);
      }

      // Calculate the location of the red dot. The red dot will be a point on the invisible
      // ellipse.
      float xDot = (float) (iconCenterX + ellipseRadius * Math.cos(angleOfDot));
      float yDot = (float) (iconCenterY - ellipseRadius * Math.sin(angleOfDot));
      if (angleOfDot == ANGLE_TOP) {
        // Because the drawable is an even number of pixels wide, the top circle is offset
        // half a pixel to the right. This fixes the overlap issues.
        xDot += HALF_PIXEL;
      }
      canvas.drawCircle(xDot, yDot, dotRadius, paintForDot);
    }
  }

  @Override
  public void resetIcon(RelativeLayout layout) {
    ImageViewCanvas view = getImageViewCanvas(layout);
    view.setPitch(0);
    view.postInvalidateOnAnimation();
  }

  @Override
  public boolean updateIconAndTextTogether() {
    return false;
  }

  @Override
  public void updateIcon(
      RelativeLayout layout,
      double detectedPitch,
      double yMin,
      double yMax,
      int screenOrientation) {
    ImageViewCanvas view = getImageViewCanvas(layout);
    view.setPitch(detectedPitch);
    view.postInvalidateOnAnimation();
  }

  @Override
  public void initializeLargeIcon(RelativeLayout layout, @Nullable Double value) {
    // Remove previous views.
    if (layout.getChildCount() > 0) {
      layout.removeAllViews();
    }
    Context context = layout.getContext();
    ImageViewCanvas largeIcon = new ImageViewCanvas(context);
    layout.addView(
        largeIcon, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
    largeIcon.setImageDrawable(
        context.getResources().getDrawable(R.drawable.sound_frequency_drawable));
    largeIcon.setPitch((value != null) ? value : 0);
  }

  @VisibleForTesting
  static void fillNoteLists() {
    noteFrequencies.addAll(SoundUtils.getPianoNoteFrequencies());
    // Add first and last items to make lookup easier. Use the approximate half-step ratio to
    // determine the first and last items.
    noteFrequencies.add(0, noteFrequencies.get(0) / HALF_STEP_FREQUENCY_RATIO);
    noteFrequencies.add(
        noteFrequencies.get(noteFrequencies.size() - 1) * HALF_STEP_FREQUENCY_RATIO);

    musicalNotes.add(new MusicalNote("-", "" /* sign */, "" /* octave */));
    for (int i = 1; i <= 88; i++) {
      String letter;
      String sign;
      switch ((i + 8) % 12) {
        case 0:
          letter = "C";
          sign = NATURAL;
          break;
        case 1:
          letter = "C";
          sign = SHARP;
          break;
        case 2:
          letter = "D";
          sign = NATURAL;
          break;
        case 3:
          letter = "E";
          sign = FLAT;
          break;
        case 4:
          letter = "E";
          sign = NATURAL;
          break;
        case 5:
          letter = "F";
          sign = NATURAL;
          break;
        case 6:
          letter = "F";
          sign = SHARP;
          break;
        case 7:
          letter = "G";
          sign = NATURAL;
          break;
        case 8:
          letter = "A";
          sign = FLAT;
          break;
        case 9:
          letter = "A";
          sign = NATURAL;
          break;
        case 10:
          letter = "B";
          sign = FLAT;
          break;
        case 11:
          letter = "B";
          sign = NATURAL;
          break;
        default:
          throw new RuntimeException("This is not possible.");
      }
      int octave = (i + 8) / 12;
      musicalNotes.add(new MusicalNote(letter, sign, "" + octave));
    }
    musicalNotes.add(new MusicalNote("+", "" /* sign */, "" /* octave */));
  }

  /**
   * Returns the index corresponding to the given sound frequency, where indices 1-88 represent the
   * notes of keys on a piano.
   */
  @VisibleForTesting
  static int pitchToLevel(double frequency) {
    if (noteFrequencies.isEmpty() || musicalNotes.isEmpty()) {
      fillNoteLists();
    }
    int i = Collections.binarySearch(noteFrequencies, frequency);
    // If there is an exact match, i will be a non-negative number, which is the index of the
    // matching value.
    if (i >= 0) {
      return i;
    }
    // If there is no exact match, i will provide the insertion point, where the observed
    // frequency would belong in the list, as (-(insertion point) - 1).
    // This is the usual case, since in most cases the observed frequency will not match a
    // specific note exactly.
    // Calculate the insertion point.
    i = -i - 1;
    if (i == 0) {
      // frequency is significantly lower than the lowest note.
      return 0;
    }
    if (i == noteFrequencies.size()) {
      // frequency is significantly higher than the highest note.
      return noteFrequencies.size() - 1;
    }
    // frequency is between two notes.
    double midpoint = (noteFrequencies.get(i - 1) + noteFrequencies.get(i)) / 2;
    return (frequency < midpoint) ? (i - 1) : i;
  }

  /**
   * Returns the difference, in half steps, between the detected pitch and the note associated with
   * the given level.
   */
  @VisibleForTesting
  static double calculateDifference(double detectedPitch, int level) {
    if (level == 0 || level == noteFrequencies.size() - 1) {
      // If the nearest musical note is more than one half step lower than the lowest musical
      // note or more than one half step higher than the highest musical note, we don't
      // calculate the difference.
      return 0;
    }
    // If the detected pitch equals a musical note the dot is at the top, which is 90
    // degrees or Math.PI / 2 radians.
    // If the detected pitch is half way between the nearest musical note and the next
    // lower musical note, the dot is at the far left, which is 180 degrees, or Math.PI
    // radians.
    // If the detected pitch is half way between the nearest musical note and the next
    // higher musical note, the dot is at the far right, which is 0 degrees, or 0 radians.
    double nearestNote = noteFrequencies.get(level);
    double difference = detectedPitch - nearestNote;
    if (difference < 0) {
      // The detected pitch is lower than the nearest musical note.
      // Adjust the difference to the range of -1 to 0, where -1 is the next lower note.
      double lowerNote = noteFrequencies.get(level - 1);
      difference /= (nearestNote - lowerNote);
      // The difference should never actually be less than -0.5, since that would
      // indicate that the detected pitch was actually closer to the lowerNote.
    } else {
      // The detected pitch is higher than the nearest musical note.
      // Adjust the difference to the range of 0 to +1, where +1 is the next higher note.
      double higherNote = noteFrequencies.get(level + 1);
      difference /= (higherNote - nearestNote);
      // The difference should never actually be greater than 0.5, since that would
      // indicate that the detected pitch was actually closer to the higherNote.
    }
    return difference;
  }

  @VisibleForTesting
  static String makeContentDescription(Context context, int noteNumber, double difference) {
    if (noteNumber < 1) {
      return context.getResources().getString(R.string.pitch_low_content_description);
    }
    if (noteNumber > 88) {
      return context.getResources().getString(R.string.pitch_high_content_description);
    }
    Locale locale = context.getResources().getConfiguration().locale;
    String differenceFormatted = String.format(locale, "%1.2f", Math.abs(difference));
    int signum = (int) Math.signum(difference);
    // differenceFormatted is in the range 0.00 to 0.50, but the decimal point may be "." or
    // ",", depending on locale. The following comparison tells us whether difference is close
    // enough to zero, that we should consider the detetected pitch as not flatter or sharper
    // than the musical note.
    if (differenceFormatted.endsWith("00")) {
      signum = 0;
    }
    MusicalNote musicalNote = musicalNotes.get(noteNumber);
    int format;
    if (musicalNote.sign.equals(FLAT)) {
      format = flatNoteDescription(signum);
    } else if (musicalNote.sign.equals(SHARP)) {
      format = sharpNoteDescription(signum);
    } else {
      format = naturalNoteDescription(signum);
    }
    return context
        .getResources()
        .getString(format, musicalNote.letter, musicalNote.octave, differenceFormatted);
  }

  private static int naturalNoteDescription(int signum) {
    if (signum < 0) {
      return R.string.pitch_flatter_than_natural_note_content_description;
    }
    if (signum > 0) {
      return R.string.pitch_sharper_than_natural_note_content_description;
    }
    return R.string.pitch_natural_note_content_description;
  }

  private static int flatNoteDescription(int signum) {
    if (signum < 0) {
      return R.string.pitch_flatter_than_flat_note_content_description;
    }
    if (signum > 0) {
      return R.string.pitch_sharper_than_flat_note_content_description;
    }
    return R.string.pitch_flat_note_content_description;
  }

  private static int sharpNoteDescription(int signum) {
    if (signum < 0) {
      return R.string.pitch_flatter_than_sharp_note_content_description;
    }
    if (signum > 0) {
      return R.string.pitch_sharper_than_sharp_note_content_description;
    }
    return R.string.pitch_sharp_note_content_description;
  }

  private static int makeShadeColor(int level) {
    if (level == 0) {
      return SHADE_LOW;
    }
    if (level == noteFrequencies.size() - 1) {
      return SHADE_HIGH;
    }
    int r = (int) Math.round(SHADE_LOW_RED + (SHADE_HIGH_RED - SHADE_LOW_RED) * level / 89.0);
    int g = (int) Math.round(SHADE_LOW_GREEN + (SHADE_HIGH_GREEN - SHADE_LOW_GREEN) * level / 89.0);
    int b = (int) Math.round(SHADE_LOW_BLUE + (SHADE_HIGH_BLUE - SHADE_LOW_BLUE) * level / 89.0);
    return Color.rgb(r, g, b);
  }
}


text:
Generic modal screen unit. for dialogs and that sort of stuff

Copyright (C) 2012 Nikolay Nemshilov

```coffee-aside
class Modal extends Element
  extend:
    current: null
    offsetX: 40
    offsetY: 40
```

Basic constructor

NOTE: the `html` attribute will be inserted into the `inner`
      block, not inside of the main modal container!

@param {Object} html options
@return {Modal} self

```coffee-aside
  constructor: (options)->
    options = merge_options(options, { class: 'lui-modal lui-locker' })
    html    = options.html || '';
    options.html = '<div class="lui-inner"></div>'

    options['class'] += ' lui-modal-nolock'  if options.nolock is true; delete(options.nolock)
    options['class'] += ' lui-modal-overlap' if options.overlap is true; delete(options.overlap)

    super('div', options)

    @_inner = @dialog = @first('.lui-inner')
    @_inner.insert(html)

    return @
```

Bypassing the {Element#html} calls to the inner element

@return {Modal} self

```coffee-aside
  html: ->
    @_inner.html.apply(@_inner, arguments)
    return @
```

Bypassing the {Element#html} calls to the inner element

@return {Modal} self

```coffee-aside
  text: ->
    @_inner.text.apply(@_inner, arguments)
    return @
```

Bypassing the {Element#insert} calls to the inner element

@return {Modal} self

```coffee-aside
  insert: ()->
    @_inner.insert.apply(@_inner, arguments)
    return @
```

Bypassing the {Element#update} calls to the inner element

@return {Modal} self

```coffee-aside
  update: ()->
    @_inner.update.apply(@_inner, arguments)
    return @
```

Bypassing the {Element#clear} calls to the inner element

@return {Modal} self

```coffee-aside
  clear: ()->
    @_inner.clear()
    return @
```

Automatically inserts the element into the `document.body`

@return {Modal} self

```coffee-aside
  show: ()->
    hide_all_modals() unless @hasClass('lui-modal-overlap')

    @insertTo(document.body)
    @$super.apply(@, arguments)
    @limit_size(dom_window.size())

    Modal.current = @constructor.current = @emit('show')
```

Removes the whole thing out of the `document.body`

@return {Modal} self

```coffee-aside
  hide: ->
    Modal.current = @constructor.current = null
    @emit('hide').remove()
```

Sets the size limits for the image

@param {Object} x: N, y: N size
@return {Zoom} this

```coffee-aside
  limit_size: (size)->
    @dialog._.style.maxWidth  = size.x - (@constructor.offsetX || Modal.offsetX) + 'px'
    @dialog._.style.maxHeight = size.y - (@constructor.offsetX || Modal.offsetY) + 'px'

    return @

# hides all visible modals on the page
hide_all_modals = ->
  modals = dom('div.lui-modal'); last_modal = modals[modals.length - 1]
  if last_modal && last_modal.hasClass('lui-modal-overlap')
    last_modal.remove()
  else
    modals.forEach('remove')

# hide all modals when the user presses 'escape'
dom(document).on('esc', hide_all_modals)
dom(document).on 'click', (event)->
  if Modal.current && (Modal.current == event.target || !event.find('.lui-modal'))
    Modal.current.hide()
    Modal.current = dom('div.lui-modal').pop() || null

# setting up the dialog max-sizes with the window
resize_timeout = new Date()
dom_window = dom(window).on 'resize', ->
  if Modal.current isnt null && (new Date() - resize_timeout) > 1
    resize_timeout = new Date()
    Modal.current.limit_size(@size())
```


text:
#ifndef ART_RUNTIME_MIRROR_OBJECT_INL_H_
#define ART_RUNTIME_MIRROR_OBJECT_INL_H_

#include "object.h"

#include "art_field.h"
#include "art_method.h"
#include "atomic.h"
#include "array-inl.h"
#include "class.h"
#include "lock_word-inl.h"
#include "monitor.h"
#include "object_array-inl.h"
#include "read_barrier-inl.h"
#include "runtime.h"
#include "reference.h"
#include "throwable.h"

namespace art {
namespace mirror {

inline uint32_t Object::ClassSize() {
  uint32_t vtable_entries = kVTableLength;
  return Class::ComputeClassSize(true, vtable_entries, 0, 0, 0);
}

template<VerifyObjectFlags kVerifyFlags, ReadBarrierOption kReadBarrierOption>
inline Class* Object::GetClass() {
  return GetFieldObject<Class, kVerifyFlags, kReadBarrierOption>(
      OFFSET_OF_OBJECT_MEMBER(Object, klass_));
}

template<VerifyObjectFlags kVerifyFlags>
inline void Object::SetClass(Class* new_klass) {
  // new_klass may be NULL prior to class linker initialization.
  // We don't mark the card as this occurs as part of object allocation. Not all objects have
  // backing cards, such as large objects.
  // We use non transactional version since we can't undo this write. We also disable checking as
  // we may run in transaction mode here.
  SetFieldObjectWithoutWriteBarrier<false, false,
      static_cast<VerifyObjectFlags>(kVerifyFlags & ~kVerifyThis)>(
      OFFSET_OF_OBJECT_MEMBER(Object, klass_), new_klass);
}

inline LockWord Object::GetLockWord(bool as_volatile) {
  if (as_volatile) {
    return LockWord(GetField32Volatile(OFFSET_OF_OBJECT_MEMBER(Object, monitor_)));
  }
  return LockWord(GetField32(OFFSET_OF_OBJECT_MEMBER(Object, monitor_)));
}

inline void Object::SetLockWord(LockWord new_val, bool as_volatile) {
  // Force use of non-transactional mode and do not check.
  if (as_volatile) {
    SetField32Volatile<false, false>(OFFSET_OF_OBJECT_MEMBER(Object, monitor_), new_val.GetValue());
  } else {
    SetField32<false, false>(OFFSET_OF_OBJECT_MEMBER(Object, monitor_), new_val.GetValue());
  }
}

inline bool Object::CasLockWordWeakSequentiallyConsistent(LockWord old_val, LockWord new_val) {
  // Force use of non-transactional mode and do not check.
  return CasFieldWeakSequentiallyConsistent32<false, false>(
      OFFSET_OF_OBJECT_MEMBER(Object, monitor_), old_val.GetValue(), new_val.GetValue());
}

inline bool Object::CasLockWordWeakRelaxed(LockWord old_val, LockWord new_val) {
  // Force use of non-transactional mode and do not check.
  return CasFieldWeakRelaxed32<false, false>(
      OFFSET_OF_OBJECT_MEMBER(Object, monitor_), old_val.GetValue(), new_val.GetValue());
}

inline uint32_t Object::GetLockOwnerThreadId() {
  return Monitor::GetLockOwnerThreadId(this);
}

inline mirror::Object* Object::MonitorEnter(Thread* self) {
  return Monitor::MonitorEnter(self, this);
}

inline bool Object::MonitorExit(Thread* self) {
  return Monitor::MonitorExit(self, this);
}

inline void Object::Notify(Thread* self) {
  Monitor::Notify(self, this);
}

inline void Object::NotifyAll(Thread* self) {
  Monitor::NotifyAll(self, this);
}

inline void Object::Wait(Thread* self) {
  Monitor::Wait(self, this, 0, 0, true, kWaiting);
}

inline void Object::Wait(Thread* self, int64_t ms, int32_t ns) {
  Monitor::Wait(self, this, ms, ns, true, kTimedWaiting);
}

inline Object* Object::GetReadBarrierPointer() {
#ifdef USE_BAKER_OR_BROOKS_READ_BARRIER
  DCHECK(kUseBakerOrBrooksReadBarrier);
  return GetFieldObject<Object, kVerifyNone, kWithoutReadBarrier>(
      OFFSET_OF_OBJECT_MEMBER(Object, x_rb_ptr_));
#else
  LOG(FATAL) << "Unreachable";
  return nullptr;
#endif
}

inline void Object::SetReadBarrierPointer(Object* rb_ptr) {
#ifdef USE_BAKER_OR_BROOKS_READ_BARRIER
  DCHECK(kUseBakerOrBrooksReadBarrier);
  // We don't mark the card as this occurs as part of object allocation. Not all objects have
  // backing cards, such as large objects.
  SetFieldObjectWithoutWriteBarrier<false, false, kVerifyNone>(
      OFFSET_OF_OBJECT_MEMBER(Object, x_rb_ptr_), rb_ptr);
#else
  LOG(FATAL) << "Unreachable";
#endif
}

inline bool Object::AtomicSetReadBarrierPointer(Object* expected_rb_ptr, Object* rb_ptr) {
#ifdef USE_BAKER_OR_BROOKS_READ_BARRIER
  DCHECK(kUseBakerOrBrooksReadBarrier);
  MemberOffset offset = OFFSET_OF_OBJECT_MEMBER(Object, x_rb_ptr_);
  byte* raw_addr = reinterpret_cast<byte*>(this) + offset.SizeValue();
  Atomic<uint32_t>* atomic_rb_ptr = reinterpret_cast<Atomic<uint32_t>*>(raw_addr);
  HeapReference<Object> expected_ref(HeapReference<Object>::FromMirrorPtr(expected_rb_ptr));
  HeapReference<Object> new_ref(HeapReference<Object>::FromMirrorPtr(rb_ptr));
  do {
    if (UNLIKELY(atomic_rb_ptr->LoadRelaxed() != expected_ref.reference_)) {
      // Lost the race.
      return false;
    }
  } while (!atomic_rb_ptr->CompareExchangeWeakSequentiallyConsistent(expected_ref.reference_,
                                                                     new_ref.reference_));
  DCHECK_EQ(new_ref.reference_, atomic_rb_ptr->LoadRelaxed());
  return true;
#else
  LOG(FATAL) << "Unreachable";
  return false;
#endif
}

inline void Object::AssertReadBarrierPointer() const {
  if (kUseBakerReadBarrier) {
    Object* obj = const_cast<Object*>(this);
    DCHECK(obj->GetReadBarrierPointer() == nullptr)
        << "Bad Baker pointer: obj=" << reinterpret_cast<void*>(obj)
        << " ptr=" << reinterpret_cast<void*>(obj->GetReadBarrierPointer());
  } else if (kUseBrooksReadBarrier) {
    Object* obj = const_cast<Object*>(this);
    DCHECK_EQ(obj, obj->GetReadBarrierPointer())
        << "Bad Brooks pointer: obj=" << reinterpret_cast<void*>(obj)
        << " ptr=" << reinterpret_cast<void*>(obj->GetReadBarrierPointer());
  } else {
    LOG(FATAL) << "Unreachable";
  }
}

template<VerifyObjectFlags kVerifyFlags>
inline bool Object::VerifierInstanceOf(Class* klass) {
  DCHECK(klass != NULL);
  DCHECK(GetClass<kVerifyFlags>() != NULL);
  return klass->IsInterface() || InstanceOf(klass);
}

template<VerifyObjectFlags kVerifyFlags>
inline bool Object::InstanceOf(Class* klass) {
  DCHECK(klass != NULL);
  DCHECK(GetClass<kVerifyNone>() != NULL);
  return klass->IsAssignableFrom(GetClass<kVerifyFlags>());
}

template<VerifyObjectFlags kVerifyFlags, ReadBarrierOption kReadBarrierOption>
inline bool Object::IsClass() {
  Class* java_lang_Class = GetClass<kVerifyFlags, kReadBarrierOption>()->
      template GetClass<kVerifyFlags, kReadBarrierOption>();
  return GetClass<static_cast<VerifyObjectFlags>(kVerifyFlags & ~kVerifyThis),
      kReadBarrierOption>() == java_lang_Class;
}

template<VerifyObjectFlags kVerifyFlags, ReadBarrierOption kReadBarrierOption>
inline Class* Object::AsClass() {
  DCHECK((IsClass<kVerifyFlags, kReadBarrierOption>()));
  return down_cast<Class*>(this);
}

template<VerifyObjectFlags kVerifyFlags>
inline bool Object::IsObjectArray() {
  constexpr auto kNewFlags = static_cast<VerifyObjectFlags>(kVerifyFlags & ~kVerifyThis);
  return IsArrayInstance<kVerifyFlags>() &&
      !GetClass<kNewFlags>()->template GetComponentType<kNewFlags>()->IsPrimitive();
}

template<class T, VerifyObjectFlags kVerifyFlags>
inline ObjectArray<T>* Object::AsObjectArray() {
  DCHECK(IsObjectArray<kVerifyFlags>());
  return down_cast<ObjectArray<T>*>(this);
}

template<VerifyObjectFlags kVerifyFlags, ReadBarrierOption kReadBarrierOption>
inline bool Object::IsArrayInstance() {
  return GetClass<kVerifyFlags, kReadBarrierOption>()->
      template IsArrayClass<kVerifyFlags, kReadBarrierOption>();
}

template<VerifyObjectFlags kVerifyFlags, ReadBarrierOption kReadBarrierOption>
inline bool Object::IsArtField() {
  return GetClass<kVerifyFlags, kReadBarrierOption>()->
      template IsArtFieldClass<kReadBarrierOption>();
}

template<VerifyObjectFlags kVerifyFlags>
inline ArtField* Object::AsArtField() {
  DCHECK(IsArtField<kVerifyFlags>());
  return down_cast<ArtField*>(this);
}

template<VerifyObjectFlags kVerifyFlags, ReadBarrierOption kReadBarrierOption>
inline bool Object::IsArtMethod() {
  return GetClass<kVerifyFlags, kReadBarrierOption>()->
      template IsArtMethodClass<kReadBarrierOption>();
}

template<VerifyObjectFlags kVerifyFlags>
inline ArtMethod* Object::AsArtMethod() {
  DCHECK(IsArtMethod<kVerifyFlags>());
  return down_cast<ArtMethod*>(this);
}

template<VerifyObjectFlags kVerifyFlags>
inline bool Object::IsReferenceInstance() {
  return GetClass<kVerifyFlags>()->IsTypeOfReferenceClass();
}

template<VerifyObjectFlags kVerifyFlags>
inline Reference* Object::AsReference() {
  DCHECK(IsReferenceInstance<kVerifyFlags>());
  return down_cast<Reference*>(this);
}

template<VerifyObjectFlags kVerifyFlags, ReadBarrierOption kReadBarrierOption>
inline Array* Object::AsArray() {
  DCHECK((IsArrayInstance<kVerifyFlags, kReadBarrierOption>()));
  return down_cast<Array*>(this);
}

template<VerifyObjectFlags kVerifyFlags>
inline BooleanArray* Object::AsBooleanArray() {
  constexpr auto kNewFlags = static_cast<VerifyObjectFlags>(kVerifyFlags & ~kVerifyThis);
  DCHECK(GetClass<kVerifyFlags>()->IsArrayClass());
  DCHECK(GetClass<kNewFlags>()->GetComponentType()->IsPrimitiveBoolean());
  return down_cast<BooleanArray*>(this);
}

template<VerifyObjectFlags kVerifyFlags>
inline ByteArray* Object::AsByteArray() {
  static const VerifyObjectFlags kNewFlags = static_cast<VerifyObjectFlags>(kVerifyFlags & ~kVerifyThis);
  DCHECK(GetClass<kVerifyFlags>()->IsArrayClass());
  DCHECK(GetClass<kNewFlags>()->template GetComponentType<kNewFlags>()->IsPrimitiveByte());
  return down_cast<ByteArray*>(this);
}

template<VerifyObjectFlags kVerifyFlags>
inline ByteArray* Object::AsByteSizedArray() {
  constexpr VerifyObjectFlags kNewFlags = static_cast<VerifyObjectFlags>(kVerifyFlags & ~kVerifyThis);
  DCHECK(GetClass<kVerifyFlags>()->IsArrayClass());
  DCHECK(GetClass<kNewFlags>()->template GetComponentType<kNewFlags>()->IsPrimitiveByte() ||
         GetClass<kNewFlags>()->template GetComponentType<kNewFlags>()->IsPrimitiveBoolean());
  return down_cast<ByteArray*>(this);
}

template<VerifyObjectFlags kVerifyFlags>
inline CharArray* Object::AsCharArray() {
  constexpr auto kNewFlags = static_cast<VerifyObjectFlags>(kVerifyFlags & ~kVerifyThis);
  DCHECK(GetClass<kVerifyFlags>()->IsArrayClass());
  DCHECK(GetClass<kNewFlags>()->template GetComponentType<kNewFlags>()->IsPrimitiveChar());
  return down_cast<CharArray*>(this);
}

template<VerifyObjectFlags kVerifyFlags>
inline ShortArray* Object::AsShortArray() {
  constexpr auto kNewFlags = static_cast<VerifyObjectFlags>(kVerifyFlags & ~kVerifyThis);
  DCHECK(GetClass<kVerifyFlags>()->IsArrayClass());
  DCHECK(GetClass<kNewFlags>()->template GetComponentType<kNewFlags>()->IsPrimitiveShort());
  return down_cast<ShortArray*>(this);
}

template<VerifyObjectFlags kVerifyFlags>
inline ShortArray* Object::AsShortSizedArray() {
  constexpr auto kNewFlags = static_cast<VerifyObjectFlags>(kVerifyFlags & ~kVerifyThis);
  DCHECK(GetClass<kVerifyFlags>()->IsArrayClass());
  DCHECK(GetClass<kNewFlags>()->template GetComponentType<kNewFlags>()->IsPrimitiveShort() ||
         GetClass<kNewFlags>()->template GetComponentType<kNewFlags>()->IsPrimitiveChar());
  return down_cast<ShortArray*>(this);
}

template<VerifyObjectFlags kVerifyFlags>
inline IntArray* Object::AsIntArray() {
  constexpr auto kNewFlags = static_cast<VerifyObjectFlags>(kVerifyFlags & ~kVerifyThis);
  DCHECK(GetClass<kVerifyFlags>()->IsArrayClass());
  DCHECK(GetClass<kNewFlags>()->template GetComponentType<kNewFlags>()->IsPrimitiveInt() ||
         GetClass<kNewFlags>()->template GetComponentType<kNewFlags>()->IsPrimitiveFloat());
  return down_cast<IntArray*>(this);
}

template<VerifyObjectFlags kVerifyFlags>
inline LongArray* Object::AsLongArray() {
  constexpr auto kNewFlags = static_cast<VerifyObjectFlags>(kVerifyFlags & ~kVerifyThis);
  DCHECK(GetClass<kVerifyFlags>()->IsArrayClass());
  DCHECK(GetClass<kNewFlags>()->template GetComponentType<kNewFlags>()->IsPrimitiveLong() ||
         GetClass<kNewFlags>()->template GetComponentType<kNewFlags>()->IsPrimitiveDouble());
  return down_cast<LongArray*>(this);
}

template<VerifyObjectFlags kVerifyFlags>
inline FloatArray* Object::AsFloatArray() {
  constexpr auto kNewFlags = static_cast<VerifyObjectFlags>(kVerifyFlags & ~kVerifyThis);
  DCHECK(GetClass<kVerifyFlags>()->IsArrayClass());
  DCHECK(GetClass<kNewFlags>()->template GetComponentType<kNewFlags>()->IsPrimitiveFloat());
  return down_cast<FloatArray*>(this);
}

template<VerifyObjectFlags kVerifyFlags>
inline DoubleArray* Object::AsDoubleArray() {
  constexpr auto kNewFlags = static_cast<VerifyObjectFlags>(kVerifyFlags & ~kVerifyThis);
  DCHECK(GetClass<kVerifyFlags>()->IsArrayClass());
  DCHECK(GetClass<kNewFlags>()->template GetComponentType<kNewFlags>()->IsPrimitiveDouble());
  return down_cast<DoubleArray*>(this);
}

template<VerifyObjectFlags kVerifyFlags>
inline String* Object::AsString() {
  DCHECK(GetClass<kVerifyFlags>()->IsStringClass());
  return down_cast<String*>(this);
}

template<VerifyObjectFlags kVerifyFlags>
inline Throwable* Object::AsThrowable() {
  DCHECK(GetClass<kVerifyFlags>()->IsThrowableClass());
  return down_cast<Throwable*>(this);
}

template<VerifyObjectFlags kVerifyFlags>
inline bool Object::IsWeakReferenceInstance() {
  return GetClass<kVerifyFlags>()->IsWeakReferenceClass();
}

template<VerifyObjectFlags kVerifyFlags>
inline bool Object::IsSoftReferenceInstance() {
  return GetClass<kVerifyFlags>()->IsSoftReferenceClass();
}

template<VerifyObjectFlags kVerifyFlags>
inline bool Object::IsFinalizerReferenceInstance() {
  return GetClass<kVerifyFlags>()->IsFinalizerReferenceClass();
}

template<VerifyObjectFlags kVerifyFlags>
inline FinalizerReference* Object::AsFinalizerReference() {
  DCHECK(IsFinalizerReferenceInstance<kVerifyFlags>());
  return down_cast<FinalizerReference*>(this);
}

template<VerifyObjectFlags kVerifyFlags>
inline bool Object::IsPhantomReferenceInstance() {
  return GetClass<kVerifyFlags>()->IsPhantomReferenceClass();
}

template<VerifyObjectFlags kVerifyFlags, ReadBarrierOption kReadBarrierOption>
inline size_t Object::SizeOf() {
  size_t result;
  constexpr auto kNewFlags = static_cast<VerifyObjectFlags>(kVerifyFlags & ~kVerifyThis);
  if (IsArrayInstance<kVerifyFlags, kReadBarrierOption>()) {
    result = AsArray<kNewFlags, kReadBarrierOption>()->
        template SizeOf<kNewFlags, kReadBarrierOption>();
  } else if (IsClass<kNewFlags, kReadBarrierOption>()) {
    result = AsClass<kNewFlags, kReadBarrierOption>()->
        template SizeOf<kNewFlags, kReadBarrierOption>();
  } else {
    result = GetClass<kNewFlags, kReadBarrierOption>()->
        template GetObjectSize<kNewFlags, kReadBarrierOption>();
  }
  DCHECK_GE(result, sizeof(Object))
      << " class=" << PrettyTypeOf(GetClass<kNewFlags, kReadBarrierOption>());
  DCHECK(!(IsArtField<kNewFlags, kReadBarrierOption>()) || result == sizeof(ArtField));
  return result;
}

template<VerifyObjectFlags kVerifyFlags, bool kIsVolatile>
inline int32_t Object::GetField32(MemberOffset field_offset) {
  if (kVerifyFlags & kVerifyThis) {
    VerifyObject(this);
  }
  const byte* raw_addr = reinterpret_cast<const byte*>(this) + field_offset.Int32Value();
  const int32_t* word_addr = reinterpret_cast<const int32_t*>(raw_addr);
  if (UNLIKELY(kIsVolatile)) {
    return reinterpret_cast<const Atomic<int32_t>*>(word_addr)->LoadSequentiallyConsistent();
  } else {
    return reinterpret_cast<const Atomic<int32_t>*>(word_addr)->LoadJavaData();
  }
}

template<VerifyObjectFlags kVerifyFlags>
inline int32_t Object::GetField32Volatile(MemberOffset field_offset) {
  return GetField32<kVerifyFlags, true>(field_offset);
}

template<bool kTransactionActive, bool kCheckTransaction, VerifyObjectFlags kVerifyFlags,
    bool kIsVolatile>
inline void Object::SetField32(MemberOffset field_offset, int32_t new_value) {
  if (kCheckTransaction) {
    DCHECK_EQ(kTransactionActive, Runtime::Current()->IsActiveTransaction());
  }
  if (kTransactionActive) {
    Runtime::Current()->RecordWriteField32(this, field_offset,
                                           GetField32<kVerifyFlags, kIsVolatile>(field_offset),
                                           kIsVolatile);
  }
  if (kVerifyFlags & kVerifyThis) {
    VerifyObject(this);
  }
  byte* raw_addr = reinterpret_cast<byte*>(this) + field_offset.Int32Value();
  int32_t* word_addr = reinterpret_cast<int32_t*>(raw_addr);
  if (kIsVolatile) {
    reinterpret_cast<Atomic<int32_t>*>(word_addr)->StoreSequentiallyConsistent(new_value);
  } else {
    reinterpret_cast<Atomic<int32_t>*>(word_addr)->StoreJavaData(new_value);
  }
}

template<bool kTransactionActive, bool kCheckTransaction, VerifyObjectFlags kVerifyFlags>
inline void Object::SetField32Volatile(MemberOffset field_offset, int32_t new_value) {
  SetField32<kTransactionActive, kCheckTransaction, kVerifyFlags, true>(field_offset, new_value);
}

// TODO: Pass memory_order_ and strong/weak as arguments to avoid code duplication?

template<bool kTransactionActive, bool kCheckTransaction, VerifyObjectFlags kVerifyFlags>
inline bool Object::CasFieldWeakSequentiallyConsistent32(MemberOffset field_offset,
                                                         int32_t old_value, int32_t new_value) {
  if (kCheckTransaction) {
    DCHECK_EQ(kTransactionActive, Runtime::Current()->IsActiveTransaction());
  }
  if (kTransactionActive) {
    Runtime::Current()->RecordWriteField32(this, field_offset, old_value, true);
  }
  if (kVerifyFlags & kVerifyThis) {
    VerifyObject(this);
  }
  byte* raw_addr = reinterpret_cast<byte*>(this) + field_offset.Int32Value();
  AtomicInteger* atomic_addr = reinterpret_cast<AtomicInteger*>(raw_addr);

  return atomic_addr->CompareExchangeWeakSequentiallyConsistent(old_value, new_value);
}

template<bool kTransactionActive, bool kCheckTransaction, VerifyObjectFlags kVerifyFlags>
inline bool Object::CasFieldWeakRelaxed32(MemberOffset field_offset,
                                          int32_t old_value, int32_t new_value) {
  if (kCheckTransaction) {
    DCHECK_EQ(kTransactionActive, Runtime::Current()->IsActiveTransaction());
  }
  if (kTransactionActive) {
    Runtime::Current()->RecordWriteField32(this, field_offset, old_value, true);
  }
  if (kVerifyFlags & kVerifyThis) {
    VerifyObject(this);
  }
  byte* raw_addr = reinterpret_cast<byte*>(this) + field_offset.Int32Value();
  AtomicInteger* atomic_addr = reinterpret_cast<AtomicInteger*>(raw_addr);

  return atomic_addr->CompareExchangeWeakRelaxed(old_value, new_value);
}

template<bool kTransactionActive, bool kCheckTransaction, VerifyObjectFlags kVerifyFlags>
inline bool Object::CasFieldStrongSequentiallyConsistent32(MemberOffset field_offset,
                                                           int32_t old_value, int32_t new_value) {
  if (kCheckTransaction) {
    DCHECK_EQ(kTransactionActive, Runtime::Current()->IsActiveTransaction());
  }
  if (kTransactionActive) {
    Runtime::Current()->RecordWriteField32(this, field_offset, old_value, true);
  }
  if (kVerifyFlags & kVerifyThis) {
    VerifyObject(this);
  }
  byte* raw_addr = reinterpret_cast<byte*>(this) + field_offset.Int32Value();
  AtomicInteger* atomic_addr = reinterpret_cast<AtomicInteger*>(raw_addr);

  return atomic_addr->CompareExchangeStrongSequentiallyConsistent(old_value, new_value);
}

template<VerifyObjectFlags kVerifyFlags, bool kIsVolatile>
inline int64_t Object::GetField64(MemberOffset field_offset) {
  if (kVerifyFlags & kVerifyThis) {
    VerifyObject(this);
  }
  const byte* raw_addr = reinterpret_cast<const byte*>(this) + field_offset.Int32Value();
  const int64_t* addr = reinterpret_cast<const int64_t*>(raw_addr);
  if (kIsVolatile) {
    return reinterpret_cast<const Atomic<int64_t>*>(addr)->LoadSequentiallyConsistent();
  } else {
    return reinterpret_cast<const Atomic<int64_t>*>(addr)->LoadJavaData();
  }
}

template<VerifyObjectFlags kVerifyFlags>
inline int64_t Object::GetField64Volatile(MemberOffset field_offset) {
  return GetField64<kVerifyFlags, true>(field_offset);
}

template<bool kTransactionActive, bool kCheckTransaction, VerifyObjectFlags kVerifyFlags,
    bool kIsVolatile>
inline void Object::SetField64(MemberOffset field_offset, int64_t new_value) {
  if (kCheckTransaction) {
    DCHECK_EQ(kTransactionActive, Runtime::Current()->IsActiveTransaction());
  }
  if (kTransactionActive) {
    Runtime::Current()->RecordWriteField64(this, field_offset,
                                           GetField64<kVerifyFlags, kIsVolatile>(field_offset),
                                           kIsVolatile);
  }
  if (kVerifyFlags & kVerifyThis) {
    VerifyObject(this);
  }
  byte* raw_addr = reinterpret_cast<byte*>(this) + field_offset.Int32Value();
  int64_t* addr = reinterpret_cast<int64_t*>(raw_addr);
  if (kIsVolatile) {
    reinterpret_cast<Atomic<int64_t>*>(addr)->StoreSequentiallyConsistent(new_value);
  } else {
    reinterpret_cast<Atomic<int64_t>*>(addr)->StoreJavaData(new_value);
  }
}

template<bool kTransactionActive, bool kCheckTransaction, VerifyObjectFlags kVerifyFlags>
inline void Object::SetField64Volatile(MemberOffset field_offset, int64_t new_value) {
  return SetField64<kTransactionActive, kCheckTransaction, kVerifyFlags, true>(field_offset,
                                                                               new_value);
}

template<bool kTransactionActive, bool kCheckTransaction, VerifyObjectFlags kVerifyFlags>
inline bool Object::CasFieldWeakSequentiallyConsistent64(MemberOffset field_offset,
                                                         int64_t old_value, int64_t new_value) {
  if (kCheckTransaction) {
    DCHECK_EQ(kTransactionActive, Runtime::Current()->IsActiveTransaction());
  }
  if (kTransactionActive) {
    Runtime::Current()->RecordWriteField64(this, field_offset, old_value, true);
  }
  if (kVerifyFlags & kVerifyThis) {
    VerifyObject(this);
  }
  byte* raw_addr = reinterpret_cast<byte*>(this) + field_offset.Int32Value();
  Atomic<int64_t>* atomic_addr = reinterpret_cast<Atomic<int64_t>*>(raw_addr);
  return atomic_addr->CompareExchangeWeakSequentiallyConsistent(old_value, new_value);
}

template<bool kTransactionActive, bool kCheckTransaction, VerifyObjectFlags kVerifyFlags>
inline bool Object::CasFieldStrongSequentiallyConsistent64(MemberOffset field_offset,
                                                           int64_t old_value, int64_t new_value) {
  if (kCheckTransaction) {
    DCHECK_EQ(kTransactionActive, Runtime::Current()->IsActiveTransaction());
  }
  if (kTransactionActive) {
    Runtime::Current()->RecordWriteField64(this, field_offset, old_value, true);
  }
  if (kVerifyFlags & kVerifyThis) {
    VerifyObject(this);
  }
  byte* raw_addr = reinterpret_cast<byte*>(this) + field_offset.Int32Value();
  Atomic<int64_t>* atomic_addr = reinterpret_cast<Atomic<int64_t>*>(raw_addr);
  return atomic_addr->CompareExchangeStrongSequentiallyConsistent(old_value, new_value);
}

template<class T, VerifyObjectFlags kVerifyFlags, ReadBarrierOption kReadBarrierOption,
         bool kIsVolatile>
inline T* Object::GetFieldObject(MemberOffset field_offset) {
  if (kVerifyFlags & kVerifyThis) {
    VerifyObject(this);
  }
  byte* raw_addr = reinterpret_cast<byte*>(this) + field_offset.Int32Value();
  HeapReference<T>* objref_addr = reinterpret_cast<HeapReference<T>*>(raw_addr);
  T* result = ReadBarrier::Barrier<T, kReadBarrierOption>(this, field_offset, objref_addr);
  if (kIsVolatile) {
    // TODO: Refactor to use a SequentiallyConsistent load instead.
    QuasiAtomic::ThreadFenceAcquire();  // Ensure visibility of operations preceding store.
  }
  if (kVerifyFlags & kVerifyReads) {
    VerifyObject(result);
  }
  return result;
}

template<class T, VerifyObjectFlags kVerifyFlags, ReadBarrierOption kReadBarrierOption>
inline T* Object::GetFieldObjectVolatile(MemberOffset field_offset) {
  return GetFieldObject<T, kVerifyFlags, kReadBarrierOption, true>(field_offset);
}

template<bool kTransactionActive, bool kCheckTransaction, VerifyObjectFlags kVerifyFlags,
    bool kIsVolatile>
inline void Object::SetFieldObjectWithoutWriteBarrier(MemberOffset field_offset,
                                                      Object* new_value) {
  if (kCheckTransaction) {
    DCHECK_EQ(kTransactionActive, Runtime::Current()->IsActiveTransaction());
  }
  if (kTransactionActive) {
    mirror::Object* obj;
    if (kIsVolatile) {
      obj = GetFieldObjectVolatile<Object>(field_offset);
    } else {
      obj = GetFieldObject<Object>(field_offset);
    }
    Runtime::Current()->RecordWriteFieldReference(this, field_offset, obj, true);
  }
  if (kVerifyFlags & kVerifyThis) {
    VerifyObject(this);
  }
  if (kVerifyFlags & kVerifyWrites) {
    VerifyObject(new_value);
  }
  byte* raw_addr = reinterpret_cast<byte*>(this) + field_offset.Int32Value();
  HeapReference<Object>* objref_addr = reinterpret_cast<HeapReference<Object>*>(raw_addr);
  if (kIsVolatile) {
    // TODO: Refactor to use a SequentiallyConsistent store instead.
    QuasiAtomic::ThreadFenceRelease();  // Ensure that prior accesses are visible before store.
    objref_addr->Assign(new_value);
    QuasiAtomic::ThreadFenceSequentiallyConsistent();
                                // Ensure this store occurs before any volatile loads.
  } else {
    objref_addr->Assign(new_value);
  }
}

template<bool kTransactionActive, bool kCheckTransaction, VerifyObjectFlags kVerifyFlags,
    bool kIsVolatile>
inline void Object::SetFieldObject(MemberOffset field_offset, Object* new_value) {
  SetFieldObjectWithoutWriteBarrier<kTransactionActive, kCheckTransaction, kVerifyFlags,
      kIsVolatile>(field_offset, new_value);
  if (new_value != nullptr) {
    Runtime::Current()->GetHeap()->WriteBarrierField(this, field_offset, new_value);
    // TODO: Check field assignment could theoretically cause thread suspension, TODO: fix this.
    CheckFieldAssignment(field_offset, new_value);
  }
}

template<bool kTransactionActive, bool kCheckTransaction, VerifyObjectFlags kVerifyFlags>
inline void Object::SetFieldObjectVolatile(MemberOffset field_offset, Object* new_value) {
  SetFieldObject<kTransactionActive, kCheckTransaction, kVerifyFlags, true>(field_offset,
                                                                            new_value);
}

template <VerifyObjectFlags kVerifyFlags>
inline HeapReference<Object>* Object::GetFieldObjectReferenceAddr(MemberOffset field_offset) {
  if (kVerifyFlags & kVerifyThis) {
    VerifyObject(this);
  }
  return reinterpret_cast<HeapReference<Object>*>(reinterpret_cast<byte*>(this) +
      field_offset.Int32Value());
}

template<bool kTransactionActive, bool kCheckTransaction, VerifyObjectFlags kVerifyFlags>
inline bool Object::CasFieldWeakSequentiallyConsistentObject(MemberOffset field_offset,
                                                             Object* old_value, Object* new_value) {
  if (kCheckTransaction) {
    DCHECK_EQ(kTransactionActive, Runtime::Current()->IsActiveTransaction());
  }
  if (kVerifyFlags & kVerifyThis) {
    VerifyObject(this);
  }
  if (kVerifyFlags & kVerifyWrites) {
    VerifyObject(new_value);
  }
  if (kVerifyFlags & kVerifyReads) {
    VerifyObject(old_value);
  }
  if (kTransactionActive) {
    Runtime::Current()->RecordWriteFieldReference(this, field_offset, old_value, true);
  }
  HeapReference<Object> old_ref(HeapReference<Object>::FromMirrorPtr(old_value));
  HeapReference<Object> new_ref(HeapReference<Object>::FromMirrorPtr(new_value));
  byte* raw_addr = reinterpret_cast<byte*>(this) + field_offset.Int32Value();
  Atomic<uint32_t>* atomic_addr = reinterpret_cast<Atomic<uint32_t>*>(raw_addr);

  bool success = atomic_addr->CompareExchangeWeakSequentiallyConsistent(old_ref.reference_,
                                                                        new_ref.reference_);

  if (success) {
    Runtime::Current()->GetHeap()->WriteBarrierField(this, field_offset, new_value);
  }
  return success;
}

template<bool kTransactionActive, bool kCheckTransaction, VerifyObjectFlags kVerifyFlags>
inline bool Object::CasFieldStrongSequentiallyConsistentObject(MemberOffset field_offset,
                                                             Object* old_value, Object* new_value) {
  if (kCheckTransaction) {
    DCHECK_EQ(kTransactionActive, Runtime::Current()->IsActiveTransaction());
  }
  if (kVerifyFlags & kVerifyThis) {
    VerifyObject(this);
  }
  if (kVerifyFlags & kVerifyWrites) {
    VerifyObject(new_value);
  }
  if (kVerifyFlags & kVerifyReads) {
    VerifyObject(old_value);
  }
  if (kTransactionActive) {
    Runtime::Current()->RecordWriteFieldReference(this, field_offset, old_value, true);
  }
  HeapReference<Object> old_ref(HeapReference<Object>::FromMirrorPtr(old_value));
  HeapReference<Object> new_ref(HeapReference<Object>::FromMirrorPtr(new_value));
  byte* raw_addr = reinterpret_cast<byte*>(this) + field_offset.Int32Value();
  Atomic<uint32_t>* atomic_addr = reinterpret_cast<Atomic<uint32_t>*>(raw_addr);

  bool success = atomic_addr->CompareExchangeStrongSequentiallyConsistent(old_ref.reference_,
                                                                          new_ref.reference_);

  if (success) {
    Runtime::Current()->GetHeap()->WriteBarrierField(this, field_offset, new_value);
  }
  return success;
}

template<bool kVisitClass, bool kIsStatic, typename Visitor>
inline void Object::VisitFieldsReferences(uint32_t ref_offsets, const Visitor& visitor) {
  if (LIKELY(ref_offsets != CLASS_WALK_SUPER)) {
    if (!kVisitClass) {
     // Mask out the class from the reference offsets.
      ref_offsets ^= kWordHighBitMask;
    }
    DCHECK_EQ(ClassOffset().Uint32Value(), 0U);
    // Found a reference offset bitmap. Visit the specified offsets.
    while (ref_offsets != 0) {
      size_t right_shift = CLZ(ref_offsets);
      MemberOffset field_offset = CLASS_OFFSET_FROM_CLZ(right_shift);
      visitor(this, field_offset, kIsStatic);
      ref_offsets &= ~(CLASS_HIGH_BIT >> right_shift);
    }
  } else {
    // There is no reference offset bitmap.  In the non-static case, walk up the class
    // inheritance hierarchy and find reference offsets the hard way. In the static case, just
    // consider this class.
    for (mirror::Class* klass = kIsStatic ? AsClass() : GetClass(); klass != nullptr;
        klass = kIsStatic ? nullptr : klass->GetSuperClass()) {
      size_t num_reference_fields =
          kIsStatic ? klass->NumReferenceStaticFields() : klass->NumReferenceInstanceFields();
      if (num_reference_fields == 0u) {
        continue;
      }
      MemberOffset field_offset = kIsStatic
          ? klass->GetFirstReferenceStaticFieldOffset()
          : klass->GetFirstReferenceInstanceFieldOffset();
      for (size_t i = 0; i < num_reference_fields; ++i) {
        // TODO: Do a simpler check?
        if (kVisitClass || field_offset.Uint32Value() != ClassOffset().Uint32Value()) {
          visitor(this, field_offset, kIsStatic);
        }
        field_offset = MemberOffset(field_offset.Uint32Value() +
                                    sizeof(mirror::HeapReference<mirror::Object>));
      }
    }
  }
}

template<bool kVisitClass, typename Visitor>
inline void Object::VisitInstanceFieldsReferences(mirror::Class* klass, const Visitor& visitor) {
  VisitFieldsReferences<kVisitClass, false>(
      klass->GetReferenceInstanceOffsets<kVerifyNone>(), visitor);
}

template<bool kVisitClass, typename Visitor>
inline void Object::VisitStaticFieldsReferences(mirror::Class* klass, const Visitor& visitor) {
  DCHECK(!klass->IsTemp());
  klass->VisitFieldsReferences<kVisitClass, true>(
      klass->GetReferenceStaticOffsets<kVerifyNone>(), visitor);
}

template <const bool kVisitClass, VerifyObjectFlags kVerifyFlags, typename Visitor,
    typename JavaLangRefVisitor>
inline void Object::VisitReferences(const Visitor& visitor,
                                    const JavaLangRefVisitor& ref_visitor) {
  mirror::Class* klass = GetClass<kVerifyFlags>();
  if (klass == Class::GetJavaLangClass()) {
    AsClass<kVerifyNone>()->VisitReferences<kVisitClass>(klass, visitor);
  } else if (klass->IsArrayClass()) {
    if (klass->IsObjectArrayClass<kVerifyNone>()) {
      AsObjectArray<mirror::Object, kVerifyNone>()->VisitReferences<kVisitClass>(visitor);
    } else if (kVisitClass) {
      visitor(this, ClassOffset(), false);
    }
  } else {
    DCHECK(!klass->IsVariableSize());
    VisitInstanceFieldsReferences<kVisitClass>(klass, visitor);
    if (UNLIKELY(klass->IsTypeOfReferenceClass<kVerifyNone>())) {
      ref_visitor(klass, AsReference());
    }
  }
}
}  // namespace mirror
}  // namespace art

#endif  // ART_RUNTIME_MIRROR_OBJECT_INL_H_


text:
"""
Test mock script that prepares an Interop namespace and namespace provider,
and then compiles namespace-neutral MOF into the default namespace (which may
have been set from the outside).

This mock script uses 'new-style' setup for Python >=3.5 and 'old-style' setup
otherwise, and is therefore useable for all supported Python versions.
On Python <3.5, the tests using this script must be run from the repo main
directory.
"""

import sys
import os
import six
import pywbem_mock

# interop namespace used by this mock environment
INTEROP_NAMESPACE = 'interop'
THIRD_NAMESPACE = "root/cimv3"

def register_dependents(conn, this_file_path, dependent_file_names):
    """
    Register a dependent file name with the pywbemcli dependent file api.
    This insures that any change to a dependent file will cause the
    script to be recompiled.
    """
    if isinstance(dependent_file_names, six.string_types):
        dependent_file_names = [dependent_file_names]

    for fn in dependent_file_names:
        dep_path = os.path.join(os.path.dirname(this_file_path), fn)
        conn.provider_dependent_registry.add_dependents(this_file_path,
                                                        dep_path)

def _setup(conn, server, verbose):
    # pylint: disable=unused-argument
    """
    Setup for this mock script.

    Parameters:
      conn (FakedWBEMConnection): Connection
      server (PywbemServer): Server
      verbose (bool): Verbose flag
    """

    if sys.version_info >= (3, 5):
        this_file_path = __file__
    else:
        # Unfortunately, it does not seem to be possible to find the file path
        # of the current script when it is executed using exec(), so we hard
        # code the file path. This requires that the tests are run from the
        # repo main directory.
        this_file_path = 'tests/unit/pywbemcli/simple_interop_mock_script.py'
        assert os.path.exists(this_file_path)

    # Create the third namespace before the interop namespace is created
    # so that it exists when the pywbem server. This namespace creation done
    # before interop created because of pywbem issue #2865
    conn.add_namespace(THIRD_NAMESPACE, verbose=verbose)

    # Prepare an Interop namespace and namespace provider

    interop_mof_file = 'mock_interop.mof'
    if INTEROP_NAMESPACE not in conn.cimrepository.namespaces:
        conn.add_namespace(INTEROP_NAMESPACE, verbose=verbose)

    interop_mof_path = os.path.join(
        os.path.dirname(this_file_path), interop_mof_file)
    conn.compile_mof_file(interop_mof_path, namespace=INTEROP_NAMESPACE,
                          verbose=verbose)
    register_dependents(conn, this_file_path, interop_mof_file)

    ns_provider = pywbem_mock.CIMNamespaceProvider(conn.cimrepository)
    conn.register_provider(ns_provider, INTEROP_NAMESPACE, verbose=verbose)

    # Add namespace-neutral MOF to the default namespace and to the third
    # namespace

    mof_file = 'simple_mock_model.mof'
    mof_path = os.path.join(os.path.dirname(this_file_path), mof_file)
    register_dependents(conn, this_file_path, mof_file)

    conn.compile_mof_file(mof_path, namespace=None, verbose=verbose)

    # Create a third namespace that has same classes and the default
    # namespace but different instances
    # TODO add different class also

    # Add the same classes and instances as in root/cimv2
    conn.compile_mof_file(mof_path, namespace=THIRD_NAMESPACE, verbose=verbose)

    inst_mof = "instance of CIM_Foo{ " \
        "InstanceID = \"CIM_Foo3-third-ns\"; " \
        "IntegerProp = 3; " \
        "};"
    conn.compile_mof_string(inst_mof, namespace=THIRD_NAMESPACE,
                            verbose=verbose)

if sys.version_info >= (3, 5):
    # New-style setup

    # If the function is defined directly, it will be detected and refused
    # by the check for setup() functions on Python <3.5, despite being defined
    # only conditionally. The indirect approach with exec() addresses that.
    # pylint: disable=exec-used
    exec("""
def setup(conn, server, verbose):
    _setup(conn, server, verbose)
""")

else:
    # Old-style setup

    global CONN  # pylint: disable=global-at-module-level
    global SERVER  # pylint: disable=global-at-module-level
    global VERBOSE  # pylint: disable=global-at-module-level

    # pylint: disable=undefined-variable
    _setup(CONN, SERVER, VERBOSE)  # noqa: F821


text:
from flask import jsonify, request, abort, Blueprint
from werkzeug.exceptions import NotFound

from models import db, Task
from app.snippets import get_object_or_404

tasks = Blueprint('tasks', __name__)

@tasks.route('/', methods=['GET'])
def get_tasks():
    task_list = [
        task.serialize()
        for task
        in Task.query.limit(50).all()
    ]
    return jsonify(task_list)

@tasks.route('/', methods=['POST'])
def create_task():
    try:
        task = Task.create(**request.json)
        db.session.add(task)
        db.session.commit()
        return jsonify(task.serialize()), 201
    except Exception as err:
        abort(400, description=err)

@tasks.route('/<task_id>', methods=['GET'])
def get_task(task_id):
    task = get_object_or_404(Task, Task.id == task_id)
    return jsonify(task.serialize())

@tasks.route('/<task_id>', methods=['DELETE'])
def delete_task(task_id):
    try:
        task = get_object_or_404(Task, Task.id == task_id)
        db.session.delete(task)
        db.session.commit()
        return jsonify({}), 204
    except NotFound:
        raise
    except Exception as err:
        abort(400, description=err)


text:
layout: category/category_sections
sections:
  - What
  - Why
  - When
  - Support
---


text:
<?php

namespace Prooph\Link\ProcessManager\Api\Factory;

use Prooph\Link\ProcessManager\Api\WorkflowRelease;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;

/**
 * Resource Factory WorkflowReleaseFactory
 *
 * @package Prooph\Link\ProcessManager\Api\Factory
 * @author Alexander Miertsch <kontakt@codeliner.ws>
 */
final class WorkflowReleaseFactory implements FactoryInterface
{
    /**
     * Create service
     *
     * @param ServiceLocatorInterface $serviceLocator
     * @return WorkflowRelease
     */
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        $resource = new WorkflowRelease();

        $resource->setWorkflowFinder($serviceLocator->getServiceLocator()->get(\Prooph\Link\ProcessManager\Projection\Workflow\WorkflowFinder::class));

        return $resource;
    }
}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.redkale.mq;

import java.util.concurrent.CompletableFuture;
import java.util.logging.Logger;

/**
 *
 * <p>
 * 详情见: https://redkale.org
 *
 * @author zhangjx
 *
 * @since 2.1.0
 */
public abstract class MessageProducer {

    protected final Logger logger;

    protected final String name;

    protected volatile boolean closed;

    protected MessageProducer(String name, Logger logger) {
        this.name = name;
        this.logger = logger;
    }

    public abstract CompletableFuture<Void> apply(MessageRecord message);

    public abstract CompletableFuture<Void> startup();

    public boolean isClosed() {
        return closed;
    }

    public abstract CompletableFuture<Void> shutdown();
}


text:
pub trait Foo<T> {
    type A;

    fn get(&self, t: T) -> Self::A;
}

trait SomeTrait<I : for<'x> Foo<&'x isize>> {
    fn some_method(&self, arg: I::A);
    //~^ ERROR cannot use the associated type of a trait with uninferred generic parameters
}

trait AnotherTrait<I : for<'x> Foo<&'x isize>> {
    fn some_method(&self, arg: <I as Foo<&isize>>::A);
}

trait YetAnotherTrait<I : for<'x> Foo<&'x isize>> {
    fn some_method<'a>(&self, arg: <I as Foo<&'a isize>>::A);
}

trait Banana<'a> {
    type Assoc: Default;
}

struct Peach<X>(std::marker::PhantomData<X>);

impl<X: for<'a> Banana<'a>> Peach<X> {
    fn mango(&self) -> X::Assoc {
    //~^ ERROR cannot use the associated type of a trait with uninferred generic parameters
        Default::default()
    }
}

pub fn main() {}


text:
import fs from 'fs'
import path from 'path'

import { run, css } from './util/run'

test('collapse adjacent rules', () => {
  let config = {
    content: [path.resolve(__dirname, './collapse-adjacent-rules.test.html')],
    corePlugins: { preflight: false },
    theme: {},
    plugins: [],
  }

  let input = css`
    @tailwind base;
    @font-face {
      font-family: 'Inter';
      src: url('/fonts/Inter.woff2') format('woff2'), url('/fonts/Inter.woff') format('woff');
    }
    @font-face {
      font-family: 'Gilroy';
      src: url('/fonts/Gilroy.woff2') format('woff2'), url('/fonts/Gilroy.woff') format('woff');
    }
    @page {
      margin: 1cm;
    }
    @tailwind components;
    @tailwind utilities;
    @layer base {
      @font-face {
        font-family: 'Poppins';
        src: url('/fonts/Poppins.woff2') format('woff2'), url('/fonts/Poppins.woff') format('woff');
      }
      @font-face {
        font-family: 'Proxima Nova';
        src: url('/fonts/ProximaNova.woff2') format('woff2'),
          url('/fonts/ProximaNova.woff') format('woff');
      }
    }
    .foo,
    .bar {
      color: black;
    }
    .foo,
    .bar {
      font-weight: 700;
    }
  `

  return run(input, config).then((result) => {
    let expectedPath = path.resolve(__dirname, './collapse-adjacent-rules.test.css')
    let expected = fs.readFileSync(expectedPath, 'utf8')

    expect(result.css).toMatchFormattedCss(expected)
  })
})


text:
namespace Envoy {
namespace Upstream {

void ClusterManagerInitHelper::addCluster(Cluster& cluster) {
  if (state_ == State::AllClustersInitialized) {
    cluster.initialize();
    return;
  }

  if (cluster.initializePhase() == Cluster::InitializePhase::Primary) {
    primary_init_clusters_.push_back(&cluster);
    cluster.initialize();
  } else {
    ASSERT(cluster.initializePhase() == Cluster::InitializePhase::Secondary);
    secondary_init_clusters_.push_back(&cluster);
    if (started_secondary_initialize_) {
      // This can happen if we get a second CDS update that adds new clusters after we have
      // already started secondary init. In this case, just immediately initialize.
      cluster.initialize();
    }
  }

  log().info("cm init: adding: cluster={} primary={} secondary={}", cluster.info()->name(),
             primary_init_clusters_.size(), secondary_init_clusters_.size());
  cluster.setInitializedCb([&cluster, this]() -> void {
    ASSERT(state_ != State::AllClustersInitialized);
    removeCluster(cluster);
  });
}

void ClusterManagerInitHelper::removeCluster(Cluster& cluster) {
  if (state_ == State::AllClustersInitialized) {
    return;
  }

  // There is a remote edge case where we can remove a cluster via CDS that has not yet been
  // initialized. When called via the remove cluster API this code catches that case.
  std::list<Cluster*>* cluster_list;
  if (cluster.initializePhase() == Cluster::InitializePhase::Primary) {
    cluster_list = &primary_init_clusters_;
  } else {
    ASSERT(cluster.initializePhase() == Cluster::InitializePhase::Secondary);
    cluster_list = &secondary_init_clusters_;
  }

  // It is possible that the cluster we are removing has already been initialized, and is not
  // present in the initializer list. If so, this is fine.
  cluster_list->remove(&cluster);
  log().info("cm init: removing: cluster={} primary={} secondary={}", cluster.info()->name(),
             primary_init_clusters_.size(), secondary_init_clusters_.size());
  maybeFinishInitialize();
}

void ClusterManagerInitHelper::maybeFinishInitialize() {
  // Do not do anything if we are still doing the initial static load or if we are waiting for
  // CDS initialize.
  if (state_ == State::Loading || state_ == State::WaitingForCdsInitialize) {
    return;
  }

  // If we are still waiting for primary clusters to initialize, do nothing.
  ASSERT(state_ == State::WaitingForStaticInitialize || state_ == State::CdsInitialized);
  if (!primary_init_clusters_.empty()) {
    return;
  }

  // If we are still waiting for secondary clusters to initialize, see if we need to first call
  // initialize on them. This is only done once.
  if (!secondary_init_clusters_.empty()) {
    if (!started_secondary_initialize_) {
      log().info("cm init: initializing secondary clusters");
      started_secondary_initialize_ = true;
      // Cluster::initialize() method can modify the list of secondary_init_clusters_ to remove
      // the item currently being initialized, so we eschew range-based-for and do this complicated
      // dance to increment the iterator before calling initialize.
      for (auto iter = secondary_init_clusters_.begin(); iter != secondary_init_clusters_.end();) {
        Cluster* cluster = *iter;
        ++iter;
        cluster->initialize();
      }
    }

    return;
  }

  // At this point, if we are doing static init, and we have CDS, start CDS init. Otherwise, move
  // directly to initialized.
  started_secondary_initialize_ = false;
  if (state_ == State::WaitingForStaticInitialize && cds_) {
    log().info("cm init: initializing cds");
    state_ = State::WaitingForCdsInitialize;
    cds_->initialize();
  } else {
    state_ = State::AllClustersInitialized;
    if (initialized_callback_) {
      initialized_callback_();
    }
  }
}

void ClusterManagerInitHelper::onStaticLoadComplete() {
  ASSERT(state_ == State::Loading);
  state_ = State::WaitingForStaticInitialize;
  maybeFinishInitialize();
}

void ClusterManagerInitHelper::setCds(CdsApi* cds) {
  ASSERT(state_ == State::Loading);
  cds_ = cds;
  if (cds_) {
    cds_->setInitializedCb([this]() -> void {
      ASSERT(state_ == State::WaitingForCdsInitialize);
      state_ = State::CdsInitialized;
      maybeFinishInitialize();
    });
  }
}

void ClusterManagerInitHelper::setInitializedCb(std::function<void()> callback) {
  if (state_ == State::AllClustersInitialized) {
    callback();
  } else {
    initialized_callback_ = callback;
  }
}

ClusterManagerImpl::ClusterManagerImpl(const Json::Object& config, ClusterManagerFactory& factory,
                                       Stats::Store& stats, ThreadLocal::Instance& tls,
                                       Runtime::Loader& runtime, Runtime::RandomGenerator& random,
                                       const LocalInfo::LocalInfo& local_info,
                                       AccessLog::AccessLogManager& log_manager)
    : factory_(factory), runtime_(runtime), stats_(stats), tls_(tls), random_(random),
      thread_local_slot_(tls.allocateSlot()), local_info_(local_info),
      cm_stats_(generateStats(stats)) {

  config.validateSchema(Json::Schema::CLUSTER_MANAGER_SCHEMA);

  if (config.hasObject("outlier_detection")) {
    std::string event_log_file_path =
        config.getObject("outlier_detection")->getString("event_log_path", "");
    if (!event_log_file_path.empty()) {
      outlier_event_logger_.reset(new Outlier::EventLoggerImpl(log_manager, event_log_file_path,
                                                               ProdSystemTimeSource::instance_,
                                                               ProdMonotonicTimeSource::instance_));
    }
  }

  if (config.hasObject("sds")) {
    loadCluster(*config.getObject("sds")->getObject("cluster"), false);

    SdsConfig sds_config{
        config.getObject("sds")->getObject("cluster")->getString("name"),
        std::chrono::milliseconds(config.getObject("sds")->getInteger("refresh_delay_ms"))};

    sds_config_.value(sds_config);
  }

  if (config.hasObject("cds")) {
    loadCluster(*config.getObject("cds")->getObject("cluster"), false);
  }

  // We can now potentially create the CDS API once the backing cluster exists.
  cds_api_ = factory_.createCds(config, *this);
  init_helper_.setCds(cds_api_.get());

  for (const Json::ObjectPtr& cluster : config.getObjectArray("clusters")) {
    loadCluster(*cluster, false);
  }

  Optional<std::string> local_cluster_name;
  if (config.hasObject("local_cluster_name")) {
    local_cluster_name.value(config.getString("local_cluster_name"));
    if (primary_clusters_.find(local_cluster_name.value()) == primary_clusters_.end()) {
      throw EnvoyException(
          fmt::format("local cluster '{}' must be defined", local_cluster_name.value()));
    }
  }

  tls.set(thread_local_slot_,
          [this, local_cluster_name](Event::Dispatcher& dispatcher)
              -> ThreadLocal::ThreadLocalObjectSharedPtr {
                return ThreadLocal::ThreadLocalObjectSharedPtr{
                    new ThreadLocalClusterManagerImpl(*this, dispatcher, local_cluster_name)};
              });

  // To avoid threading issues, for those clusters that start with hosts already in them (like the
  // static cluster), we need to post an update onto each thread to notify them of the update. We
  // also require this for dynamic clusters where an immediate resolve occurred in the cluster
  // constructor, prior to the member update callback being configured.
  for (auto& cluster : primary_clusters_) {
    postInitializeCluster(*cluster.second.cluster_);
  }

  init_helper_.onStaticLoadComplete();
}

ClusterManagerStats ClusterManagerImpl::generateStats(Stats::Scope& scope) {
  std::string final_prefix = "cluster_manager.";
  return {ALL_CLUSTER_MANAGER_STATS(POOL_COUNTER_PREFIX(scope, final_prefix),
                                    POOL_GAUGE_PREFIX(scope, final_prefix))};
}

void ClusterManagerImpl::postInitializeCluster(Cluster& cluster) {
  if (cluster.hosts().empty()) {
    return;
  }

  postThreadLocalClusterUpdate(cluster, cluster.hosts(), std::vector<HostSharedPtr>{});
}

bool ClusterManagerImpl::addOrUpdatePrimaryCluster(const Json::Object& new_config) {
  // First we need to see if this new config is new or an update to an existing dynamic cluster.
  // We don't allow updates to statically configured clusters in the main configuration.
  std::string cluster_name = new_config.getString("name");
  auto existing_cluster = primary_clusters_.find(cluster_name);
  if (existing_cluster != primary_clusters_.end() &&
      (!existing_cluster->second.added_via_api_ ||
       existing_cluster->second.config_hash_ == new_config.hash())) {
    return false;
  }

  if (existing_cluster != primary_clusters_.end()) {
    init_helper_.removeCluster(*existing_cluster->second.cluster_);
  }

  loadCluster(new_config, true);
  ClusterInfoConstSharedPtr new_cluster = primary_clusters_.at(cluster_name).cluster_->info();
  tls_.runOnAllThreads([this, new_cluster]() -> void {
    ThreadLocalClusterManagerImpl& cluster_manager =
        tls_.getTyped<ThreadLocalClusterManagerImpl>(thread_local_slot_);

    cluster_manager.thread_local_clusters_[new_cluster->name()].reset(
        new ThreadLocalClusterManagerImpl::ClusterEntry(cluster_manager, new_cluster));
  });

  postInitializeCluster(*primary_clusters_.at(cluster_name).cluster_);
  return true;
}

bool ClusterManagerImpl::removePrimaryCluster(const std::string& cluster_name) {
  auto existing_cluster = primary_clusters_.find(cluster_name);
  if (existing_cluster == primary_clusters_.end() || !existing_cluster->second.added_via_api_) {
    return false;
  }

  init_helper_.removeCluster(*existing_cluster->second.cluster_);
  primary_clusters_.erase(existing_cluster);
  cm_stats_.cluster_removed_.inc();
  cm_stats_.total_clusters_.set(primary_clusters_.size());
  tls_.runOnAllThreads([this, cluster_name]() -> void {
    ThreadLocalClusterManagerImpl& cluster_manager =
        tls_.getTyped<ThreadLocalClusterManagerImpl>(thread_local_slot_);

    cluster_manager.thread_local_clusters_.erase(cluster_name);
  });

  return true;
}

void ClusterManagerImpl::loadCluster(const Json::Object& cluster, bool added_via_api) {
  ClusterPtr new_cluster =
      factory_.clusterFromJson(cluster, *this, sds_config_, outlier_event_logger_);

  init_helper_.addCluster(*new_cluster);
  if (!added_via_api) {
    if (primary_clusters_.find(new_cluster->info()->name()) != primary_clusters_.end()) {
      throw EnvoyException(
          fmt::format("cluster manager: duplicate cluster '{}'", new_cluster->info()->name()));
    }
  }

  const Cluster& primary_cluster_reference = *new_cluster;
  new_cluster->addMemberUpdateCb(
      [&primary_cluster_reference, this](const std::vector<HostSharedPtr>& hosts_added,
                                         const std::vector<HostSharedPtr>& hosts_removed) {
        // This fires when a cluster is about to have an updated member set. We need to send this
        // out to all of the thread local configurations.
        postThreadLocalClusterUpdate(primary_cluster_reference, hosts_added, hosts_removed);
      });

  // emplace() will do nothing if the key already exists. Always erase first.
  size_t num_erased = primary_clusters_.erase(primary_cluster_reference.info()->name());
  primary_clusters_.emplace(
      primary_cluster_reference.info()->name(),
      PrimaryClusterData{cluster.hash(), added_via_api, std::move(new_cluster)});

  cm_stats_.total_clusters_.set(primary_clusters_.size());
  if (num_erased) {
    cm_stats_.cluster_modified_.inc();
  } else {
    cm_stats_.cluster_added_.inc();
  }
}

ThreadLocalCluster* ClusterManagerImpl::get(const std::string& cluster) {
  ThreadLocalClusterManagerImpl& cluster_manager =
      tls_.getTyped<ThreadLocalClusterManagerImpl>(thread_local_slot_);

  auto entry = cluster_manager.thread_local_clusters_.find(cluster);
  if (entry != cluster_manager.thread_local_clusters_.end()) {
    return entry->second.get();
  } else {
    return nullptr;
  }
}

Http::ConnectionPool::Instance*
ClusterManagerImpl::httpConnPoolForCluster(const std::string& cluster, ResourcePriority priority,
                                           LoadBalancerContext* context) {
  ThreadLocalClusterManagerImpl& cluster_manager =
      tls_.getTyped<ThreadLocalClusterManagerImpl>(thread_local_slot_);

  // Select a host and create a connection pool for it if it does not already exist.
  auto entry = cluster_manager.thread_local_clusters_.find(cluster);
  if (entry == cluster_manager.thread_local_clusters_.end()) {
    return nullptr;
  }

  return entry->second->connPool(priority, context);
}

void ClusterManagerImpl::postThreadLocalClusterUpdate(
    const Cluster& primary_cluster, const std::vector<HostSharedPtr>& hosts_added,
    const std::vector<HostSharedPtr>& hosts_removed) {
  const std::string& name = primary_cluster.info()->name();
  HostVectorConstSharedPtr hosts_copy(new std::vector<HostSharedPtr>(primary_cluster.hosts()));
  HostVectorConstSharedPtr healthy_hosts_copy(
      new std::vector<HostSharedPtr>(primary_cluster.healthyHosts()));
  HostListsConstSharedPtr hosts_per_zone_copy(
      new std::vector<std::vector<HostSharedPtr>>(primary_cluster.hostsPerZone()));
  HostListsConstSharedPtr healthy_hosts_per_zone_copy(
      new std::vector<std::vector<HostSharedPtr>>(primary_cluster.healthyHostsPerZone()));

  tls_.runOnAllThreads([this, name, hosts_copy, healthy_hosts_copy, hosts_per_zone_copy,
                        healthy_hosts_per_zone_copy, hosts_added, hosts_removed]() -> void {
    ThreadLocalClusterManagerImpl::updateClusterMembership(
        name, hosts_copy, healthy_hosts_copy, hosts_per_zone_copy, healthy_hosts_per_zone_copy,
        hosts_added, hosts_removed, tls_, thread_local_slot_);
  });
}

Host::CreateConnectionData ClusterManagerImpl::tcpConnForCluster(const std::string& cluster) {
  ThreadLocalClusterManagerImpl& cluster_manager =
      tls_.getTyped<ThreadLocalClusterManagerImpl>(thread_local_slot_);

  auto entry = cluster_manager.thread_local_clusters_.find(cluster);
  if (entry == cluster_manager.thread_local_clusters_.end()) {
    throw EnvoyException(fmt::format("unknown cluster '{}'", cluster));
  }

  HostConstSharedPtr logical_host = entry->second->lb_->chooseHost(nullptr);
  if (logical_host) {
    return logical_host->createConnection(cluster_manager.thread_local_dispatcher_);
  } else {
    entry->second->cluster_info_->stats().upstream_cx_none_healthy_.inc();
    return {nullptr, nullptr};
  }
}

Http::AsyncClient& ClusterManagerImpl::httpAsyncClientForCluster(const std::string& cluster) {
  ThreadLocalClusterManagerImpl& cluster_manager =
      tls_.getTyped<ThreadLocalClusterManagerImpl>(thread_local_slot_);
  auto entry = cluster_manager.thread_local_clusters_.find(cluster);
  if (entry != cluster_manager.thread_local_clusters_.end()) {
    return entry->second->http_async_client_;
  } else {
    throw EnvoyException(fmt::format("unknown cluster '{}'", cluster));
  }
}

ClusterManagerImpl::ThreadLocalClusterManagerImpl::ThreadLocalClusterManagerImpl(
    ClusterManagerImpl& parent, Event::Dispatcher& dispatcher,
    const Optional<std::string>& local_cluster_name)
    : parent_(parent), thread_local_dispatcher_(dispatcher) {
  // If local cluster is defined then we need to initialize it first.
  if (local_cluster_name.valid()) {
    auto& local_cluster = parent.primary_clusters_.at(local_cluster_name.value()).cluster_;
    thread_local_clusters_[local_cluster_name.value()].reset(
        new ClusterEntry(*this, local_cluster->info()));
  }

  local_host_set_ = local_cluster_name.valid()
                        ? &thread_local_clusters_[local_cluster_name.value()]->host_set_
                        : nullptr;

  for (auto& cluster : parent.primary_clusters_) {
    // If local cluster name is set then we already initialized this cluster.
    if (local_cluster_name.valid() && local_cluster_name.value() == cluster.first) {
      continue;
    }

    thread_local_clusters_[cluster.first].reset(
        new ClusterEntry(*this, cluster.second.cluster_->info()));
  }
}

ClusterManagerImpl::ThreadLocalClusterManagerImpl::~ThreadLocalClusterManagerImpl() {
  ASSERT(thread_local_clusters_.empty());
  ASSERT(host_http_conn_pool_map_.empty());
}

void ClusterManagerImpl::ThreadLocalClusterManagerImpl::drainConnPools(
    const std::vector<HostSharedPtr>& hosts) {
  for (const HostSharedPtr& host : hosts) {
    auto container = host_http_conn_pool_map_.find(host);
    if (container != host_http_conn_pool_map_.end()) {
      drainConnPools(host, container->second);
    }
  }
}

void ClusterManagerImpl::ThreadLocalClusterManagerImpl::drainConnPools(
    HostSharedPtr old_host, ConnPoolsContainer& container) {
  for (const Http::ConnectionPool::InstancePtr& pool : container.pools_) {
    if (pool) {
      container.drains_remaining_++;
    }
  }

  for (const Http::ConnectionPool::InstancePtr& pool : container.pools_) {
    if (!pool) {
      continue;
    }

    pool->addDrainedCallback([this, old_host]() -> void {
      ConnPoolsContainer& container = host_http_conn_pool_map_[old_host];
      ASSERT(container.drains_remaining_ > 0);
      container.drains_remaining_--;
      if (container.drains_remaining_ == 0) {
        for (Http::ConnectionPool::InstancePtr& pool : container.pools_) {
          thread_local_dispatcher_.deferredDelete(std::move(pool));
        }
        host_http_conn_pool_map_.erase(old_host);
      }
    });
  }
}

void ClusterManagerImpl::ThreadLocalClusterManagerImpl::updateClusterMembership(
    const std::string& name, HostVectorConstSharedPtr hosts, HostVectorConstSharedPtr healthy_hosts,
    HostListsConstSharedPtr hosts_per_zone, HostListsConstSharedPtr healthy_hosts_per_zone,
    const std::vector<HostSharedPtr>& hosts_added, const std::vector<HostSharedPtr>& hosts_removed,
    ThreadLocal::Instance& tls, uint32_t thead_local_slot) {

  ThreadLocalClusterManagerImpl& config =
      tls.getTyped<ThreadLocalClusterManagerImpl>(thead_local_slot);

  ASSERT(config.thread_local_clusters_.find(name) != config.thread_local_clusters_.end());
  config.thread_local_clusters_[name]->host_set_.updateHosts(
      hosts, healthy_hosts, hosts_per_zone, healthy_hosts_per_zone, hosts_added, hosts_removed);
}

void ClusterManagerImpl::ThreadLocalClusterManagerImpl::shutdown() {
  // Clear out connection pools as well as the thread local cluster map so that we release all
  // primary cluster pointers.
  host_http_conn_pool_map_.clear();
  thread_local_clusters_.clear();
}

ClusterManagerImpl::ThreadLocalClusterManagerImpl::ClusterEntry::ClusterEntry(
    ThreadLocalClusterManagerImpl& parent, ClusterInfoConstSharedPtr cluster)
    : parent_(parent), cluster_info_(cluster),
      http_async_client_(*cluster, parent.parent_.stats_, parent.thread_local_dispatcher_,
                         parent.parent_.local_info_, parent.parent_, parent.parent_.runtime_,
                         parent.parent_.random_,
                         Router::ShadowWriterPtr{new Router::ShadowWriterImpl(parent.parent_)}) {

  switch (cluster->lbType()) {
  case LoadBalancerType::LeastRequest: {
    lb_.reset(new LeastRequestLoadBalancer(host_set_, parent.local_host_set_, cluster->stats(),
                                           parent.parent_.runtime_, parent.parent_.random_));
    break;
  }
  case LoadBalancerType::Random: {
    lb_.reset(new RandomLoadBalancer(host_set_, parent.local_host_set_, cluster->stats(),
                                     parent.parent_.runtime_, parent.parent_.random_));
    break;
  }
  case LoadBalancerType::RoundRobin: {
    lb_.reset(new RoundRobinLoadBalancer(host_set_, parent.local_host_set_, cluster->stats(),
                                         parent.parent_.runtime_, parent.parent_.random_));
    break;
  }
  case LoadBalancerType::RingHash: {
    lb_.reset(new RingHashLoadBalancer(host_set_, cluster->stats(), parent.parent_.runtime_,
                                       parent.parent_.random_));
    break;
  }
  }

  host_set_.addMemberUpdateCb([this](const std::vector<HostSharedPtr>&,
                                     const std::vector<HostSharedPtr>& hosts_removed) -> void {
    // We need to go through and purge any connection pools for hosts that got deleted.
    // Even if two hosts actually point to the same address this will be safe, since if a
    // host is readded it will be a different physical HostSharedPtr.
    parent_.drainConnPools(hosts_removed);
  });
}

ClusterManagerImpl::ThreadLocalClusterManagerImpl::ClusterEntry::~ClusterEntry() {
  // We need to drain all connection pools for the cluster being removed. Then we can remove the
  // cluster.
  //
  // TODO(mattklein123): Optimally, we would just fire member changed callbacks and remove all of
  // the hosts inside of the HostImpl destructor. That is a change with wide implications, so we are
  // going with a more targeted approach for now.
  parent_.drainConnPools(host_set_.hosts());
}

Http::ConnectionPool::Instance*
ClusterManagerImpl::ThreadLocalClusterManagerImpl::ClusterEntry::connPool(
    ResourcePriority priority, LoadBalancerContext* context) {
  HostConstSharedPtr host = lb_->chooseHost(context);
  if (!host) {
    cluster_info_->stats().upstream_cx_none_healthy_.inc();
    return nullptr;
  }

  ConnPoolsContainer& container = parent_.host_http_conn_pool_map_[host];
  ASSERT(enumToInt(priority) < container.pools_.size());
  if (!container.pools_[enumToInt(priority)]) {
    container.pools_[enumToInt(priority)] =
        parent_.parent_.factory_.allocateConnPool(parent_.thread_local_dispatcher_, host, priority);
  }

  return container.pools_[enumToInt(priority)].get();
}

Http::ConnectionPool::InstancePtr
ProdClusterManagerFactory::allocateConnPool(Event::Dispatcher& dispatcher, HostConstSharedPtr host,
                                            ResourcePriority priority) {
  if ((host->cluster().features() & ClusterInfo::Features::HTTP2) &&
      runtime_.snapshot().featureEnabled("upstream.use_http2", 100)) {
    return Http::ConnectionPool::InstancePtr{
        new Http::Http2::ProdConnPoolImpl(dispatcher, host, priority)};
  } else {
    return Http::ConnectionPool::InstancePtr{
        new Http::Http1::ConnPoolImplProd(dispatcher, host, priority)};
  }
}

ClusterPtr
ProdClusterManagerFactory::clusterFromJson(const Json::Object& cluster, ClusterManager& cm,
                                           const Optional<SdsConfig>& sds_config,
                                           Outlier::EventLoggerSharedPtr outlier_event_logger) {
  return ClusterImplBase::create(cluster, cm, stats_, tls_, dns_resolver_, ssl_context_manager_,
                                 runtime_, random_, primary_dispatcher_, sds_config, local_info_,
                                 outlier_event_logger);
}

CdsApiPtr ProdClusterManagerFactory::createCds(const Json::Object& config, ClusterManager& cm) {
  return CdsApiImpl::create(config, cm, primary_dispatcher_, random_, local_info_, stats_);
}

} // Upstream
} // Envoy


text:
#import <UIKit/UIKit.h>

#import "MADayView.h" // MADayViewDataSource,MADayViewDelegate

@interface DayViewExampleController : UIViewController<MADayViewDataSource,MADayViewDelegate> {

}

@end