text:
package imagepicker.util;

import android.content.Context;
import android.database.Cursor;
import android.graphics.Color;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.widget.ImageView;

import com.renard.ocr.R;

import java.util.ArrayList;
import java.util.HashMap;

import imagepicker.model.AlbumEntry;
import imagepicker.model.ImageEntry;
import imagepicker.ui.PickerActivity;

/**
 *  MIP工具类 (存在不少多余的方法,暂时保留,以后清理)
 *
 * Created by yazeed44 on 11/22/14.
 */
public final class Util {

    public static final TypedValue TYPED_VALUE = new TypedValue();
    public static final String CAMERA_FOLDER = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getAbsolutePath() + "/" + "Camera/";

    private Util() {
        throw new AssertionError();
    }

    public static ArrayList<AlbumEntry> getAlbums(final Context context, final Picker pickOptions) {
        final ArrayList<AlbumEntry> albumsSorted = new ArrayList<>();
        final HashMap<Integer, AlbumEntry> albums = new HashMap<Integer, AlbumEntry>();
        AlbumEntry allPhotosAlbum = null;

        Cursor imagesCursor = null;
        Cursor videosCursor = null;
        try {
            imagesCursor = queryImages(context);
            iterateCursor(context, imagesCursor, allPhotosAlbum, albumsSorted, albums, false);//allPhotosAlbum =
//            if (pickOptions.videosEnabled) {
//                videosCursor = queryVideos(context);
//                iterateCursor(context, videosCursor, allPhotosAlbum, albumsSorted, albums, true);
//            }
        } catch (Exception ex) {
            Log.e("getAlbums", ex.getMessage());
        } finally {
            closeCursors(imagesCursor, videosCursor);
        }

        setPickedFlagForPickedImages(albumsSorted);
        for (final AlbumEntry album : albumsSorted) {
            album.sortImagesByTimeDesc();
        }
        return albumsSorted;
    }

    private static void closeCursors(final Cursor imagesCursor, final Cursor videosCursor) {
        if (imagesCursor != null) {
            imagesCursor.close();
        }
        if (videosCursor != null) {
            videosCursor.close();
        }
    }

    private static Cursor queryImages(final Context context) {
        final String[] projectionPhotos = {
                MediaStore.Images.Media._ID,
                MediaStore.Images.Media.BUCKET_ID,
                MediaStore.Images.Media.BUCKET_DISPLAY_NAME,
                MediaStore.Images.Media.DATA,
                MediaStore.Images.Media.DATE_MODIFIED,
                MediaStore.Images.Media.ORIENTATION
        };

        return MediaStore.Images.Media.query(context.getContentResolver(), MediaStore.Images.Media.EXTERNAL_CONTENT_URI
                , projectionPhotos, "", null, MediaStore.Images.Media.DATE_MODIFIED + " DESC");
    }

    private static Cursor queryVideos(final Context context) {
        final String[] projectionVideos = {
                MediaStore.Video.Media._ID,
                MediaStore.Video.Media.BUCKET_ID,
                MediaStore.Video.Media.BUCKET_DISPLAY_NAME,
                MediaStore.Video.Media.DATA,
                MediaStore.Video.Media.DATE_MODIFIED
        };

        return MediaStore.Video.query(context.getContentResolver(), MediaStore.Video.Media.EXTERNAL_CONTENT_URI
                , projectionVideos);
    }

    private static void setPickedFlagForPickedImages(final ArrayList<AlbumEntry> albumsSorted) {
        //Check all photos album
        final AlbumEntry allPhotosAlbum = getAllPhotosAlbum(albumsSorted);

        if (allPhotosAlbum == null) {
            return;
        }

        if (!PickerActivity.sCheckedImages.isEmpty() && !allPhotosAlbum.imageList.isEmpty()) {
            for (final ImageEntry checkedImage : PickerActivity.sCheckedImages) {
                for (final ImageEntry imageEntry : allPhotosAlbum.imageList) {
                    imageEntry.isPicked = imageEntry.equals(checkedImage);
                }
            }
        }
    }

    public static AlbumEntry getAllPhotosAlbum(final ArrayList<AlbumEntry> albumEntries) {
        for (final AlbumEntry albumEntry : albumEntries) {
            if (albumEntry.id == 0) {
                return albumEntry;
            }
        }
        return null;
    }

    private static AlbumEntry iterateCursor(final Context context, final Cursor cursor, AlbumEntry allPhotosAlbum, final ArrayList<AlbumEntry> albumsSorted, final HashMap<Integer, AlbumEntry> albums, final boolean isVideoCursor) {
        if (cursor == null) return null;
        final int bucketNameColumn = cursor.getColumnIndex(MediaStore.Images.Media.BUCKET_DISPLAY_NAME);
        final int bucketIdColumn = cursor.getColumnIndex(MediaStore.Images.Media.BUCKET_ID);

        while (cursor.moveToNext()) {
            final ImageEntry imageEntry = getImageFromCursor(cursor, isVideoCursor);
            if (imageEntry.path == null || imageEntry.path.length() == 0) {
                continue;
            }

            allPhotosAlbum = createAllPhotosAlbumIfDoesntExist(context, allPhotosAlbum, albumsSorted);
            allPhotosAlbum.addPhoto(imageEntry);

            final int bucketId = cursor.getInt(bucketIdColumn);
            final String bucketName = cursor.getString(bucketNameColumn);
            AlbumEntry albumEntry = albums.get(bucketId);
            if (albumEntry == null) {
                albumEntry = createNewAlbumAndAddItToArray(albums, bucketId, bucketName);

                if (shouldCreateCameraAlbum(imageEntry)) {
                    addCameraAlbumToArray(albumsSorted, albumEntry);
                } else {
                    albumsSorted.add(albumEntry);
                }
            }

            albumEntry.addPhoto(imageEntry);
        }

        return allPhotosAlbum;
    }

    private static void addCameraAlbumToArray(final ArrayList<AlbumEntry> albumsSorted, final AlbumEntry albumEntry) {
        albumsSorted.add(0, albumEntry);
    }

    private static boolean shouldCreateCameraAlbum(final ImageEntry imageEntry) {
        return imageEntry.path.startsWith(CAMERA_FOLDER);
    }

    @NonNull
    private static AlbumEntry createNewAlbumAndAddItToArray(final HashMap<Integer, AlbumEntry> albums, final int bucketId, final String bucketName) {

        final AlbumEntry albumEntry = new AlbumEntry(bucketId, bucketName);
        albums.put(bucketId, albumEntry);
        return albumEntry;
    }

    @NonNull
    private static ImageEntry getImageFromCursor(final Cursor cursor, final boolean isVideoCursor) {
        final ImageEntry imageEntry = ImageEntry.from(cursor);
        return imageEntry;
    }

    @NonNull
    private static AlbumEntry createAllPhotosAlbumIfDoesntExist(Context context, AlbumEntry allPhotosAlbum, ArrayList<AlbumEntry> albumsSorted) {
        if (allPhotosAlbum == null) {
            allPhotosAlbum = new AlbumEntry(0, context.getResources().getString(R.string.all_photos));
            addCameraAlbumToArray(albumsSorted, allPhotosAlbum);
        }
        return allPhotosAlbum;
    }

    public static int getPositionOfChild(final View child, final int childParentId, final RecyclerView recyclerView) {
        if (child.getId() == childParentId) {
            return recyclerView.getChildAdapterPosition(child);
        }

        View parent = (View) child.getParent();
        while (parent.getId() != childParentId) {
            parent = (View) parent.getParent();
        }
        return recyclerView.getChildAdapterPosition(parent);
    }

    public static int getActionBarHeight(final Context context) {
        context.getTheme().resolveAttribute(android.R.attr.actionBarSize, TYPED_VALUE, true);
        return TypedValue.complexToDimensionPixelSize(TYPED_VALUE.data, context.getResources().getDisplayMetrics());
    }

    public static int getActionBarThemeResId(final Context context) {
        context.getTheme().resolveAttribute(R.attr.actionBarTheme, TYPED_VALUE, true);
        return TYPED_VALUE.resourceId;
    }

//    public static int getToolbarThemeResId(final Context context) {
//        return R.style.ThemeOverlay_AppCompat_ActionBar;
//
////        if (isActionbarThemeLight(context)) {
////            return R.style.ThemeOverlay_AppCompat_ActionBar;
////        } else {
////            return R.style.ThemeOverlay_AppCompat_Dark_ActionBar;
////        }
//    }

    public static int getDefaultPopupTheme(final Context context) {
        if (isActionbarThemeLight(context)) {
            return R.style.ThemeOverlay_AppCompat_Dark;
        } else {
            return R.style.ThemeOverlay_AppCompat_Light;
        }
    }

    public static boolean isActionbarThemeLight(final Context context) {
        return context.getTheme().obtainStyledAttributes(getActionBarThemeResId(context), new int[]{R.attr.isLightTheme}).getBoolean(0, true);
    }

    public static int getDefaultIconTintColor(final Context context) {
        if (isActionbarThemeLight(context)) {
            return Color.BLACK;
        } else {
            return Color.WHITE;
        }
    }

    public interface OnClickImage {
        void onClickImage(final View layout, final ImageView thumbnail, final ImageView check);
    }

    public interface OnClickAlbum {
        void onClickAlbum(final View layout);
    }

}


text:
class GodMessage < ActiveRecord::Base
  def self.latest
    self.find(:first, :order => 'created_on DESC')
  end
end

redpajama_set_name: RedPajamaGithub


text:
<?php

class Google_Service_CloudHealthcare_GoogleCloudHealthcareV1alpha2FhirRestImportResourcesResponse extends Google_Model
{
  public $fhirStore;
  public $inputSize;

  public function setFhirStore($fhirStore)
  {
    $this->fhirStore = $fhirStore;
  }
  public function getFhirStore()
  {
    return $this->fhirStore;
  }
  public function setInputSize($inputSize)
  {
    $this->inputSize = $inputSize;
  }
  public function getInputSize()
  {
    return $this->inputSize;
  }
}


text:
set -ex

# Multipackage installation does not fail in yum
yum -y install epel-release
yum -y install git
yum -y install wget
yum -y install atlas-devel # Provide clbas headerfiles
yum -y install openblas-devel
yum -y install lapack-devel
yum -y install opencv-devel
yum -y install openssl-devel
yum -y install gcc-c++-4.8.*
yum -y install make
yum -y install cmake
yum -y install wget
yum -y install unzip
yum -y install ninja-build


text:
@implementation UIImageView (LNVToolbox)

- (void)lnv_clipImageToRoundInBackground {
    __weak __typeof__(self) weakSelf = self;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
        CGFloat widthInPixel = weakSelf.image.size.width;
        CGFloat heightInPixel = weakSelf.image.size.height;
        CGFloat cornerRadiusInPixel = MIN(self.image.size.width, self.image.size.height) / 2;

        UIImage *roundedImage = [weakSelf.image lnv_roundedImageWithSize:CGSizeMake(widthInPixel, heightInPixel) cornerRadius:cornerRadiusInPixel];

        dispatch_async(dispatch_get_main_queue(), ^{
            weakSelf.image = roundedImage;
        });
    });
}

- (void)lnv_clipImageCornerInBackgroundWithCornerRadius:(CGFloat)cornerRadius {
    __weak __typeof__(self) weakSelf = self;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
        CGFloat widthInPixel = weakSelf.image.size.width;
        CGFloat heightInPixel = weakSelf.image.size.height;
        CGFloat cornerRadiusInPixel = cornerRadius * [UIScreen mainScreen].scale;

        UIImage *roundedImage = [weakSelf.image lnv_roundedImageWithSize:CGSizeMake(widthInPixel, heightInPixel) cornerRadius:cornerRadiusInPixel];

        dispatch_async(dispatch_get_main_queue(), ^{
            weakSelf.image = roundedImage;
        });
    });
}

@end


text:
package lx.af.demo.fragment;

import lx.af.demo.consts.DemoConfig;
import lx.af.demo.consts.ActionModel;

/**
 * author: lx
 * date: 16-1-5
 */
public class MainTab3 extends MainTabList {

    @Override
    protected ActionModel[] getActionModelArray() {
        return DemoConfig.UTILS_DEMO;
    }

}


text:
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateUnitPerkTypesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('unit_perk_types', function (Blueprint $table) {
            $table->increments('id');
            $table->string('key')->unique();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('unit_perk_types');
    }
}


text:
package org.apache.amber.oauth2.as.request;

import play.api.mvc.Request;

