text:
import newUuid from 'uuid';
import Transaction from './Transaction.js';

/*
 * Holds index maps to transform a table array into a colleciton of Transaction objects.
 */
class TransactionMapper {
  constructor(amountIndex, dateIndex, descriptionIndex, categoryIndex) {
    this.amountIndex = amountIndex;
    this.dateIndex = dateIndex;
    this.descriptionIndex = descriptionIndex;
    this.categoryIndex = categoryIndex;
  }

  /*
   * Build a mapper instance from a collection of headers.
   * headers: <[]> Collection of string headers
   * returns a TransactionMapper
   */
  static build(headers) {
    let lowercaseHeaders = headers.map(h => h.toLowerCase());
    let amountIndex = lowercaseHeaders.findIndex(h => h === 'debit');
    let dateIndex = lowercaseHeaders.findIndex(h => h === 'transaction date');
    let descriptionIndex = lowercaseHeaders.findIndex(h => h === 'description');
    let categoryIndex = lowercaseHeaders.findIndex(h => h === 'category');
    return new TransactionMapper(amountIndex, dateIndex, descriptionIndex, categoryIndex);
  }
}

/*
 * Builds transactions from raw data.
 */
class TransactionBuilder {
  /*
   * Using a single bank identifier and a collection representing a table of transactions, including a header,
   * return a collection of Transaction objects.
   * transactionTable: <[][]> Multi-dimensional array representing a table of transactions where the first
   *   row contains the table headers.
   */
  static build(transactionTable) {
    let mapper = TransactionMapper.build(transactionTable[0]);

    let transactions = [];
    for (let i = 1; i < transactionTable.length; i++) {
      transactions.push(
        new Transaction({
          id: newUuid(),
          date: transactionTable[i][mapper.dateIndex],
          amount: parseFloat(transactionTable[i][mapper.amountIndex]),
          description: transactionTable[i][mapper.descriptionIndex],
          category: transactionTable[i][mapper.categoryIndex]
        }));
    }

    return transactions;
  }
}

export default TransactionBuilder;

redpajama_set_name: RedPajamaGithub


text:
using System.IO;
using System.Xml;
using System.Xml.Serialization;
using System.Web.Script.Serialization; // Add reference: System.Web.Extensions

namespace SplitXmlFile
{
  public static class ParseHelpers
  {
    private static JavaScriptSerializer _json;
    private static JavaScriptSerializer Json => _json ?? (_json = new JavaScriptSerializer());

    public static Stream ToStream(this string @this)
    {
      var stream = new MemoryStream();
      var writer = new StreamWriter(stream);
      writer.Write(@this);
      writer.Flush();
      stream.Position = 0;
      return stream;
    }

    public static T ParseXml<T>(this string @this) where T : class
    {
      var reader = XmlReader.Create(@this.Trim().ToStream(), new XmlReaderSettings { ConformanceLevel = ConformanceLevel.Document });
      return new XmlSerializer(typeof(T)).Deserialize(reader) as T;
    }

    public static T ParseJson<T>(this string @this) where T : class
    {
      return Json.Deserialize<T>(@this.Trim());
    }
  }
}


text:
#ifndef LULLABY_MODULES_LULLSCRIPT_SCRIPT_AST_BUILDER_H_
#define LULLABY_MODULES_LULLSCRIPT_SCRIPT_AST_BUILDER_H_

#include "lullaby/modules/lullscript/script_parser.h"
#include "lullaby/modules/lullscript/script_types.h"

namespace lull {

class ScriptEnv;

// ParserCallback that generates the abstract syntax tree (AST) representation.
class ScriptAstBuilder : public ParserCallbacks {
 public:
  explicit ScriptAstBuilder(ScriptEnv* env);

  // Creates an AstNode from the given |type| and associated data.
  void Process(TokenType type, const void* ptr, string_view token) override;

  // Returns the root of the AST from the processed data.
  AstNode GetRoot() const;

  // Sets the internal state to an error state.
  void Error(string_view token, string_view message) override;

 private:
  struct ScriptValueList {
    ScriptValue head;
    ScriptValue tail;
  };

  void Append(const ScriptValue& value, string_view token);
  void Push();
  void Pop();

  ScriptEnv* env_;
  std::vector<ScriptValueList> stack_;
  bool error_ = false;
};

}  // namespace lull

#endif  // LULLABY_MODULES_LULLSCRIPT_SCRIPT_AST_BUILDER_H_


text:
__version__ = (0, 0, 'pre-alpha')
__authors__ = ['Markus Döllinger']

def get_version():
    """
    :return: Returns the version as a nicely formatted string
    """
    return "%d.%d%s" % (__version__[0], __version__[1],
            (" %s" % __version__[2]) if len(__version__) > 1 else "")

def get_authors():
    """
    :return: Returns the list of authors
    """
    return ", ".join(__authors__)


text:
package com.device42.client.services.parameters;

import java.util.Map;

/**
 * Indicates that implementation will provide the key-value parameters map for
 * the REST API request
 */
public interface InputParameters {
	/**
	 * Get the key-value parameters map for the REST API request
	 *
	 * @return key-value parameter map
	 */
	Map<String, String> parametersMap();
}


text:
package com.csvsim.wrapper;

import org.apache.commons.math3.distribution.ExponentialDistribution;
import org.apache.commons.math3.random.RandomGenerator;

import com.csvsim.generator.GeneratorWrapper;
import com.csvsim.random.AbstractRealDistributionWrapper;

public class Exponential implements Generator<com.csvsim.generator.utils.Field<java.lang.Double>>, Distribution<java.lang.Double> {

	Field field;
	java.lang.Double mean;
	java.lang.Double inverseCumAccuracy;

	public Exponential() {
	}

	public java.lang.Double getMean() {
		return this.mean;
	}

	public void setMean(java.lang.Double mean) {
		this.mean = mean;
	}

	public java.lang.Double getInverseCumAccuracy() {
		return this.inverseCumAccuracy;
	}

	public void setInverseCumAccuracy(java.lang.Double inverseCumAccuracy) {
		this.inverseCumAccuracy = inverseCumAccuracy;
	}

	public void setField(Field field) {
		this.field = field;
	}

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

	@Override
	public Field getField() {
		return this.field;
	}

	@Override
	public com.csvsim.generator.Generator getGenerator(com.csvsim.generator.utils.Field<java.lang.Double> field, RandomGenerator randomGenerator) {
		return new GeneratorWrapper<java.lang.Double>(field, this.getDistribution(randomGenerator));
	}

	@Override
	public com.csvsim.random.Distribution<java.lang.Double> getDistribution(RandomGenerator randomGenerator) {
		if (mean != null) {
			if (inverseCumAccuracy == null) {
				return new AbstractRealDistributionWrapper(new ExponentialDistribution(randomGenerator, mean));
			}
			else{
				return new AbstractRealDistributionWrapper(new ExponentialDistribution(randomGenerator, mean, inverseCumAccuracy));
			}
		}
		return null;
	}

}


text:
<?php
/**
 * User: louis
 * Time: 18-5-11 上午10:34
 */

namespace ArrowWorker;

/**
 * Class Upload
 * @package ArrowWorker
 */
/**
 * Class Upload
 * @package ArrowWorker
 */
class Upload
{
    /**
     * default configuraion
     */
    private $config =[
        'savePath'  => APP_PATH.'/Runtime/Upload/',
        'extension' => [
            'jpg',
            'png',
            'jpeg',
            'rar',
            'zip'
        ]
    ];

    /**
     * file : file information
     * @var
     */
    private $file;

    /**
     * newFileName : file name for saving
     * @var null
     */
    private $newFileName = null;

    /**
     * extension : upload file extension
     * @var null
     */
    private $extension = null;

    /**
     * Upload constructor.
     * @param string $name
     */
    public function __construct(string $name)
    {
        $this->file= $_FILES[$name];
        $this->checkConfig();
        $this->getFileExt();
    }

    /**
     * checkConfig
     * @throws \Exception
     */
    private function checkConfig()
    {
        $config = Config::App('Upload');
        if( false===$config )
        {
            throw new \Exception('upload config is not found');
        }
        $this->config = array_merge($this->config, $config);
    }

    /**
     * IsExtAllowed : check if the upload file extension is allowed
     * @return bool
     * @throws \Exception
     */
    private function IsExtAllowed() :bool
    {
        $ext = $this->GetFileExt();
        if( false===$ext )
        {
            return false;
        }

        return in_array( $ext, $this->config['extension'] );
    }

    /**
     * GetFileExt : get file extension
     */
    private function getFileExt()
    {
        $dotPos = strrpos($this->file['name'],'.');
        if( false===$dotPos )
        {
            throw new \Exception('file extension does not exits');
        }
        $this->extension = strtolower( substr($this->file['name'],$dotPos+1) );
    }

    /**
     * FileExt : return file extension
     * @return null
     */
    public function FileExt()
    {
        return $this->extension;
    }

    /**
     * Attr
     * @return array
     */
    public function Attr() : array
    {
        return $this->file;
    }

    /**
     * SetNewName
     * @param string|null $name
     * @return $this
     */
    public function SetNewName(string $name=null)
    {
        if( !is_null($name) )
        {
            $this->newFileName = $name;
        }
        return $this;
    }

    /**
     * Save :save upload file
     * @param string|null $savePath
     * @return bool
     */
    public function Save(string $savePath = null )
    {
        if( is_null( $this->newFileName) )
        {
            $this->newFileName = microtime(true).mt_rand(1000,1000000);
        }

        var_dump($this->config['savePath'].$this->newFileName.'.'.$this->extension);
        var_dump( file_exists($this->file['tmp_name']) );
        return move_uploaded_file( $this->file['tmp_name'], $this->config['savePath'].$this->newFileName.'.'.$this->extension);
    }

}


text:
package com.gentics.mesh.core.search.index.node;

import com.gentics.mesh.core.data.branch.HibBranch;
import com.gentics.mesh.core.rest.schema.SchemaModel;
import com.gentics.mesh.search.index.MappingProvider;

import io.vertx.core.json.JsonObject;

/**
 * Elasticsearch index mapping provider for the node indices which store node contents.
 */
public interface NodeContainerMappingProvider extends MappingProvider {

	/**
	 * Return the type specific mapping which is constructed using the provided schema.
	 *
	 * @param schema
	 *            Schema from which the mapping should be constructed
	 * @param branch
	 *            The branch-version which should be used for the construction
	 * @param language
	 *            The language override to use
	 * @return An ES-Mapping for the given Schema in the branch
	 */
	JsonObject getMapping(SchemaModel schema, HibBranch branch, String language);

	/**
	 * Return the type specific mapping which is constructed using the provided schema.
	 *
	 * @param schema
	 *            Schema from which the mapping should be constructed
	 * @return An ES-Mapping for the given Schema
	 */
	JsonObject getMapping(SchemaModel schema);

}


text:
<?php

namespace PHPExiftool\Driver\Tag\XMPDwc;

use JMS\Serializer\Annotation\ExclusionPolicy;
use PHPExiftool\Driver\AbstractTag;

/**
 * @ExclusionPolicy("all")
 */
class LithostratigraphicTerms extends AbstractTag
{

    protected $Id = 'GeologicalContextLithostratigraphicTerms';

    protected $Name = 'LithostratigraphicTerms';

    protected $FullName = 'DarwinCore::Main';

    protected $GroupName = 'XMP-dwc';

    protected $g0 = 'XMP';

    protected $g1 = 'XMP-dwc';

