text:
import Asset from './Asset';

// TODO add:
//  disableFocusOnAndroid
//  audio routes (at least did become noisy on android)
//  pan
//  pitch
//  API to explicitly request audio focus / session
//  API to select stream type on Android
//  subtitles API

export type PlaybackSource = number | { uri: string } | Asset;

export type PlaybackStatus =
  | {
      isLoaded: false,
      androidImplementation?: string,
      error?: string, // populated exactly once when an error forces the object to unload
    }
  | {
      isLoaded: true,
      androidImplementation?: string,

      uri: string,

      progressUpdateIntervalMillis: number,
      durationMillis?: number,
      positionMillis: number,
      playableDurationMillis?: number,

      shouldPlay: boolean,
      isPlaying: boolean,
      isBuffering: boolean,

      rate: number,
      shouldCorrectPitch: boolean,
      volume: number,
      isMuted: boolean,
      isLooping: boolean,

      didJustFinish: boolean, // true exactly once when the track plays to finish
    };

export type PlaybackStatusToSet = {
  androidImplementation?: string,
  progressUpdateIntervalMillis?: number,
  positionMillis?: number,
  shouldPlay?: boolean,
  rate?: number,
  shouldCorrectPitch?: boolean,
  volume?: number,
  isMuted?: boolean,
  isLooping?: boolean,
};

export const _DEFAULT_PROGRESS_UPDATE_INTERVAL_MILLIS: number = 500;
export const _DEFAULT_INITIAL_PLAYBACK_STATUS: PlaybackStatusToSet = {
  positionMillis: 0,
  progressUpdateIntervalMillis: _DEFAULT_PROGRESS_UPDATE_INTERVAL_MILLIS,
  shouldPlay: false,
  rate: 1.0,
  shouldCorrectPitch: false,
  volume: 1.0,
  isMuted: false,
  isLooping: false,
};

const _getAssetFromPlaybackSource = (source: ?PlaybackSource): ?Asset => {
  if (source == null) {
    return null;
  }

  let asset: ?Asset = null;
  if (typeof source === 'number') {
    asset = Asset.fromModule(source);
  } else if ('constructor' in source && source.constructor.name === 'Asset') {
    asset = source;
  }
  return asset;
};

export const _getURIFromSource = (source: ?PlaybackSource): ?string => {
  let uri: ?string = null;
  let asset: ?Asset = _getAssetFromPlaybackSource(source);
  if (asset != null) {
    uri = asset.localUri || asset.uri;
  } else if (
    source != null &&
    typeof source !== 'number' &&
    'uri' in source &&
    typeof source.uri === 'string'
  ) {
    uri = source.uri;
  }
  return uri;
};

export const _throwErrorIfValuesOutOfBoundsInStatus = async (
  status: PlaybackStatusToSet
) => {
  if (
    typeof status.rate === 'number' &&
    (status.rate < 0.0 || status.rate > 32.0)
  ) {
    throw new Error('Rate value must be between 0.0 and 32.0.');
  }
  if (
    typeof status.volume === 'number' &&
    (status.volume < 0.0 || status.volume > 1.0)
  ) {
    throw new Error('Volume value must be between 0.0 and 1.0.');
  }
};

export const _getURIAndFullInitialStatusForLoadAsync = async (
  source: ?PlaybackSource,
  initialStatus: ?PlaybackStatusToSet,
  downloadFirst: boolean
): Promise<{ uri: string, fullInitialStatus: PlaybackStatusToSet }> => {
  // Download first if necessary.
  let asset: ?Asset = _getAssetFromPlaybackSource(source);
  if (downloadFirst && asset != null) {
    // TODO we can download remote uri too once @nikki93 has integrated this into Asset
    await asset.downloadAsync();
  }

  // Get the URI
  const uri: ?string = _getURIFromSource(source);
  if (uri == null) {
    throw new Error('Cannot load null source!');
  }

  // Get the full initial status
  const fullInitialStatus: PlaybackStatusToSet =
    initialStatus == null
      ? _DEFAULT_INITIAL_PLAYBACK_STATUS
      : {
          ..._DEFAULT_INITIAL_PLAYBACK_STATUS,
          ...initialStatus,
        };
  _throwErrorIfValuesOutOfBoundsInStatus(fullInitialStatus);

  return { uri, fullInitialStatus };
};

export const _getUnloadedStatus = (error: ?string = null): PlaybackStatus => {
  const status: Object = { isLoaded: false };
  if (error) {
    status.error = error;
  }
  return status;
};

// TODO Unify 8 native calls into 4 by folding out PlayerData and then setting it in the Video component.
export const _COMMON_AV_PLAYBACK_METHODS = {
  // The following are separately defined in each playback object:
  //   getStatusAsync
  //   setOnPlaybackStatusUpdate
  //   loadAsync
  //   unloadAsync
  //   setStatusAsync

  async playAsync(): Promise<PlaybackStatus> {
    return this.setStatusAsync({ shouldPlay: true });
  },
  async playFromPositionAsync(positionMillis: number): Promise<PlaybackStatus> {
    return this.setStatusAsync({ positionMillis, shouldPlay: true });
  },
  async pauseAsync(): Promise<PlaybackStatus> {
    return this.setStatusAsync({ shouldPlay: false });
  },
  async stopAsync(): Promise<PlaybackStatus> {
    return this.setStatusAsync({ positionMillis: 0, shouldPlay: false });
  },
  async setPositionAsync(positionMillis: number): Promise<PlaybackStatus> {
    return this.setStatusAsync({ positionMillis });
  },
  async setRateAsync(
    rate: number,
    shouldCorrectPitch: boolean
  ): Promise<PlaybackStatus> {
    return this.setStatusAsync({ rate, shouldCorrectPitch });
  },
  async setVolumeAsync(volume: number): Promise<PlaybackStatus> {
    return this.setStatusAsync({ volume });
  },
  async setIsMutedAsync(isMuted: boolean): Promise<PlaybackStatus> {
    return this.setStatusAsync({ isMuted });
  },
  async setIsLoopingAsync(isLooping: boolean): Promise<PlaybackStatus> {
    return this.setStatusAsync({ isLooping });
  },
  async setProgressUpdateIntervalAsync(
    progressUpdateIntervalMillis: number
  ): Promise<PlaybackStatus> {
    return this.setStatusAsync({ progressUpdateIntervalMillis });
  },
};


text:
package org.apache.camel.component.jms;

import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Session;

import org.apache.camel.BindToRegistry;
import org.apache.camel.CamelContext;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.test.junit5.CamelTestSupport;
import org.junit.jupiter.api.Test;
import org.springframework.jms.support.destination.DestinationResolutionException;
import org.springframework.jms.support.destination.DestinationResolver;

import static org.apache.camel.component.jms.JmsComponent.jmsComponentAutoAcknowledge;

/**
 *
 */
public class JmsInOnlyInvalidDestinationTest extends CamelTestSupport {

    @BindToRegistry("myResolver")
    private MyDestinationResolver resolver = new MyDestinationResolver();