import org.apache.amber.oauth2.as.validator.AuthorizationCodeValidator;
import org.apache.amber.oauth2.as.validator.ClientCredentialValidator;
import org.apache.amber.oauth2.as.validator.PasswordValidator;
import org.apache.amber.oauth2.as.validator.RefreshTokenValidator;
import org.apache.amber.oauth2.common.OAuth;
import org.apache.amber.oauth2.common.exception.OAuthProblemException;
import org.apache.amber.oauth2.common.exception.OAuthSystemException;
import org.apache.amber.oauth2.common.message.types.GrantType;
import org.apache.amber.oauth2.common.utils.OAuthUtils;
import org.apache.amber.oauth2.common.validators.OAuthValidator;

/**
 *
 *
 *
 */
public class OAuthTokenRequest extends OAuthRequest {

    public OAuthTokenRequest(Request request) throws OAuthSystemException, OAuthProblemException {
        super(request);
    }

    @Override
    protected OAuthValidator<Request> initValidator() throws OAuthProblemException, OAuthSystemException {
        validators.put(GrantType.PASSWORD.toString(), PasswordValidator.class);
        validators.put(GrantType.CLIENT_CREDENTIALS.toString(), ClientCredentialValidator.class);
        validators.put(GrantType.AUTHORIZATION_CODE.toString(), AuthorizationCodeValidator.class);
        validators.put(GrantType.REFRESH_TOKEN.toString(), RefreshTokenValidator.class);
        String requestTypeValue = getParam(OAuth.OAUTH_GRANT_TYPE);
        if (OAuthUtils.isEmpty(requestTypeValue)) {
            throw OAuthUtils.handleOAuthProblemException("Missing grant_type parameter value");
        }
        Class<? extends OAuthValidator<Request>> clazz = validators.get(requestTypeValue);
        if (clazz == null) {
            throw OAuthUtils.handleOAuthProblemException("Invalid grant_type parameter value");
        }
        return OAuthUtils.instantiateClass(clazz);
    }

    public String getPassword() {
        return getParam(OAuth.OAUTH_PASSWORD);
    }

    public String getUsername() {
        return getParam(OAuth.OAUTH_USERNAME);
    }

    public String getRefreshToken() {
        return getParam(OAuth.OAUTH_REFRESH_TOKEN);
    }

    public String getCode() {
        return getParam(OAuth.OAUTH_CODE);
    }

    public String getGrantType() {
        return getParam(OAuth.OAUTH_GRANT_TYPE);
    }

}


text:
package core

// An Address is a location in the inferior's address space.
type Address uint64

// Sub subtracts b from a. Requires a >= b.
func (a Address) Sub(b Address) int64 {
	return int64(a - b)
}

// Add adds x to address a.
func (a Address) Add(x int64) Address {
	return a + Address(x)
}

// Max returns the larger of a and b.
func (a Address) Max(b Address) Address {
	if a > b {
		return a
	}
	return b
}

// Min returns the smaller of a and b.
func (a Address) Min(b Address) Address {
	if a < b {
		return a
	}
	return b
}

// Align rounds a up to a multiple of x.
// x must be a power of 2.
func (a Address) Align(x int64) Address {
	return (a + Address(x) - 1) & ^(Address(x) - 1)
}