    protected $g2 = 'Other';

    protected $Type = 'string';

    protected $Writable = true;

    protected $Description = 'Lithostratigraphic Terms';
}


text:
package com.leavessilent.mylibrary.adapters;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.test.TouchUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 自定义的一个通用RecyclerAdapter
 * Created by Leavessilent on 2016/8/29.
 */
public abstract class UniversalAdapter<T> extends RecyclerView.Adapter<UniversalAdapter.RecyclerViewHolder> implements View.OnClickListener {

    private static final String TAG = UniversalAdapter.class.getSimpleName();
    protected List<T> mData;
    private LayoutInflater mInflater;
    private RecyclerView mRecyclerView;
    private View mItemView;

    public UniversalAdapter(Context context, List<T> data) {
        if (data == null) {
            mData = new ArrayList<>();
        } else {
            mData = data;
        }
        mInflater = LayoutInflater.from(context);
    }

    public UniversalAdapter(Context context) {
        this(context, null);
    }

    public void updateRes(List<T> data) {
        if (data != null) {
            mData.clear();
            mData.addAll(data);
            notifyDataSetChanged();
        }
    }

    public void addDataList(List<T> data) {
        if (data != null) {
            mData.addAll(data);
            notifyDataSetChanged();
        }
    }

    public void clear() {
        mData.clear();
        notifyDataSetChanged();
    }

    public void add(T t, int positon) {
        if (t != null) {
            mData.add(t);
            notifyItemInserted(positon);
        }
    }

    public void remove(int positon) {
        mData.remove(positon);
        notifyItemRemoved(positon);
    }

    @Override
    public RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = mInflater.inflate(getItemLayoutID(viewType), parent, false);
        itemView.setOnClickListener(this);
        return new RecyclerViewHolder(itemView);
    }

    @Override
    public void onAttachedToRecyclerView(RecyclerView recyclerView) {
        super.onAttachedToRecyclerView(recyclerView);
        mRecyclerView = recyclerView;
    }

    @Override
    public void onBindViewHolder(RecyclerViewHolder holder, int position) {
        onBindDataToView(holder, mData.get(position), position);
    }

    public View getItemView() {
        return mItemView;
    }

    public T getItem(int position) {
        return mData.get(position);
    }

    /**
     * 通过viewType获取layoutId
     *
     * @param viewType
     * @return
     */
    public abstract int getItemLayoutID(int viewType);

    /**
     * 绑定数据到Item的空间中去
     *
     * @param holder
     * @param t
     */
    protected abstract void onBindDataToView(RecyclerViewHolder holder, T t, int position);

    @Override
    public int getItemCount() {
        return mData.size();
    }

    @Override
    public void onClick(View v) {
        mItemView = v;
        int position = mRecyclerView.getChildAdapterPosition(v);
        if (position >= 0 && position < mData.size()) {
            if (mOnItemClickListener != null) {
                mOnItemClickListener.onItemClick(v, position);
            }
        }
    }

    public static class RecyclerViewHolder extends RecyclerView.ViewHolder {

        private View mItemView;
        private Map<Integer, View> mViewsCache;

        public RecyclerViewHolder(View itemView) {
            super(itemView);
            mItemView = itemView;
            mViewsCache = new HashMap<>();
        }

        public <T extends View> T getView(int viewId) {
            View view;
            if (mViewsCache.containsKey(viewId)) {
                view = mViewsCache.get(viewId);
            } else {
                view = mItemView.findViewById(viewId);
                mViewsCache.put(viewId, view);
            }
            return (T) view;
        }

        public TextView getTextView(int viewId) {
            return getView(viewId);
        }

        public ImageView getImageView(int viewId) {
            return getView(viewId);
        }

    }

    private OnItemClickListener mOnItemClickListener;

    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        mOnItemClickListener = onItemClickListener;
    }

    public interface OnItemClickListener {
        void onItemClick(View view, int position);
    }
}


text:
import sys
import clr
import time

sys.path.append(r"C:\Program Files\MtApi5")
asm = clr.AddReference("MtApi5")
import MtApi5 as mt5

def testCopyRates():
    symbol = str('EURUSD')
    startPos = 1
    count = 100
    rates = []
    tf = mt5.ENUM_TIMEFRAMES.PERIOD_M5
    out_dummy = []
    try:
        result_count, rates_out = client.CopyRates(symbol, tf, startPos, count, out_dummy)
    except Exception as e:
        print(e)
        print('Error in CopyRates = %s\n ', e)
        exit()

    print("CopyRates: result_count = ", result_count)

if __name__ == '__main__':

    client = mt5.MtApi5Client()
    ip = str('192.168.178.15')
    port = 8300
    sleeps = 10
    try:

        while sleeps > 0:

            print("Connecting...")
            client.BeginConnect(ip, port)
            time.sleep(1)

            sleeps = sleeps - 1

            if client.ConnectionState == 1:
                print("Connected")
                testCopyRates()
                break
            if client.ConnectionState == 0:
                print("Connecting...")
                continue
            if client.ConnectionState == 4:
                print("Connection failed")
                break

    except Exception as e:
        print(e)

    client.BeginDisconnect()


text:
(function() {
"use strict";

    console.log('watch working?');

    //set to -1 to indicate the index leading up to the first slide
    //change last one back to 50 sec
    var data, currentSlideId = 8, countDownOn=false, hasStarted=false, startTime = 0,
        endTime = 0;

    var totalTimeforTest = null;

    //TODO:
    function invertColor(hexTripletColor) {
        var color = hexTripletColor;
        color = color.substring(1);           // remove #
        color = parseInt(color, 16);          // convert to integer
        color = 0xFFFFFF ^ color;             // invert three bytes
        color = color.toString(16);           // convert to hex
        color = ("000000" + color).slice(-6); // pad with leading zeros
        color = "#" + color;                  // prepend #
        return color;
    }

    var generateRandColor = function () {
        var hexDigitArray = '0123456789ABCDEF'.split('');
        var randColorHex = '#';
        for (var i = 0; i < 6; i++)
            randColorHex += hexDigitArray[Math.floor(Math.random()*16)];
        document.body.style.backgroundColor = randColorHex;
        //some saturated hues are difficult to read on their inverse
        document.body.style.color = invertColor(randColorHex);
    };

    var showElapsedTime = function() {
        var elapsedTimeDiv = document.getElementById("timeElapsed");
        //if (totalTimeforTest) {
        //    totalTimeforTest -=
        //}
        elapsedTimeDiv.textContent = "You did this many";
    };

    var showNextSlide = function() {
        if (hasStarted === false) {
            startTime = new Date().getTime();
            hasStarted = true;
        }

        generateRandColor();
        showElapsedTime();
        var slideObject = data[++currentSlideId];
        console.log(currentSlideId);

        if (!slideObject) {
            console.log("Test Done!");
            endTime = new Date().getTime();
            console.log((endTime - startTime));
            return;
        }

        var thisSlideTime =  slideObject.seconds;
        var remainingSecondsDiv = document.getElementById("remaining-seconds");
        var instructionsDiv = document.getElementById("instructions");

        remainingSecondsDiv.textContent = thisSlideTime;
        instructionsDiv.textContent = slideObject.instructions;
        setCountdown(thisSlideTime, remainingSecondsDiv);
        countDownOn = true;
    };

    function setCountdown(seconds, secondsDiv) {
            var idCountDown = setInterval(function () {
                secondsDiv.textContent = --seconds;
                if (seconds === 0) {
                    clearInterval(idCountDown);
                    showNextSlide();
                }
            }, 1000);
    }

    var request = new XMLHttpRequest();
    request.open('GET', '/data.json', true);

    request.onload = function() {
        if (request.status >= 200 && request.status < 400) {
            // Success!
            data = JSON.parse(request.responseText).slide;
            showNextSlide();
            for (var i = 0; i < data.length; i++) {
                totalTimeforTest += data[i].seconds*1000;
            }
            console.log(totalTimeforTest);
        } else {
            // We reached our target server, but it returned an error

        }
    };

    request.onerror = function() {
        // There was a connection error of some sort
    };

request.send();

    var startButton = document.getElementById("startTime");
    startButton.addEventListener("click", function () {
        showNextSlide();
    });

    var t = setTimeout(function() {console.log("I am alive"), 5000});

})();


text:
module Gistto
# Messages used in the application

# Message used when a configuration file already exists
MSG_CONFIG_EXISTS= <<-EOS
Gistto is already configured on your MAC :) !!

but

if you want to overwrite the configuration please follow the next steps:

1.- Delete the personal token access from your profile in Github associated to Gistto
2.- Run the next command : gistto config -n

enjoy Gistto!! <3
EOS

MSG_GITHUB_USER_NOT_CONFIGURED = <<-EOS
git config --global user.name is not configured, do you want to type user name instead ? (y/n)
EOS

MSG_BANNER = <<-EOS
Usage  : gistto [action] [options] [arguments] ...
* action :
* config [-n|--new]
* add    [-p|--private] file-path1 file-path2 ...  file-pathN
* get    [-o|--open] [-c|--clipboard] [-l|--local] [-s|--show] gist-ID
* delete gist-ID
* list

warn: [-l|--local] will overwrite local files without mercy :)

	-n, --new                        Makes a new user configuration
	-p, --private                    Save Gist as private
	-o, --open                       Open Gist in browser in raw format
	-c, --clipboard                  Copy Gist to clipboard
	-l, --local                      Copy Gist file(s) to gissto folder
	-s, --show                       Show Gist file(s) in the screen
	-v, --version                    Display Gistto current version
	-h, --help                       Display help screen
EOS

end


text:
package json

import (
	"testing"

	"github.com/stretchr/testify/assert"
)

const (
	validJSON              = "{\"a\": 5, \"b\": {\"c\": 6}}"
	validJSONNewline       = "\n{\"d\": 7, \"b\": {\"d\": 8}}\n"
	validJSONArray         = "[{\"a\": 5, \"b\": {\"c\": 6}}]"
	validJSONArrayMultiple = "[{\"a\": 5, \"b\": {\"c\": 6}}, {\"a\": 7, \"b\": {\"c\": 8}}]"
	invalidJSON            = "I don't think this is JSON"
	invalidJSON2           = "{\"a\": 5, \"b\": \"c\": 6}}"
)

const validJSONTags = `
{
    "a": 5,
    "b": {
        "c": 6
    },
    "mytag": "foobar",
    "othertag": "baz"
}
`

const validJSONArrayTags = `
[
{
    "a": 5,
    "b": {
        "c": 6
    },
    "mytag": "foo",
    "othertag": "baz"
},
{
    "a": 7,
    "b": {
        "c": 8
    },
    "mytag": "bar",
    "othertag": "baz"
}
]
`

func TestParseValidJSON(t *testing.T) {
	parser := JSONParser{
		MetricName: "json_test",
	}

	// Most basic vanilla test
	metrics, err := parser.Parse([]byte(validJSON))
	assert.NoError(t, err)
	assert.Len(t, metrics, 1)
	assert.Equal(t, "json_test", metrics[0].Name())
	assert.Equal(t, map[string]interface{}{
		"a":   float64(5),
		"b_c": float64(6),
	}, metrics[0].Fields())
	assert.Equal(t, map[string]string{}, metrics[0].Tags())

	// Test that newlines are fine
	metrics, err = parser.Parse([]byte(validJSONNewline))
	assert.NoError(t, err)
	assert.Len(t, metrics, 1)
	assert.Equal(t, "json_test", metrics[0].Name())
	assert.Equal(t, map[string]interface{}{
		"d":   float64(7),
		"b_d": float64(8),
	}, metrics[0].Fields())
	assert.Equal(t, map[string]string{}, metrics[0].Tags())

	// Test that strings without TagKeys defined are ignored
	metrics, err = parser.Parse([]byte(validJSONTags))
	assert.NoError(t, err)
	assert.Len(t, metrics, 1)
	assert.Equal(t, "json_test", metrics[0].Name())
	assert.Equal(t, map[string]interface{}{
		"a":   float64(5),
		"b_c": float64(6),
	}, metrics[0].Fields())
	assert.Equal(t, map[string]string{}, metrics[0].Tags())
}