    @Test
    public void testInvalidDestination() throws Exception {
        getMockEndpoint("mock:dead").expectedMessageCount(1);

        template.sendBodyAndHeader("direct:foo", "Hello World", "foo", "activemq:queue:foo?destinationResolver=#myResolver");

        assertMockEndpointsSatisfied();
    }

    @Override
    protected CamelContext createCamelContext() throws Exception {
        CamelContext camelContext = super.createCamelContext();
        ConnectionFactory connectionFactory = CamelJmsTestHelper.createConnectionFactory();
        camelContext.addComponent("activemq", jmsComponentAutoAcknowledge(connectionFactory));
        return camelContext;
    }

    @Override
    protected RouteBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                errorHandler(deadLetterChannel("mock:dead").maximumRedeliveries(1));

                from("direct:foo").recipientList(header("foo"));
            }
        };
    }

    private static class MyDestinationResolver implements DestinationResolver {

        @Override
        public Destination resolveDestinationName(Session session, String destinationName, boolean pubSubDomain)
                throws JMSException {
            throw new DestinationResolutionException("Forced");
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
#include "logger.hpp"

namespace RESTClient {

#if MIN_LOG_LEVEL != NONE
std::string log_channel;
#endif

} /* RESTClient */


text:
/*
SEE: prev/next
SEE: dateIncrement tests in fullcalendar-scheduler
*/


text:
[![CI Status](http://img.shields.io/travis/corin8823/Popover.svg?style=flat)](https://travis-ci.org/corin8823/Popover)
[![Version](https://img.shields.io/cocoapods/v/Popover.svg?style=flat)](http://cocoapods.org/pods/Popover)
[![License](https://img.shields.io/cocoapods/l/Popover.svg?style=flat)](http://cocoapods.org/pods/Popover)
[![Platform](https://img.shields.io/cocoapods/p/Popover.svg?style=flat)](http://cocoapods.org/pods/Popover)

## Description and [appetize.io`s DEMO](https://appetize.io/app/q4n81yf0aakkx20x2cejh107b4)

![](https://github.com/corin8823/Popover/blob/master/ScreenShots/Screenshot.gif)

## Usage

To run the example project, clone the repo, and run `pod install` from the Example directory first.

### Simple

```swift
let startPoint = CGPoint(x: self.view.frame.width - 60, y: 55)
let aView = UIView(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: 180))
let popover = Popover()
popover.show(aView, point: startPoint)
```

### Custom

```swift
@IBOutlet weak var leftBottomButton: UIButton!

let width = self.view.frame.width / 4
let aView = UIView(frame: CGRect(x: 0, y: 0, width: width, height: width))
let options = [
  .type(.up),
  .cornerRadius(width / 2),
  .animationIn(0.3),
  .blackOverlayColor(UIColor.red),
  .arrowSize(CGSize.zero)
  ] as [PopoverOption]
let popover = Popover(options: options, showHandler: nil, dismissHandler: nil)
popover.show(aView, fromView: self.leftBottomButton)
```

## Requirements
- iOS 9.0+
- Swift 5

## Installation

### CocoaPods (iOS 8+)
Popover is available through [CocoaPods](http://cocoapods.org). To install
it, simply add the following line to your `Podfile`:

```ruby
use_frameworks!
pod "Popover"
```

### Carthage (iOS 8+)
You can use [Carthage](https://github.com/Carthage/Carthage) to install `Popover` by adding it to your `Cartfile`:
```ruby
github "corin8823/Popover"
```

### Manual Installation
The class file required for Popover is located in the Classes folder in the root of this repository as listed below:
```
Popover.swift
```

## Customization

### Enum
- ``case arrowSize(CGSize)``
- ``case animationIn(NSTimeInterval)``
- ``case animationOut(NSTimeInterval)``
- ``case cornerRadius(CGFloat)``
- ``case sideEdge(CGFloat)``
- ``case blackOverlayColor(UIColor)``
- ``case overlayBlur(UIBlurEffectStyle)``
- ``case type(Popover.PopoverType)``
- ``case color(UIColor)``
- ``case dismissOnBlackOverlayTap(Bool)``
- ``case showBlackOverlay(Bool)``

### Property
- ``arrowSize: CGSize = CGSize(width: 16.0, height: 10.0)``
- ``animationIn: NSTimeInterval = 0.6``
- ``animationOut: NSTimeInterval = 0.3``
- ``cornerRadius: CGFloat = 6.0``
- ``sideEdge: CGFloat = 20.0``
- ``popoverType: PopoverType = .down``
- ``blackOverlayColor: UIColor = UIColor(white: 0.0, alpha: 0.2)``
- ``overlayBlur: UIBlurEffect?``
- ``popoverColor: UIColor = UIColor.white``

## Acknowledgments
Inspired by [DXPopover](https://github.com/xiekw2010/DXPopover) in [xiekw2010](https://github.com/xiekw2010)

## License

Popover is available under the MIT license. See the LICENSE file for more info.


text:
@implementation CircleProgressView

{
    CGFloat fakeProgress;
    NSTimer *timer;//定时器用作动画
}

- (instancetype)init {
    if (self = [super init]) {
        [self initialization];
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        [self initialization];
    }
    return self;
}

//初始化
- (instancetype)initWithFrame:(CGRect)frame
                pathBackColor:(UIColor *)pathBackColor
                pathFillColor:(UIColor *)pathFillColor
                   startAngle:(CGFloat)startAngle
                  strokeWidth:(CGFloat)strokeWidth {
    if (self = [super initWithFrame:frame]) {
        [self initialization];
        if (pathBackColor) {
            _pathBackColor = pathBackColor;
        }
        if (pathFillColor) {
            _pathFillColor = pathFillColor;
        }
        _startAngle = CircleDegreeToRadian(startAngle);
        _strokeWidth = strokeWidth;
    }
    return self;
}

//初始化数据
- (void)initialization {
    self.backgroundColor = [UIColor clearColor];
    _pathBackColor = [UIColor colorWithRed:204 green:204 blue:204 alpha:1];//RGB(204, 204, 204);
    _pathFillColor = [UIColor colorWithRed:219 green:184 blue:102 alpha:1];//RGB(219, 184, 102);
    _strokeWidth = 10;//线宽默认为10
    _startAngle = -CircleDegreeToRadian(90);//圆起点位置
    _reduceValue = CircleDegreeToRadian(0);//整个圆缺少的角度
    _animationModel = CircleIncreaseByProgress;//根据进度来
    _showPoint = YES;//小圆点
    _showProgressText = YES;//文字
    _forceRefresh = NO;//一直刷新动画

    fakeProgress = 0.0;//用来逐渐增加直到等于progress的值
    //起点图片
    //    _pointImage = [UIImage imageNamed:@"circle_point1"];
}

#pragma mark - Setter/Getter
- (void)setStartAngle:(CGFloat)startAngle {
    if (_startAngle != CircleDegreeToRadian(startAngle)) {
        _startAngle = CircleDegreeToRadian(startAngle);
        [self setNeedsDisplay];
    }
}

- (void)setReduceValue:(CGFloat)reduceValue {
    if (_reduceValue != CircleDegreeToRadian(reduceValue)) {
        if (reduceValue>=360) {
            return;
        }
        _reduceValue = CircleDegreeToRadian(reduceValue);
        [self setNeedsDisplay];
    }
}

- (void)setStrokeWidth:(CGFloat)strokeWidth {
    if (_strokeWidth != strokeWidth) {
        _strokeWidth = strokeWidth;
        [self setNeedsDisplay];
    }
}

- (void)setPathBackColor:(UIColor *)pathBackColor {
    if (_pathBackColor != pathBackColor) {
        _pathBackColor = pathBackColor;
        [self setNeedsDisplay];
    }
}

- (void)setPathFillColor:(UIColor *)pathFillColor {
    if (_pathFillColor != pathFillColor) {
        _pathFillColor = pathFillColor;
        [self setNeedsDisplay];
    }
}

- (void)setShowPoint:(BOOL)showPoint {
    if (_showPoint != showPoint) {
        _showPoint = showPoint;
        [self setNeedsDisplay];
    }
}

-(void)setShowProgressText:(BOOL)showProgressText {
    if (_showProgressText != showProgressText) {
        _showProgressText = showProgressText;
        [self setNeedsDisplay];
    }
}

//画背景线、填充线、小圆点、文字
- (void)drawRect:(CGRect)rect {
    [super drawRect:rect];

    //获取图形上下文
    CGContextRef ctx = UIGraphicsGetCurrentContext();

    //设置中心点 半径 起点及终点
    CGFloat maxWidth = self.frame.size.width < self.frame.size.height ? self.frame.size.width:self.frame.size.height;
    CGPoint center = CGPointMake(maxWidth/2.0, maxWidth/2.0);
    CGFloat radius = maxWidth / 2.0 - _strokeWidth / 2.0 - 1;//留出一像素,防止与边界相切的地方被切平
    CGFloat endA = _startAngle + (CircleDegreeToRadian(360) - _reduceValue);//圆终点位置
    CGFloat valueEndA = _startAngle + (CircleDegreeToRadian(360) - _reduceValue) * fakeProgress;  //数值终点位置

    //背景线
    UIBezierPath *basePath = [UIBezierPath bezierPathWithArcCenter:center radius:radius startAngle:_startAngle endAngle:endA clockwise:YES];
    //线条宽度
    CGContextSetLineWidth(ctx, _strokeWidth);
    //设置线条顶端
    CGContextSetLineCap(ctx, kCGLineCapRound);
    //线条颜色
    [_pathBackColor setStroke];
    //把路径添加到上下文
    CGContextAddPath(ctx, basePath.CGPath);
    //渲染背景线
    CGContextStrokePath(ctx);

    //路径线
    UIBezierPath *valuePath = [UIBezierPath bezierPathWithArcCenter:center radius:radius startAngle:_startAngle endAngle:valueEndA clockwise:YES];
    //设置线条顶端
    CGContextSetLineCap(ctx, kCGLineCapRound);
    //线条颜色
    [_pathFillColor setStroke];
    //把路径添加到上下文
    CGContextAddPath(ctx, valuePath.CGPath);
    //渲染数值线
    CGContextStrokePath(ctx);

    //画小圆点
    if (_showPoint) {

        CGContextDrawImage(ctx, CGRectMake(self.frame.size.width / 2 + ((CGRectGetWidth(self.bounds)-_strokeWidth)/2.f-1)*cosf(valueEndA)-_strokeWidth/2.0, self.frame.size.width / 2 + ((CGRectGetWidth(self.bounds)-_strokeWidth)/2.f-1)*sinf(valueEndA)-_strokeWidth/2.0, _strokeWidth, _strokeWidth), _pointImage.CGImage);
    }

    if (_showProgressText) {
        //画文字
        NSString *currentText = [NSString stringWithFormat:@"%.2f%%",fakeProgress*100];
        //段落格式
        NSMutableParagraphStyle *textStyle = [[NSMutableParagraphStyle defaultParagraphStyle] mutableCopy];
        textStyle.lineBreakMode = NSLineBreakByWordWrapping;
        textStyle.alignment = NSTextAlignmentCenter;//水平居中
        //字体
        UIFont *font = [UIFont systemFontOfSize:0.15 * self.frame.size.width];
        //构建属性集合
        NSDictionary *attributes = @{NSFontAttributeName:font, NSParagraphStyleAttributeName:textStyle};
        //获得size
        CGSize stringSize = [currentText sizeWithAttributes:attributes];
        //垂直居中
        CGRect r = CGRectMake((self.frame.size.width - stringSize.width)/2.0, (self.frame.size.height - stringSize.height)/2.0,stringSize.width, stringSize.height);
        [currentText drawInRect:r withAttributes:attributes];
    }

}

//设置进度
- (void)setProgress:(CGFloat)progress {

    if ((_progress == progress && !_forceRefresh) || progress>1.0 || progress<0.0) {
        return;
    }

    fakeProgress = _increaseFromLast==YES?_progress:0.0;
    BOOL isReverse = progress<fakeProgress?YES:NO;
    //赋真实值
    _progress = progress;

    //先暂停计时器
    if (timer) {
        [timer invalidate];
        timer = nil;
    }
    //如果为0或没有动画则直接刷新
    if (_progress == 0.0 || _notAnimated) {
        fakeProgress = _progress;
        [self setNeedsDisplay];
        return;
    }

    //设置每次增加的数值
    CGFloat sameTimeIncreaseValue = _increaseFromLast==YES?fabs(fakeProgress-_progress):_progress;
    CGFloat defaultIncreaseValue = isReverse==YES?-0.01:0.01;

    __weak typeof(self) weakSelf = self;

    timer = [NSTimer scheduledTimerWithTimeInterval:0.005 repeats:YES block:^(NSTimer * _Nonnull timer){

        __strong typeof(weakSelf)strongSelf = weakSelf;

        //反方向动画
        if (isReverse) {
            if (fakeProgress <= _progress || fakeProgress <= 0.0f) {
                [strongSelf dealWithLast];
                return;
            } else {
                //进度条动画
                [strongSelf setNeedsDisplay];
            }
        } else {
            //正方向动画
            if (fakeProgress >= _progress || fakeProgress >= 1.0f) {
                [strongSelf dealWithLast];
                return;
            } else {
                //进度条动画
                [strongSelf setNeedsDisplay];
            }
        }

        //数值增加或减少
        if (_animationModel == CircleIncreaseSameTime) {
            fakeProgress += defaultIncreaseValue*sameTimeIncreaseValue;//不同进度动画时间基本相同
        } else {
            fakeProgress += defaultIncreaseValue;//进度越大动画时间越长。
        }

    }];
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];

}

//最后一次动画所做的处理
- (void)dealWithLast {
    //最后一次赋准确值
    fakeProgress = _progress;
    [self setNeedsDisplay];
    if (timer) {
        [timer invalidate];
        timer = nil;
    }
}

@end


text:
#include <stdbool.h>
#include <stdlib.h>

#include "../../common/io/printWriter.h"

#include "../../common/log/logger.h"
#include "../../common/log/logLevel.h"

#include "ioExpander.h"
#include "pcf8574.h"

#define PCF8574_IO_COUNT     ((unsigned int) 8)

I2cBusConnection* getIOExpanderBusConnection(IOExpander* ioExpander) {
    return (I2cBusConnection*) ioExpander->object;
}

// Forward declaration
unsigned char ioExpanderPCF8574ReadValue(IOExpander* ioExpander);

bool ioExpanderPCF8574Init(IOExpander* ioExpander) {
    I2cBusConnection* i2cBusConnection = getIOExpanderBusConnection(ioExpander);
    ioExpander->value = ioExpanderPCF8574ReadValue(ioExpander);
    return isPCF8574Present(i2cBusConnection);
}

// SINGLE BITS

unsigned char ioExpanderPCF8574ReadValue(IOExpander* ioExpander) {
    I2cBusConnection* i2cBusConnection = getIOExpanderBusConnection(ioExpander);
    unsigned char result = readPCF8574(i2cBusConnection);
    if (result != ioExpander->value) {
        ioExpander->value = result;
        if (ioExpander->ioExpanderOnValueChangeEvent != NULL) {
            ioExpander->ioExpanderOnValueChangeEvent(ioExpander, ioExpander->value, ioExpander->eventContext);
        }
    }
    return result;
}

void ioExpanderPCF8574WriteValue(IOExpander* ioExpander, unsigned char value) {
    I2cBusConnection* i2cBusConnection = getIOExpanderBusConnection(ioExpander);
    writePCF8574(i2cBusConnection, value);
    ioExpander->value = value;
}

// ALL BITS

bool ioExpanderPCF8574ReadSingleValue(IOExpander* ioExpander, unsigned int index) {
    unsigned value = ioExpanderPCF8574ReadValue(ioExpander);
    return (bool) (value & (1 << index));
}

void ioExpanderPCF8574WriteSingleValue(IOExpander* ioExpander, unsigned int index, bool value) {
    unsigned char valueToWrite;
    if (value) {
        // Set the specified bit, but keeping other value
        valueToWrite = (1 << index) | (ioExpander->value);
    } else {
        // Set the specified bit, reverts bits, and do an AND operation
        valueToWrite = (~(1UL << index)) & (ioExpander->value);
    }
    ioExpanderPCF8574WriteValue(ioExpander, valueToWrite);
}

void initIOExpanderPCF8574(IOExpander* ioExpander, const char* name, I2cBusConnection* i2cBusConnection) {
    initIOExpander(ioExpander,
            name,
            &ioExpanderPCF8574Init,
            &ioExpanderPCF8574ReadValue,
            &ioExpanderPCF8574WriteValue,
            &ioExpanderPCF8574ReadSingleValue,
            &ioExpanderPCF8574WriteSingleValue,
            PCF8574_IO_COUNT,
            (int*) i2cBusConnection);
}


text:
document.getElementById('button-call').onclick = function() {
  // get the phone number to connect the call to
  const params = { To: '15558675310' };

  console.log('Calling ' + params.To + '...');
  Twilio.Device.connect(params);
};


text:
The OpenCensus Prometheus Stats Exporter is a stats exporter that exposes stats
to the
[Prometheus cpp client library](https://github.com/jupp0r/prometheus-cpp).

## Quickstart

### Prerequisites

The Prometheus exporter exposes stats on an HTTP endpoint that is scraped by
a Prometheus server. To install and run the Prometheus server, follow
the instructions [here](https://prometheus.io/docs/introduction/first_steps/).

### Register the exporter

#### Using the Prometheus client library's exposer

Register the Exposer on a selected port, and then register the OpenCensus
Prometheus exporter with that exposer. This may be done either before or after
views are registered for export and data is recorded, but stats will not be
available to Prometheus until the exporter is registered.

```c++
  auto exporter =
      std::make_shared<opencensus::exporters::stats::PrometheusExporter>();

  // Expose a Prometheus endpoint.
  prometheus::Exposer exposer("127.0.0.1:8080");
  exposer.RegisterCollectable(exporter);
```

See also the Prometheus client library's
[instructions](https://github.com/jupp0r/prometheus-cpp#usage).

#### Using a custom exposer

If your application already runs an HTTP server, you may want to expose
Prometheus stats on a page by that server rather than through the default
exposer. To do this, create an instance of the `PrometheusExporter` and then
call `Collect()` to retrieve the latest stats, which can be serialized with the
tools in the Prometheus client library:

```c++
#include "metrics.pb.h"
#include "opencensus/exporters/stats/prometheus/prometheus_exporter.h"
#include "prometheus/text_serializer.h"

...

opencensus::exporters::stats::PrometheusExporter exporter;
prometheus::TextSerializer serializer;

const std::vector<io::prometheus::client::MetricFamily> metrics =
    exporter.Collect();
const std::string formatted_metrics = serializer.Serialize(metrics);

```


text:
/*
 * Copyright (C) 2000,
 *
 * Arjuna Solutions Limited,
 * Newcastle upon Tyne,
 * Tyne and Wear,
 * UK.
 *
 * $Id: ContextClientRequestInterceptorImpl.java 2342 2006-03-30 13:06:17Z  $
 */

package com.arjuna.ats.jts.orbspecific.javaidl.interceptors.context;

import org.omg.CORBA.Any;
import org.omg.CORBA.BAD_PARAM;
import org.omg.CORBA.LocalObject;
import org.omg.CORBA.SystemException;
import org.omg.CORBA.TCKind;
import org.omg.CORBA.TRANSACTION_REQUIRED;
import org.omg.CORBA.UNKNOWN;
import org.omg.CosTransactions.Coordinator;
import org.omg.CosTransactions.TransactionalObject;
import org.omg.CosTransactions.TransactionalObjectHelper;
import org.omg.CosTransactions.Unavailable;
import org.omg.IOP.Codec;
import org.omg.IOP.ServiceContext;
import org.omg.PortableInterceptor.ClientRequestInfo;
import org.omg.PortableInterceptor.ClientRequestInterceptor;

import com.arjuna.ats.arjuna.utils.ThreadUtil;
import com.arjuna.ats.internal.jts.ControlWrapper;
import com.arjuna.ats.internal.jts.ORBManager;
import com.arjuna.ats.internal.jts.OTSImpleManager;
import com.arjuna.ats.jts.OTSManager;
import com.arjuna.ats.jts.common.InterceptorInfo;
import com.arjuna.ats.jts.logging.jtsLogger;

/**
 * PortableInterceptor::ClientRequestInterceptor implementation which adds a
 * service context carrying the transaction context.
 */

/*
 * Only add and remove transactional context if the
 * destination object is inherited from TransactionalObject.
 *
 * When we have finished implementing fully checked transactions
 * we will use the filter to prevent remote access to the factory
 * and the terminator.
 */

/*
 * If we're not within a transaction when we call a TransactionalObject
 * the spec. implies that we should raise a TransactionExpected exception.
 * This is too restrictive, and removed the ability to build modular
 * applications. Therefore, by default we will *not* do this, but this
 * can be overridden with an appropriate environment variable. (Could do
 * this through a separate base class.)
 */

class ContextClientRequestInterceptorImpl extends LocalObject implements ClientRequestInterceptor
{

	/**
	 * Provides an opportunity to destroy this interceptor.
	 * The destroy method is called during ORB.destroy. When an
	 * application calls ORB.destroy, the ORB:
	 *

	 *
waits for all requests in progress to complete

	 *
calls the Interceptor.destroy operation for each
	 *       interceptor

	 *
completes destruction of the ORB

	 *

	 * Method invocations from within Interceptor.destroy on
	 * object references for objects implemented on the ORB being destroyed
	 * result in undefined behavior. However, method invocations on objects
	 * implemented on an ORB other than the one being destroyed are
	 * permitted. (This means that the ORB being destroyed is still capable
	 * of acting as a client, but not as a server.)
	 */
	public void destroy()
	{
	}
    /*
     * Only the transaction creator can terminate the transaction. So don't
     * propagate the terminator.
     */

    /*
     * Propagate/expect context if:
     *
     * (i) we are a TransactionalObject.
     * (ii) we define otsAlwaysPropagate to TRUE.
     *
     * Throw an exception at the client/server side if there is no context if:
     *
     * (i) we define otsNeedTranContext to FALSE.
     */

public ContextClientRequestInterceptorImpl (int localSlot, Codec codec)
    {
	if (jtsLogger.logger.isTraceEnabled())
	{
	    jtsLogger.logger.trace("ContextClientRequestInterceptorImpl ( "+localSlot+" )");
	}

	_localSlot = localSlot;
	_codec = codec;
    }

public String name ()
    {
	return "OTS_Context";
    }

public void send_request (ClientRequestInfo request_info) throws SystemException
    {
	if (jtsLogger.logger.isTraceEnabled())
	{
	    jtsLogger.logger.trace("ContextClientRequestInterceptorImpl::send_request ( "+request_info+" )");
	}

	if (systemCall(request_info))
	    return;

	final boolean otsAlwaysPropagate = InterceptorInfo.getAlwaysPropagate() ;
	try
	{
	    if (!otsAlwaysPropagate)
	    {
		TransactionalObject ptr = TransactionalObjectHelper.narrow(request_info.target());

		if (ptr == null)
		    throw new BAD_PARAM();
	    }
	    else
	    {
		/** If we are set to always propagate then ensure we're not already in use **/
	        /** If the value is not null then we are currently in use **/
                if ( _inUse.get() != null )
                {
            	    return;
                }
                else
                {
            	    _inUse.set(_inUse);
                }
	    }

	    try
	    {
		/*
		 * We get back an Any, which contains a key which we must
		 * now use to get the actual transaction context. This
		 * saves use having to pack and unpack the context every
		 * time it changes, even if we don't then make a remote
		 * invocation.
		 */

		Any localData = request_info.get_slot(_localSlot);
		String threadId = null;
		boolean problem = false;
		String stringRef = null;

		/*
		 * If we are using co-location optimisations, then
		 * filters may not have been used to set up the
		 * thread-to-context association. So, if the PI slot
		 * is null, check whether the current thread has a context
		 * on it already. If so, use it.
		 */

		if (localData.type().kind().value() != TCKind._tk_null)
		{
		    if ((threadId = localData.extract_string()) == null)
			throw new UNKNOWN(jtsLogger.i18NLogger.get_orbspecific_javaidl_interceptors_context_invalidparam());
		}
		else
		    threadId = ThreadUtil.getThreadId() ;

		if (threadId != null)
		{
		    ControlWrapper theControl = OTSImpleManager.current().contextManager().current(threadId);

		    if (theControl != null)
		    {
			try
			{
			    Coordinator theCoordinator = theControl.get_coordinator();

			    if (theCoordinator != null)
			    {
				stringRef = ORBManager.getORB().orb().object_to_string(theCoordinator);
			    }
			    else
			    {
				problem = true;
			    }
			}
			catch (Unavailable e)
			{
			    problem = true;
			}

			theControl = null;
		    }
		    else
			problem = true;
		}
		else
		    problem = true;

		if (problem)
		{
		    /*
		     * Only throw an exception if we have no
		     * transaction context and we require one.
		     */

		    if (InterceptorInfo.getNeedTranContext())
			throw new TRANSACTION_REQUIRED();
		    else
			stringRef = null;
		}

		if (stringRef != null)
		{
		    Any data = ORBManager.getORB().orb().create_any();

		    data.insert_string(stringRef);

		    byte[] octets = _codec.encode_value(data);
		    ServiceContext service_context = new ServiceContext(OTSManager.serviceId, octets);

		    request_info.add_request_service_context(service_context, true);
		}
	    }
	    catch (SystemException e)
	    {
		throw e;
	    }
	    catch (Exception ex) {
            jtsLogger.i18NLogger.warn_orbspecific_javaidl_interceptors_context_error(ex);

            throw new UNKNOWN(ex.toString());
        }
            finally
            {
                /** If we are set to always propagate then ensure we clear the inuse flag **/
                if (otsAlwaysPropagate)
                {
                        _inUse.set(null);
                }
            }
	}
	catch (BAD_PARAM ex)
	{
	    // narrow failed, so not a transactional object.
	}
    }

public void send_poll (ClientRequestInfo request_info) throws SystemException
    {
	if (jtsLogger.logger.isTraceEnabled())
	{
	    jtsLogger.logger.trace("ContextClientRequestInterceptorImpl::send_poll ( "+request_info+" )");
	}
    }

public void receive_reply (ClientRequestInfo request_info) throws SystemException
    {
	if (jtsLogger.logger.isTraceEnabled())
	{
	    jtsLogger.logger.trace("ContextClientRequestInterceptorImpl::receive_reply ( "+request_info+" )");
	}
    }

public void receive_exception (ClientRequestInfo request_info) throws SystemException
    {
	if (jtsLogger.logger.isTraceEnabled())
	{
	    jtsLogger.logger.trace("ContextClientRequestInterceptorImpl::receive_exception ( "+request_info+" )");
	}

	// mark transaction as rollback only if a system exception
    }

public void receive_other (ClientRequestInfo request_info) throws SystemException
    {
	if (jtsLogger.logger.isTraceEnabled())
	{
	    jtsLogger.logger.trace("ContextClientRequestInterceptorImpl::receive_other ( "+request_info+" )");
	}
    }

private final boolean systemCall (ClientRequestInfo request_info)
    {
	if (request_info.operation().equals("_is_a"))
	    return true;
	else
	    return false;
    }

private int   _localSlot;
private Codec _codec;
private ThreadLocal _inUse = new ThreadLocal();
}


text:
import { override } from "@microsoft/decorators";
import { setup as pnpSetup } from "@pnp/common";
import * as React from "react";
import * as ReactDom from "react-dom";
import { Version } from "@microsoft/sp-core-library";
import { IPropertyPaneConfiguration, PropertyPaneTextField } from "@microsoft/sp-property-pane";
import { BaseClientSideWebPart } from "@microsoft/sp-webpart-base";

import * as strings from "UserAndGroupInfoWebPartStrings";
import UserAndGroupInfo from "./components/UserAndGroupInfo";
import { IUserAndGroupInfoProps } from "./components/IUserAndGroupInfoProps";

export interface IUserAndGroupInfoWebPartProps {
  description: string;
}

export default class UserAndGroupInfoWebPart extends BaseClientSideWebPart<IUserAndGroupInfoWebPartProps> {
  @override
  public async onInit(): Promise<void> {
    await super.onInit();
    console.debug("Initialising SPFX context", this.context);
    pnpSetup({ spfxContext: this.context });
  }

  public render(): void {
    const element: React.ReactElement<IUserAndGroupInfoProps> = React.createElement(UserAndGroupInfo, {
      context: this.context,
    });

    ReactDom.render(element, this.domElement);
  }

  protected onDispose(): void {
    ReactDom.unmountComponentAtNode(this.domElement);
  }

  protected get dataVersion(): Version {
    return Version.parse("1.0");
  }

  protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
    return {
      pages: [
        {
          header: {
            description: strings.PropertyPaneDescription,
          },
          groups: [
            {
              groupName: strings.BasicGroupName,
              groupFields: [
                PropertyPaneTextField("description", {
                  label: strings.DescriptionFieldLabel,
                }),
              ],
            },
          ],
        },
      ],
    };
  }
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using System;

namespace Azure.Storage.Blobs.Models
{
    /// <summary>
    /// BlobSnapshotInfo
    /// </summary>
    public class BlobSnapshotInfo
    {
        /// <summary>
        /// Uniquely identifies the snapshot and indicates the snapshot version. It may be used in subsequent requests to access the snapshot.
        /// </summary>
        public string Snapshot { get; internal set; }

        /// <summary>
        /// The ETag contains a value that you can use to perform operations conditionally.
        /// If the request version is 2011-08-18 or newer, the ETag value will be in quotes.
        /// </summary>
        public ETag ETag { get; internal set; }

        /// <summary>
        /// Returns the date and time the container was last modified. Any operation that modifies the blob,
        /// including an update of the blob's metadata or properties, changes the last-modified time of the blob.
        /// </summary>
        public DateTimeOffset LastModified { get; internal set; }

        /// <summary>
        /// A DateTime value returned by the service that uniquely identifies the blob.
        /// The value of this header indicates the blob version, and may be used in subsequent requests to access this version of the blob.
        /// </summary>
        public string VersionId { get; internal set; }

        /// <summary>
        /// True if the contents of the request are successfully encrypted using the specified algorithm, and false otherwise.
        /// For a snapshot request, this header is set to true when metadata was provided in the request and encrypted with a customer-provided key.
        /// </summary>
        public bool IsServerEncrypted { get; internal set; }

        /// <summary>
        /// Prevent direct instantiation of BlobSnapshotInfo instances.
        /// You can use BlobsModelFactory.BlobSnapshotInfo instead.
        /// </summary>
        internal BlobSnapshotInfo() { }
    }
}


text:
package com.mopub.nativeads;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import com.mopub.common.CacheService;
import com.mopub.common.CacheServiceTest;
import com.mopub.nativeads.test.support.SdkTestRunner;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.robolectric.Robolectric;
import org.robolectric.tester.org.apache.http.FakeHttpLayer;

import java.io.*;
import java.util.*;
import java.util.concurrent.*;

import static com.mopub.nativeads.ImageService.ImageServiceListener;
import static org.fest.assertions.api.Assertions.assertThat;
import static org.mockito.Matchers.anyMap;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.robolectric.Robolectric.shadowOf;

@RunWith(SdkTestRunner.class)
public class ImageServiceTest {

    private ImageServiceListener imageServiceListener;
    private Semaphore semaphore;
    private Map<String, Bitmap> bitmaps;
    private FakeHttpLayer fakeHttpLayer;
    private String url1;
    private String url2;
    private String url3;
    private String imageData1;
    private String imageData2;
    private String imageData3;
    private Context context;

    @Before
    public void setUp() throws Exception {
        semaphore = new Semaphore(0);
        imageServiceListener = mock(ImageServiceListener.class);
        doAnswer(new Answer() {
            @Override
            public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
                Object[] args = invocationOnMock.getArguments();
                Map<String, Bitmap> bitmaps = (Map)args[0];
                ImageServiceTest.this.bitmaps = bitmaps;
                semaphore.release();
                return null;
            }
        }).when(imageServiceListener).onSuccess(anyMap());
        doAnswer(new Answer() {
            @Override
            public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
                semaphore.release();
                return null;
            }
        }).when(imageServiceListener).onFail();

        fakeHttpLayer = Robolectric.getFakeHttpLayer();
        url1 = "http://www.mopub.com/";
        url2 = "http://www.twitter.com";
        url3 = "http://www.guydot.com";
        imageData1 = "image_data_1";
        imageData2 = "image_data_2";
        imageData3 = "image_data_3";
        context = new Activity();
    }

    @After
    public void tearDown() throws Exception {
        CacheService.clearAndNullCaches();
    }

    @Test
    public void get_shouldInitializeCaches() throws Exception {
        CacheService.clearAndNullCaches();
        assertThat(CacheService.getMemoryLruCache()).isNull();
        assertThat(CacheService.getDiskLruCache()).isNull();

        ImageService.get(context, new ArrayList<String>(), imageServiceListener);

        assertThat(CacheService.getMemoryLruCache()).isNotNull();
        assertThat(CacheService.getDiskLruCache()).isNotNull();
    }

    @Test
    public void get_withImageInMemoryCache_shouldReturnImage() throws Exception {
        CacheService.initializeCaches(context);
        CacheServiceTest.assertCachesAreEmpty();
        CacheService.putToMemoryCache(url1, imageData1.getBytes());

        ImageService.get(context, Arrays.asList(url1), imageServiceListener);
        // no need for semaphore since memory cache is synchronous

        assertThat(shadowOf(bitmaps.get(url1)).getCreatedFromBytes()).isEqualTo(imageData1.getBytes());
    }

    @Test
    public void get_withImageInDiskCache_shouldReturnImage() throws Exception {
        CacheService.initializeCaches(context);
        CacheServiceTest.assertCachesAreEmpty();
        CacheService.putToDiskCache(url1, imageData1.getBytes());

        ImageService.get(context, Arrays.asList(url1), imageServiceListener);
        semaphore.acquire();

        assertThat(fakeHttpLayer.getLastSentHttpRequestInfo()).isNull();
        assertThat(shadowOf(bitmaps.get(url1)).getCreatedFromBytes()).isEqualTo(imageData1.getBytes());
    }

    @Test
    public void get_withEmptyCaches_shouldGetImageFromNetwork() throws Exception {
        CacheService.initializeCaches(context);
        CacheServiceTest.assertCachesAreEmpty();

        fakeHttpLayer.addPendingHttpResponse(200, imageData1);

        ImageService.get(context, Arrays.asList(url1), imageServiceListener);
        semaphore.acquire();

        assertThat(shadowOf(bitmaps.get(url1)).getCreatedFromBytes()).isEqualTo(imageData1.getBytes());
    }

    @Test
    public void get_withImagesInMemoryCacheAndDiskCache_shouldReturnBothImages() throws Exception {
        CacheService.initializeCaches(context);
        CacheServiceTest.assertCachesAreEmpty();

        CacheService.putToMemoryCache(url1, imageData1.getBytes());
        CacheService.putToDiskCache(url2, imageData2.getBytes());

        ImageService.get(context, Arrays.asList(url1, url2), imageServiceListener);
        semaphore.acquire();

        assertThat(shadowOf(bitmaps.get(url1)).getCreatedFromBytes()).isEqualTo(imageData1.getBytes());
        assertThat(fakeHttpLayer.getLastSentHttpRequestInfo()).isNull();
        assertThat(shadowOf(bitmaps.get(url2)).getCreatedFromBytes()).isEqualTo(imageData2.getBytes());
    }

    @Test
    public void get_withImagesInMemoryAndNetwork_shouldReturnBothImages() throws Exception {
        CacheService.initializeCaches(context);
        CacheServiceTest.assertCachesAreEmpty();

        CacheService.putToMemoryCache(url1, imageData1.getBytes());
        fakeHttpLayer.addPendingHttpResponse(200, imageData2);

        ImageService.get(context, Arrays.asList(url1, url2), imageServiceListener);
        semaphore.acquire();

        assertThat(shadowOf(bitmaps.get(url1)).getCreatedFromBytes()).isEqualTo(imageData1.getBytes());
        assertThat(fakeHttpLayer.getLastSentHttpRequestInfo().getHttpHost().toString()).isEqualTo(url2);
        assertThat(shadowOf(bitmaps.get(url2)).getCreatedFromBytes()).isEqualTo(imageData2.getBytes());
    }

    @Test
    public void get_withImagesInDiskAndNetwork_shouldReturnBothImages() throws Exception {
        CacheService.initializeCaches(context);
        CacheServiceTest.assertCachesAreEmpty();

        CacheService.putToDiskCache(url1, imageData1.getBytes());
        fakeHttpLayer.addPendingHttpResponse(200, imageData2);

        ImageService.get(context, Arrays.asList(url1, url2), imageServiceListener);
        semaphore.acquire();

        assertThat(shadowOf(bitmaps.get(url1)).getCreatedFromBytes()).isEqualTo(imageData1.getBytes());
        assertThat(fakeHttpLayer.getLastSentHttpRequestInfo().getHttpHost().toString()).isEqualTo(url2);
        assertThat(shadowOf(bitmaps.get(url2)).getCreatedFromBytes()).isEqualTo(imageData2.getBytes());
    }

    @Test
    public void get_withImagesInMemoryAndDiskAndNetwork_shouldReturnAllImages() throws Exception {
        CacheService.initializeCaches(context);
        CacheServiceTest.assertCachesAreEmpty();

        CacheService.putToMemoryCache(url1, imageData1.getBytes());
        CacheService.putToDiskCache(url2, imageData2.getBytes());
        fakeHttpLayer.addPendingHttpResponse(200, imageData3);

        ImageService.get(context, Arrays.asList(url1, url2, url3), imageServiceListener);
        semaphore.acquire();

        assertThat(shadowOf(bitmaps.get(url1)).getCreatedFromBytes()).isEqualTo(imageData1.getBytes());
        assertThat(shadowOf(bitmaps.get(url2)).getCreatedFromBytes()).isEqualTo(imageData2.getBytes());
        assertThat(shadowOf(bitmaps.get(url3)).getCreatedFromBytes()).isEqualTo(imageData3.getBytes());
    }

    @Test
    public void get_withSameKeysInMemoryAndDiskCache_shouldReturnValueFromMemoryCache() throws Exception {
        CacheService.initializeCaches(context);
        CacheServiceTest.assertCachesAreEmpty();

        CacheService.putToMemoryCache(url1, imageData2.getBytes());
        CacheService.putToDiskCache(url1, imageData1.getBytes());

        ImageService.get(context, Arrays.asList(url1), imageServiceListener);
        semaphore.acquire();

        assertThat(shadowOf(bitmaps.get(url1)).getCreatedFromBytes()).isEqualTo(imageData2.getBytes());
    }

    @Test
    public void get_withSameKeysInMemoryAndNetwork_shouldReturnValueFromMemoryCache() throws Exception {
        CacheService.initializeCaches(context);
        CacheServiceTest.assertCachesAreEmpty();

        CacheService.putToMemoryCache(url1, imageData2.getBytes());
        fakeHttpLayer.addPendingHttpResponse(200, imageData1);

        ImageService.get(context, Arrays.asList(url1), imageServiceListener);
        semaphore.acquire();

        assertThat(shadowOf(bitmaps.get(url1)).getCreatedFromBytes()).isEqualTo(imageData2.getBytes());
    }

    @Test
    public void get_withSameKeysInDiskAndNetwork_shouldReturnValueFromDiskCache() throws Exception {
        CacheService.initializeCaches(context);
        CacheServiceTest.assertCachesAreEmpty();

        CacheService.putToDiskCache(url1, imageData2.getBytes());
        fakeHttpLayer.addPendingHttpResponse(200, imageData1);

        ImageService.get(context, Arrays.asList(url1), imageServiceListener);
        semaphore.acquire();

        assertThat(shadowOf(bitmaps.get(url1)).getCreatedFromBytes()).isEqualTo(imageData2.getBytes());
    }

    @Test
    public void get_withNetworkFailure_shouldFail() throws Exception {
        CacheService.initializeCaches(context);
        CacheServiceTest.assertCachesAreEmpty();

        CacheService.putToMemoryCache(url1, imageData1.getBytes());
        CacheService.putToDiskCache(url2, imageData2.getBytes());
        fakeHttpLayer.addPendingHttpResponse(500, imageData3);

        ImageService.get(context, Arrays.asList(url1, url2, url3), imageServiceListener);
        semaphore.acquire();

        assertThat(bitmaps).isNull();
    }

    @Test
    public void get_withMultipleNetworkSuccessAndOneFailure_shouldFail() throws Exception {
        CacheService.initializeCaches(context);
        CacheServiceTest.assertCachesAreEmpty();

        fakeHttpLayer.addPendingHttpResponse(200, imageData1);
        fakeHttpLayer.addPendingHttpResponse(200, imageData2);
        fakeHttpLayer.addPendingHttpResponse(500, imageData3);

        ImageService.get(context, Arrays.asList(url1, url2, url3), imageServiceListener);
        semaphore.acquire();

        assertThat(bitmaps).isNull();
    }

    @Test
    public void putBitmapsInCache_populatesCaches() throws Exception {
        CacheService.initializeCaches(context);

        Bitmap bitmap1 = BitmapFactory.decodeStream(getInputStreamFromString(imageData1));
        Bitmap bitmap2 = BitmapFactory.decodeStream(getInputStreamFromString(imageData2));

        Map<String, Bitmap> bitmaps = new HashMap<String, Bitmap>(2);
        bitmaps.put(url1, bitmap1);
        bitmaps.put(url2, bitmap2);

        assertThat(ImageService.getBitmapFromDiskCache(url1)).isNull();
        assertThat(ImageService.getBitmapFromDiskCache(url2)).isNull();
        assertThat(ImageService.getBitmapFromMemoryCache(url1)).isNull();
        assertThat(ImageService.getBitmapFromMemoryCache(url2)).isNull();

        ImageService.putBitmapsInCache(bitmaps);
        Thread.sleep(500); // disk cache put is async

        assertThat(ImageService.getBitmapFromDiskCache(url1)).isNotNull();
        assertThat(ImageService.getBitmapFromDiskCache(url2)).isNotNull();
        assertThat(ImageService.getBitmapFromMemoryCache(url1)).isNotNull();
        assertThat(ImageService.getBitmapFromMemoryCache(url2)).isNotNull();
    }

    @Test
    public void getBitmapsFromMemoryCache_withEmptyCacheAndTwoUrls_returnsNoCacheHitsAndTwoCacheMisses() throws Exception {
        CacheService.initializeCaches(context);
        assertThat(CacheService.getMemoryLruCache().size()).isEqualTo(0);

        Map<String, Bitmap> cacheHits = new HashMap<String, Bitmap>(2);
        List<String> cacheMisses =
                ImageService.getBitmapsFromMemoryCache(Arrays.asList(url1, url2), cacheHits);

        assertThat(cacheHits).isEmpty();
        assertThat(cacheMisses).containsOnly(url1, url2);
    }

    @Test
    public void getBitmapsFromMemoryCache_withOneCacheEntryAndTwoUrls_returnsOneCacheHitAndOneCacheMiss() throws Exception {
        CacheService.initializeCaches(context);

        assertThat(CacheService.getMemoryLruCache().size()).isEqualTo(0);

        CacheService.putToMemoryCache(url1, imageData1.getBytes());

        Map<String, Bitmap> cacheHits = new HashMap<String, Bitmap>(2);
        List<String> cacheMisses =
                ImageService.getBitmapsFromMemoryCache(Arrays.asList(url1, url2), cacheHits);

        assertThat(cacheHits.keySet()).containsOnly(url1);
        assertThat(cacheMisses).containsOnly(url2);
    }

    private static InputStream getInputStreamFromString(final String string) {
        return spy(new ByteArrayInputStream(string.getBytes()));
    }
}


text:
<!DOCTYPE html>

        <link rel="stylesheet" href="style.css">


text:
import {Repository} from '../data_access/repository';
import {Post} from '../model/post';
import moment = require('moment');

export class PostsService {
    constructor(private postsRepository: Repository<Post>) {
    }

    public getAll(): Array<Post> {
        return this.postsRepository.getAll();
    }

    public getById(id: number): Post {
        return this.postsRepository.getById(id);
    }
}


text:
import React, { Component } from 'react';
import {Card, CardActions, CardHeader, CardMedia, CardTitle, CardText} from 'material-ui/Card';
import Toggle from 'material-ui/Toggle';
import Divider from 'material-ui/Divider';
import * as _colorManipulator from "material-ui/utils/colorManipulator";

const cardStyle = {
  height: 'auto',
  width: '50%',
  minWidth: '256px',
  marginBottom: '16px',
  textAlign: 'left',
};

const allowNewLine = {
  whiteSpace: 'pre',
};

class Article extends Component {

  constructor(props) {
    super(props);
    this.state = {
      expanded: false,
    };
  }

  handleExpandChange = (expanded) => {
    this.setState({expanded: expanded});
  };

  handleToggle = (event, toggle) => {
    this.setState({expanded: toggle});
  };

  render() {
    return (
      <Card expanded={this.state.expanded} onExpandChange={this.handleExpandChange} style={cardStyle}>
        <CardHeader
          title={this.props.author}
          subtitle={this.props.created}
          avatar={this.props.avatar}
        />
        <CardMedia>
          <img src={this.props.image} />
        </CardMedia>
        <CardTitle title={this.props.title} subtitle={this.props.ingress} style={allowNewLine} />
        <Divider />
        <CardText expandable={true} style={allowNewLine}>
          {this.props.content}
        </CardText>
        <Divider />
        <CardActions>
          <Toggle
            thumbSwitchedStyle={{
              backgroundColor: this.props.muiTheme.palette.accent1Color,
            }}
            trackSwitchedStyle={{
              backgroundColor: _colorManipulator.fade(this.props.muiTheme.palette.accent1Color, 0.5),
            }}
            toggled={this.state.expanded}
            onToggle={this.handleToggle}
            labelPosition="right"
            label="Expand article"
          />
        </CardActions>
      </Card>
    );
  }
}

export default Article;


text:
import { createSelector, createStructuredSelector } from 'reselect';
import { currentUserSelector } from './userSelectors';

const baseSelector = state => state.votes;

const createPropSelector = (base, prop) => createSelector(base, obj => obj[prop]);
const createIsSelector = type => createSelector(
  type,
  currentUserSelector,
  (users, me) => !!me && users.includes(me._id),
);
const createCountSelector = type => createSelector(
  type,
  array => array.length,
);

export const favoritesSelector = createPropSelector(baseSelector, 'favorites');
export const upvotesSelector = createPropSelector(baseSelector, 'upvotes');
export const downvotesSelector = createPropSelector(baseSelector, 'downvotes');

export const currentVotesSelector = createStructuredSelector({
  favorites: favoritesSelector,
  upvotes: upvotesSelector,
  downvotes: downvotesSelector,
});

export const isFavoriteSelector = createIsSelector(favoritesSelector);
export const isUpvoteSelector = createIsSelector(upvotesSelector);
export const isDownvoteSelector = createIsSelector(downvotesSelector);

export const favoritesCountSelector = createCountSelector(favoritesSelector);
export const upvotesCountSelector = createCountSelector(upvotesSelector);
export const downvotesCountSelector = createCountSelector(downvotesSelector);

export const currentVoteStatsSelector = createStructuredSelector({
  isFavorite: isFavoriteSelector,
  isUpvote: isUpvoteSelector,
  isDownvote: isDownvoteSelector,
  favoritesCount: favoritesCountSelector,
  upvotesCount: upvotesCountSelector,
  downvotesCount: downvotesCountSelector,
});