text:
**TaobaoFu** is a Rails plugin (supports Rails 3.0.0 or above) as an unofficial Ruby SDK for the Taobao Open Platform(http://open.taobao.com/).

### Compatibility

TaobaoFu is developed against Ruby 1.8.6, 1.8.7, 1.9.1, 1.9.2

### Installation

Get the TaobaoFu plugin from github.com:

    > cd your_rails_app
    > rails plugin install git://github.com/why404/taobao_fu.git

Or you can install it as a git submodule(Recommended):

    > cd your_rails_app
    > git submodule add git://github.com/why404/taobao_fu.git vendor/plugins/taobao_fu
    > git submodule init
    > git submodule update

For Rails applications add the gem dependencies to your Gemfile:

    gem "crack"     # Required
    gem "patron"    # Optional, if you set the :use_curl option is true in config/taobao.yml

Setup of access the TOP API is handled by using automatic configuration with a config/taobao.yml. You can generate a taobao.yml via the following command:

    > rails generate taobao_fu config

An example configuration is as follows, with the default values showing:
config/taobao.yml:

    defaults: &defaults
      app_key:          # YOUR_APP_KEY
      secret_key:       # YOUR_APP_SECRET_TOKEN
      taobaoke_pid:     # YOUR_TAOBAOKE_PID
      taobaoke_nick:    # YOUR_TAOBAOKE_NICKNAME

    development:
      <<: *defaults
      is_sandbox: false # If true, it will work under the sandbox environment(tbsandbox.com, not taobao.com).
      use_curl: false   # If true, it will use gem "patron" as the REST client.

    test:
      <<: *defaults
      is_sandbox: ture
      use_curl: false

    production:
      <<: *defaults
      is_sandbox: false
      use_curl: true

### Example

Here is an example shows you how to get some information of a commodity from taobao.com by using the TaobaoFu.get method.

    > cd your_rails_app
    > rails console
    > TaobaoFu.get(:method => 'taobao.item.get',
                   :nick   => 'simul官方旗舰店',
                   :iid    => '3b54462a34e2ed84c330dc3e5fb4a94f',
                   :fields => 'title, price')

There are four methods mapping HTTP verbs(GET/POST/PUT/DELETE).

    TaobaoFu.get    #(Available)
    TaobaoFu.post
    TaobaoFu.update
    TaobaoFu.delete

There is also an additional method is using for switching between sandbox and production environment of TOP. For instance:

    TaobaoFu.switch_to(TaobaoFu::SANDBOX) # switching to sandbox(tbsandbox.com)
    TaobaoFu.switch_to(TaobaoFu::PRODBOX) # back to production environment(taobao.com)

### Copyright

Copyright (c) 2010 why404(why404#gmail), released under the MIT license.


text:
'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
	Schema = mongoose.Schema

/**
 * Inmueble Schema
 */
var InmuebleSchema = new Schema({
	titulo: { type: String, default: '', required: 'Ingresa un título para tu anuncio', trim: true },
	tipo_inmueble: { type: String, default: '', required: 'Ingresa la categoria de tu inmueble', trim: true },
	tipo_trans: { type: String, default: '', required: 'Ingresa el tipo de transacción', trim: true },
	estado: { type: String, default: '', trim: true },
	ciudad: { type: String, default: '', trim: true },
	zona: { type: String, default: '', trim: true },
	colonia: { type: String, default: '', trim: true },
	direccion: { type: String, default: '', required: 'Ingresa la calle y numero del inmueble', trim: true },
	precio: { type: Number, default: 0 },
	moneda: {type: String, default: 'MNX'},
	no_plantas: { type: Number, default: 1 },
	no_habitaciones: { type: Number, default: 1 },
	no_banos: { type: Number, default: 1 },
	no_carros: { type: Number, default: 0 },
	m2terreno: { type: Number, default: 0 },
	m2construccion: { type: Number, default: 0 },
	infoAdicional:{ type: String, default: '' },
	nombreContacto:{ type: String, default: '' },
	telContacto:{ type: String, default: '' },
	mailContacto:{ type: String, default: '' },
	image:{ type: Array, default:'/uploads/Default.png' },
	tipoDestacado:{type: Number, default: 0},
	created: { type: Date, default: Date.now },
	user: { type: Schema.ObjectId, ref: 'User'}
});

mongoose.model('Inmueble', InmuebleSchema);


text:
<?php

namespace CodingBeard\Emails\Groups;

use models\Users;
use models\Emailchanges;

class Account
{

    /**
     * Send an email verification email
     * @param Users $user
     * @param string $token
     * @return array
     */
    public static function emailVerification($user, $token)
    {
        return [
            'folder'     => 'account',
            'file'       => 'emailVerification',
            'variables'  => [
                'user'  => $user,
                'token' => $token,
            ],
            'from_email' => 'No-reply@',
            'to'         => [['email' => $user->email, 'name' => $user->getName()]],
            'subject'    => "Thanks for registering at CodingBeard! Please verify your email",
        ];
    }

    /**
     * Send an rest pass email
     * @param Users $user
     * @param string $token
     * @return array
     */
    public static function resetPass($user, $token)
    {
        return [
            'folder'     => 'account',
            'file'       => 'resetPass',
            'variables'  => [
                'user'  => $user,
                'token' => $token,
            ],
            'from_email' => 'No-reply@',
            'to'         => [['email' => $user->email, 'name' => $user->getName()]],
            'subject'    => "Password reset",
        ];
    }

    /**
     * Send an email change confirmation/revoke email
     * @param Users $user
     * @param Emailchanges $emailChange
     * @param string $token
     * @return array
     */
    public static function changeEmail($user, $emailChange, $token)
    {
        return [
            [
                'folder'     => 'account',
                'file'       => 'changeEmailRevoke',
                'variables'  => [
                    'user'     => $user,
                    'oldEmail' => $emailChange->oldEmail,
                    'token'    => $token,
                ],
                'from_email' => 'No-reply@',
                'to'         => [['email' => $emailChange->oldEmail, 'name' => $user->getName()]],
                'subject'    => "Your CodingBeard email has been changed",
            ],
            [
                'folder'     => 'account',
                'file'       => 'changeEmailNotice',
                'variables'  => [
                    'user'     => $user,
                    'oldEmail' => $emailChange->oldEmail,
                    'token'    => $token,
                ],
                'from_email' => 'No-reply@',
                'to'         => [['email' => $user->email, 'name' => $user->getName()]],
                'subject'    => "Your CodingBeard email has been changed",
            ],
        ];
    }

}


text:
namespace llvm {
namespace libc_benchmarks {

// The context encapsulates the buffers, parameters and the measure.
struct MemcmpContext : public BenchmarkRunner {
  using FunctionPrototype = int (*)(const void *, const void *, size_t);

  struct ParameterType {
    uint16_t Offset = 0;
  };

  explicit MemcmpContext(const StudyConfiguration &Conf)
      : MOD(Conf), OD(Conf), ABuffer(Conf.BufferSize), BBuffer(Conf.BufferSize),
        PP(*this) {
    std::uniform_int_distribution<char> Dis;
    // Generate random buffer A.
    for (size_t I = 0; I < Conf.BufferSize; ++I)
      ABuffer[I] = Dis(Gen);
    // Copy buffer A to B.
    ::memcpy(BBuffer.begin(), ABuffer.begin(), Conf.BufferSize);
    if (Conf.MemcmpMismatchAt == 0)
      return; // all same.
    else if (Conf.MemcmpMismatchAt == 1)
      for (char &c : BBuffer)
        ++c; // all different.
    else
      for (const auto I : MOD.getMismatchIndices())
        ++BBuffer[I];
  }

  // Needed by the ParameterProvider to update the current batch of parameter.
  void Randomize(MutableArrayRef<ParameterType> Parameters) {
    if (MOD)
      for (auto &P : Parameters)
        P.Offset = MOD(Gen, CurrentSize);
    else
      for (auto &P : Parameters)
        P.Offset = OD(Gen);
  }

  ArrayRef<StringRef> getFunctionNames() const override {
    static std::array<StringRef, 1> kFunctionNames = {"memcmp"};
    return kFunctionNames;
  }

  BenchmarkResult benchmark(const BenchmarkOptions &Options,
                            StringRef FunctionName, size_t Size) override {
    CurrentSize = Size;
    // FIXME: Add `bcmp` once we're guaranteed that the function is provided.
    FunctionPrototype Function =
        StringSwitch<FunctionPrototype>(FunctionName).Case("memcmp", &::memcmp);
    return llvm::libc_benchmarks::benchmark(
        Options, PP, [this, Function, Size](ParameterType p) {
          return Function(ABuffer + p.Offset, BBuffer + p.Offset, Size);
        });
  }

private:
  std::default_random_engine Gen;
  MismatchOffsetDistribution MOD;
  OffsetDistribution OD;
  size_t CurrentSize = 0;
  AlignedBuffer ABuffer;
  AlignedBuffer BBuffer;
  SmallParameterProvider<MemcmpContext> PP;
};

std::unique_ptr<BenchmarkRunner> getRunner(const StudyConfiguration &Conf) {
  return std::make_unique<MemcmpContext>(Conf);
}

} // namespace libc_benchmarks
} // namespace llvm


text:
layout: post
title: Kickstart Android Studio Plugins
categories: [post]
tags: [Android, Plugins, Android Studio]
---
After almost a year of planning a.k.a. laziness, I am finally writing a post on the `Android Studio Plugins` that I use when starting with fresh Android installation.
I will be listing them and giving some quick intro. I hope this will help some and mainly I am trying to make sure that I don't forget them and find the list easily. :blush:

![Kickstart Android Studio Plugins](/images/android-plugins-2.png)

Mostly some of the Plugins mentioned below are for to `make the android development faster` and some are for `lessen up the developer hassle`.

### .gitignore

I am sure by the name of this plugin we developers can know that it's `a plugin for ignoring files in Version Control`. Here are some of its features that I pulled from the original site.

    * Files syntax highlight
    * Coloring ignored files in the Project View
    * Show ignored files by specified ignore file (right click on .gitignore file)
    * Hide ignored files in Project View
    * Suggesting .gitignore file creation for new project
    * Renaming entries from ignore file
    * Close opened ignored files action

[.gitignore JetBrains Site](https://plugins.jetbrains.com/plugin/7495--ignore){:target="_blank"}

### ADB Idea

Are you lazy enough to `clean data`, `uninstall`, `restart app` when you are developing/testing an app? This plugin makes an android developer life easy by making below actions easy:

    * ADB Uninstall App
    * ADB Kill App
    * ADB Start App
    * ADB Restart App
    * ADB Clear App Data
    * ADB Clear App Data and Restart

[ADB Idea JetBrains Site](https://plugins.jetbrains.com/plugin/7380-adb-idea){:target="_blank"}

### String Manipulation

It's another `lovely plugin` which helps you when `working with string` and you wish to have some `faster way of playing with Strings in Android Studio`. It makes easy to `toggle styles of Strings`, `Un/Escape`, `Encode/Decode`, `Increment/Decrement`, `Sort with natural order`, `Align` and so many other stuffs.  :heart: :heart: :heart:

[String Manipulation JetBrains Site](https://plugins.jetbrains.com/plugin/2162-string-manipulation){:target="_blank"} /
[Github link](https://github.com/krasa/StringManipulation){:target="_blank"}

### Key Promoter

If you are a `short-cut key guy *(or even if you are not)*`, then you gonna love this plugin. It will help you setting up the keys and also `will remind you the short-cut` incase you didn't use it. Sometimes you may feel annoying that it keeps reminding you, but trust me its for your own good & you `will fall in love with this` eventually :wink:

[Key Promoter JetBrains Site](https://plugins.jetbrains.com/plugin/4455-key-promoter){:target="_blank"}

### Android ButterKnife Zelezny

If you are an Android Developer I am sure, you are using or must have used the [Butterknife from Jake Wharton](https://github.com/JakeWharton/butterknife){:target="_blank"}. So this plugin allows one-click creation of Butterknife view injections by creating ButterKnife injections from selected layout XMLs in activities/fragments/adapters.

[Android ButterKnife Zelezny JetBrains Site](https://plugins.jetbrains.com/plugin/7369-android-butterknife-zelezny){:target="_blank"} /
[Github link](https://github.com/avast/android-butterknife-zelezny){:target="_blank"}

### Android Color Manager

While we can find lots of `color related plugins`, I am using this Color Manager plugin for my Android Studio. It helps you to do:

    * See all color listed in Color Manager window
    * Drag and drop where you want to copy the color name/tag
    * Edit, Delete, Move, Search colors or colors name

[Android Color Manager JetBrains Site](https://plugins.jetbrains.com/plugin/8583-android-color-manager){:target="_blank"} /
[Github link](https://github.com/shiraji/color-manager/){:target="_blank"}

<hr class="post-list__divider ">

Phewwww :sweat:, I think & we all know, we can not include all the plugins in this single post, but these are the basic Andriod Studio Plugins, that I have been using to setup my Android Studio to be development ready. So guys, sorry if I have missed any of your favorite plugins, will try to write some more later.

>I get by with a little help from my friends.


text:
% animate_flow Display flow animation
%
% DESCRIPTION
% flow = animate_flow(flow,animationTime,framerate,animationFilename)
% animationTime has units of seconds
% framerate has units of 1/second
%
% EXAMPLE
% addpath('flow_templates')
% doubleGyre = double_gyre;
% doubleGyre.flow = animate_flow(doubleGyre.flow);

function flow = animate_flow(flow,animationTime,framerate,animationFilename)

narginchk(1,4)

% FIXME Replace with inputParser
if nargin < 4
    animationFilename = false;
end

if nargin < 3
    framerate = 10;
end

if nargin < 2
    animationTime = 10;
end

initialPosition = initialize_ic_grid(flow.resolution,flow.domain);

if ~isfield(flow,'solution')
    % The equation of variation terms are not needed to produce the flow
    % animation
    useEoV = false;
    flow.solution = integrate_flow(flow,initialPosition,useEoV);
end

mainAxes = setup_figure(flow.domain);

% Set default values for flow structure
p = inputParser;
p.KeepUnmatched = true;
addParameter(p,'coupledIntegration',true,@islogical);
parse(p,flow);
coupledIntegration = p.Results.coupledIntegration;

if coupledIntegration
    position = deval(flow.solution,flow.timespan(1));
    position = [position(1:2:end-1),position(2:2:end)];
    position = transpose(position);
else
    position = arrayfun(@(iSolution)deval(iSolution,flow.timespan(1)),flow.solution,'UniformOutput',false);
    position = cell2mat(position);
end
p1 = plot(mainAxes,position(1,:),position(2,:));
set(p1,'LineStyle','none')
set(p1,'Marker','o')
set(p1,'MarkerFaceColor','b')
set(p1,'MarkerSize',4)

t1 = text(0,0,['t = ',num2str(flow.timespan(1))]);
xLabelPos = get(get(mainAxes,'XLabel'),'position');
t1Pos = [flow.domain(1,1) + diff(flow.domain(1,:))*.9 xLabelPos(2)];
set(t1,'parent',mainAxes)
set(t1,'position',t1Pos)
set(t1,'VerticalAlignment',get(get(mainAxes,'XLabel'),'VerticalAlignment'))
set(t1,'tag','timeText')
drawnow
tic

totalFrames = framerate*animationTime+1;
timesteps = linspace(flow.timespan(1),flow.timespan(2),totalFrames);

if animationFilename
    if exist(animationFilename,'file')
        error(['File exists: ',animationFilename])
    end
    writerObj = VideoWriter(animationFilename);
    writerObj.FrameRate = framerate;
    open(writerObj)
    frame = getframe(gcf);
    writeVideo(writerObj,frame);
end

warningDisplayed = false;
for idx = 2:length(timesteps)
    if coupledIntegration
        position = deval(flow.solution,timesteps(idx));
        position = [position(1:2:end-1),position(2:2:end)];
        position = transpose(position);
    else
        position = arrayfun(@(iSolution)deval(iSolution,timesteps(idx)),flow.solution,'UniformOutput',false);
        position = cell2mat(position);
    end

    if isfield(flow,'periodicBc') && any(flow.periodicBc)
        position = apply_periodic_bc(position,flow.periodicBc,flow.domain);
    end

    set(p1,'xData',position(1,:),'yData',position(2,:))
    set(t1,'string',['t = ',num2str(timesteps(idx))])
    drawnow
    delay = 1/framerate - toc;
    if (delay < 0) && (warningDisplayed == false)
        warning([mfilename,':negative_delay'],'Frame rate too high')
        warningDisplayed = true;
    end
    if animationFilename
        frame = getframe(gcf);
        writeVideo(writerObj,frame);
    end
    pause(delay)
    tic
end

if animationFilename
    close(writerObj)
end


text:
package org.apache.sqoop.metastore;

import java.io.File;

import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.apache.hadoop.conf.Configuration;

public class AutoGenericJobStorage extends GenericJobStorage {

  public static final Log LOG = LogFactory.getLog(AutoGenericJobStorage.class.getName());

  /**
   * Configuration key specifying whether this storage agent is active.
   * Defaults to "on" to allow zero-conf local users.
   */
  public static final String AUTO_STORAGE_IS_ACTIVE_KEY =
      "sqoop.metastore.client.enable.autoconnect";

  /**
   * Configuration key specifying the connect string used by this
   * storage agent.
   */
  public static final String AUTO_STORAGE_CONNECT_STRING_KEY =
      "sqoop.metastore.client.autoconnect.url";

  /**
   * Configuration key specifying the username to bind with.
   */
  public static final String AUTO_STORAGE_USER_KEY =
      "sqoop.metastore.client.autoconnect.username";

  /** HSQLDB default user is named 'SA'. */
  private static final String DEFAULT_AUTO_USER = "SA";

  /**
   * Configuration key specifying the password to bind with.
   */
  public static final String AUTO_STORAGE_PASS_KEY =
      "sqoop.metastore.client.autoconnect.password";

  /** HSQLDB default user has an empty password. */
  public static final String DEFAULT_AUTO_PASSWORD = "";

  @Override
  /** {@inheritDoc} */
  public boolean canAccept(Map<String, String> descriptor) {
    Configuration conf = this.getConf();
    return conf.getBoolean(AUTO_STORAGE_IS_ACTIVE_KEY, true);
  }

  /**
   * Determine the user's home directory and return a connect
   * string to HSQLDB that uses ~/.sqoop/ as the storage location
   * for the metastore database.
   */
  private String getHomeDirFileConnectStr() {
    String homeDir = System.getProperty("user.home");

    File homeDirObj = new File(homeDir);
    File sqoopDataDirObj = new File(homeDirObj, ".sqoop");
    File databaseFileObj = new File(sqoopDataDirObj, "metastore.db");

    String dbFileStr = databaseFileObj.toString();
    return "jdbc:hsqldb:file:" + dbFileStr
        + ";hsqldb.write_delay=false;shutdown=true";
  }

  @Override
  protected void setConnectionParameters(Map<String, String> descriptor) {
    Configuration conf = getConf();
    setMetastoreConnectStr(conf.get(AUTO_STORAGE_CONNECT_STRING_KEY, getHomeDirFileConnectStr()));
    setMetastoreUser(conf.get(AUTO_STORAGE_USER_KEY, DEFAULT_AUTO_USER));
    setMetastorePassword(conf.get(AUTO_STORAGE_PASS_KEY, DEFAULT_AUTO_PASSWORD));
  }
}


text:
namespace ash {

namespace {
internal::DisplayManager* GetDisplayManager() {
  return Shell::GetInstance()->display_manager();
}

DisplayController* GetDisplayController() {
  return Shell::GetInstance()->display_controller();
}
}  // namespace

ScreenAsh::ScreenAsh() {
}

ScreenAsh::~ScreenAsh() {
}

// static
gfx::Display ScreenAsh::FindDisplayContainingPoint(const gfx::Point& point) {
  return GetDisplayManager()->FindDisplayContainingPoint(point);
}

// static
gfx::Rect ScreenAsh::GetMaximizedWindowBoundsInParent(aura::Window* window) {
  if (internal::GetRootWindowController(window->GetRootWindow())->shelf())
    return GetDisplayWorkAreaBoundsInParent(window);
  else
    return GetDisplayBoundsInParent(window);
}

// static
gfx::Rect ScreenAsh::GetDisplayBoundsInParent(aura::Window* window) {
  return ConvertRectFromScreen(
      window->parent(),
      Shell::GetScreen()->GetDisplayNearestWindow(window).bounds());
}

// static
gfx::Rect ScreenAsh::GetDisplayWorkAreaBoundsInParent(aura::Window* window) {
  return ConvertRectFromScreen(
      window->parent(),
      Shell::GetScreen()->GetDisplayNearestWindow(window).work_area());
}

// static
gfx::Rect ScreenAsh::ConvertRectToScreen(aura::Window* window,
                                         const gfx::Rect& rect) {
  gfx::Point point = rect.origin();
  aura::client::GetScreenPositionClient(window->GetRootWindow())->
      ConvertPointToScreen(window, &point);
  return gfx::Rect(point, rect.size());
}

// static
gfx::Rect ScreenAsh::ConvertRectFromScreen(aura::Window* window,
                                           const gfx::Rect& rect) {
  gfx::Point point = rect.origin();
  aura::client::GetScreenPositionClient(window->GetRootWindow())->
      ConvertPointFromScreen(window, &point);
  return gfx::Rect(point, rect.size());
}

// static
const gfx::Display& ScreenAsh::GetSecondaryDisplay() {
  internal::DisplayManager* display_manager = GetDisplayManager();
  CHECK_EQ(2U, display_manager->GetNumDisplays());
  return display_manager->GetDisplayAt(0).id() ==
      DisplayController::GetPrimaryDisplay().id() ?
      display_manager->GetDisplayAt(1) : display_manager->GetDisplayAt(0);
}

// static
const gfx::Display& ScreenAsh::GetDisplayForId(int64 display_id) {
  return GetDisplayManager()->GetDisplayForId(display_id);
}

void ScreenAsh::NotifyBoundsChanged(const gfx::Display& display) {
  FOR_EACH_OBSERVER(gfx::DisplayObserver, observers_,
                    OnDisplayBoundsChanged(display));
}

void ScreenAsh::NotifyDisplayAdded(const gfx::Display& display) {
  FOR_EACH_OBSERVER(gfx::DisplayObserver, observers_, OnDisplayAdded(display));
}

void ScreenAsh::NotifyDisplayRemoved(const gfx::Display& display) {
  FOR_EACH_OBSERVER(
      gfx::DisplayObserver, observers_, OnDisplayRemoved(display));
}

bool ScreenAsh::IsDIPEnabled() {
  return true;
}

gfx::Point ScreenAsh::GetCursorScreenPoint() {
  return aura::Env::GetInstance()->last_mouse_location();
}

gfx::NativeWindow ScreenAsh::GetWindowUnderCursor() {
  return GetWindowAtScreenPoint(Shell::GetScreen()->GetCursorScreenPoint());
}

gfx::NativeWindow ScreenAsh::GetWindowAtScreenPoint(const gfx::Point& point) {
  return wm::GetRootWindowAt(point)->GetTopWindowContainingPoint(point);
}

int ScreenAsh::GetNumDisplays() const {
  return DisplayController::GetNumDisplays();
}

std::vector<gfx::Display> ScreenAsh::GetAllDisplays() const {
  return GetDisplayManager()->displays();
}

gfx::Display ScreenAsh::GetDisplayNearestWindow(gfx::NativeView window) const {
  return GetDisplayController()->GetDisplayNearestWindow(window);
}

gfx::Display ScreenAsh::GetDisplayNearestPoint(const gfx::Point& point) const {
  return GetDisplayController()->GetDisplayNearestPoint(point);
}

gfx::Display ScreenAsh::GetDisplayMatching(const gfx::Rect& match_rect) const {
  return GetDisplayController()->GetDisplayMatching(match_rect);
}

gfx::Display ScreenAsh::GetPrimaryDisplay() const {
  return DisplayController::GetPrimaryDisplay();
}

void ScreenAsh::AddObserver(gfx::DisplayObserver* observer) {
  observers_.AddObserver(observer);
}

void ScreenAsh::RemoveObserver(gfx::DisplayObserver* observer) {
  observers_.RemoveObserver(observer);
}

}  // namespace ash


text:
// Copyright 2019 The IREE Authors
//
// Licensed under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception

#include "iree/hal/drivers/vulkan/direct_command_buffer.h"

#include <cstddef>
#include <cstdint>

#include "iree/base/api.h"
#include "iree/base/internal/inline_array.h"
#include "iree/base/internal/math.h"
#include "iree/base/tracing.h"
#include "iree/hal/drivers/vulkan/descriptor_set_arena.h"
#include "iree/hal/drivers/vulkan/dynamic_symbols.h"
#include "iree/hal/drivers/vulkan/native_event.h"
#include "iree/hal/drivers/vulkan/native_executable.h"
#include "iree/hal/drivers/vulkan/native_pipeline_layout.h"
#include "iree/hal/drivers/vulkan/status_util.h"
#include "iree/hal/drivers/vulkan/util/ref_ptr.h"
#include "iree/hal/drivers/vulkan/vma_buffer.h"
#include "iree/hal/utils/resource_set.h"

using namespace iree::hal::vulkan;

// Command buffer implementation that directly maps to VkCommandBuffer.
// This records the commands on the calling thread without additional threading
// indirection.
typedef struct iree_hal_vulkan_direct_command_buffer_t {
  iree_hal_command_buffer_t base;
  VkDeviceHandle* logical_device;
  iree_hal_vulkan_tracing_context_t* tracing_context;
  iree_arena_block_pool_t* block_pool;

  VkCommandPoolHandle* command_pool;
  VkCommandBuffer handle;

  DynamicSymbols* syms;

  // Maintains a reference to all resources used within the command buffer.
  // Reset on each begin.
  iree_hal_resource_set_t* resource_set;

  // TODO(benvanik): may grow large - should try to reclaim or reuse.
  DescriptorSetArena descriptor_set_arena;

  // The current descriptor set group in use by the command buffer, if any.
  // This must remain valid until all in-flight submissions of the command
  // buffer complete.
  DescriptorSetGroup descriptor_set_group;

  BuiltinExecutables* builtin_executables;

  // Shadow copy of push constants used during normal operation, for restoring
  // after builtin_executables uses vkCmdPushConstants. Size must be greater
  // than or equal to the push constant memory used by builtin_executables.
  // TODO(scotttodd): use [maxPushConstantsSize - 16, maxPushConstantsSize]
  //                  instead of [0, 16] to reduce frequency of updates
  uint8_t push_constants_storage[IREE_HAL_VULKAN_BUILTIN_PUSH_CONSTANT_COUNT];
} iree_hal_vulkan_direct_command_buffer_t;

namespace {
extern const iree_hal_command_buffer_vtable_t
    iree_hal_vulkan_direct_command_buffer_vtable;
}  // namespace

static iree_hal_vulkan_direct_command_buffer_t*
iree_hal_vulkan_direct_command_buffer_cast(
    iree_hal_command_buffer_t* base_value) {
  IREE_HAL_ASSERT_TYPE(base_value,
                       &iree_hal_vulkan_direct_command_buffer_vtable);
  return (iree_hal_vulkan_direct_command_buffer_t*)base_value;
}

iree_status_t iree_hal_vulkan_direct_command_buffer_allocate(
    iree_hal_device_t* device,
    iree::hal::vulkan::VkDeviceHandle* logical_device,
    iree::hal::vulkan::VkCommandPoolHandle* command_pool,
    iree_hal_command_buffer_mode_t mode,
    iree_hal_command_category_t command_categories,
    iree_hal_queue_affinity_t queue_affinity, iree_host_size_t binding_capacity,
    iree_hal_vulkan_tracing_context_t* tracing_context,
    iree::hal::vulkan::DescriptorPoolCache* descriptor_pool_cache,
    iree::hal::vulkan::BuiltinExecutables* builtin_executables,
    iree_arena_block_pool_t* block_pool,
    iree_hal_command_buffer_t** out_command_buffer) {
  IREE_ASSERT_ARGUMENT(logical_device);
  IREE_ASSERT_ARGUMENT(command_pool);
  IREE_ASSERT_ARGUMENT(descriptor_pool_cache);
  IREE_ASSERT_ARGUMENT(block_pool);
  IREE_ASSERT_ARGUMENT(out_command_buffer);
  *out_command_buffer = NULL;

  if (binding_capacity > 0) {
    // TODO(#10144): support indirect command buffers with binding tables.
    return iree_make_status(IREE_STATUS_UNIMPLEMENTED,
                            "indirect command buffers not yet implemented");
  }

  IREE_TRACE_ZONE_BEGIN(z0);

  VkCommandBufferAllocateInfo allocate_info;
  allocate_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
  allocate_info.pNext = NULL;
  allocate_info.commandPool = *command_pool;
  allocate_info.commandBufferCount = 1;
  allocate_info.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;

  VkCommandBuffer handle = VK_NULL_HANDLE;
  IREE_RETURN_AND_END_ZONE_IF_ERROR(
      z0, command_pool->Allocate(&allocate_info, &handle));

  iree_hal_vulkan_direct_command_buffer_t* command_buffer = NULL;
  iree_status_t status =
      iree_allocator_malloc(logical_device->host_allocator(),
                            sizeof(*command_buffer), (void**)&command_buffer);
  if (iree_status_is_ok(status)) {
    iree_hal_command_buffer_initialize(
        device, mode, command_categories, queue_affinity, binding_capacity,
        &iree_hal_vulkan_direct_command_buffer_vtable, &command_buffer->base);
    command_buffer->logical_device = logical_device;
    command_buffer->tracing_context = tracing_context;
    command_buffer->block_pool = block_pool;
    command_buffer->command_pool = command_pool;
    command_buffer->handle = handle;
    command_buffer->syms = logical_device->syms().get();

    new (&command_buffer->descriptor_set_arena)
        DescriptorSetArena(descriptor_pool_cache);
    new (&command_buffer->descriptor_set_group) DescriptorSetGroup();

    command_buffer->builtin_executables = builtin_executables;
    status = iree_hal_resource_set_allocate(block_pool,
                                            &command_buffer->resource_set);
  }

  if (iree_status_is_ok(status)) {
    *out_command_buffer = &command_buffer->base;
  } else {
    command_pool->Free(handle);
  }

  IREE_TRACE_ZONE_END(z0);
  return status;
}

bool iree_hal_vulkan_direct_command_buffer_isa(
    iree_hal_command_buffer_t* command_buffer) {
  return iree_hal_command_buffer_dyn_cast(
      command_buffer, &iree_hal_vulkan_direct_command_buffer_vtable);
}

static void* iree_hal_vulkan_direct_command_buffer_dyn_cast(
    iree_hal_command_buffer_t* command_buffer, const void* vtable) {
  if (vtable == &iree_hal_vulkan_direct_command_buffer_vtable) {
    IREE_HAL_ASSERT_TYPE(command_buffer, vtable);
    return command_buffer;
  }
  return NULL;
}

static void iree_hal_vulkan_direct_command_buffer_destroy(
    iree_hal_command_buffer_t* base_command_buffer) {
  iree_hal_vulkan_direct_command_buffer_t* command_buffer =
      iree_hal_vulkan_direct_command_buffer_cast(base_command_buffer);
  iree_allocator_t host_allocator =
      command_buffer->logical_device->host_allocator();
  IREE_TRACE_ZONE_BEGIN(z0);

  command_buffer->command_pool->Free(command_buffer->handle);

  IREE_IGNORE_ERROR(command_buffer->descriptor_set_group.Reset());
  command_buffer->descriptor_set_group.~DescriptorSetGroup();
  command_buffer->descriptor_set_arena.~DescriptorSetArena();

  iree_hal_resource_set_free(command_buffer->resource_set);
  iree_allocator_free(host_allocator, command_buffer);

  IREE_TRACE_ZONE_END(z0);
}

VkCommandBuffer iree_hal_vulkan_direct_command_buffer_handle(
    iree_hal_command_buffer_t* base_command_buffer) {
  iree_hal_vulkan_direct_command_buffer_t* command_buffer =
      (iree_hal_vulkan_direct_command_buffer_t*)
          iree_hal_command_buffer_dyn_cast(
              base_command_buffer,
              &iree_hal_vulkan_direct_command_buffer_vtable);
  return command_buffer->handle;
}

static iree_status_t iree_hal_vulkan_direct_command_buffer_begin(
    iree_hal_command_buffer_t* base_command_buffer) {
  iree_hal_vulkan_direct_command_buffer_t* command_buffer =
      iree_hal_vulkan_direct_command_buffer_cast(base_command_buffer);

  VkCommandBufferBeginInfo begin_info;
  begin_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
  begin_info.pNext = NULL;
  begin_info.flags = iree_all_bits_set(command_buffer->base.mode,
                                       IREE_HAL_COMMAND_BUFFER_MODE_ONE_SHOT)
                         ? VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT
                         : 0;
  begin_info.pInheritanceInfo = NULL;
  VK_RETURN_IF_ERROR(command_buffer->syms->vkBeginCommandBuffer(
                         command_buffer->handle, &begin_info),
                     "vkBeginCommandBuffer");

  IREE_VULKAN_TRACE_ZONE_BEGIN_EXTERNAL(
      command_buffer->tracing_context, command_buffer->handle,
      /*file_name=*/NULL, 0,
      /*line=*/0, /*func_name=*/NULL, 0,
      "iree_hal_vulkan_direct_command_buffer",
      strlen("iree_hal_vulkan_direct_command_buffer"));

  return iree_ok_status();
}

static iree_status_t iree_hal_vulkan_direct_command_buffer_end(
    iree_hal_command_buffer_t* base_command_buffer) {
  iree_hal_vulkan_direct_command_buffer_t* command_buffer =
      iree_hal_vulkan_direct_command_buffer_cast(base_command_buffer);

  IREE_VULKAN_TRACE_ZONE_END(command_buffer->tracing_context,
                             command_buffer->handle);

  VK_RETURN_IF_ERROR(
      command_buffer->syms->vkEndCommandBuffer(command_buffer->handle),
      "vkEndCommandBuffer");

  // Flush all pending descriptor set writes (if any).
  command_buffer->descriptor_set_group =
      command_buffer->descriptor_set_arena.Flush();

  return iree_ok_status();
}

static void iree_hal_vulkan_direct_command_buffer_begin_debug_group(
    iree_hal_command_buffer_t* base_command_buffer, iree_string_view_t label,
    iree_hal_label_color_t label_color,
    const iree_hal_label_location_t* location) {
  iree_hal_vulkan_direct_command_buffer_t* command_buffer =
      iree_hal_vulkan_direct_command_buffer_cast(base_command_buffer);
  IREE_VULKAN_TRACE_ZONE_BEGIN_EXTERNAL(
      command_buffer->tracing_context, command_buffer->handle,
      location ? location->file.data : NULL, location ? location->file.size : 0,
      location ? location->line : 0, /*func_name=*/NULL, 0, label.data,
      label.size);
  if (command_buffer->syms->vkCmdBeginDebugUtilsLabelEXT) {
    char label_buffer[128];
    snprintf(label_buffer, sizeof(label_buffer), "%.*s", (int)label.size,
             label.data);
    VkDebugUtilsLabelEXT label_info = {
        /*.sType=*/VK_STRUCTURE_TYPE_DEBUG_UTILS_LABEL_EXT,
        /*.pNext=*/NULL,
        /*.pLabelName=*/label_buffer,
        /*.color=*/
        {
            /*r=*/label_color.r / 255.0f,
            /*g=*/label_color.g / 255.0f,
            /*b=*/label_color.b / 255.0f,
            /*a=*/label_color.a / 255.0f,
        },
    };
    command_buffer->syms->vkCmdBeginDebugUtilsLabelEXT(command_buffer->handle,
                                                       &label_info);
  }
}

static void iree_hal_vulkan_direct_command_buffer_end_debug_group(
    iree_hal_command_buffer_t* base_command_buffer) {
  iree_hal_vulkan_direct_command_buffer_t* command_buffer =
      iree_hal_vulkan_direct_command_buffer_cast(base_command_buffer);
  if (command_buffer->syms->vkCmdEndDebugUtilsLabelEXT) {
    command_buffer->syms->vkCmdEndDebugUtilsLabelEXT(command_buffer->handle);
  }
  IREE_VULKAN_TRACE_ZONE_END(command_buffer->tracing_context,
                             command_buffer->handle);
}

static VkPipelineStageFlags iree_hal_vulkan_convert_pipeline_stage_flags(
    iree_hal_execution_stage_t stage_mask) {
  VkPipelineStageFlags flags = 0;
  flags |= iree_any_bit_set(stage_mask, IREE_HAL_EXECUTION_STAGE_COMMAND_ISSUE)
               ? VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT
               : 0;
  flags |=
      iree_any_bit_set(stage_mask, IREE_HAL_EXECUTION_STAGE_COMMAND_PROCESS)
          ? VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT
          : 0;
  flags |= iree_any_bit_set(stage_mask, IREE_HAL_EXECUTION_STAGE_DISPATCH)
               ? VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT
               : 0;
  flags |= iree_any_bit_set(stage_mask, IREE_HAL_EXECUTION_STAGE_TRANSFER)
               ? VK_PIPELINE_STAGE_TRANSFER_BIT
               : 0;
  flags |= iree_any_bit_set(stage_mask, IREE_HAL_EXECUTION_STAGE_COMMAND_RETIRE)
               ? VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT
               : 0;
  flags |= iree_any_bit_set(stage_mask, IREE_HAL_EXECUTION_STAGE_HOST)
               ? VK_PIPELINE_STAGE_HOST_BIT
               : 0;
  return flags;
}

static VkAccessFlags iree_hal_vulkan_convert_access_mask(
    iree_hal_access_scope_t access_mask) {
  VkAccessFlags flags = 0;
  flags |=
      iree_any_bit_set(access_mask, IREE_HAL_ACCESS_SCOPE_INDIRECT_COMMAND_READ)
          ? VK_ACCESS_INDIRECT_COMMAND_READ_BIT
          : 0;
  flags |= iree_any_bit_set(access_mask, IREE_HAL_ACCESS_SCOPE_CONSTANT_READ)
               ? VK_ACCESS_UNIFORM_READ_BIT
               : 0;
  flags |= iree_any_bit_set(access_mask, IREE_HAL_ACCESS_SCOPE_DISPATCH_READ)
               ? VK_ACCESS_SHADER_READ_BIT
               : 0;
  flags |= iree_any_bit_set(access_mask, IREE_HAL_ACCESS_SCOPE_DISPATCH_WRITE)
               ? VK_ACCESS_SHADER_WRITE_BIT
               : 0;
  flags |= iree_any_bit_set(access_mask, IREE_HAL_ACCESS_SCOPE_TRANSFER_READ)
               ? VK_ACCESS_TRANSFER_READ_BIT
               : 0;
  flags |= iree_any_bit_set(access_mask, IREE_HAL_ACCESS_SCOPE_TRANSFER_WRITE)
               ? VK_ACCESS_TRANSFER_WRITE_BIT
               : 0;
  flags |= iree_any_bit_set(access_mask, IREE_HAL_ACCESS_SCOPE_HOST_READ)
               ? VK_ACCESS_HOST_READ_BIT
               : 0;
  flags |= iree_any_bit_set(access_mask, IREE_HAL_ACCESS_SCOPE_HOST_WRITE)
               ? VK_ACCESS_HOST_WRITE_BIT
               : 0;
  flags |= iree_any_bit_set(access_mask, IREE_HAL_ACCESS_SCOPE_MEMORY_READ)
               ? VK_ACCESS_MEMORY_READ_BIT
               : 0;
  flags |= iree_any_bit_set(access_mask, IREE_HAL_ACCESS_SCOPE_MEMORY_WRITE)
               ? VK_ACCESS_MEMORY_WRITE_BIT
               : 0;
  return flags;
}

static iree_status_t iree_hal_vulkan_direct_command_buffer_execution_barrier(
    iree_hal_command_buffer_t* base_command_buffer,
    iree_hal_execution_stage_t source_stage_mask,
    iree_hal_execution_stage_t target_stage_mask,
    iree_hal_execution_barrier_flags_t flags,
    iree_host_size_t memory_barrier_count,
    const iree_hal_memory_barrier_t* memory_barriers,
    iree_host_size_t buffer_barrier_count,
    const iree_hal_buffer_barrier_t* buffer_barriers) {
  iree_hal_vulkan_direct_command_buffer_t* command_buffer =
      iree_hal_vulkan_direct_command_buffer_cast(base_command_buffer);
  iree_allocator_t host_allocator =
      command_buffer->logical_device->host_allocator();

  iree_inline_array(VkMemoryBarrier, memory_barrier_infos, memory_barrier_count,
                    host_allocator);
  for (int i = 0; i < memory_barrier_count; ++i) {
    const auto& memory_barrier = memory_barriers[i];
    VkMemoryBarrier* info = iree_inline_array_at(memory_barrier_infos, i);
    info->sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER;
    info->pNext = NULL;
    info->srcAccessMask =
        iree_hal_vulkan_convert_access_mask(memory_barrier.source_scope);
    info->dstAccessMask =
        iree_hal_vulkan_convert_access_mask(memory_barrier.target_scope);
  }

  iree_inline_array(VkBufferMemoryBarrier, buffer_barrier_infos,
                    buffer_barrier_count, host_allocator);
  for (int i = 0; i < buffer_barrier_count; ++i) {
    const auto& buffer_barrier = buffer_barriers[i];
    VkBufferMemoryBarrier* info = iree_inline_array_at(buffer_barrier_infos, i);
    info->sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER;
    info->pNext = NULL;
    info->srcAccessMask =
        iree_hal_vulkan_convert_access_mask(buffer_barrier.source_scope);
    info->dstAccessMask =
        iree_hal_vulkan_convert_access_mask(buffer_barrier.target_scope);
    info->srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
    info->dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
    info->buffer = iree_hal_vulkan_vma_buffer_handle(
        iree_hal_buffer_allocated_buffer(buffer_barrier.buffer));
    info->offset = buffer_barrier.offset;
    info->size = buffer_barrier.length;
  }

  command_buffer->syms->vkCmdPipelineBarrier(
      command_buffer->handle,
      iree_hal_vulkan_convert_pipeline_stage_flags(source_stage_mask),
      iree_hal_vulkan_convert_pipeline_stage_flags(target_stage_mask),
      /*dependencyFlags=*/0, (uint32_t)memory_barrier_count,
      iree_inline_array_data(memory_barrier_infos),
      (uint32_t)buffer_barrier_count,
      iree_inline_array_data(buffer_barrier_infos), 0, NULL);

  iree_inline_array_deinitialize(memory_barrier_infos);
  iree_inline_array_deinitialize(buffer_barrier_infos);

  return iree_ok_status();
}

static iree_status_t iree_hal_vulkan_direct_command_buffer_signal_event(
    iree_hal_command_buffer_t* base_command_buffer, iree_hal_event_t* event,
    iree_hal_execution_stage_t source_stage_mask) {
  iree_hal_vulkan_direct_command_buffer_t* command_buffer =
      iree_hal_vulkan_direct_command_buffer_cast(base_command_buffer);

  IREE_RETURN_IF_ERROR(
      iree_hal_resource_set_insert(command_buffer->resource_set, 1, &event));

  command_buffer->syms->vkCmdSetEvent(
      command_buffer->handle, iree_hal_vulkan_native_event_handle(event),
      iree_hal_vulkan_convert_pipeline_stage_flags(source_stage_mask));

  return iree_ok_status();
}

static iree_status_t iree_hal_vulkan_direct_command_buffer_reset_event(
    iree_hal_command_buffer_t* base_command_buffer, iree_hal_event_t* event,
    iree_hal_execution_stage_t source_stage_mask) {
  iree_hal_vulkan_direct_command_buffer_t* command_buffer =
      iree_hal_vulkan_direct_command_buffer_cast(base_command_buffer);

  IREE_RETURN_IF_ERROR(
      iree_hal_resource_set_insert(command_buffer->resource_set, 1, &event));

  command_buffer->syms->vkCmdResetEvent(
      command_buffer->handle, iree_hal_vulkan_native_event_handle(event),
      iree_hal_vulkan_convert_pipeline_stage_flags(source_stage_mask));

  return iree_ok_status();
}

static iree_status_t iree_hal_vulkan_direct_command_buffer_wait_events(
    iree_hal_command_buffer_t* base_command_buffer,
    iree_host_size_t event_count, const iree_hal_event_t** events,
    iree_hal_execution_stage_t source_stage_mask,
    iree_hal_execution_stage_t target_stage_mask,
    iree_host_size_t memory_barrier_count,
    const iree_hal_memory_barrier_t* memory_barriers,
    iree_host_size_t buffer_barrier_count,
    const iree_hal_buffer_barrier_t* buffer_barriers) {
  iree_hal_vulkan_direct_command_buffer_t* command_buffer =
      iree_hal_vulkan_direct_command_buffer_cast(base_command_buffer);
  iree_allocator_t host_allocator =
      command_buffer->logical_device->host_allocator();

  IREE_RETURN_IF_ERROR(iree_hal_resource_set_insert(
      command_buffer->resource_set, event_count, events));

  iree_inline_array(VkEvent, event_handles, event_count, host_allocator);
  for (int i = 0; i < event_count; ++i) {
    *iree_inline_array_at(event_handles, i) =
        iree_hal_vulkan_native_event_handle(events[i]);
  }

  iree_inline_array(VkMemoryBarrier, memory_barrier_infos, memory_barrier_count,
                    host_allocator);
  for (int i = 0; i < memory_barrier_count; ++i) {
    const auto& memory_barrier = memory_barriers[i];
    VkMemoryBarrier* info = iree_inline_array_at(memory_barrier_infos, i);
    info->sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER;
    info->pNext = NULL;
    info->srcAccessMask =
        iree_hal_vulkan_convert_access_mask(memory_barrier.source_scope);
    info->dstAccessMask =
        iree_hal_vulkan_convert_access_mask(memory_barrier.target_scope);
  }

  iree_inline_array(VkBufferMemoryBarrier, buffer_barrier_infos,
                    buffer_barrier_count, host_allocator);
  for (int i = 0; i < buffer_barrier_count; ++i) {
    const auto& buffer_barrier = buffer_barriers[i];
    VkBufferMemoryBarrier* info = iree_inline_array_at(buffer_barrier_infos, i);
    info->sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER;
    info->pNext = NULL;
    info->srcAccessMask =
        iree_hal_vulkan_convert_access_mask(buffer_barrier.source_scope);
    info->dstAccessMask =
        iree_hal_vulkan_convert_access_mask(buffer_barrier.target_scope);
    info->srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
    info->dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
    info->buffer = iree_hal_vulkan_vma_buffer_handle(
        iree_hal_buffer_allocated_buffer(buffer_barrier.buffer));
    info->offset = buffer_barrier.offset;
    info->size = buffer_barrier.length;
  }

  command_buffer->syms->vkCmdWaitEvents(
      command_buffer->handle, (uint32_t)event_count,
      iree_inline_array_data(event_handles),
      iree_hal_vulkan_convert_pipeline_stage_flags(source_stage_mask),
      iree_hal_vulkan_convert_pipeline_stage_flags(target_stage_mask),
      (uint32_t)memory_barrier_count,
      iree_inline_array_data(memory_barrier_infos),
      (uint32_t)buffer_barrier_count,
      iree_inline_array_data(buffer_barrier_infos), 0, NULL);

  iree_inline_array_deinitialize(event_handles);
  iree_inline_array_deinitialize(memory_barrier_infos);
  iree_inline_array_deinitialize(buffer_barrier_infos);

  return iree_ok_status();
}

static iree_status_t iree_hal_vulkan_direct_command_buffer_discard_buffer(
    iree_hal_command_buffer_t* base_command_buffer, iree_hal_buffer_t* buffer) {
  // NOTE: we could use this to prevent queue family transitions.
  return iree_ok_status();
}

// Splats a pattern value of 1, 2, or 4 bytes out to a 4 byte value.
static uint32_t iree_hal_vulkan_splat_pattern(const void* pattern,
                                              size_t pattern_length) {
  switch (pattern_length) {
    case 1: {
      uint32_t pattern_value = *static_cast<const uint8_t*>(pattern);
      return (pattern_value << 24) | (pattern_value << 16) |
             (pattern_value << 8) | pattern_value;
    }
    case 2: {
      uint32_t pattern_value = *static_cast<const uint16_t*>(pattern);
      return (pattern_value << 16) | pattern_value;
    }
    case 4: {
      uint32_t pattern_value = *static_cast<const uint32_t*>(pattern);
      return pattern_value;
    }
    default:
      return 0;  // Already verified that this should not be possible.
  }
}

static iree_status_t iree_hal_vulkan_direct_command_buffer_fill_buffer(
    iree_hal_command_buffer_t* base_command_buffer,
    iree_hal_buffer_t* target_buffer, iree_device_size_t target_offset,
    iree_device_size_t length, const void* pattern,
    iree_host_size_t pattern_length) {
  iree_hal_vulkan_direct_command_buffer_t* command_buffer =
      iree_hal_vulkan_direct_command_buffer_cast(base_command_buffer);
  VkBuffer target_device_buffer = iree_hal_vulkan_vma_buffer_handle(
      iree_hal_buffer_allocated_buffer(target_buffer));

  IREE_RETURN_IF_ERROR(iree_hal_resource_set_insert(
      command_buffer->resource_set, 1, &target_buffer));

  // vkCmdFillBuffer requires a 4 byte alignment for the offset, pattern, and
  // length. We use a polyfill here that fills the unaligned start and end of
  // fill operations, if needed.

  if (target_offset % 4 != 0 || length % 4 != 0) {
    // TODO(scotttodd): only restore push constants that have been modified?
    //                  (this can pass uninitialized memory right now, which
    //                   *should* be safe but is wasteful)
    IREE_RETURN_IF_ERROR(
        command_buffer->builtin_executables->FillBufferUnaligned(
            command_buffer->handle, &(command_buffer->descriptor_set_arena),
            target_buffer, target_offset, length, pattern, pattern_length,
            command_buffer->push_constants_storage));

    // Continue using vkCmdFillBuffer below, but only for the inner aligned
    // portion of the fill operation.
    // For example:
    //   original offset 2, length 8
    //   aligned  offset 4, length 4
    // [0x00,0x00,0xAB,0xAB | 0xAB,0xAB,0xAB,0xAB | 0xAB,0xAB,0x00,0x00]
    //            <-------> <---------------------> <------->
    //            unaligned     vkCmdFillBuffer     unaligned
    iree_device_size_t aligned_target_offset =
        iree_device_align(target_offset, 4);
    iree_device_size_t target_end = target_offset + length;
    iree_device_size_t rounded_down_target_end = (target_end / 4) * 4;
    length -= (aligned_target_offset - target_offset) +
              (target_end - rounded_down_target_end);
    target_offset = aligned_target_offset;
  }

  if (length > 0) {
    // Note that vkCmdFillBuffer only accepts 4-byte aligned values so we need
    // to splat out our variable-length pattern.
    target_offset += iree_hal_buffer_byte_offset(target_buffer);
    uint32_t dword_pattern =
        iree_hal_vulkan_splat_pattern(pattern, pattern_length);
    command_buffer->syms->vkCmdFillBuffer(command_buffer->handle,
                                          target_device_buffer, target_offset,
                                          length, dword_pattern);
  }

  return iree_ok_status();
}

static iree_status_t iree_hal_vulkan_direct_command_buffer_update_buffer(
    iree_hal_command_buffer_t* base_command_buffer, const void* source_buffer,
    iree_host_size_t source_offset, iree_hal_buffer_t* target_buffer,
    iree_device_size_t target_offset, iree_device_size_t length) {
  iree_hal_vulkan_direct_command_buffer_t* command_buffer =
      iree_hal_vulkan_direct_command_buffer_cast(base_command_buffer);
  VkBuffer target_device_buffer = iree_hal_vulkan_vma_buffer_handle(
      iree_hal_buffer_allocated_buffer(target_buffer));

  IREE_RETURN_IF_ERROR(iree_hal_resource_set_insert(
      command_buffer->resource_set, 1, &target_buffer));

  // Vulkan only allows updates of <= 65536 because you really, really, really
  // shouldn't do large updates like this (as it wastes command buffer space and
  // may be slower than just using write-through mapped memory). The
  // recommendation in the spec for larger updates is to split the single update
  // into multiple updates over the entire desired range.
  const auto* source_buffer_ptr =
      static_cast<const uint8_t*>(source_buffer) + source_offset;
  target_offset += iree_hal_buffer_byte_offset(target_buffer);
  while (length > 0) {
    iree_device_size_t chunk_length =
        iree_min((iree_device_size_t)65536u, length);
    command_buffer->syms->vkCmdUpdateBuffer(command_buffer->handle,
                                            target_device_buffer, target_offset,
                                            chunk_length, source_buffer_ptr);
    source_buffer_ptr += chunk_length;
    target_offset += chunk_length;
    length -= chunk_length;
  }

  return iree_ok_status();
}

static iree_status_t iree_hal_vulkan_direct_command_buffer_copy_buffer(
    iree_hal_command_buffer_t* base_command_buffer,
    iree_hal_buffer_t* source_buffer, iree_device_size_t source_offset,
    iree_hal_buffer_t* target_buffer, iree_device_size_t target_offset,
    iree_device_size_t length) {
  iree_hal_vulkan_direct_command_buffer_t* command_buffer =
      iree_hal_vulkan_direct_command_buffer_cast(base_command_buffer);
  VkBuffer source_device_buffer = iree_hal_vulkan_vma_buffer_handle(
      iree_hal_buffer_allocated_buffer(source_buffer));
  VkBuffer target_device_buffer = iree_hal_vulkan_vma_buffer_handle(
      iree_hal_buffer_allocated_buffer(target_buffer));

  const iree_hal_buffer_t* buffers[2] = {source_buffer, target_buffer};
  IREE_RETURN_IF_ERROR(
      iree_hal_resource_set_insert(command_buffer->resource_set, 2, buffers));

  VkBufferCopy region;
  region.srcOffset = iree_hal_buffer_byte_offset(source_buffer) + source_offset;
  region.dstOffset = iree_hal_buffer_byte_offset(target_buffer) + target_offset;
  region.size = length;
  command_buffer->syms->vkCmdCopyBuffer(command_buffer->handle,
                                        source_device_buffer,
                                        target_device_buffer, 1, &region);

  return iree_ok_status();
}

static iree_status_t iree_hal_vulkan_direct_command_buffer_push_constants(
    iree_hal_command_buffer_t* base_command_buffer,
    iree_hal_pipeline_layout_t* pipeline_layout, iree_host_size_t offset,
    const void* values, iree_host_size_t values_length) {
  iree_hal_vulkan_direct_command_buffer_t* command_buffer =
      iree_hal_vulkan_direct_command_buffer_cast(base_command_buffer);

  iree_host_size_t storage_size =
      IREE_ARRAYSIZE(command_buffer->push_constants_storage);
  if (offset < storage_size) {
    memcpy(command_buffer->push_constants_storage + offset, values,
           std::min(values_length, storage_size) - offset);
  }

  command_buffer->syms->vkCmdPushConstants(
      command_buffer->handle,
      iree_hal_vulkan_native_pipeline_layout_handle(pipeline_layout),
      VK_SHADER_STAGE_COMPUTE_BIT, (uint32_t)offset, (uint32_t)values_length,
      values);

  return iree_ok_status();
}

static iree_status_t iree_hal_vulkan_direct_command_buffer_push_descriptor_set(
    iree_hal_command_buffer_t* base_command_buffer,
    iree_hal_pipeline_layout_t* pipeline_layout, uint32_t set,
    iree_host_size_t binding_count,
    const iree_hal_descriptor_set_binding_t* bindings) {
  iree_hal_vulkan_direct_command_buffer_t* command_buffer =
      iree_hal_vulkan_direct_command_buffer_cast(base_command_buffer);

  // TODO(benvanik): batch insert by getting the resources in their own list.
  for (iree_host_size_t i = 0; i < binding_count; ++i) {
    if (bindings[i].buffer) {
      IREE_RETURN_IF_ERROR(iree_hal_resource_set_insert(
          command_buffer->resource_set, 1, &bindings[i].buffer));
    }
  }

  // Either allocate, update, and bind a descriptor set or use push descriptor
  // sets to use the command buffer pool when supported.
  return command_buffer->descriptor_set_arena.BindDescriptorSet(
      command_buffer->handle, pipeline_layout, set, binding_count, bindings);
}

static iree_status_t iree_hal_vulkan_direct_command_buffer_dispatch(
    iree_hal_command_buffer_t* base_command_buffer,
    iree_hal_executable_t* executable, int32_t entry_point,
    uint32_t workgroup_x, uint32_t workgroup_y, uint32_t workgroup_z) {
  iree_hal_vulkan_direct_command_buffer_t* command_buffer =
      iree_hal_vulkan_direct_command_buffer_cast(base_command_buffer);

  IREE_TRACE({
    iree_hal_vulkan_source_location_t source_location;
    iree_hal_vulkan_native_executable_entry_point_source_location(
        executable, entry_point, &source_location);
    IREE_VULKAN_TRACE_ZONE_BEGIN_EXTERNAL(
        command_buffer->tracing_context, command_buffer->handle,
        source_location.file_name.data, source_location.file_name.size,
        source_location.line, /*func_name=*/NULL, 0,
        source_location.func_name.data, source_location.func_name.size);
  });

  IREE_RETURN_IF_ERROR(iree_hal_resource_set_insert(
      command_buffer->resource_set, 1, &executable));

  // Get the compiled and linked pipeline for the specified entry point and
  // bind it to the command buffer.
  VkPipeline pipeline_handle = VK_NULL_HANDLE;
  IREE_RETURN_IF_ERROR(
      iree_hal_vulkan_native_executable_pipeline_for_entry_point(
          executable, entry_point, &pipeline_handle));
  command_buffer->syms->vkCmdBindPipeline(
      command_buffer->handle, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline_handle);

  command_buffer->syms->vkCmdDispatch(command_buffer->handle, workgroup_x,
                                      workgroup_y, workgroup_z);

  IREE_VULKAN_TRACE_ZONE_END(command_buffer->tracing_context,
                             command_buffer->handle);

  return iree_ok_status();
}

static iree_status_t iree_hal_vulkan_direct_command_buffer_dispatch_indirect(
    iree_hal_command_buffer_t* base_command_buffer,
    iree_hal_executable_t* executable, int32_t entry_point,
    iree_hal_buffer_t* workgroups_buffer,
    iree_device_size_t workgroups_offset) {
  iree_hal_vulkan_direct_command_buffer_t* command_buffer =
      iree_hal_vulkan_direct_command_buffer_cast(base_command_buffer);

  const void* resources[2] = {executable, workgroups_buffer};
  IREE_RETURN_IF_ERROR(iree_hal_resource_set_insert(
      command_buffer->resource_set, IREE_ARRAYSIZE(resources), resources));

  iree_hal_vulkan_source_location_t source_location;
  iree_hal_vulkan_native_executable_entry_point_source_location(
      executable, entry_point, &source_location);
  IREE_VULKAN_TRACE_ZONE_BEGIN_EXTERNAL(
      command_buffer->tracing_context, command_buffer->handle,
      source_location.file_name.data, source_location.file_name.size,
      source_location.line, /*func_name=*/NULL, 0,
      source_location.func_name.data, source_location.func_name.size);

  // Get the compiled and linked pipeline for the specified entry point and
  // bind it to the command buffer.
  VkPipeline pipeline_handle = VK_NULL_HANDLE;
  IREE_RETURN_IF_ERROR(
      iree_hal_vulkan_native_executable_pipeline_for_entry_point(
          executable, entry_point, &pipeline_handle));
  command_buffer->syms->vkCmdBindPipeline(
      command_buffer->handle, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline_handle);

  VkBuffer workgroups_device_buffer = iree_hal_vulkan_vma_buffer_handle(
      iree_hal_buffer_allocated_buffer(workgroups_buffer));
  workgroups_offset += iree_hal_buffer_byte_offset(workgroups_buffer);
  command_buffer->syms->vkCmdDispatchIndirect(
      command_buffer->handle, workgroups_device_buffer, workgroups_offset);

  IREE_VULKAN_TRACE_ZONE_END(command_buffer->tracing_context,
                             command_buffer->handle);

  return iree_ok_status();
}

static iree_status_t iree_hal_vulkan_direct_command_buffer_execute_commands(
    iree_hal_command_buffer_t* base_command_buffer,
    iree_hal_command_buffer_t* base_commands,
    iree_hal_buffer_binding_table_t binding_table) {
  iree_hal_vulkan_direct_command_buffer_t* command_buffer =
      iree_hal_vulkan_direct_command_buffer_cast(base_command_buffer);

  if (binding_table.count > 0) {
    // TODO(#10144): support indirect command buffers with binding tables.
    // Since Vulkan doesn't natively support this we'd need to emulate things
    // with an iree_hal_vulkan_indirect_command_buffer_t type that captured the
    // command buffer using deferred command buffer and allowed replay with a
    // binding table. If we wanted to actually reuse the command buffers we'd
    // need to use update-after-bind (where supported), device pointers (where
    // supported), or descriptor indexing and a big ringbuffer (make a 1024
    // element descriptor array and cycle through it with each submission).
    return iree_make_status(IREE_STATUS_UNIMPLEMENTED,
                            "indirect command buffers not yet implemented");
  }

  IREE_RETURN_IF_ERROR(iree_hal_resource_set_insert(
      command_buffer->resource_set, 1, &base_commands));

  iree_hal_vulkan_direct_command_buffer_t* commands =
      iree_hal_vulkan_direct_command_buffer_cast(base_commands);

  command_buffer->syms->vkCmdExecuteCommands(command_buffer->handle, 1,
                                             &commands->handle);

  return iree_ok_status();
}

namespace {
const iree_hal_command_buffer_vtable_t
    iree_hal_vulkan_direct_command_buffer_vtable = {
        /*.destroy=*/iree_hal_vulkan_direct_command_buffer_destroy,
        /*.dyn_cast=*/iree_hal_vulkan_direct_command_buffer_dyn_cast,
        /*.begin=*/iree_hal_vulkan_direct_command_buffer_begin,
        /*.end=*/iree_hal_vulkan_direct_command_buffer_end,
        /*.begin_debug_group=*/
        iree_hal_vulkan_direct_command_buffer_begin_debug_group,
        /*.end_debug_group=*/
        iree_hal_vulkan_direct_command_buffer_end_debug_group,
        /*.execution_barrier=*/
        iree_hal_vulkan_direct_command_buffer_execution_barrier,
        /*.signal_event=*/
        iree_hal_vulkan_direct_command_buffer_signal_event,
        /*.reset_event=*/iree_hal_vulkan_direct_command_buffer_reset_event,
        /*.wait_events=*/iree_hal_vulkan_direct_command_buffer_wait_events,
        /*.discard_buffer=*/
        iree_hal_vulkan_direct_command_buffer_discard_buffer,
        /*.fill_buffer=*/iree_hal_vulkan_direct_command_buffer_fill_buffer,
        /*.update_buffer=*/
        iree_hal_vulkan_direct_command_buffer_update_buffer,
        /*.copy_buffer=*/iree_hal_vulkan_direct_command_buffer_copy_buffer,
        /*.push_constants=*/
        iree_hal_vulkan_direct_command_buffer_push_constants,
        /*.push_descriptor_set=*/
        iree_hal_vulkan_direct_command_buffer_push_descriptor_set,
        /*.dispatch=*/iree_hal_vulkan_direct_command_buffer_dispatch,
        /*.dispatch_indirect=*/
        iree_hal_vulkan_direct_command_buffer_dispatch_indirect,
        /*.execute_commands=*/
        iree_hal_vulkan_direct_command_buffer_execute_commands,
};
}  // namespace


text:
using System;
using Acr.UserDialogs.Builders;
using Android.App;
using Android.Content;
using Android.Views;

namespace Acr.UserDialogs.Fragments
{
    public class TimeAppCompatDialogFragment : AbstractAppCompatDialogFragment<TimePromptConfig>
    {
        protected override void OnKeyPress(object sender, DialogKeyEventArgs args)
        {
            base.OnKeyPress(sender, args);
            if (args.KeyCode != Keycode.Back)
                return;

            args.Handled = true;
            if (this.Config.IsCancellable)
            {
                this.Config?.OnAction?.Invoke(new TimePromptResult(false, TimeSpan.MinValue));
                this.Dismiss();
            }
        }

        protected override void SetDialogDefaults(Dialog dialog)
        {
            dialog.SetCancelable(false);
            dialog.SetCanceledOnTouchOutside(false);
            dialog.KeyPress += this.OnKeyPress;
        }

        protected override Dialog CreateDialog(TimePromptConfig config)
        {
            return TimePromptBuilder.Build(this.AppCompatActivity, config);
        }
    }
}


text:
package org.lumongo.ui.client.charting.options;

import com.google.gwt.core.client.JavaScriptObject;

public class PlotOptions extends JavaScriptObject {

	public static PlotOptions create() {
		return createObject().cast();
	}

	protected PlotOptions() {
	}

	public final native PlotOptions setArea(AreaOptions area) /*-{
        this.area = area;
        return this;
    }-*/;

	public final native PlotOptions setBar(BarOptions bar) /*-{
        this.bar = bar;
        return this;
    }-*/;

	public final native PlotOptions setPie(PieOptions pie) /*-{
        this.pie = pie;
        return this;
    }-*/;

	public final native PlotOptions setColumn(ColumnOptions column) /*-{
        this.column = column;
        return this;
    }-*/;

	public final native PlotOptions setSeries(SeriesOptions series) /*-{
        this.series = series;
        return this;
    }-*/;

}


text:
j-metadata-extractor
====================

Source of the metedata extractor from google code https://code.google.com/p/metadata-extractor/. Revision eb70b234529a .


text:
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('working_waterfronts_api', '0002_auto_20150121_2106'),
    ]

    operations = [
        migrations.AlterField(
            model_name='hazard',
            name='pointofinterests',
            field=models.ManyToManyField(
                to='working_waterfronts_api.PointOfInterest',
                null=True, blank=True),
            preserve_default=True,
        ),
    ]


text:
package androidx.camera.view.internal.compat.quirk;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.camera.core.impl.Quirk;
import androidx.camera.core.impl.Quirks;

/**
 * Provider of device specific quirks for the view module, which are used for device specific
 * workarounds.
 *

 * Device specific quirks depend on device properties, including the manufacturer
 * ({@link android.os.Build#MANUFACTURER}), model ({@link android.os.Build#MODEL}) and OS
 * level ({@link android.os.Build.VERSION#SDK_INT}).
 *

 * Device specific quirks are lazily loaded, i.e. They are loaded the first time they're needed.
 */
@RequiresApi(21) // TODO(b/200306659): Remove and replace with annotation on package-info.java
public class DeviceQuirks {

    @NonNull
    private static final Quirks QUIRKS;

    static {
        QUIRKS = new Quirks(DeviceQuirksLoader.loadQuirks());
    }

    private DeviceQuirks() {
    }

    /**
     * Retrieves a specific device {@link Quirk} instance given its type.
     *
     * @param quirkClass The type of device quirk to retrieve.
     * @return A device {@link Quirk} instance of the provided type, or {@code null} if it isn't
     * found.
     */
    @Nullable
    public static <T extends Quirk> T get(@NonNull final Class<T> quirkClass) {
        return QUIRKS.get(quirkClass);
    }
}


text:
require File.expand_path('../application', __FILE__)

# Initialize the Rails application.
Rails.application.initialize!
Rails.logger = Le.new('0f1cef8d-b05f-363c-8b75-4bb23c4a9374', :debug => true, :local => true)


text:
@interface Tests : XCTestCase

@end

@implementation Tests

- (void)setUp {
    [super setUp];
    // Put setup code here. This method is called before the invocation of each test method in the class.
}

- (void)tearDown {
    // Put teardown code here. This method is called after the invocation of each test method in the class.
    [super tearDown];
}

- (void)testAdd {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(test) name:@"test" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(test) name:@"test" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(test) name:@"test" object:nil];

    XCTAssert([[NSNotificationCenter defaultCenter] vis_mapsWithObject:self].count == 1,
              @"Repeat add observer");
}

- (void)testRemove {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(test) name:@"test" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self];

    XCTAssert([[NSNotificationCenter defaultCenter] vis_mapsWithObject:self].count == 0,
              @"The observer has not been removed");

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(test) name:@"test" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"test" object:nil];

    XCTAssert([[NSNotificationCenter defaultCenter] vis_mapsWithObject:self].count == 0,
              @"The observer has not been removed");
}

- (void)testPerformanceExample {
    // This is an example of a performance test case.
    [self measureBlock:^{
        // Put the code you want to measure the time of here.
    }];
}

@end


text:
package org.ml4j.dronez.histories;

import org.ml4j.dronez.NumericAction;
import org.ml4j.dronez.PositionDeltaWithVelocity;
import org.ml4j.dronez.PositionVelocityWithRecentActions;
import org.ml4j.dronez.VelocityAndRecentActions;
import org.ml4j.mapping.LabeledData;
import org.ml4j.mdp.StateAction;
import org.ml4j.mdp.StateActionSequenceHistory;

public class SingleDimensionPositionDeltaStateActionSequenceHistory<A extends NumericAction> extends StateActionSequenceHistory<VelocityAndRecentActions<A>, PositionDeltaWithVelocity, A> {

	/**
	 *
	 */
	private static final long serialVersionUID = 1L;

	public SingleDimensionPositionDeltaStateActionSequenceHistory(StateActionSequenceHistory<PositionVelocityWithRecentActions<A>, PositionVelocityWithRecentActions<A>, A> history)
	{
		int iteration = 0;
		for (LabeledData<StateAction<PositionVelocityWithRecentActions<A>, A>, PositionVelocityWithRecentActions<A>> data : history.getLabeledDataSet())
		{
			double positionDelta = data.getLabel().getPosition() - data.getData().getState().getPosition();
			onStateActionStateSequence(iteration++, new VelocityAndRecentActions<A>(data.getData().getState().getVelocity(),data.getData().getState().getRecentActions()), data.getData().getAction(), new PositionDeltaWithVelocity(positionDelta,data.getLabel().getVelocity()));
		}
	}

}


text:
package ec.algorithms.simulatedannealing;

import java.io.IOException;
import java.util.Properties;

import ec.main.EC;
import ec.util.Constants;

public class RunSA implements EC {

	int number_of_experiments;
	boolean isTSP = Boolean.FALSE;

	public RunSA(){}

	@Override
	public void start(Properties prop) throws IOException
	{

		 this.number_of_experiments = Integer.parseInt(prop.getProperty(Constants.NUMBER_OF_EXPERIMENTS));
		 this.isTSP                 = Boolean.parseBoolean(prop.getProperty(Constants.IF_TSP_TRUE_IF_VRP_FALSE));

		 for(int i=0;i<this.number_of_experiments;i++)
	     {
	         System.out.println("\nInitializing population for Run # "+i +"\n");

     	     long start = System.currentTimeMillis();

	         if(this.isTSP) //set a flag to determine if its VRP or TSP
	         {
	        	 new StartTSP(prop,i).start();
	         }
	         else
	         {
	        	 System.out.println("Starting Capacitated Vehicle Routing Problem...");
	        	 new StartCVRP(prop,i);
	         }

	         long end = System.nanoTime();
  	         //System.out.println("Took: " + (System.currentTimeMillis() - start) + " ms!");
  	         System.out.println("Took: " + Math.floor((end-start) * Math.pow(10, -9)) + " ms!");

	     }

	}

}


text:
package structs

// Interface for a bidirectional map
type BidiMap interface {
	Put(interface{}, interface{})
	Get(interface{}) (interface{}, bool)
	GetValue(interface{}) (interface{}, bool)
	Remove(interface{})
	RemoveValue(interface{})
	Keys() []interface{}
	Values() []interface{}
	Len() int
}

// Implementation of a bidirectional hash map
type bidiHashMap struct {
	forward  map[interface{}]interface{}
	backward map[interface{}]interface{}
}

// Create a new bidirectional hash map
func NewBidiHashMap() *bidiHashMap {
	return &bidiHashMap{make(map[interface{}]interface{}), make(map[interface{}]interface{})}
}

// Insert a new key
func (m *bidiHashMap) Put(key interface{}, value interface{}) {
	if k, ok := m.backward[value]; ok {
		delete(m.forward, k)
	}
	if v, ok := m.forward[key]; ok {
		delete(m.backward, v)
	}
	m.forward[key] = value
	m.backward[value] = key
}

// get by key
func (m *bidiHashMap) Get(key interface{}) (interface{}, bool) {
	v, ok := m.forward[key]
	return v, ok
}

// get by value
func (m *bidiHashMap) GetValue(value interface{}) (interface{}, bool) {
	k, ok := m.backward[value]
	return k, ok
}

// remove key
func (m *bidiHashMap) Remove(key interface{}) {
	v, ok := m.forward[key]
	if !ok {
		return
	}

	delete(m.forward, key)
	delete(m.backward, v)
}

// remove value
func (m *bidiHashMap) RemoveValue(value interface{}) {
	k, ok := m.backward[value]
	if !ok {
		return
	}

	delete(m.backward, value)
	delete(m.forward, k)
}

// get all the keys in the map
func (m *bidiHashMap) Keys() []interface{} {
	keys := make([]interface{}, len(m.forward))
	for k, _ := range m.forward {
		keys = append(keys, k)
	}
	return keys
}

// get all the values in the map
func (m *bidiHashMap) Values() []interface{} {
	values := make([]interface{}, len(m.backward))
	for v, _ := range m.backward {
		values = append(values, v)
	}
	return values
}

// get the number of elements in the map
func (m *bidiHashMap) Len() int {
	return len(m.forward)
}


text:
#pragma once

#include "envoy/buffer/buffer.h"

namespace Envoy {
namespace Compressor {

/**
 * Compressor state whether to flush the compressor or to finish the compression stream.
 */
enum class State { Flush, Finish };

/**
 * Allows compressing data.
 */
class Compressor {
public:
  virtual ~Compressor() {}

  /**
   * Compresses data buffer.
   * @param buffer supplies the reference to data to be compressed. The content of the buffer will
   *        be replaced inline with the compressed data.
   * @param state supplies the compressor state.
   */
  virtual void compress(Buffer::Instance& buffer, State state) PURE;
};

} // namespace Compressor
} // namespace Envoy


text:
Dispel Magic

**Source** [_dispel magic_](spells/dispelMagic#_dispel-magic)

When used as a targeted dispel, this spell can end two spells affecting the target instead of just one. If the targeted dispel successfully dispels at least one spell, you heal 1d4 points of damage for every spell level of the dispelled spell. If you dispel two spells, this healing applies only to the highest-level spell dispelled. If you use this spell to counterspell, roll your dispel check twice and take the higher result.


text:
<?php

/*
 * If the current post is protected by a password and
 * the visitor has not yet entered the password we will
 * return early without loading the comments.
 */
if ( post_password_required() )
	return;
?>

	<?php // You can start editing here -- including this comment! ?>

	<?php if ( have_comments() ) : ?>

			<?php
				printf(
					_n( 'One thought on “%2$s”', '%1$s thoughts on “%2$s”', get_comments_number(), 'starter' ),
					number_format_i18n( get_comments_number() ), '' . get_the_title() . ''
				);
			?>

			<?php wp_list_comments( array( 'callback' => 'starter_comment', 'style' => 'ol' ) ); ?>

	<?php
	if ( get_comment_pages_count() > 1 && get_option( 'page_comments' ) ):
		// are there comments to navigate through ?>

<?php _e( 'Comment navigation', 'starter' ); ?>

<?php previous_comments_link( __( '← Older Comments', 'starter' ) ); ?>

<?php next_comments_link( __( 'Newer Comments →', 'starter' ) ); ?>

		<?php endif; // check for comment navigation ?>

	<?php
	/* If there are no comments and comments are closed, let's leave a note.
	 * But we only want the note on posts and pages that had comments in the first place.
	 */
	if ( ! comments_open() && get_comments_number() ) : ?>

<?php _e( 'Comments are closed.' , 'starter' ); ?>

	<?php endif; ?>

	<?php endif; // have_comments() ?>

	<?php comment_form(); ?>


text:
package io.proleap.cobol.asg.metamodel.data.datadescription.impl;

import io.proleap.cobol.CobolParser.DataDescriptionEntryExecSqlContext;
import io.proleap.cobol.asg.metamodel.ProgramUnit;
import io.proleap.cobol.asg.metamodel.data.datadescription.DataDescriptionEntryContainer;
import io.proleap.cobol.asg.metamodel.data.datadescription.DataDescriptionEntryExecSql;

public class DataDescriptionEntryExecSqlImpl extends DataDescriptionEntryImpl implements DataDescriptionEntryExecSql {

	protected final DataDescriptionEntryExecSqlContext ctx;

	protected String execSqlText;

	public DataDescriptionEntryExecSqlImpl(final DataDescriptionEntryContainer dataDescriptionEntryContainer,
			final ProgramUnit programUnit, final DataDescriptionEntryExecSqlContext ctx) {
		super(null, dataDescriptionEntryContainer, programUnit, ctx);

		this.ctx = ctx;
	}

	@Override
	public DataDescriptionEntryType getDataDescriptionEntryType() {
		return DataDescriptionEntryType.EXEC_SQL;
	}

	@Override
	public String getExecSqlText() {
		return execSqlText;
	}

	@Override
	public void setExecSqlText(final String execSqlText) {
		this.execSqlText = execSqlText;
	}
}


text:
            ${page.navigation.title}

        <%
        page.sections.each { Map section ->
            def link = "#" + section.id
        %>

            ${section.name}

        <% } %>


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <!--android:layout_marginTop="@dimen/margin_default_medium"-->

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:gravity="center_vertical"
        android:orientation="vertical">

        <include layout="@layout/include_item_forum_thread_person_no_avatar" />

        <include layout="@layout/include_item_forum_thread_tags" />

    </RelativeLayout>
</LinearLayout>


text:
/**
 * @constructor
 */
WebInspector.AuditFormatters = function()
{
}

WebInspector.AuditFormatters.Registry = {
    text: function(text)
    {
        return document.createTextNode(text);
    },

    snippet: function(snippetText)
    {
        var div = document.createElement("div");
        div.textContent = snippetText;
        div.className = "source-code";
        return div;
    },

    concat: function()
    {
        var parent = document.createElement("span");
        for (var arg = 0; arg < arguments.length; ++arg)
            parent.appendChild(WebInspector.auditFormatters.apply(arguments[arg]));
        return parent;
    },

    url: function(url, displayText, allowExternalNavigation)
    {
        var a = document.createElement("a");
        a.href = sanitizeHref(url);
        a.title = url;
        a.textContent = displayText || url;
        if (allowExternalNavigation)
            a.target = "_blank";
        return a;
    },

    resourceLink: function(url, line)
    {
        // FIXME: use WebInspector.Linkifier
        return WebInspector.linkifyResourceAsNode(url, line, "console-message-url webkit-html-resource-link");
    }
};

WebInspector.AuditFormatters.prototype = {
    /**
     * @param {string|boolean|number|!Object} value
     */
    apply: function(value)
    {
        var formatter;
        var type = typeof value;
        var args;

        switch (type) {
        case "string":
        case "boolean":
        case "number":
            formatter = WebInspector.AuditFormatters.Registry.text;
        args = [ value.toString() ];
        break;

        case "object":
            if (value instanceof Node)
                return value;
            if (value instanceof Array) {
                formatter = WebInspector.AuditFormatters.Registry.concat;
                args = value;
            } else if (value.type && value.arguments) {
                formatter = WebInspector.AuditFormatters.Registry[value.type];
                args = value.arguments;
            }
        }
        if (!formatter)
            throw "Invalid value or formatter: " + type + JSON.stringify(value);

        return formatter.apply(null, args);
    },

    /**
     * @param {!Object} formatters
     * @param {?Object} thisArgument
     * @param {string|boolean|number|!Object} value
     */
    partiallyApply: function(formatters, thisArgument, value)
    {
        if (value instanceof Array)
            return value.map(this.partiallyApply.bind(this, formatters, thisArgument));
        if (typeof value === "object" && typeof formatters[value.type] === "function" && value.arguments)
            return formatters[value.type].apply(thisArgument, value.arguments);
        return value;
    }
}

WebInspector.auditFormatters = new WebInspector.AuditFormatters();


text:
package imgserver

import (
	"errors"
	"net/http"
	"net/url"

	"golang.org/x/net/context"
	"golang.org/x/net/context/ctxhttp"
)

type ctxValueKeyType int

//private keys
const (
	ctxURLParamKey ctxValueKeyType = iota
)

// public keys upper handler can
const (
	CtxHTTPClientKey = "httpclient"
	CtxLoggerKey     = "logger"
)

func cxtAwareGet(ctx context.Context, URL string) (*http.Response, error) {
	// request will be canceled on context cancel or timeout
	return ctxhttp.Get(ctx, getClient(ctx), URL)

	// another way to do context-aware request.
	// Way to set req.Cancel = ctx.Done seems have better performance, but return not ctx.Err() on ctx.Done
	//req, err := http.NewRequest("GET", reqUrl, nil)
	//req.Cancel = ctx.Done()
	//if err != nil {
	//	return nil, &HandlerError{500, "Can't get requested page", err}
	//}
	//return h.Client.Do(req)
}

func newImgLogicContext(ctx context.Context, client *http.Client, urlParam *url.URL) context.Context {
	//don't override passed context
	ctx = context.WithValue(ctx, CtxLoggerKey, SetEmitter(getLogger(ctx), "ImgLogicHandler"))
	if _, ok := ctx.Value(CtxHTTPClientKey).(*http.Client); !ok {
		ctx = context.WithValue(ctx, CtxHTTPClientKey, client)
	}
	ctx = context.WithValue(ctx, ctxURLParamKey, urlParam)
	return ctx
}

func getLogger(ctx context.Context) Logger {
	log, ok := ctx.Value(CtxLoggerKey).(Logger)
	if !ok {
		panic(errors.New("No logger in context"))
	}
	return log
}

func setLogger(ctx context.Context, log Logger) context.Context {
	return context.WithValue(ctx, CtxLoggerKey, log)
}

func getClient(ctx context.Context) *http.Client {
	client, ok := ctx.Value(CtxHTTPClientKey).(*http.Client)
	if !ok {
		panic(errors.New("No client in context"))
	}
	return client
}

func getURLParam(ctx context.Context) *url.URL {
	urlParam, ok := ctx.Value(ctxURLParamKey).(*url.URL)
	if !ok {
		panic(errors.New("No urlParam in context"))
	}
	return urlParam
}

func getLocalLogger(ctx context.Context, emitter string) Logger {
	return SetEmitter(getLogger(ctx), emitter)
}


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="Boundaries is the first book of the epic true-life Oblivious Trilogy, following a solo journey through Africa on a Royal Enfield. Now available in digital!">
    <title>Boundaries - Book One of the Oblivious Trilogy | A Royal Enfield in Africa</title>
    <meta property="og:locale" content="en_US" />
	<meta property="og:type" content="website" />
	<meta property="og:title" content="Boundaries - Book One of the Oblivious Trilogy" />
	<meta property="og:description" content="Now available for free in digital/kindle! Head to ObliviousTheBook.com to get your copy..." />
	<meta property="og:url" content="http://www.obliviousthebook.com/" />
	<meta property="og:site_name" content="ObliviousTheBook.com" />
	<meta property="fb:admins" content="563453705" />
	<meta property="og:image" content="http://www.obliviousthebook.com/img/portfolio/fullsize/3d-adventure-for-free.jpg" />
    <meta name="twitter:card" content="summary_large_image" />
    <meta name="twitter:description" content="Boundaries is the first book of the epic true-life Oblivious Trilogy, following a solo journey through Africa on a Royal Enfield" />
    <meta name="twitter:title" content="Boundaries - Book One of the Oblivious Trilogy" />
    <meta name="twitter:image" content="http://www.obliviousthebook.com/img/portfolio/fullsize/3D-cover-text-twitter.jpg" />
    <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <link href="vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href='https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'>
    <link href='https://fonts.googleapis.com/css?family=Merriweather:400,300,300italic,400italic,700,700italic,900,900italic' rel='stylesheet' type='text/css'>

    <link href="css/creative.min.css" rel="stylesheet">
    <link href="css/shotsfromthebar.css" rel="stylesheet">

    <link rel="icon" href="img/portfolio/fullsize/logofav.png"/>

Available for free on Digital/Kindle (Limited release!)

                Previous

                Next

AS FEATURED IN

Available for free on Digital/Kindle (Limited release!)

Having trouble? Get in touch

SHARE THE ADVENTURE!