func TestParseLineValidJSON(t *testing.T) {
	parser := JSONParser{
		MetricName: "json_test",
	}

	// Most basic vanilla test
	metric, err := parser.ParseLine(validJSON)
	assert.NoError(t, err)
	assert.Equal(t, "json_test", metric.Name())
	assert.Equal(t, map[string]interface{}{
		"a":   float64(5),
		"b_c": float64(6),
	}, metric.Fields())
	assert.Equal(t, map[string]string{}, metric.Tags())

	// Test that newlines are fine
	metric, err = parser.ParseLine(validJSONNewline)
	assert.NoError(t, err)
	assert.Equal(t, "json_test", metric.Name())
	assert.Equal(t, map[string]interface{}{
		"d":   float64(7),
		"b_d": float64(8),
	}, metric.Fields())
	assert.Equal(t, map[string]string{}, metric.Tags())

	// Test that strings without TagKeys defined are ignored
	metric, err = parser.ParseLine(validJSONTags)
	assert.NoError(t, err)
	assert.Equal(t, "json_test", metric.Name())
	assert.Equal(t, map[string]interface{}{
		"a":   float64(5),
		"b_c": float64(6),
	}, metric.Fields())
	assert.Equal(t, map[string]string{}, metric.Tags())
}

func TestParseInvalidJSON(t *testing.T) {
	parser := JSONParser{
		MetricName: "json_test",
	}

	_, err := parser.Parse([]byte(invalidJSON))
	assert.Error(t, err)
	_, err = parser.Parse([]byte(invalidJSON2))
	assert.Error(t, err)
	_, err = parser.ParseLine(invalidJSON)
	assert.Error(t, err)
}

func TestParseWithTagKeys(t *testing.T) {
	// Test that strings not matching tag keys are ignored
	parser := JSONParser{
		MetricName: "json_test",
		TagKeys:    []string{"wrongtagkey"},
	}
	metrics, err := parser.Parse([]byte(validJSONTags))
	assert.NoError(t, err)
	assert.Len(t, metrics, 1)
	assert.Equal(t, "json_test", metrics[0].Name())
	assert.Equal(t, map[string]interface{}{
		"a":   float64(5),
		"b_c": float64(6),
	}, metrics[0].Fields())
	assert.Equal(t, map[string]string{}, metrics[0].Tags())

	// Test that single tag key is found and applied
	parser = JSONParser{
		MetricName: "json_test",
		TagKeys:    []string{"mytag"},
	}
	metrics, err = parser.Parse([]byte(validJSONTags))
	assert.NoError(t, err)
	assert.Len(t, metrics, 1)
	assert.Equal(t, "json_test", metrics[0].Name())
	assert.Equal(t, map[string]interface{}{
		"a":   float64(5),
		"b_c": float64(6),
	}, metrics[0].Fields())
	assert.Equal(t, map[string]string{
		"mytag": "foobar",
	}, metrics[0].Tags())

	// Test that both tag keys are found and applied
	parser = JSONParser{
		MetricName: "json_test",
		TagKeys:    []string{"mytag", "othertag"},
	}
	metrics, err = parser.Parse([]byte(validJSONTags))
	assert.NoError(t, err)
	assert.Len(t, metrics, 1)
	assert.Equal(t, "json_test", metrics[0].Name())
	assert.Equal(t, map[string]interface{}{
		"a":   float64(5),
		"b_c": float64(6),
	}, metrics[0].Fields())
	assert.Equal(t, map[string]string{
		"mytag":    "foobar",
		"othertag": "baz",
	}, metrics[0].Tags())
}

func TestParseLineWithTagKeys(t *testing.T) {
	// Test that strings not matching tag keys are ignored
	parser := JSONParser{
		MetricName: "json_test",
		TagKeys:    []string{"wrongtagkey"},
	}
	metric, err := parser.ParseLine(validJSONTags)
	assert.NoError(t, err)
	assert.Equal(t, "json_test", metric.Name())
	assert.Equal(t, map[string]interface{}{
		"a":   float64(5),
		"b_c": float64(6),
	}, metric.Fields())
	assert.Equal(t, map[string]string{}, metric.Tags())

	// Test that single tag key is found and applied
	parser = JSONParser{
		MetricName: "json_test",
		TagKeys:    []string{"mytag"},
	}
	metric, err = parser.ParseLine(validJSONTags)
	assert.NoError(t, err)
	assert.Equal(t, "json_test", metric.Name())
	assert.Equal(t, map[string]interface{}{
		"a":   float64(5),
		"b_c": float64(6),
	}, metric.Fields())
	assert.Equal(t, map[string]string{
		"mytag": "foobar",
	}, metric.Tags())

	// Test that both tag keys are found and applied
	parser = JSONParser{
		MetricName: "json_test",
		TagKeys:    []string{"mytag", "othertag"},
	}
	metric, err = parser.ParseLine(validJSONTags)
	assert.NoError(t, err)
	assert.Equal(t, "json_test", metric.Name())
	assert.Equal(t, map[string]interface{}{
		"a":   float64(5),
		"b_c": float64(6),
	}, metric.Fields())
	assert.Equal(t, map[string]string{
		"mytag":    "foobar",
		"othertag": "baz",
	}, metric.Tags())
}

func TestParseValidJSONDefaultTags(t *testing.T) {
	parser := JSONParser{
		MetricName: "json_test",
		TagKeys:    []string{"mytag"},
		DefaultTags: map[string]string{
			"t4g": "default",
		},
	}

	// Most basic vanilla test
	metrics, err := parser.Parse([]byte(validJSON))
	assert.NoError(t, err)
	assert.Len(t, metrics, 1)
	assert.Equal(t, "json_test", metrics[0].Name())
	assert.Equal(t, map[string]interface{}{
		"a":   float64(5),
		"b_c": float64(6),
	}, metrics[0].Fields())
	assert.Equal(t, map[string]string{"t4g": "default"}, metrics[0].Tags())

	// Test that tagkeys and default tags are applied
	metrics, err = parser.Parse([]byte(validJSONTags))
	assert.NoError(t, err)
	assert.Len(t, metrics, 1)
	assert.Equal(t, "json_test", metrics[0].Name())
	assert.Equal(t, map[string]interface{}{
		"a":   float64(5),
		"b_c": float64(6),
	}, metrics[0].Fields())
	assert.Equal(t, map[string]string{
		"t4g":   "default",
		"mytag": "foobar",
	}, metrics[0].Tags())
}

// Test that default tags are overridden by tag keys
func TestParseValidJSONDefaultTagsOverride(t *testing.T) {
	parser := JSONParser{
		MetricName: "json_test",
		TagKeys:    []string{"mytag"},
		DefaultTags: map[string]string{
			"mytag": "default",
		},
	}

	// Most basic vanilla test
	metrics, err := parser.Parse([]byte(validJSON))
	assert.NoError(t, err)
	assert.Len(t, metrics, 1)
	assert.Equal(t, "json_test", metrics[0].Name())
	assert.Equal(t, map[string]interface{}{
		"a":   float64(5),
		"b_c": float64(6),
	}, metrics[0].Fields())
	assert.Equal(t, map[string]string{"mytag": "default"}, metrics[0].Tags())

	// Test that tagkeys override default tags
	metrics, err = parser.Parse([]byte(validJSONTags))
	assert.NoError(t, err)
	assert.Len(t, metrics, 1)
	assert.Equal(t, "json_test", metrics[0].Name())
	assert.Equal(t, map[string]interface{}{
		"a":   float64(5),
		"b_c": float64(6),
	}, metrics[0].Fields())
	assert.Equal(t, map[string]string{
		"mytag": "foobar",
	}, metrics[0].Tags())
}

// Test that json arrays can be parsed
func TestParseValidJSONArray(t *testing.T) {
	parser := JSONParser{
		MetricName: "json_array_test",
	}

	// Most basic vanilla test
	metrics, err := parser.Parse([]byte(validJSONArray))
	assert.NoError(t, err)
	assert.Len(t, metrics, 1)
	assert.Equal(t, "json_array_test", metrics[0].Name())
	assert.Equal(t, map[string]interface{}{
		"a":   float64(5),
		"b_c": float64(6),
	}, metrics[0].Fields())
	assert.Equal(t, map[string]string{}, metrics[0].Tags())

	// Basic multiple datapoints
	metrics, err = parser.Parse([]byte(validJSONArrayMultiple))
	assert.NoError(t, err)
	assert.Len(t, metrics, 2)
	assert.Equal(t, "json_array_test", metrics[0].Name())
	assert.Equal(t, map[string]interface{}{
		"a":   float64(5),
		"b_c": float64(6),
	}, metrics[0].Fields())
	assert.Equal(t, map[string]string{}, metrics[1].Tags())
	assert.Equal(t, "json_array_test", metrics[1].Name())
	assert.Equal(t, map[string]interface{}{
		"a":   float64(7),
		"b_c": float64(8),
	}, metrics[1].Fields())
	assert.Equal(t, map[string]string{}, metrics[1].Tags())
}

func TestParseArrayWithTagKeys(t *testing.T) {
	// Test that strings not matching tag keys are ignored
	parser := JSONParser{
		MetricName: "json_array_test",
		TagKeys:    []string{"wrongtagkey"},
	}
	metrics, err := parser.Parse([]byte(validJSONArrayTags))
	assert.NoError(t, err)
	assert.Len(t, metrics, 2)
	assert.Equal(t, "json_array_test", metrics[0].Name())
	assert.Equal(t, map[string]interface{}{
		"a":   float64(5),
		"b_c": float64(6),
	}, metrics[0].Fields())
	assert.Equal(t, map[string]string{}, metrics[0].Tags())

	assert.Equal(t, "json_array_test", metrics[1].Name())
	assert.Equal(t, map[string]interface{}{
		"a":   float64(7),
		"b_c": float64(8),
	}, metrics[1].Fields())
	assert.Equal(t, map[string]string{}, metrics[1].Tags())

	// Test that single tag key is found and applied
	parser = JSONParser{
		MetricName: "json_array_test",
		TagKeys:    []string{"mytag"},
	}
	metrics, err = parser.Parse([]byte(validJSONArrayTags))
	assert.NoError(t, err)
	assert.Len(t, metrics, 2)
	assert.Equal(t, "json_array_test", metrics[0].Name())
	assert.Equal(t, map[string]interface{}{
		"a":   float64(5),
		"b_c": float64(6),
	}, metrics[0].Fields())
	assert.Equal(t, map[string]string{
		"mytag": "foo",
	}, metrics[0].Tags())

	assert.Equal(t, "json_array_test", metrics[1].Name())
	assert.Equal(t, map[string]interface{}{
		"a":   float64(7),
		"b_c": float64(8),
	}, metrics[1].Fields())
	assert.Equal(t, map[string]string{
		"mytag": "bar",
	}, metrics[1].Tags())

	// Test that both tag keys are found and applied
	parser = JSONParser{
		MetricName: "json_array_test",
		TagKeys:    []string{"mytag", "othertag"},
	}
	metrics, err = parser.Parse([]byte(validJSONArrayTags))
	assert.NoError(t, err)
	assert.Len(t, metrics, 2)
	assert.Equal(t, "json_array_test", metrics[0].Name())
	assert.Equal(t, map[string]interface{}{
		"a":   float64(5),
		"b_c": float64(6),
	}, metrics[0].Fields())
	assert.Equal(t, map[string]string{
		"mytag":    "foo",
		"othertag": "baz",
	}, metrics[0].Tags())

	assert.Equal(t, "json_array_test", metrics[1].Name())
	assert.Equal(t, map[string]interface{}{
		"a":   float64(7),
		"b_c": float64(8),
	}, metrics[1].Fields())
	assert.Equal(t, map[string]string{
		"mytag":    "bar",
		"othertag": "baz",
	}, metrics[1].Tags())
}


text:
package com.suscipio_solutions.consecro_mud.Abilities.Prayers;
import java.util.Vector;

import com.suscipio_solutions.consecro_mud.Abilities.interfaces.Ability;
import com.suscipio_solutions.consecro_mud.Common.interfaces.CMMsg;
import com.suscipio_solutions.consecro_mud.Common.interfaces.CharState;
import com.suscipio_solutions.consecro_mud.MOBS.interfaces.MOB;
import com.suscipio_solutions.consecro_mud.core.CMClass;
import com.suscipio_solutions.consecro_mud.core.CMLib;
import com.suscipio_solutions.consecro_mud.core.interfaces.Physical;

@SuppressWarnings("rawtypes")
public class Prayer_CauseExhaustion extends Prayer
{
	@Override public String ID() { return "Prayer_CauseExhaustion"; }
	private final static String localizedName = CMLib.lang().L("Cause Exhaustion");
	@Override public String name() { return localizedName; }
	@Override public int abstractQuality(){ return Ability.QUALITY_MALICIOUS;}
	@Override public int classificationCode(){return Ability.ACODE_PRAYER|Ability.DOMAIN_VEXING;}
	@Override public long flags(){return Ability.FLAG_UNHOLY;}

	@Override
	public boolean invoke(MOB mob, Vector commands, Physical givenTarget, boolean auto, int asLevel)
	{
		final MOB target=this.getTarget(mob,commands,givenTarget);
		if(target==null) return false;

		if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
			return false;

		final boolean success=proficiencyCheck(mob,0,auto);

		if(success)
		{
			// it worked, so build a copy of this ability,
			// and add it to the affects list of the
			// affected MOB.  Then tell everyone else
			// what happened.
			final CMMsg msg=CMClass.getMsg(mob,target,this,CMMsg.MASK_MALICIOUS|verbalCastCode(mob,target,auto),L(auto?"A light fatigue overcomes <T-NAME>.":"^S<S-NAME> "+prayWord(mob)+" for fatigue to overcome <T-NAMESELF>!^?"));
			if(mob.location().okMessage(mob,msg))
			{
				mob.location().send(mob,msg);
				if(msg.value()<=0)
				{
					final int harming=CMLib.dice().roll(5,adjustedLevel(mob,asLevel),20);
					if((target.curState().getFatigue()<=CharState.FATIGUED_MILLIS)
					&&(target.maxState().getFatigue()>Long.MIN_VALUE/2))
						target.curState().setFatigue(CharState.FATIGUED_MILLIS+1);
					target.curState().adjMovement(-harming,target.maxState());
					target.tell(L("You feel slightly more fatigued!"));
				}
			}
		}
		else
			return maliciousFizzle(mob,target,L("<S-NAME> point(s) at <T-NAMESELF> and @x1, but nothing happens.",prayWord(mob)));

		// return whether it worked
		return success;
	}
}


text:
package rbd

import (
	"fmt"
	"os"
	"time"

	"k8s.io/api/core/v1"
	"k8s.io/apimachinery/pkg/types"
	"k8s.io/klog"
	"k8s.io/kubernetes/pkg/util/mount"
	"k8s.io/kubernetes/pkg/volume"
	volutil "k8s.io/kubernetes/pkg/volume/util"
)

// NewAttacher implements AttachableVolumePlugin.NewAttacher.
func (plugin *rbdPlugin) NewAttacher() (volume.Attacher, error) {
	return plugin.newAttacherInternal(&RBDUtil{})
}

// NewDeviceMounter implements DeviceMountableVolumePlugin.NewDeviceMounter
func (plugin *rbdPlugin) NewDeviceMounter() (volume.DeviceMounter, error) {
	return plugin.NewAttacher()
}

func (plugin *rbdPlugin) newAttacherInternal(manager diskManager) (volume.Attacher, error) {
	return &rbdAttacher{
		plugin:  plugin,
		manager: manager,
		mounter: volutil.NewSafeFormatAndMountFromHost(plugin.GetPluginName(), plugin.host),
	}, nil
}

// NewDetacher implements AttachableVolumePlugin.NewDetacher.
func (plugin *rbdPlugin) NewDetacher() (volume.Detacher, error) {
	return plugin.newDetacherInternal(&RBDUtil{})
}

// NewDeviceUnmounter implements DeviceMountableVolumePlugin.NewDeviceUnmounter
func (plugin *rbdPlugin) NewDeviceUnmounter() (volume.DeviceUnmounter, error) {
	return plugin.NewDetacher()
}

func (plugin *rbdPlugin) newDetacherInternal(manager diskManager) (volume.Detacher, error) {
	return &rbdDetacher{
		plugin:  plugin,
		manager: manager,
		mounter: volutil.NewSafeFormatAndMountFromHost(plugin.GetPluginName(), plugin.host),
	}, nil
}

// GetDeviceMountRefs implements AttachableVolumePlugin.GetDeviceMountRefs.
func (plugin *rbdPlugin) GetDeviceMountRefs(deviceMountPath string) ([]string, error) {
	mounter := plugin.host.GetMounter(plugin.GetPluginName())
	return mounter.GetMountRefs(deviceMountPath)
}

func (plugin *rbdPlugin) CanAttach(spec *volume.Spec) (bool, error) {
	return true, nil
}

func (plugin *rbdPlugin) CanDeviceMount(spec *volume.Spec) (bool, error) {
	return true, nil
}

// rbdAttacher implements volume.Attacher interface.
type rbdAttacher struct {
	plugin  *rbdPlugin
	mounter *mount.SafeFormatAndMount
	manager diskManager
}

var _ volume.Attacher = &rbdAttacher{}

var _ volume.DeviceMounter = &rbdAttacher{}

// Attach implements Attacher.Attach.
// We do not lock image here, because it requires kube-controller-manager to
// access external `rbd` utility. And there is no need since AttachDetach
// controller will not try to attach RWO volumes which are already attached to
// other nodes.
func (attacher *rbdAttacher) Attach(spec *volume.Spec, nodeName types.NodeName) (string, error) {
	return "", nil
}

// VolumesAreAttached implements Attacher.VolumesAreAttached.
// There is no way to confirm whether the volume is attached or not from
// outside of the kubelet node. This method needs to return true always, like
// iSCSI, FC plugin.
func (attacher *rbdAttacher) VolumesAreAttached(specs []*volume.Spec, nodeName types.NodeName) (map[*volume.Spec]bool, error) {
	volumesAttachedCheck := make(map[*volume.Spec]bool)
	for _, spec := range specs {
		volumesAttachedCheck[spec] = true
	}
	return volumesAttachedCheck, nil
}

// WaitForAttach implements Attacher.WaitForAttach. It's called by kubelet to
// attach volume onto the node.
// This method is idempotent, callers are responsible for retrying on failure.
func (attacher *rbdAttacher) WaitForAttach(spec *volume.Spec, devicePath string, pod *v1.Pod, timeout time.Duration) (string, error) {
	klog.V(4).Infof("rbd: waiting for attach volume (name: %s) for pod (name: %s, uid: %s)", spec.Name(), pod.Name, pod.UID)
	mounter, err := attacher.plugin.createMounterFromVolumeSpecAndPod(spec, pod)
	if err != nil {
		klog.Warningf("failed to create mounter: %v", spec)
		return "", err
	}
	realDevicePath, err := attacher.manager.AttachDisk(*mounter)
	if err != nil {
		return "", err
	}
	klog.V(3).Infof("rbd: successfully wait for attach volume (spec: %s, pool: %s, image: %s) at %s", spec.Name(), mounter.Pool, mounter.Image, realDevicePath)
	return realDevicePath, nil
}

// GetDeviceMountPath implements Attacher.GetDeviceMountPath.
func (attacher *rbdAttacher) GetDeviceMountPath(spec *volume.Spec) (string, error) {
	img, err := getVolumeSourceImage(spec)
	if err != nil {
		return "", err
	}
	pool, err := getVolumeSourcePool(spec)
	if err != nil {
		return "", err
	}
	return makePDNameInternal(attacher.plugin.host, pool, img), nil
}

// MountDevice implements Attacher.MountDevice. It is called by the kubelet to
// mount device at the given mount path.
// This method is idempotent, callers are responsible for retrying on failure.
func (attacher *rbdAttacher) MountDevice(spec *volume.Spec, devicePath string, deviceMountPath string) error {
	klog.V(4).Infof("rbd: mouting device %s to %s", devicePath, deviceMountPath)
	notMnt, err := attacher.mounter.IsLikelyNotMountPoint(deviceMountPath)
	if err != nil {
		if os.IsNotExist(err) {
			if err := os.MkdirAll(deviceMountPath, 0750); err != nil {
				return err
			}
			notMnt = true
		} else {
			return err
		}
	}
	if !notMnt {
		return nil
	}
	fstype, err := getVolumeSourceFSType(spec)
	if err != nil {
		return err
	}
	ro, err := getVolumeSourceReadOnly(spec)
	if err != nil {
		return err
	}
	options := []string{}
	if ro {
		options = append(options, "ro")
	}
	mountOptions := volutil.MountOptionFromSpec(spec, options...)
	err = attacher.mounter.FormatAndMount(devicePath, deviceMountPath, fstype, mountOptions)
	if err != nil {
		os.Remove(deviceMountPath)
		return fmt.Errorf("rbd: failed to mount device %s at %s (fstype: %s), error %v", devicePath, deviceMountPath, fstype, err)
	}
	klog.V(3).Infof("rbd: successfully mount device %s at %s (fstype: %s)", devicePath, deviceMountPath, fstype)
	return nil
}

// rbdDetacher implements volume.Detacher interface.
type rbdDetacher struct {
	plugin  *rbdPlugin
	manager diskManager
	mounter *mount.SafeFormatAndMount
}

var _ volume.Detacher = &rbdDetacher{}

var _ volume.DeviceUnmounter = &rbdDetacher{}

// UnmountDevice implements Detacher.UnmountDevice. It unmounts the global
// mount of the RBD image. This is called once all bind mounts have been
// unmounted.
// Internally, it does four things:
//  - Unmount device from deviceMountPath.
//  - Detach device from the node.
//  - Remove lock if found. (No need to check volume readonly or not, because
//  device is not on the node anymore, it's safe to remove lock.)
//  - Remove the deviceMountPath at last.
// This method is idempotent, callers are responsible for retrying on failure.
func (detacher *rbdDetacher) UnmountDevice(deviceMountPath string) error {
	if pathExists, pathErr := mount.PathExists(deviceMountPath); pathErr != nil {
		return fmt.Errorf("Error checking if path exists: %v", pathErr)
	} else if !pathExists {
		klog.Warningf("Warning: Unmount skipped because path does not exist: %v", deviceMountPath)
		return nil
	}
	devicePath, _, err := mount.GetDeviceNameFromMount(detacher.mounter, deviceMountPath)
	if err != nil {
		return err
	}
	// Unmount the device from the device mount point.
	klog.V(4).Infof("rbd: unmouting device mountpoint %s", deviceMountPath)
	if err = detacher.mounter.Unmount(deviceMountPath); err != nil {
		return err
	}
	klog.V(3).Infof("rbd: successfully umount device mountpath %s", deviceMountPath)

	klog.V(4).Infof("rbd: detaching device %s", devicePath)
	err = detacher.manager.DetachDisk(detacher.plugin, deviceMountPath, devicePath)
	if err != nil {
		return err
	}
	klog.V(3).Infof("rbd: successfully detach device %s", devicePath)
	err = os.Remove(deviceMountPath)
	if err != nil {
		return err
	}
	klog.V(3).Infof("rbd: successfully remove device mount point %s", deviceMountPath)
	return nil
}

// Detach implements Detacher.Detach.
func (detacher *rbdDetacher) Detach(volumeName string, nodeName types.NodeName) error {
	return nil
}


text:
#include "CRC_DistanceSensor.h"

CRC_DistanceSensor::CRC_DistanceSensor(int activationPin, int readingPin)
{
	_readingPin = readingPin;
	_activationPin = activationPin;
}

void CRC_DistanceSensor::activate() {
	pinMode(_activationPin, OUTPUT);
	digitalWrite(_activationPin, HIGH);
}

void CRC_DistanceSensor::deactivate() {
	pinMode(_activationPin, OUTPUT);
	digitalWrite(_activationPin, LOW);
}


text:
package org.openqa.selenium;

import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.openqa.selenium.UnexpectedAlertBehaviour.IGNORE;
import static org.openqa.selenium.WaitingConditions.elementTextToEqual;
import static org.openqa.selenium.remote.CapabilityType.UNEXPECTED_ALERT_BEHAVIOUR;
import static org.openqa.selenium.testing.drivers.Browser.CHROME;
import static org.openqa.selenium.testing.drivers.Browser.EDGE;
import static org.openqa.selenium.testing.drivers.Browser.HTMLUNIT;
import static org.openqa.selenium.testing.drivers.Browser.SAFARI;

import org.junit.jupiter.api.Test;
import org.openqa.selenium.support.ui.Wait;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.testing.Ignore;
import org.openqa.selenium.testing.JupiterTestBase;
import org.openqa.selenium.testing.NoDriverBeforeTest;

import java.time.Duration;

@Ignore(value = SAFARI, reason = "Does not support alerts yet")
public class UnexpectedAlertBehaviorTest extends JupiterTestBase {

  @Test
  @Ignore(value = CHROME, reason = "Legacy behaviour, not W3C conformant")
  @Ignore(value = EDGE, reason = "Legacy behaviour, not W3C conformant")
  @Ignore(value = HTMLUNIT, reason = "Legacy behaviour, not W3C conformant")
  @NoDriverBeforeTest
  public void canAcceptUnhandledAlert() {
    runScenarioWithUnhandledAlert(UnexpectedAlertBehaviour.ACCEPT_AND_NOTIFY, "This is a default value", false);
  }

  @Test
  @Ignore(value = CHROME, reason = "Legacy behaviour, not W3C conformant")
  @Ignore(value = EDGE, reason = "Legacy behaviour, not W3C conformant")
  @Ignore(value = HTMLUNIT, reason = "Legacy behaviour, not W3C conformant")
  @NoDriverBeforeTest
  public void canSilentlyAcceptUnhandledAlert() {
    runScenarioWithUnhandledAlert(UnexpectedAlertBehaviour.ACCEPT, "This is a default value", true);
  }

  @Test
  @Ignore(value = CHROME, reason = "Unstable Chrome behavior")
  @Ignore(value = EDGE, reason = "Unstable Chrome behavior")
  @Ignore(value = HTMLUNIT, reason = "Legacy behaviour, not W3C conformant")
  @NoDriverBeforeTest
  public void canDismissUnhandledAlert() {
    runScenarioWithUnhandledAlert(UnexpectedAlertBehaviour.DISMISS_AND_NOTIFY, "null", false);
  }

  @Test
  @Ignore(value = CHROME, reason = "Legacy behaviour, not W3C conformant")
  @Ignore(value = EDGE, reason = "Legacy behaviour, not W3C conformant")
  @Ignore(value = HTMLUNIT, reason = "Legacy behaviour, not W3C conformant")
  @NoDriverBeforeTest
  public void canSilentlyDismissUnhandledAlert() {
    runScenarioWithUnhandledAlert(UnexpectedAlertBehaviour.DISMISS, "null", true);
  }

  @Test
  @Ignore(value = CHROME, reason = "Chrome uses IGNORE mode by default")
  @Ignore(value = EDGE, reason = "Edge uses IGNORE mode by default")
  @NoDriverBeforeTest
  public void canDismissUnhandledAlertsByDefault() {
    runScenarioWithUnhandledAlert(null, "null", false);
  }

  @Test
  @Ignore(value = CHROME, reason = "Unstable Chrome behavior")
  @Ignore(value = EDGE, reason = "Unstable Chrome behavior")
  @NoDriverBeforeTest
  public void canIgnoreUnhandledAlert() {
    assertThatExceptionOfType(UnhandledAlertException.class).isThrownBy(
        () -> runScenarioWithUnhandledAlert(IGNORE, "Text ignored", true));
    driver.switchTo().alert().dismiss();
  }

  private void runScenarioWithUnhandledAlert(
      UnexpectedAlertBehaviour behaviour,
      String expectedAlertText,
      boolean silently) {
    Capabilities caps = behaviour == null
                        ? new ImmutableCapabilities()
                        : new ImmutableCapabilities(UNEXPECTED_ALERT_BEHAVIOUR, behaviour);
    createNewDriver(caps);

    driver.get(pages.alertsPage);
    driver.findElement(By.id("prompt-with-default")).click();

    Wait<WebDriver> wait1
        = silently
        ? wait
        : new WebDriverWait(driver, Duration.ofSeconds(10))
              .ignoring(UnhandledAlertException.class);
    wait1.until(elementTextToEqual(By.id("text"), expectedAlertText));
  }

}


text:
<?php

class Akt_Connection_Adapter_Ssh_Libssh2_Authentication_Hostbased
    implements Akt_Connection_Adapter_Ssh_Libssh2_Authentication_Authentication
{
    /**
     * Auth username
     * @var string
     */
    protected $_username;

    /**
     * Hostname
     * @var string
     */
    protected $_hostname;

    /**
     * Path to public key file
     * @var string
     */
    protected $_publicKeyFile;

    /**
     * Path to private key file
     * @var string
     */
    protected $_privateKeyFile;

    /**
     * User pass phrase
     * @var string
     */
    protected $_passPhrase;

    /**
     * Local username
     * @var string
     */
    protected $_localUsername;

    /**
     * Constructor.
     *
     * @param string $username
     * @param string $hostname
     * @param string $publicKeyFile
     * @param string $privateKeyFile
     * @param string|null $passPhrase
     * @param string|null $localUsername If omitted, then the value for username will be used for it.
     */
    public function __construct($username, $hostname, $publicKeyFile, $privateKeyFile,
        $passPhrase = null, $localUsername = null
    ) {
        $this->_username       = (string) $username;
        $this->_hostname       = (string) $hostname;
        $this->_publicKeyFile  = (string) $publicKeyFile;
        $this->_privateKeyFile = (string) $privateKeyFile;
        $this->_passPhrase     = $passPhrase;
        $this->_localUsername  = $localUsername;
    }

    /**
     * Authenticate session
     *
     * @param  Akt_Connection_Adapter_Ssh_Libssh2_Session|resource $session
     * @return bool
     */
    function authenticate($session)
    {
        if ($session instanceof Akt_Connection_Adapter_Ssh_Libssh2_Session) {
            $session = $session->getResource();
        }
        return ssh2_auth_hostbased_file(
            $session,
            $this->_username,
            $this->_hostname,
            $this->_publicKeyFile,
            $this->_privateKeyFile,
            $this->_passPhrase,
            $this->_localUsername
        );
    }
}


text:
<?php

declare(strict_types=1);

namespace DI\Definition\ObjectDefinition;

/**
 * Describe an injection in a class property.
 *
 * @author Matthieu Napoli <matthieu@mnapoli.fr>
 */
class PropertyInjection
{
    /**
     * Property name.
     * @var string
     */
    private $propertyName;

    /**
     * Value that should be injected in the property.
     * @var mixed
     */
    private $value;

    /**
     * Use for injecting in properties of parent classes: the class name
     * must be the name of the parent class because private properties
     * can be attached to the parent classes, not the one we are resolving.
     * @var string|null
     */
    private $className;

    /**
     * @param string $propertyName Property name
     * @param mixed $value Value that should be injected in the property
     */
    public function __construct(string $propertyName, $value, string $className = null)
    {
        $this->propertyName = $propertyName;
        $this->value = $value;
        $this->className = $className;
    }

    public function getPropertyName() : string
    {
        return $this->propertyName;
    }

    /**
     * @return mixed Value that should be injected in the property
     */
    public function getValue()
    {
        return $this->value;
    }

    /**
     * @return string|null
     */
    public function getClassName()
    {
        return $this->className;
    }

    public function replaceNestedDefinition(callable $replacer)
    {
        $this->value = $replacer($this->value);
    }
}


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package gov.hhs.fha.nhinc.presentationservices;

import com.gargoylesoftware.htmlunit.HttpMethod;
import com.gargoylesoftware.htmlunit.WebRequest;
import com.gargoylesoftware.htmlunit.util.NameValuePair;
import java.net.URL;
import java.util.ArrayList;
import com.gargoylesoftware.htmlunit.Page;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.WebResponse;
import org.apache.commons.logging.LogFactory;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;

/**
 *
 * @author nhin
 */
public class DiagnosticsTests {

    private String server = PresentationServicesSuite.defaultServer;
    private String dxProcId = "b7ed7564-f832-4cb3-b120-98a1f8343ad2";
    private String actId = "f3889adf-31c0-40b0-bf46-fa18fd9e2229";

    public DiagnosticsTests() {
    }

    @BeforeClass
    public static void setUpClass() throws Exception {
    }

    @AfterClass
    public static void tearDownClass() throws Exception {
    }

    @Before
    public void setUp() {
        LogFactory.getFactory().setAttribute("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.NoOpLog");
        System.out.println("DIAGNOSTICS TESTS - HOST IS: " + server);
    }

    @After
    public void tearDown() {
    }
    // TODO add test methods here.
    // The methods must be annotated with annotation @Test. For example:
    //

    @Test
    public void testStartDGProcess() throws Exception {
        System.out.println("TEST CASE: testStartDGProcess");
        System.out.println("Request URL is " + startDGProcessURL());
        final WebClient webClient = new WebClient();
        final Page page = webClient.getPage(startDGProcessURL());
        WebResponse response = page.getWebResponse();
        System.out.println("\n" + response.getContentAsString() + "\n");
        assertTrue(response.getContentAsString().contains(startDGProcessResponse()));
        webClient.closeAllWindows();
    }

    @Test
    public void testGetDGProcessStatus() throws Exception {
        System.out.println("TEST CASE: testGetDGProcessStatus");
        System.out.println("Request URL is " + getDGProcessStatusUrl());
        final WebClient webClient = new WebClient();
        final Page page = webClient.getPage(getDGProcessStatusUrl());
        System.out.println("Request URL is " + getDGProcessStatusUrl());
        WebResponse response = page.getWebResponse();
        System.out.println("\n" + response.getContentAsString() + "\n");
        assertTrue(response.getContentAsString().contains(getDGProcessStatusResponse()));
        webClient.closeAllWindows();
    }

    @Test
    public void testSetDiagActionStatus() throws Exception {
        System.out.println("TEST CASE: testSetDiagActionStatus");
        final WebClient client = new WebClient();
        WebRequest request = new WebRequest(
                new URL("http://" + server
                + ":8080/PresentationServices/setDiagnosticActionStatus"),
                HttpMethod.POST);

        request.setRequestParameters(new ArrayList());
        request.getRequestParameters().add(new NameValuePair("token", "6C"));
        request.getRequestParameters().add(new NameValuePair("userId", "1"));
        request.getRequestParameters().add(new NameValuePair("patientId", "99990070"));
        request.getRequestParameters().add(new NameValuePair("dxProcessId", dxProcId));
        request.getRequestParameters().add(new NameValuePair("actionId", actId));
        request.getRequestParameters().add(new NameValuePair("status", "Started"));

        System.out.println("\nREQUEST URL IS: " + request.toString());

        Page page = client.getPage(request);
        String stringResponse = page.getWebResponse().getContentAsString();
        System.out.println("\nSETDIAG RESPONSE IS: \n" + stringResponse + "\n");
        assertTrue(stringResponse.contains(setDiagActionStatusResponse()));

        client.closeAllWindows();
    }

    @Test
    public void testCompleteDGProcess() throws Exception {
        System.out.println("TEST CASE: testCompleteDGProcess");
        final WebClient webClient = new WebClient();
        final Page page = webClient.getPage(completeDGProcessURL());
        System.out.println("Request URL is " + completeDGProcessURL());
        WebResponse response = page.getWebResponse();
        System.out.println("\n" + response.getContentAsString() + "\n");
        assertTrue(response.getContentAsString().contains(completeDGProcessResponse()));
        webClient.closeAllWindows();
    }

    @Test
    public void testAdvanceDGProcess() throws Exception {
        System.out.println("TEST CASE: testAdvanceDGProcess");
        final WebClient webClient = new WebClient();
        final Page page = webClient.getPage(advanceDGProcessURL());
        System.out.println("Request URL is " + advanceDGProcessURL());
        WebResponse response = page.getWebResponse();
        System.out.println("\n" + response.getContentAsString() + "\n");
        assertTrue(response.getContentAsString().contains(advanceDGProcessResponse()));
        webClient.closeAllWindows();
    }

    private String getDGProcessStatusUrl() {

        String url = "http://" + server + ":8080/PresentationServices"
                + "/getDiagnosticGuideProcessStatus?dxProcessId=" + dxProcId
                + "&userId=1&patientId=99990070&token=6C";
        return url;
    }

    private String startDGProcessURL() {
        String url = "http://" + server + ":8080/PresentationServices"
                + "/startDiagnosticGuideProcess?userId=1&token=6C&"
                + "disease=Post Traumatic Stress Disorder&patientId=99990070";
        return url;
    }

    private String completeDGProcessURL() {
        String url = "http://" + server + ":8080/PresentationServices"
                + "/completeDiagnosticGuideProcess?"
                + "dxProcessId=" + dxProcId + "&token=6C&"
                + "status=Complete&userId=1&patientId=99990070";
        return url;
    }

    private String advanceDGProcessURL() {
        String url = "http://" + server + ":8080/PresentationServices"
                + "/advanceDiagnosticGuideProcess?"
                + "dxProcessId=" + dxProcId + "&token=6C&"
                + "userId=1&patientId=99990070";
        return url;
    }

    // Just make sure some respnose came back. Can't completely check as
    // responses are dynamic

    private String getDGProcessStatusResponse() {
        String response = "diagModel";
        return response;
    }

    private String setDiagActionStatusResponse() {
        String response = "[";
        return response;
    }

    private String startDGProcessResponse() {
        String response = "[";
        return response;
    }

    private String completeDGProcessResponse() {
        String response = "";
        return response;
    }

    private String advanceDGProcessResponse() {
        String response = "diagModel";
        return response;
    }
}


text:
from setuptools import setup, find_packages

setup(name='nlptoolkit',
      version='0.1',
      description='My minimal NLP tools for Biocreative IV contest',
      author='Chia-Jung, Yang',
      author_email='jeroyang@gmail.com',
      packages=find_packages(),
      url = "https://github.com/jeroyang/nlptoolkit",
)


text:
<?php

namespace common\models\base;

use Yii;
use yii\behaviors\BlameableBehavior;
use yii\behaviors\TimestampBehavior;

/**
 * This is the base model class for table "trans_seats_type".
 *
 * @property integer $id
 * @property string $name
 * @property string $description
 * @property string $date_add
 * @property string $date_edit
 * @property integer $created_by
 * @property integer $updated_by
 * @property integer $lock
 *
 * @property \common\models\TransSeats[] $transSeats
 */
class TransSeatsType extends \yii\db\ActiveRecord
{
    use \mootensai\relation\RelationTrait;

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['name'], 'required'],
            [['date_add', 'date_edit'], 'safe'],
            [['created_by', 'updated_by', 'lock'], 'integer'],
            [['name'], 'string', 'max' => 100],
            [['description'], 'string', 'max' => 255],
            [['lock'], 'default', 'value' => '0'],
            [['lock'], 'mootensai\components\OptimisticLockValidator']
        ];
    }

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'trans_seats_type';
    }

    /**
     *
     * @return string
     * overwrite function optimisticLock
     * return string name of field are used to stored optimistic lock
     *
     */
    public function optimisticLock()
    {
        return 'lock';
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('app', 'Идентификатор'),
            'name' => Yii::t('app', 'Наименование типа'),
            'description' => Yii::t('app', 'Краткое описание типа места в транспорте'),
            'date_add' => Yii::t('app', 'Date Add'),
            'date_edit' => Yii::t('app', 'Date Edit'),
            'lock' => Yii::t('app', 'Lock'),
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getTransSeats()
    {
        return $this->hasMany(\common\models\TransSeats::className(), ['trans_seats_type_id' => 'id']);
    }

    /**
     * @inheritdoc
     * @return array mixed
     */
    public function behaviors()
    {
        return [
            'timestamp' => [
                'class' => TimestampBehavior::className(),
                'createdAtAttribute' => 'date_add',
                'updatedAtAttribute' => 'date_edit',
                'value' => new \yii\db\Expression('NOW()'),
            ],
            'blameable' => [
                'class' => BlameableBehavior::className(),
                'createdByAttribute' => 'created_by',
                'updatedByAttribute' => 'updated_by',
            ],
        ];
    }

    /**
     * @inheritdoc
     * @return \common\models\TransSeatsTypeQuery the active query used by this AR class.
     */
    public static function find()
    {
        return new \common\models\TransSeatsTypeQuery(get_called_class());
    }
}


text:
#ifndef _RWSTD_LOC_MESSAGES_H_INCLUDED
#define _RWSTD_LOC_MESSAGES_H_INCLUDED

#if __GNUG__ >= 3
#  pragma GCC system_header
#endif   // gcc >= 3

#include <string>

#include <loc/_facet.h>
#include <loc/_codecvt.h>
#include <loc/_locale.h>

#include <rw/_defs.h>

_RWSTD_NAMESPACE (__rw) {

int __rw_cat_open (const _STD::string&, const _V3_LOCALE::locale&);

const char* __rw_get_message (int, int, int);

const _V3_LOCALE::locale& __rw_get_locale (int);

void __rw_cat_close (int);

}   // namespace __rw

_RWSTD_NAMESPACE (_V3_LOCALE) {

struct _RWSTD_EXPORT messages_base
{
    typedef int catalog;
};

// 22.2.7.1
_EXPORT
template <class _CharT>
class messages: public _RW::__rw_facet,
                public messages_base
{
public:
    typedef _CharT char_type;

    typedef basic_string<char_type, char_traits<char_type>,
                         allocator<char_type> > string_type;

    _EXPLICIT messages (_RWSTD_SIZE_T __refs = 0)
        : _RW::__rw_facet (__refs), messages_base () { }

    catalog open (const string& __fun, const locale& __loc) const {
        return do_open (__fun, __loc);
    }

    string_type get (catalog __c, int __set, int __msgid,
                     const string_type& __df) const {
        return do_get (__c, __set, __msgid, __df);
    }

    void close (catalog __c) const {
        do_close (__c);
    }

    static _RW::__rw_facet_id id;

protected:

    virtual catalog do_open (const string& __fun, const locale&__loc) const {
        return _RW::__rw_cat_open (__fun, __loc);
    }

    virtual string_type do_get (catalog, int, int, const string_type&) const;

    virtual void do_close (catalog __cat) const {
	_RW::__rw_cat_close (__cat);
    }
};

#ifndef _RWSTD_NO_SPECIALIZED_FACET_ID

_RWSTD_SPECIALIZED_CLASS
_RW::__rw_facet_id messages<char>::id;

#  ifndef _RWSTD_NO_WCHAR_T

_RWSTD_SPECIALIZED_CLASS
_RW::__rw_facet_id messages<wchar_t>::id;

#  endif   // _RWSTD_NO_WCHAR_T
#endif   // _RWSTD_NO_SPECIALIZED_FACET_ID

// 22.2.7.2
template <class _CharT>
class messages_byname: public messages<_CharT>
{
    char _C_namebuf [32];

public:

    _EXPLICIT messages_byname (const char *__name, _RWSTD_SIZE_T __refs = 0)
        : messages<_CharT>(__refs) {
        this->_C_set_name (__name, _C_namebuf, sizeof _C_namebuf);
    }
};

}   // namespace _V3_LOCALE

#if _RWSTD_DEFINE_TEMPLATE_FIRST (_MESSAGES)
#  include <loc/_messages.cc>
#endif   // _RWSTD_DEFINE_TEMPLATE_FIRST (MESSAGES)

_RWSTD_NAMESPACE (_V3_LOCALE) {

#if _RWSTD_INSTANTIATE (_MESSAGES, _CHAR)

_RWSTD_INSTANTIATE_1 (class _RWSTD_EXPORT messages<char>);

#endif   // _RWSTD_INSTANTIATE (_MESSAGES, _CHAR)

#if _RWSTD_INSTANTIATE (_MESSAGES, _WCHAR_T)

_RWSTD_INSTANTIATE_1 (class _RWSTD_EXPORT messages<wchar_t>);

#endif   // _RWSTD_INSTANTIATE (_MESSAGES, _WCHAR_T)

}   // namespace _V3_LOCALE

#if _RWSTD_DEFINE_TEMPLATE_LAST (_MESSAGES)
#  include <loc/_messages.cc>
#endif   // _RWSTD_DEFINE_TEMPLATE_LAST (MESSAGES)

#endif   // _RWSTD_LOC_MESSAGES_H_INCLUDED


text:
CoutlookAddinModule _AtlModule;
HINSTANCE g_inst;
// DLL Èë¿Úµã
extern "C" BOOL WINAPI DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID lpReserved)
{
	g_inst = hInstance;
	return _AtlModule.DllMain(dwReason, lpReserved);
}


text:
play-alias-only

The following example assumes that the ``play`` alias exists in the
:mc-cmd:`mc` :ref:`configuration file <mc-configuration>`. You can
replace ``play`` with the alias for your preferred S3-compatible deployment.

See :mc-cmd:`mc alias` for more information on aliases.

end-play-alias-only

play-s3-alias

The following example assumes that the ``play`` and ``s3`` aliases exist in the
:mc-cmd:`mc` :ref:`configuration file <mc-configuration>`. You can replace
``play`` and ``s3`` with the aliases for your preferred S3-compatible
deployments.

See :mc-cmd:`mc alias` for more information on aliases.

end-play-s3-alias

myminio-alias

The following example uses the default ``myminio`` alias. The ``myminio``
alias points to a local ``minio`` server running on port ``9000``. See
<installation instructions> for more information on installing and running
a local ``minio`` server instance.

See :mc-cmd:`mc alias` for more information on aliases.

end-myminio-alias


text:
<!DOCTYPE html>

{{text}}


text:
## Introduction

### cheap.set64Bit(is64Bit)

Make `is64Bit` true to make pointers 8 bytes, false to make pointers 4 bytes.

This does not apply retroactively to previously defined structs; it is therefore
possible to mix 64-bit and 32-bit pointers in the same heap.

*"Pointer? Heap? Wtf?"*  The `cheap` object has a single, virtual heap
implemented as a doubly linked list of `block` objects.  These blocks have a
virtual start and end address (between [2^16, 2^31 - 2^16]) and contain an
ArrayBuffer representing allocated memory.  Even though any pointer into this
virtual heap can occupy at most 31 bits, it can be helpful to have 8-byte
pointers for mocking 64-bit C structures.  This library does not currently
support 64-bit integers because it's an unperformant pain in the ass, so all
pointers are read as 32-bit uints regardless of size.

Moving on, here's how to define a struct:

### cheap.struct(definition)

`definition` should be an array of member definitions.  Member definitions are
described in detail later, but as an example:

```js
var simple = cheap.struct([
  cheap.int('someInt'),
  cheap.float('someVec', 4),
  cheap.double('someNumbers')
]);
```

This is similar to, in C:

```c
struct simple {
  int someInt;
  float someVec[4];
  double *someNumbers;
};
```

To refer to the same memory with more than one type, aka union, definition
should be an object:

```js
var medium = cheap.struct({
  theInt: cheap.int(0),
  theFloat: cheap.float(0),
  theLow: cheap.int(8),
  theHigh: cheap.int(12),
  theDouble: cheap.double(8)
});
```

This is similar to, in C11:

```c
struct medium {
  union {
    int theInt;
    float theFloat;
  };
  union {
    struct {
      int theLow;
      int theHigh;
    };
    double theDouble;
  }
};
```

The object definition syntax **requires** an explicit offset for each member.
Since an object is not guaranteed to preserve the order of its members, the
array syntax is required to implicitly define member offsets.  To use the object
definition syntax, simply place the desired offset where the `memberName`
argument should be, and make the `memberName` the key to the appropriate member
definition.

## Struct member definitions

### cheap.{type}(memberName, [arrayLength])

Creates a struct member of type `{type}` with name `memberName`.  Optionally
specify arrayLength to make this an array member.

{type} may be any user-defined type (see below), or any of the default types:

- `uint`: 32-bit unsigned integer
- `int`: 32-bit signed integer
- `ushort`: 16-bit unsigned integer
- `short`: 16-bit signed integer
- `uchar`: 8-bit unsigned integer
- `char`: 8-bit signed integer
- `float`: 32-bit float
- `double`: 64-bit float
- `void`: undefined, cannot be dereferenced

### cheap.typedef(typeName, structDef)

Assigns the name `typeName` to `structDef`.  This defines the property with name
`typeName` on the `cheap` object.  To prevent name collisions, the cheap library
will never define a default property that starts with an uppercase letter on the
cheap object.  As a guideline, user-defined types should have an UpperCamelCase
name.  Once `typedef` is called, the defined type can be used in `cheap.{type}`
and `cheap.ptr` like any other type.

### cheap.ptr(typeName, memberName, [depth = 1])

Creates a struct member of a pointer to type `{typeName}` with name `memberName`
and depth (number of `*`s) `depth`.  Depth < 1 is currently Fundefined behavior.

## Struct objects

A struct object is created by `new`ing the function returned by `cheap.struct`
with a `block` (see Heap functions below) and a relative address into the block
as arguments:

```js
var block = cheap.malloc(0x1000);
var myObj = new simple(block, 0);
```

Once created, all the fields on the object can be read from and written to:

```js
myObj.someInt; // 0
myObj.someInt = 123;
myObj.someInt; // 123
// Let's overflow int32:
myObj.someInt = 1e10;
myObj.someInt; // 1410065408
// Array example:
myObj.someVec(2); // 0
myObj.someVec(2, 2.3);
myObj.someVec(2); // 2.29999...
// And we can escape the bounds of the array easily:
myObj.someVec(200, 1);
myObj.someVec(200); // 1
// But Fundefined behavior may occur:
myObj.someVec(1000, 1);
myObj.someVec(1000); // undefined
// Make someNumbers point to after the array (plus a few bytes for alignment)
myObj.someNumbers = cheap.ptr(block).add((cheap.sizeof(simple)+7)&-8);
myObj.someNumbers.set(23, 45);
myObj.someNumbers.deref(23); // 45
```

There is no type checking on value assignments.  Numeric types are implicitly
converted between one another by virtue of everything in javascript being a
double; assignments simply overflow when writing to words of too-short width.

### obj.{simple member}

Both basic and complex types can be read from and assigned to simple members of
struct objects.  Complex types are assigned using `cheap.memcpy`, so the
assigning member should be relocatable.

### obj.{array member}

Basic and complex array types are read and written using the member as a
`function(idx, [val])`:  `idx` is the array index, and, if writing to the array,
`val` is the desired value.

### obj.{pointer member}

The member is a `ptr` object.

### obj.__a

The relative heap address of the object within its block.

### obj.__b

The block the object exists in.

### ptr.deref(idx, *)

Dereferences the ptr, subtracting 1 from its depth (i.e. the number of '*'s) and
returning the typed value if depth reaches 0.  `idx` acts the same as in an
array member.  If multiple arguments are supplied, each is treated as an `idx`
to dereference a the corresponding ptr.

### ptr.set(idx, val)

Sets the value at ptr[idx] to val.

### ptr.cast(type)

Casts the ptr to `type`.  If `type` is a string, it is interpreted as a defined
type and a series of '*'s afterwards will translate to pointer depth.  If no
'*'s are present in `type`, the depth will remain the same.  `type` may also be
a struct definition, in which case only the type may be changed.

## Struct helpers

### cheap.sizeof(type)

Gets the size of a type.  `type` may be a string representing one of the above
default types or a struct definition as returned by `cheap.struct`.

### cheap.alignof(type)

Gets the required alignment of a type.  `type` has the same requirements as
`cheap.sizeof`.

### cheap.strideof(type)

Gets the array stride of a type, according to its size and alignment
requirements.  Rounds up `sizeof(type)` to the nearest multiple of
`alignof(type)`.

### cheap.offsetof(structDef, member)

Gets the offset of `member` in `structDef`.

### cheap.ref(locatable, [memberName])

Gets a `ptr` object representing the address of the arguments.  `locatable` may
be a `block` returned by `cheap.malloc` or a struct object.  If `memberName` is
specified, the returned `ptr` will point to the corresponding member on
`locatable`.

## Heap functions

### cheap.malloc(size)

Allocates a heap `block` of `size` bytes.  Even if the return value isn't saved,
the heap block will remain on the virtual heap until it is freed.  This makes
leaking memory quite simple.  Always free blocks once they're no longer in use.
The `a` field on blocks is part of the public interface and will not change.

### block.free()

Frees the block, removing it from the heap.

### block.a

The virtual heap address (absolute) of the block.

### block.{typedView}

Allows direct access to the block's Typed Array views of its buffer, where
`typedView` is one of:  ui32, i32, ui16, i16, ui8, i8, f32, f64.

### cheap.free(address)

Searches for a block in the heap starting at `address` and frees it.  If the
address is not the start of any block, no change will occur.

### cheap.memcpy(dst, src, size)

Copies heap memory of length `size` bytes from `dst` to `src`.

### cheap.getBufferAddress(address)

Returns [heap block, relative address] for absolute address `address`.
`address` may also be a `ptr` object.

### cheap.copyBuffer(buf)

Copies an ArrayBuffer `buf` onto the heap and returns the newly allocated block.
Useful for interacting with binary files, in particular.


text:
MBAlertView
===================

`MBAlertView` is a fast block-based alert and HUD library with a simple API.

### Features

Nested alerts and HUDs

Block based

Images

Nice animations

Doesn't use any PNG files. Everything is drawn with code.

## Usage

### Alerts: Flat

[![](http://i.imgur.com/08iRFnk.png)](http://i.imgur.com/08iRFnk.png)

``` objective-c
MBFlatAlertView *alert = [MBFlatAlertView alertWithTitle:@"Special Instructions" detailText:@"Are you sure?" cancelTitle:@"Cancel" cancelBlock:nil];
[alert addButtonWithTitle:@"Hello" type:MBFlatAlertButtonTypeBold action:^{}];
[alert addToDisplayQueue];
```

### Alerts: Classic

[![](http://i.imgur.com/3s3eJ.png)](http://i.imgur.com/3s3eJ.png)
[![](http://i.imgur.com/7CbbT.png)](http://i.imgur.com/7CbbT.png)
[![](http://i.imgur.com/lq53u.png)](http://i.imgur.com/lq53u.png)
[![](http://i.imgur.com/Aqfnr.png)](http://i.imgur.com/Aqfnr.png)

``` objective-c
MBAlertView *alert = [MBAlertView alertWithBody:@"Are you sure you want to delete this note? You cannot undo this." cancelTitle:@"Cancel" cancelBlock:nil];
[alert addButtonWithText:@"Delete" type:MBAlertViewItemTypeDestructive block:^{}];
[alert addToDisplayQueue];
```

### HUDs
``` objective-c
[MBHUDView hudWithBody:@"Wait." type:MBAlertViewHUDTypeActivityIndicator hidesAfter:4.0 show:YES];
```

You can see more in the easy to follow demo.

##Other

[Bitar](http://www.bitar.io/paragraphs/) [@bitario](https://twitter.com/bitario)

## License
MBAlertView is available under the MIT license.


text:
/**
 * wp.media.controller.VideoDetails
 *
 * The controller for the Video Details state
 *
 * @class
 * @augments wp.media.controller.State
 * @augments Backbone.Model
 */
var State = wp.media.controller.State,
	l10n = wp.media.view.l10n,
	VideoDetails;

VideoDetails = State.extend({
	defaults: {
		id: 'video-details',
		toolbar: 'video-details',
		title: l10n.videoDetailsTitle,
		content: 'video-details',
		menu: 'video-details',
		router: false,
		priority: 60
	},

	initialize: function( options ) {
		this.media = options.media;
		State.prototype.initialize.apply( this, arguments );
	}
});

module.exports = VideoDetails;


text:
package rfc

import (
	"unicode/utf8"

	"github.com/zmap/zcrypto/x509"
	"github.com/zmap/zlint/v3/lint"
	"github.com/zmap/zlint/v3/util"
)

type subjectGivenNameMaxLength struct{}

/************************************************
RFC 5280: A.1
-- Naming attributes of type X520name

id-at-givenName           AttributeType ::= { id-at 42 }

-- Naming attributes of type X520Name:
--   X520name ::= DirectoryString (SIZE (1..ub-name))
--
-- Expanded to avoid parameterized type:
X520name ::= CHOICE {
      teletexString     TeletexString   (SIZE (1..ub-name)),
      printableString   PrintableString (SIZE (1..ub-name)),
      universalString   UniversalString (SIZE (1..ub-name)),
      utf8String        UTF8String      (SIZE (1..ub-name)),
      bmpString         BMPString       (SIZE (1..ub-name)) }

--  specifications of Upper Bounds MUST be regarded as mandatory
--  from Annex B of ITU-T X.411 Reference Definition of MTS Parameter
--  Upper Bounds

-- Upper Bounds
ub-name INTEGER ::= 32768
************************************************/

func init() {
	lint.RegisterLint(&lint.Lint{
		Name:          "e_subject_given_name_max_length",
		Description:   "The 'GivenName' field of the subject MUST be less than 32769 characters",
		Citation:      "RFC 5280: A.1",
		Source:        lint.RFC5280,
		EffectiveDate: util.RFC2459Date,
		Lint:          NewSubjectGivenNameMaxLength,
	})
}

func NewSubjectGivenNameMaxLength() lint.LintInterface {
	return &subjectGivenNameMaxLength{}
}

func (l *subjectGivenNameMaxLength) CheckApplies(c *x509.Certificate) bool {
	return true
}

func (l *subjectGivenNameMaxLength) Execute(c *x509.Certificate) *lint.LintResult {
	for _, givenName := range c.Subject.GivenName {
		characters := utf8.RuneCountInString(givenName)
		if characters > 32768 {
			return &lint.LintResult{Status: lint.Error}
		}
	}
	return &lint.LintResult{Status: lint.Pass}
}


text:
#if _MSC_VER >= 1700
#pragma warning( disable: 4005 )
#endif

#include "pch.h"
#include <WolfViewportRenderer.h>
#include "Commands\WLoadSceneCmd.h"

static MFnPlugin* plugin = 0;
static WolfViewportRenderer* renderer = 0;
static __declspec(align(16)) char g_d3dRendererStorage[sizeof(WolfViewportRenderer)];
static MCallbackId	 D3DfileNewCallbackId = 0;
static MCallbackId	 D3DmayaExitCallbackId = 0;

static bool ReleaseRenderer()
{
	if (renderer)
	{
		auto status = renderer->deregisterRenderer();
		if (status != MStatus::kSuccess)
		{
			status.perror("Failed to UnRegister wolf engine renderer properly.");
			return false;
		}
		renderer->~WolfViewportRenderer();
		renderer = 0;

		Log("Renderer UnRegistered");
	}

	return true;
}

static void D3DfileNewCallback(void* clientData)
{
	Log("New Call back");
	//if (renderer)
	//{
	//	g_d3dRenderer->clearResources(false, false); /* keep shaders */
	//}
}

static void D3DmayaExitCallback(void* clientData)
{
	Log("Exit Call back");
	if (renderer)
	{
		renderer->~WolfViewportRenderer();
		renderer = 0;
	}
}

MStatus initializePlugin(MObject obj)
{
	Log("Initializing Wolf plugin");

	MStatus status = MStatus::kFailure;
	plugin = new MFnPlugin(obj, "Pooya.Eimandar", "1.0.0", "Any");

	// Register the renderer
	if (!ReleaseRenderer())
	{
		status.perror("Failed to release last renderer.");
		return status;
	}

	//Create renderer
	renderer = new (g_d3dRendererStorage) WolfViewportRenderer();
	if (renderer)
	{
		status = renderer->registerRenderer();
		if (status != MStatus::kSuccess)
		{
			status.perror("Failed to register wolf engine renderer properly.");
		}

		// Must add in these callbacks as on exit Maya never calls uninitializePlugin() !!
		if (D3DfileNewCallbackId == 0)
		{
			D3DfileNewCallbackId = MSceneMessage::addCallback(MSceneMessage::kBeforeNew, D3DfileNewCallback);
		}
		if (D3DmayaExitCallbackId == 0)
		{
			D3DmayaExitCallbackId = MSceneMessage::addCallback(MSceneMessage::kMayaExiting, D3DmayaExitCallback);
		}

		Log("Wolf plugin initialized");
	}

	//Register commands
	Wolf::Commands = Wolf::WCommnads::NOP;
	status = plugin->registerCommand("WLoadScene", WLoadSceneCmd::Command);
	CHECK_MSTATUS_AND_RETURN_IT(status);

#pragma region Open and compile main wolf python commands

	int pythonFileStatus = -1;
	auto pythonSource = Wolf::System::IO::ReadTextFile(L"Scripts\\WolfCmds.py", pythonFileStatus);

	if (pythonFileStatus != 1)
	{
		if (pythonFileStatus == -1)
		{
			LogError("Could not find the file \"WolfCmds.py\"");
		}
		else if (pythonFileStatus == -2)
		{
			LogError("The file \"WolfCmds.py\" might be corrupted");
		}
		else if (pythonFileStatus == -3)
		{
			LogError("The file \"WolfCmds.py\" is empty");
		}
		else if (pythonFileStatus == -4)
		{
			LogError("Could not open the file \"WolfCmds.py\"");
		}
		status = MStatus::kFailure;
		CHECK_MSTATUS_AND_RETURN_IT(status);

		return status;
	}

	MGlobal::executePythonCommandStringResult(pythonSource);

#pragma endregion

	return status;
}

MStatus uninitializePlugin(MObject obj)
{
	Log("Unloading Wolf plugin");

	MStatus status = MStatus::kSuccess;

	// Remove callbacks when plugin is unloaded.
	if (D3DfileNewCallbackId)
	{
		MMessage::removeCallback(D3DfileNewCallbackId);
		D3DfileNewCallbackId = 0;
	}
	if (D3DmayaExitCallbackId)
	{
		MMessage::removeCallback(D3DmayaExitCallbackId);
		D3DmayaExitCallbackId = 0;
	}

	// De-register the renderer
	if (!ReleaseRenderer())
	{
		Log("Problem on releasing renderer");
	}

	//De-register the commands
	plugin->deregisterCommand("WLoadScene");

	plugin = 0;

	Log("Wolf plugin Unloaded");

	return status;
}


text:
{
  "title": "I am unwilling to divulge how much time I just lost thinking Hugo or blogdown was totally borked on my computer WHEN IT WAS A TINY PUNCTUATION PROBLEM IN MY YAML THE WHOLE TIME. https://t.co/EhW18Pn0kf",
  "date": "2018-01-26"
}

# blogdown

> **Julia Silge** (@juliasilge; 38/1): I am unwilling to divulge how much time I just lost thinking Hugo or blogdown was totally borked on my computer WHEN IT WAS A TINY PUNCTUATION PROBLEM IN MY YAML THE WHOLE TIME. https://t.co/EhW18Pn0kf  [↪](https://twitter.com/xieyihui/status/956368770250964994)

<!-- -->

> **Levi Thatcher** (@levithatcher; 10/1): If you missed it, blogdown makes stats blogging a dream:
>
RMarkdown (code/formatting) ->
git/github (version) ->
blogdown (the glue) ->
hugo (generator) ->
netlify (host)
>
All are free and all impressive. #rstats https://t.co/EpRCCVIJVZ https://t.co/juvgwLK6QA  [↪](https://twitter.com/xieyihui/status/956387225687662593)

<!-- -->

> **R-Ladies Brussels** (@RladiesBrussels; 3/1): And @orchid00  is sharing her enthusiasm about #blogdown. More blogs coming soon hopefully 🎉🎉 https://t.co/Nk8YJMMG97  [↪](https://twitter.com/xieyihui/status/956613397222756355)

<!-- -->

> **Richard Lent** (@LentRichard; 0/0): blogdown: Creating Websites with R Markdown https://t.co/VlPsB8xol5 #edtech #webdesign #rstudio  [↪](https://twitter.com/xieyihui/status/956549382027071490)

<!-- -->

> **Ed Tech** (@HolyCrossEdTech; 0/0): blogdown: Creating Websites with R Markdown https://t.co/CMq4363ZM5 #edtech #webdesign #rstudio  [↪](https://twitter.com/xieyihui/status/956549381834133504)

<!-- -->

# bookdown

> **Levi Thatcher** (@levithatcher; 10/1): If you missed it, blogdown makes stats blogging a dream:
>
RMarkdown (code/formatting) ->
git/github (version) ->
blogdown (the glue) ->
hugo (generator) ->
netlify (host)
>
All are free and all impressive. #rstats https://t.co/EpRCCVIJVZ https://t.co/juvgwLK6QA  [↪](https://twitter.com/xieyihui/status/956387225687662593)

<!-- -->

> **Paula Andrea** (@orchid00; 5/3): If you liked the #R4ds book chapter 1 about #ggplot2 then you will love @ClausWilke's book on #dataviz https://t.co/DagywqQAjo Excellent! #Rstas #tidyverse #rmarkdown #bookdown #openaccess  [↪](https://twitter.com/xieyihui/status/956537141043105792)

<!-- -->

> **CRAN Package Updates** (@CRANberriesFeed; 0/1): CRAN updates: bookdown frailtyEM lazyWeave reproducible https://t.co/y5W2NTKSXT #rstats  [↪](https://twitter.com/xieyihui/status/956512717615128576)

<!-- -->

> **Chris Tufts** (@devlintufts; 0/0): I wanted to learn more about Latent Dirichlet Allocation. Started writing notes, then some code .... and now I've written a good portion of a book.  https://t.co/ng9qAGfGD3 #rstats #bookdown #lda #topicmodeling  [↪](https://twitter.com/xieyihui/status/956695374231736321)

<!-- -->

# knitr

> **Robert M Flight** (@rmflight; 4/3): For the daytime crowd:
>
knitrProgressBar is my new #rstats pkg to use dplyr like progress bars inside knitr and see the progress.
>
Please test it, provide feedback, etc (even does the name make sense?)
>
https://t.co/TIPLXqMxaA  [↪](https://twitter.com/xieyihui/status/956587165806456833)

<!-- -->

> **Robert M Flight** (@rmflight; 4/2): Want to watch progress of a function even when using knitr and rmarkdown::render? Try my new #rstats pkg knitrProgressBar
>
https://t.co/vAriqFD48B
>
Try using rmarkdown::render on this file: https://t.co/vAriqFD48B  [↪](https://twitter.com/xieyihui/status/956372360302604288)

<!-- -->

> **Cool** (@iss_iskandar; 0/0): Kable r <b>package</b>: Kable r package. The knitr package provides the kable function… https://t.co/9X6dnOSQLG  [↪](https://twitter.com/xieyihui/status/956574497016041474)

<!-- -->

# xaringan

> **{doctoRant}📊📚** (@_AntoineB; 1/1): Dans un #xaringan, je veux inclure l'emoji 💥 (sous Windows)
Mais ni :boom:, ni `r emo::ji("boom")` ne fonctionnent :(
#RStats #RStatsFR #rmarkdown  [↪](https://twitter.com/xieyihui/status/956467510253178880)

<!-- -->