text:
package com.taobao.weex.dom;

import java.util.Collection;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;
import java.util.Set;

import android.support.annotation.NonNull;
import android.support.annotation.UiThread;
import android.support.v4.util.ArrayMap;
import android.text.TextUtils;
import com.taobao.weex.common.Constants;
import com.taobao.weex.common.Constants.Name;
import com.taobao.weex.common.WXImageSharpen;
import com.taobao.weex.dom.binding.ELUtils;
import com.taobao.weex.dom.binding.WXStatement;
import com.taobao.weex.el.parse.Parser;
import com.taobao.weex.ui.view.listview.WXRecyclerView;
import com.taobao.weex.utils.WXLogUtils;
import com.taobao.weex.utils.WXUtils;
import com.taobao.weex.utils.WXViewUtils;

import static com.taobao.weex.dom.binding.ELUtils.COMPONENT_PROPS;
import static com.taobao.weex.dom.binding.ELUtils.EXCLUDES_BINDING;
import static java.lang.Boolean.parseBoolean;

/**
 * store value of component attribute
 *
 */
public class WXAttr implements Map<String, Object>,Cloneable {

  private static final long serialVersionUID = -2619357510079360946L;

  /**
   * static attrs
   * */
  private @NonNull Map<String, Object> attr;
  private Map<String, Object> writeAttr;

  /**
   * dynamic binding attrs, can be null, only weex use
   * */
  private ArrayMap<String, Object>  mBindingAttrs;

  /**
   * dynamic binding statement for match, can be null, only weex use
   * */
  private WXStatement mStatement;

  public WXAttr(){
    attr =new ArrayMap<>();
  }

  public WXAttr(@NonNull Map<String,Object> standardMap) {
    this();
    attr.putAll(standardMap);
  }

  public WXAttr(@NonNull Map<String,Object> standardMap, int extra){
    this();
    attr.putAll(standardMap);
  }

  public static String getPrefix(Map<String, Object> attr) {
    if (attr == null) {
      return null;
    }
    Object src = attr.get(Constants.Name.PREFIX);
    if (src == null) {
      return null;
    }
    return src.toString();
  }

  public static String getSuffix(Map<String, Object> attr) {
    if (attr == null) {
      return null;
    }
    Object src = attr.get(Constants.Name.SUFFIX);
    if (src == null) {
      return null;
    }
    return src.toString();
  }

  /**
   * Compatible with value、content
   *
   * @return
   */
  public static String getValue(Map<String, Object> attr) {
    if (attr == null) {
      return null;
    }
    Object src = attr.get(Constants.Name.VALUE);
    if (src == null) {
      src = attr.get("content");
      if (src == null) {
        return null;
      }
    }
    return src.toString();
  }

  public WXImageQuality getImageQuality() {
    Object obj = containsKey(Name.QUALITY) ? get(Name.QUALITY) : get(Name.IMAGE_QUALITY);
    WXImageQuality imageQuality = WXImageQuality.AUTO;
    String value;
    if (obj != null && !TextUtils.isEmpty(value = obj.toString())) {
      try {
        imageQuality = WXImageQuality.valueOf(value.toUpperCase(Locale.US));
      }catch (IllegalArgumentException e){
        WXLogUtils.e("Image", "Invalid value image quality. Only low, normal, high, original are valid");
      }
    }
    return imageQuality;
  }

  public WXImageSharpen getImageSharpen() {
    Object obj = get(Constants.Name.SHARPEN);
    if (obj == null) {
      obj = get(Constants.Name.IMAGE_SHARPEN);
    }
    if (obj == null) {
      return WXImageSharpen.UNSHARPEN;
    }
    String imageSharpen = obj.toString();
    WXImageSharpen waImageSharpen = WXImageSharpen.UNSHARPEN;
    if (imageSharpen.equals("sharpen")) {
      waImageSharpen = WXImageSharpen.SHARPEN;
    }

    return waImageSharpen;
  }

  public String getImageSrc() {
    Object src = get(Constants.Name.SRC);
    if (src == null) {
      return null;
    }
    return src.toString();
  }

  public boolean canRecycled() {
    Object obj = get(Constants.Name.RECYCLE);
    if (obj == null) {
      return true;
    }
    try {
      return parseBoolean(String.valueOf(obj));
    } catch (Exception e) {
      WXLogUtils.e("[WXAttr] recycle:", e);
    }
    return true;
  }

  public boolean showIndicators() {
    Object obj = get(Constants.Name.SHOW_INDICATORS);
    if (obj == null) {
      return true;
    }

    try {
      return parseBoolean(String.valueOf(obj));
    } catch (Exception e) {
      WXLogUtils.e("[WXAttr] showIndicators:", e);
    }
    return true;
  }

  public boolean autoPlay() {
    Object obj = get(Constants.Name.AUTO_PLAY);
    if (obj == null) {
      return false;
    }

    try {
      return parseBoolean(String.valueOf(obj));
    } catch (Exception e) {
      WXLogUtils.e("[WXAttr] autoPlay:", e);
    }
    return false;
  }

  public String getScope() {
    Object src = get(Constants.Name.SCOPE);
    if (src == null) {
      return null;
    }
    return src.toString();
  }
  public String getLoadMoreRetry() {
    Object src = get(Constants.Name.LOADMORERETRY);
    if (src == null) {
      return null;
    }
    return src.toString();
  }

  public String getLoadMoreOffset() {
    Object src = get(Constants.Name.LOADMOREOFFSET);
    if (src == null) {
      return null;
    }
    return src.toString();
  }

  public String optString(String key){
    if(containsKey(key)){
      Object value = get(key);
      if (value instanceof String) {
        return (String) value;
      } else if (value != null) {
        return String.valueOf(value);
      }
    }
    return "";
  }

  public boolean getIsRecycleImage() {
    Object obj = get(Constants.Name.RECYCLE_IMAGE);
    if (obj == null) {
      return true;
    }

    try {
      return parseBoolean(String.valueOf(obj));
    } catch (Exception e) {
      WXLogUtils.e("[WXAttr] recycleImage:", e);
    }
    return false;
  }
  public String getScrollDirection() {
    Object scrollDirection = get("scrollDirection");
    if (scrollDirection == null) {
      return "vertical";
    }
    return scrollDirection.toString();
  }

  public int getOrientation() {
    String direction = getScrollDirection();
    if(!TextUtils.isEmpty(direction)){
      if(direction.equals(Constants.Value.HORIZONTAL)){
        return Constants.Orientation.HORIZONTAL;
      }
    }
    Object value = get(Name.ORIENTATION);
    if(value != null && Constants.Value.HORIZONTAL.equals(value.toString())){
      return Constants.Orientation.HORIZONTAL;
    }
    return Constants.Orientation.VERTICAL;
  }

  public float getElevation(int viewPortW) {
    Object obj = get(Constants.Name.ELEVATION);
    float ret = Float.NaN;
    if (obj != null) {
      String number = obj.toString();
      if (!TextUtils.isEmpty(number)) {
        ret = WXViewUtils.getRealSubPxByWidth(WXUtils.getFloat(number),viewPortW);
      } else {
        ret = 0;
      }
    }
    return ret;
  }

  public float getColumnWidth(){

    Object obj = get(Constants.Name.COLUMN_WIDTH);
    if (obj == null) {
      return Constants.Value.AUTO;
    }

    String value = String.valueOf(obj);
    if(Constants.Name.AUTO.equals(value)){
      return Constants.Value.AUTO;
    }

    try {
      float columnWidth = Float.parseFloat(value);
      return columnWidth > 0 ? columnWidth : 0;
    } catch (Exception e) {
      WXLogUtils.e("[WXAttr] getColumnWidth:", e);
    }
    return Constants.Value.AUTO;
  }

  public int getColumnCount() {

    Object obj = get(Constants.Name.COLUMN_COUNT);
    if (obj == null) {
      return Constants.Value.AUTO;
    }

    String value = String.valueOf(obj);
    if(Constants.Name.AUTO.equals(value)){
      return Constants.Value.AUTO;
    }

    try {
      int columnCount = Integer.parseInt(value);
      return columnCount > 0 ? columnCount : Constants.Value.AUTO;
    } catch (Exception e) {
      WXLogUtils.e("[WXAttr] getColumnCount:", e);
      return Constants.Value.AUTO;
    }
  }

  public float getColumnGap() {

    Object obj = get(Constants.Name.COLUMN_GAP);
    if (obj == null) {
      return Constants.Value.COLUMN_GAP_NORMAL;
    }

    String value = String.valueOf(obj);
    if (Constants.Name.NORMAL.equals(value)) {
      return Constants.Value.COLUMN_GAP_NORMAL;
    }

    try {
      float columnGap = Float.parseFloat(value);
      return columnGap >= 0 ? columnGap : Constants.Value.AUTO;
    } catch (Exception e) {
      WXLogUtils.e("[WXAttr] getColumnGap:", e);
    }
    return Constants.Value.COLUMN_GAP_NORMAL;
  }

  public int getLayoutType(){
    Object obj = get(Constants.Name.LAYOUT);
    if (obj == null) {
      return WXRecyclerView.TYPE_LINEAR_LAYOUT;
    }

    try {
      switch(String.valueOf(obj)){
        case Constants.Value.MULTI_COLUMN :
          return  WXRecyclerView.TYPE_STAGGERED_GRID_LAYOUT;
        case Constants.Value.GRID :
          return  WXRecyclerView.TYPE_GRID_LAYOUT;
        default:
          return WXRecyclerView.TYPE_LINEAR_LAYOUT;
      }
    } catch (Exception e) {
      WXLogUtils.e("[WXAttr] getLayoutType:", e);
    }
    return WXRecyclerView.TYPE_LINEAR_LAYOUT;
  }

  @Override
  public boolean equals(Object o) {
    return attr.equals(o);
  }

  @Override
  public int hashCode() {
    return attr.hashCode();
  }

  @Override
  public void clear() {
    attr.clear();
  }

  @Override
  public boolean containsKey(Object key) {
    return attr.containsKey(key);
  }

  @Override
  public boolean containsValue(Object value) {
    return attr.containsValue(value);
  }

  @NonNull
  @Override
  public Set<Entry<String, Object>> entrySet() {
    return attr.entrySet();
  }

  @Override
  public Object get(Object key) {
    Map<String, Object> temp = writeAttr;
    if (null != temp) {
      Object obj = temp.get(key);
      if (null != obj) {
        return obj;
      }
    }
    return attr.get(key);
  }

  @Override
  public boolean isEmpty() {
    return attr.isEmpty();
  }

  @NonNull
  @Override
  public Set<String> keySet() {
    return attr.keySet();
  }

  @Override
  public Object put(String key, Object value) {
    if(addBindingAttrIfStatement(key, value)){
      return null;
    }
    return attr.put(key,value);
  }

  @Override
  public void putAll(Map<? extends String, ?> map) {
    //this.attr.putAll(map);
    if (this.writeAttr == null) {
      this.writeAttr = new ArrayMap<>();
    }
    this.writeAttr.putAll(map);
  }

  @Override
  public Object remove(Object key) {
    return attr.remove(key);
  }

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

  @NonNull
  @Override
  public Collection<Object> values() {
    return attr.values();
  }

  /**
   * can by null, in most contion without template list, the value is null
   * */
  public ArrayMap<String, Object> getBindingAttrs() {
    return mBindingAttrs;
  }

  /**
   * can by null, in most contion without template list, the value is null
   * */
  public WXStatement getStatement() {
    return mStatement;
  }

  public void setBindingAttrs(ArrayMap<String, Object> mBindingAttrs) {
    this.mBindingAttrs = mBindingAttrs;
  }

  public void setStatement(WXStatement mStatement) {
    this.mStatement = mStatement;
  }

  public void parseStatements(){
    if(this.attr != null){
       this.attr = filterStatementsFromAttrs(this.attr);
    }
  }

  /**
   * filter dynamic state ment
   * */
  private Map<String, Object> filterStatementsFromAttrs(Map attrs) {
    if(attrs == null || attrs.size() == 0){
      return attrs;
    }
    Set<Map.Entry<String,Object>> entries = attrs.entrySet();
    Iterator<Entry<String,Object>> it =  entries.iterator();
    while (it.hasNext()){
      Map.Entry<String,Object> entry = it.next();
      if(COMPONENT_PROPS.equals(entry.getKey())){
        Object blockValue = ELUtils.bindingBlock(entry.getValue());
        entry.setValue(blockValue);
        continue;
      }
      if(addBindingAttrIfStatement(entry.getKey(), entry.getValue())){
        it.remove();
      }
    }
    return attrs;
  }

  /**
   * filter dynamic attrs and statements
   * */
  private boolean addBindingAttrIfStatement(String key, Object value) {
    for(String exclude : EXCLUDES_BINDING){
      if(key.equals(exclude)){
        return  false;
      }
    }
    if(ELUtils.isBinding(value)){
      if(mBindingAttrs == null){
        mBindingAttrs = new ArrayMap<String, Object>();
      }
      value = ELUtils.bindingBlock(value);
      mBindingAttrs.put(key, value);
      return  true;
    }
    if(WXStatement.WX_IF.equals(key)){
      if(mStatement == null){
        mStatement = new WXStatement();
      }
      if(value != null) {
        mStatement.put(key, Parser.parse(value.toString()));
      }
      return  true;
    }

    if(WXStatement.WX_FOR.equals(key)){
      if(mStatement == null){
        mStatement = new WXStatement();
      }
      value = ELUtils.vforBlock(value);
      if(value != null) {
        mStatement.put(key, value);
        return  true;
      }
    }

    if(WXStatement.WX_ONCE.equals(key)){
      if(mStatement == null){
        mStatement = new WXStatement();
      }
      mStatement.put(key, true);
    }
    return  false;
  }

  public void skipFilterPutAll(Map<String,Object> attrs){
    this.attr.putAll(attrs);
  }

  @UiThread
  public void mergeAttr() {
    if (null != this.writeAttr) {
      this.attr.putAll(this.writeAttr);
      this.writeAttr = null;
    }
  }

  @Override
  public WXAttr clone() {
    WXAttr wxAttr = new WXAttr();
    wxAttr.skipFilterPutAll(attr);
    if (mBindingAttrs != null) {
      wxAttr.mBindingAttrs = new ArrayMap<>(mBindingAttrs);
    }
    if (mStatement != null){
      wxAttr.mStatement = new WXStatement(mStatement);
    }
    return wxAttr;
  }
}


text:
using EasyPost;

using System;
using System.Linq;
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace EasyPostTest {
    [TestClass]
    public class BatchTest {
        Dictionary<string, object> fromAddress;
        Dictionary<string, object> toAddress;
        Dictionary<string, object> shipmentParameters;

        [TestInitialize]
        public void Initialize() {
            Client.apiKey = "cueqNZUb3ldeWTNX7MU3Mel8UXtaAMUi";

            fromAddress = new Dictionary<string, object>() {
                {"name", "Andrew Tribone"}, {"street1", "480 Fell St"}, {"street2", "#3"},
                {"city", "San Francisco"}, {"state", "CA"}, {"country", "US"}, {"zip", "94102"}
            };
            toAddress = new Dictionary<string, object>() {
                {"company", "Simpler Postage Inc"}, {"street1", "164 Townsend Street"}, {"street2", "Unit 1"},
                {"city", "San Francisco"}, {"state", "CA"}, {"country", "US"}, {"zip", "94107"}
            };
            shipmentParameters = new Dictionary<string, object>() {
                {"parcel", new Dictionary<string, object>() {{"length", 8}, {"width", 6}, {"height", 5}, {"weight", 10}}},
                {"to_address", toAddress}, {"from_address", fromAddress}, {"carrier", "USPS"}, {"service", "Priority"}
            };
        }

        [TestMethod]
        public void TestRetrieve() {
            Batch batch = Batch.Create();
            Batch retrieved = Batch.Retrieve(batch.id);
            Assert.AreEqual(batch.id, retrieved.id);
        }

        [TestMethod]
        public void TestAddRemoveShipments() {
            Batch batch = Batch.Create();
            Shipment shipment = Shipment.Create(shipmentParameters);
            Shipment otherShipment = Shipment.Create(shipmentParameters);

            while (batch.state != "created")
                batch = Batch.Retrieve(batch.id);
            batch.AddShipments(new List<Shipment>() { shipment, otherShipment });

            while (batch.shipments == null) { batch = Batch.Retrieve(batch.id); }
            List<string> shipmentIds = batch.shipments.Select(ship => ship.id).ToList();
            Assert.AreEqual(batch.num_shipments, 2);
            CollectionAssert.Contains(shipmentIds, shipment.id);
            CollectionAssert.Contains(shipmentIds, otherShipment.id);

            batch.RemoveShipments(new List<Shipment>() { shipment, otherShipment });
            Assert.AreEqual(batch.num_shipments, 0);
        }

        public Batch CreateBatch() {
            Dictionary<string, object> parameters = new Dictionary<string, object>() {
                {"reference", "EasyPostCSharpTest"},
                {"shipments", new List<Dictionary<string, object>>() {shipmentParameters}}
            };

            return Batch.Create(parameters);
        }

        [TestMethod]
        public void TestCreateThenBuyThenGenerateLabelAndScanForm() {
            Batch batch = CreateBatch();

            Assert.IsNotNull(batch.id);
            Assert.AreEqual(batch.reference, "EasyPostCSharpTest");
            Assert.AreEqual(batch.state, "creating");

            while (batch.state == "creating") { batch = Batch.Retrieve(batch.id); }
            batch.Buy();

            while (batch.state == "created") { batch = Batch.Retrieve(batch.id); }
            Assert.AreEqual(batch.state, "purchased");

            batch.GenerateLabel("pdf");
            Assert.AreEqual(batch.state, "label_generating");

            batch.GenerateScanForm();
        }

        [TestMethod]
        public void TestGenerateLabelWithOrderBy() {
            Batch batch = CreateBatch();

            while (batch.state == "creating") { batch = Batch.Retrieve(batch.id); }
            batch.Buy();

            while (batch.state == "created") { batch = Batch.Retrieve(batch.id); }
            batch.GenerateLabel("pdf", orderBy: "reference DESC");

            Assert.AreEqual(batch.state, "label_generating");
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
using System;
using Shouldly;
using Veggerby.Algorithm.Calculus;
using Xunit;

namespace Veggerby.Algorithm.Tests.Calculus
{
    public class ConstantTests
    {
        [Fact]
        public void Should_initialize_from_constructor()
        {
            // arrange

            // act
            var actual = ValueConstant.Create(123);

            // assert
            actual.Value.ShouldBe(123);
        }

        [Fact]
        public void Should_have_zero_static()
        {
            // arrange
            // act
            // assert
            ValueConstant.Zero.Value.ShouldBe(0);
        }

        [Fact]
        public void Should_have_one_static()
        {
            // arrange
            // act
            // assert
            ValueConstant.One.Value.ShouldBe(1);
        }

        [Fact]
        public void Should_have_pi_static()
        {
            // arrange
            // act
            // assert
            ValueConstant.Pi.Symbol.ShouldBe("π");
            ValueConstant.Pi.Value.ShouldBe(Math.PI);
        }

        [Fact]
        public void Should_have_e_static()
        {
            // arrange
            // act
            // assert
            ValueConstant.e.Symbol.ShouldBe("e");
            ValueConstant.e.Value.ShouldBe(Math.E);
        }

        [Fact]
        public void Should_equal_self()
        {
            // arrange
            var v = ValueConstant.Create(4);

            // act
            var actual = v.Equals(v);

            // assert
            actual.ShouldBeTrue();
        }

        [Fact]
        public void Should_not_equal_null()
        {
            // arrange
            var v = ValueConstant.Create(3);

            // act
            var actual = v.Equals(null);

            // assert
            actual.ShouldBeFalse();
        }

        [Fact]
        public void Should_equal_same_operands()
        {
            // arrange
            var v1 = ValueConstant.Create(3);
            var v2 = ValueConstant.Create(3);

            // act
            var actual = v1.Equals(v2);

            // assert
            actual.ShouldBeTrue();
        }

        [Fact]
        public void Should_not_equal_different_operands()
        {
            // arrange
            var v1 = ValueConstant.One;
            var v2 = ValueConstant.Create(3);

            // act
            var actual = v1.Equals(v2);

            // assert
            actual.ShouldBeFalse();
        }
    }
}


text:
var path = require('path'),
    express = require('express'),
    nano = require('nano'),
    _ = require('lodash'),
    ConfigLoader = require('./lib/config_loader'),
    middleware = require('./lib/middleware'),
    routes = require('./routes/index'),
    Radio = require('./lib/radio'),
    MpdPool = require('./lib/mpd_pool'),
    AlarmClock = require('./lib/alarm_clock'),
    Settings = require('./lib/settings'),
    RadioStationsKeeper = require('./lib/radio_stations_keeper'),
    Application = require('./lib/application');

var config = ConfigLoader.load(path.normalize(__dirname + '/configs/config.json'));

var settings = new Settings(nano(config.storage.settings)),
    stationsKeeper = new RadioStationsKeeper(config.radioStations),
    alarm = new AlarmClock(),
    mpdPool = new MpdPool({
        host: config.mpd.host,
        port: config.mpd.port,
        reconnect: true,
        timeout: 100
    }),
    radio = new Radio(mpdPool);

radio.setCurrentStation(_.find(config.radioStations, function(station) {
    return station.id === config.defaultRadioStation;
}));

var app = new Application(radio, stationsKeeper, alarm, settings);

app.run().then(function() {
    return new Promise(function(resolve, reject) {
        // Initialize entire server application.
        var server = express();

        // Use Handlebars template engine.
        server.set('view engine', 'handlebars');
        server.engine('handlebars', require('hbs').__express);

        // Serve static files.
        server.use(express.static(__dirname + '/public'));

        // Mount routes.
        server.use('/', routes(app));

        // Mount other middleware.
        server.use(middleware.notFound);
        server.use(middleware.serverError);

        // Connect HTTP server.
        server.listen(
            config.server.port,
            function(err) {
                if (err) {
                    reject(err);
                } else {
                    resolve();
                }
            }
        );
    });
}).then(function() {
    console.log('Application is up on port ' + config.server.port.toString());
}).catch(function(err) {
    console.error(err);
    process.exit();
});


text:
package com.cinchapi.concourse.importer;

import java.util.List;
import java.util.Set;

import javax.annotation.Nullable;

import com.cinchapi.concourse.Concourse;
import com.cinchapi.concourse.importer.util.Importables;
import com.cinchapi.concourse.util.FileOps;
import com.google.common.collect.Lists;

/**
 * An {@link Importer} that splits each line of input by a {@link #delimiter()}
 * to produce key/value pairs for import. Each line is imported entirely into at
 * least one record in Concourse.
 *
 * @author Jeff Nelson
 */
public abstract class DelimitedLineImporter extends Importer {

    /**
     * The character on which each line in the text is split to generate tokens.
     * This is set by the subclass using the {@link #delimiter()} method.
     */
    private final char delimiter;

    /**
     * A collection of column/key names that map to each of the delimited tokens
     * in a line, respectively.
     */
    private final List<String> header;

    /**
     * The {@link Transformer} that possible alters key/value pairs prior to
     * import. This is set by the subclass using the {@link #transformer()}
     * method.
     */
    @Nullable
    private final Transformer transformer;

    /**
     * Construct a new instance.
     *
     * @param concourse the connection to Concourse to use for importing
     */
    protected DelimitedLineImporter(Concourse concourse) {
        super(concourse);
        this.delimiter = delimiter();
        this.transformer = transformer();
        this.header = header();
    }

    @Override
    public final Set<Long> importFile(String file) {
        return importFile(file, null);
    }

    /**
     * Import all of the lines from {@code file} into Concourse and determine
     * the appropriate destination record(s) for each line using the
     * {@code resolveKey}.
     *
     * @param file the path to the file to import
     * @param resolveKey the key to use when resolving one or more existing
     *            records into which to import a line. When using a
     *            {@code resolveKey}, the Importer instructs Concourse to find
     *            all the records that contain the same value for the key that
     *            exists in the line and import the rest of the data in the line
     *            into those records
     * @return the records into which the data is imported
     */
    public final Set<Long> importFile(String file, @Nullable String resolveKey) {
        List<String> lines = FileOps.readLines(file);
        StringBuilder sb = new StringBuilder();
        sb.append('[');
        for (String line : lines) {
            int length = sb.length();
            Importables.delimitedStringToJsonObject(line, resolveKey,
                    delimiter, header, transformer, sb);
            if(sb.length() > length) {
                sb.append(',');
            }
        }
        sb.deleteCharAt(sb.length() - 1);
        sb.append(']');
        return concourse.insert(sb.toString());
    }

    @Override
    public Set<Long> importString(String data) {
        return importString(data, null);
    }

    /**
     * Import all the {@code lines} into Concourse and determine the appropriate
     * destination record(s) for each line using the {@code resolveKey}.
     *
     * @param lines the text to import
     * @param resolveKey the key to use when resolving one or more existing
     *            records into which to import a line. When using a
     *            {@code resolveKey}, the Importer instructs Concourse to find
     *            all the records that contain the same value for the key that
     *            exists in the line and import the rest of the data in the line
     *            into those records
     * @return the records into which the data is imported
     */
    public final Set<Long> importString(String lines,
            @Nullable String resolveKey) {
        String json = Importables.delimitedStringToJsonArray(lines, resolveKey,
                delimiter, header, transformer);
        return concourse.insert(json);
    }

    /**
     * The delimiter that is used to split field on each line.
     *
     * @return the delimiter
     */
    protected abstract char delimiter();

    /**
     * Provide an ordered list of header columns/keys if they are not provided
     * in the first line that is processed by this importer.
     *
     * @return the header
     */
    protected List<String> header() {
        return Lists.newArrayList();
    }

    /**
     * Return a {@link Transformer} to potentially alter key/value pairs seen by
     * this importer.
     *
     * @return the transformer
     */
    protected Transformer transformer() {
        return null;
    }

}


text:
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/ash/arc/nearby_share/nearby_share_session_impl.h"

#include <memory>
#include <string>
#include <vector>

#include "ash/components/arc/arc_features.h"
#include "ash/components/arc/arc_util.h"
#include "ash/public/cpp/app_types_util.h"
#include "base/bind.h"
#include "base/callback_forward.h"
#include "base/callback_helpers.h"
#include "base/feature_list.h"
#include "base/files/file_util.h"
#include "base/location.h"
#include "base/numerics/safe_conversions.h"
#include "base/system/sys_info.h"
#include "base/task/task_traits.h"
#include "base/task/thread_pool.h"
#include "base/time/time.h"
#include "chrome/browser/apps/app_service/intent_util.h"
#include "chrome/browser/ash/arc/arc_util.h"
#include "chrome/browser/ash/arc/fileapi/arc_content_file_system_url_util.h"
#include "chrome/browser/ash/arc/nearby_share/arc_nearby_share_uma.h"
#include "chrome/browser/ash/arc/nearby_share/ui/error_dialog_view.h"
#include "chrome/browser/ash/arc/nearby_share/ui/low_disk_space_dialog_view.h"
#include "chrome/browser/ash/arc/nearby_share/ui/nearby_share_overlay_view.h"
#include "chrome/browser/ash/arc/nearby_share/ui/progress_bar_dialog_view.h"
#include "chrome/browser/ash/file_manager/fileapi_util.h"
#include "chrome/browser/ash/file_manager/path_util.h"
#include "chrome/browser/ash/fileapi/external_file_url_util.h"
#include "chrome/browser/ash/fusebox/fusebox_server.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/sharesheet/sharesheet_service.h"
#include "chrome/browser/sharesheet/sharesheet_service_factory.h"
#include "chrome/browser/sharesheet/sharesheet_types.h"
#include "chrome/browser/ui/settings_window_manager_chromeos.h"
#include "chrome/browser/ui/webui/settings/chromeos/constants/routes.mojom-forward.h"
#include "chrome/browser/webshare/prepare_directory_task.h"
#include "chrome/common/chrome_paths_internal.h"
#include "components/services/app_service/public/cpp/intent.h"
#include "components/services/app_service/public/cpp/intent_util.h"
#include "content/public/browser/browser_thread.h"
#include "net/base/filename_util.h"
#include "storage/browser/file_system/file_system_context.h"
#include "third_party/cros_system_api/constants/cryptohome.h"

// Enable VLOG level 1.
#undef ENABLED_VLOG_LEVEL
#define ENABLED_VLOG_LEVEL 1

namespace arc {

namespace {
// Maximum time to wait for the ARC window to be initialized.
// ARC Wayland messages and Mojo messages are sent across the same pipe. The
// order in which the messages are sent is not deterministic. If the ARC
// activity starts Nearby Share before the wayland message for the new has been
// processed, the corresponding aura::Window for a given ARC activity task ID
// will not be found. To get around this, NearbyShareSessionImpl will wait a
// little while for the Wayland message to be processed and the window to be
// initialized.
constexpr base::TimeDelta kWindowInitializationTimeout = base::Seconds(1);

constexpr base::TimeDelta kProgressBarUpdateInterval = base::Milliseconds(1500);

constexpr uint64_t kShowProgressBarMinSizeInBytes = 12000000;  // 12MB.

constexpr char kIntentExtraText[] = "android.intent.extra.TEXT";

constexpr base::FilePath::CharType kArcNearbyShareDirname[] =
    FILE_PATH_LITERAL(".NearbyShare");

void DeletePathAndFiles(const base::FilePath& file_path) {
  DVLOG(1) << __func__;
  if (!file_path.empty() && base::PathExists(file_path)) {
    base::DeletePathRecursively(file_path);
  }
}

void DoDeleteShareCacheFilePaths(const base::FilePath& profile_path,
                                 const base::FilePath& user_cache_file_path) {
  // Up until M99, shared files were stored in <user_cache_dir>/.NearbyShare.
  // We should remove this obsolete directory path if it is still present.
  base::FilePath cache_base_path;
  chrome::GetUserCacheDirectory(profile_path, &cache_base_path);
  DeletePathAndFiles(cache_base_path.Append(kArcNearbyShareDirname));

  // Delete the current user cache file path.
  DeletePathAndFiles(user_cache_file_path);
}

// Calculate the amount of disk space, in bytes, needed in |share_dir| to
// stream |total_file_size| bytes from Android to the Chrome OS file system.
static int64_t CalculateRequiredSpace(const base::FilePath& share_dir,
                                      const uint64_t total_file_size) {
  DVLOG(1) << __func__;
  int64_t free_disk_space = base::SysInfo::AmountOfFreeDiskSpace(share_dir);
  VLOG(1) << "Free disk space: " << free_disk_space;
  int64_t shared_files_size =
      static_cast<int64_t>(cryptohome::kMinFreeSpaceInBytes + total_file_size);
  VLOG(1) << "Shared file size: " << shared_files_size;
  return shared_files_size - free_disk_space;
}

base::FilePath GetUserCacheFilePath(Profile* const profile) {
  DCHECK(profile);
  base::FilePath file_path = file_manager::util::GetShareCacheFilePath(profile);
  return file_path.Append(kArcNearbyShareDirname);
}

void DestroySharedMonikers(const std::vector<fusebox::Moniker>& monikers) {
  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
  if (monikers.empty()) {
    return;
  }

  fusebox::Server* fusebox_server = fusebox::Server::GetInstance();
  if (!fusebox_server) {
    LOG(ERROR)
        << "FuseBox server was unavailable when cleaning up shared files.";
    return;
  }

  for (const fusebox::Moniker& moniker : monikers) {
    fusebox_server->DestroyMoniker(moniker);
  }
}

void DeleteFilesAndMonikers(const base::FilePath& file_path,
                            const std::vector<fusebox::Moniker>& monikers) {
  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
  DestroySharedMonikers(monikers);
  base::ThreadPool::PostTask(FROM_HERE, {base::MayBlock()},
                             base::BindOnce(&DeletePathAndFiles, file_path));
}

absl::optional<fusebox::Moniker> ConvertToMoniker(Profile* profile,
                                                  const GURL& content_url) {
  GURL external_file_url = arc::ArcUrlToExternalFileUrl(content_url);

  const base::FilePath virtual_path =
      ash::ExternalFileURLToVirtualPath(external_file_url);

  const storage::FileSystemURL fs_url =
      file_manager::util::GetFileManagerFileSystemContext(profile)
          ->CreateCrackedFileSystemURL(
              blink::StorageKey(file_manager::util::GetFilesAppOrigin()),
              storage::kFileSystemTypeExternal, virtual_path);
  if (!fs_url.is_valid()) {
    LOG(ERROR) << "Failed to create moniker for invalid FileSystemURL.";
    return absl::nullopt;
  }

  fusebox::Server* fusebox_server = fusebox::Server::GetInstance();
  if (!fusebox_server) {
    LOG(ERROR) << "FuseBox server was unavailable when creating moniker.";
    return absl::nullopt;
  }

  return fusebox_server->CreateMoniker(fs_url, /*read_only=*/true);
}

bool FileSharingThroughFuseBoxEnabled() {
  return base::FeatureList::IsEnabled(arc::kEnableArcNearbyShareFuseBox);
}

}  // namespace

NearbyShareSessionImpl::NearbyShareSessionImpl(
    Profile* profile,
    uint32_t task_id,
    mojom::ShareIntentInfoPtr share_info,
    mojo::PendingRemote<mojom::NearbyShareSessionInstance> session_instance,
    mojo::PendingReceiver<mojom::NearbyShareSessionHost> session_receiver,
    SessionFinishedCallback session_finished_callback)
    : task_id_(task_id),
      session_instance_(std::move(session_instance)),
      session_receiver_(this, std::move(session_receiver)),
      share_info_(std::move(share_info)),
      profile_(profile),
      backend_task_runner_(base::ThreadPool::CreateSequencedTaskRunner(
          // Should be USER_VISIBLE because we are downloading files requested
          // by the user and updating the UI on progress of transfers.
          // IO operations for temp files / directories cleanup should be
          // completed before shutdown.
          {base::MayBlock(), base::TaskPriority::USER_VISIBLE,
           base::TaskShutdownBehavior::BLOCK_SHUTDOWN})),
      session_finished_callback_(std::move(session_finished_callback)) {
  session_receiver_.set_disconnect_handler(base::BindOnce(
      &NearbyShareSessionImpl::CleanupSession, weak_ptr_factory_.GetWeakPtr(),
      /*should_cleanup_files=*/true));
  aura::Window* const arc_window = GetArcWindow(task_id_);
  if (arc_window) {
    VLOG(1) << "ARC window found";
    UpdateNearbyShareWindowFound(true);
    base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
        FROM_HERE, base::BindOnce(&NearbyShareSessionImpl::OnArcWindowFound,
                                  weak_ptr_factory_.GetWeakPtr(), arc_window));
  } else {
    VLOG(1) << "No ARC window found for task ID: " << task_id_;
    env_observation_.Observe(aura::Env::GetInstance());
    window_initialization_timer_.Start(FROM_HERE, kWindowInitializationTimeout,
                                       this,
                                       &NearbyShareSessionImpl::OnTimerFired);
  }
}

NearbyShareSessionImpl::~NearbyShareSessionImpl() = default;

// static
void NearbyShareSessionImpl::DeleteShareCacheFilePaths(Profile* const profile) {
  DCHECK(profile);

  base::ThreadPool::PostTask(
      FROM_HERE, {base::MayBlock()},
      base::BindOnce(&DoDeleteShareCacheFilePaths, profile->GetPath(),
                     GetUserCacheFilePath(profile)));
}

void NearbyShareSessionImpl::OnNearbyShareClosed(
    views::Widget::ClosedReason reason) {
  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);

  DVLOG(1) << __func__;
  // If share is not continuing after sharesheet closes (e.g. cancel, esc key,
  // lost focus, etc.), we will clean up the current session including files.
  // Otherwise cleanup session object and wait for Nearby Share to cleanup cache
  // files when they are no longer needed for transfer.
  bool should_cleanup_files =
      reason != views::Widget::ClosedReason::kAcceptButtonClicked;
  CleanupSession(should_cleanup_files);
}

// Overridden from aura::EnvObserver:
void NearbyShareSessionImpl::OnWindowInitialized(aura::Window* const window) {
  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
  DCHECK(window);

  DVLOG(1) << __func__;
  if (!ash::IsArcWindow(window))
    return;

  absl::optional<int> maybe_id = arc::GetWindowTaskId(window);
  if (!maybe_id.has_value() || maybe_id.value() < 0 ||
      static_cast<uint32_t>(maybe_id.value()) != task_id_) {
    return;
  }
  env_observation_.Reset();
  arc_window_observation_.Observe(window);
}

// Overridden from aura::WindowObserver
void NearbyShareSessionImpl::OnWindowVisibilityChanged(
    aura::Window* const window,
    bool visible) {
  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);

  DVLOG(1) << __func__;
  absl::optional<int> task_id = arc::GetWindowTaskId(window);
  DCHECK(task_id.has_value());
  DCHECK_GE(task_id.value(), 0);
  if (visible && (base::checked_cast<uint32_t>(task_id.value()) == task_id_)) {
    VLOG(1) << "ARC Window is visible";
    if (window_initialization_timer_.IsRunning()) {
      window_initialization_timer_.Stop();
    }
    base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
        FROM_HERE, base::BindOnce(&NearbyShareSessionImpl::OnArcWindowFound,
                                  weak_ptr_factory_.GetWeakPtr(), window));
  }
}

void NearbyShareSessionImpl::OnArcWindowFound(aura::Window* const arc_window) {
  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
  DCHECK(arc_window);
  DCHECK(profile_);

  DVLOG(1) << __func__;
  arc_window_ = arc_window;
  if (share_info_->files.has_value() && !FileSharingThroughFuseBoxEnabled()) {
    // File sharing through temporary copy.
    const base::FilePath arc_nearby_share_directory =
        GetUserCacheFilePath(profile_);

    file_handler_ = base::MakeRefCounted<ShareInfoFileHandler>(
        profile_, share_info_.get(), arc_nearby_share_directory,
        backend_task_runner_);

    prepare_directory_task_ = std::make_unique<webshare::PrepareDirectoryTask>(
        arc_nearby_share_directory, file_handler_->GetTotalSizeOfFiles());
    prepare_directory_task_->StartWithCallback(
        base::BindOnce(&NearbyShareSessionImpl::OnPreparedDirectory,
                       weak_ptr_factory_.GetWeakPtr()));
  } else {
    // Sharing text, or file sharing through FuseBox.
    ShowNearbyShareBubbleInArcWindow();
  }
}

apps::IntentPtr NearbyShareSessionImpl::ConvertShareIntentInfoToIntent() {
  DCHECK(share_info_);

  DVLOG(1) << __func__;
  // Sharing files
  if (share_info_->files.has_value()) {
    if (FileSharingThroughFuseBoxEnabled()) {
      return ConvertShareIntentInfoToMonikerFileIntent();
    }
    const auto share_file_paths = file_handler_->GetFilePaths();
    DCHECK_GT(share_file_paths.size(), 0u);
    const auto share_file_mime_types = file_handler_->GetMimeTypes();
    const size_t expected_total_files = file_handler_->GetNumberOfFiles();
    DCHECK_GT(expected_total_files, 0u);

    if (share_file_paths.size() != expected_total_files) {
      LOG(ERROR)
          << "Actual number of files streamed does not match expected number: "
          << expected_total_files;
      return nullptr;
    }
    return apps_util::CreateShareIntentFromFiles(
        profile_, share_file_paths, share_file_mime_types, std::string(),
        share_info_->title);
  }

  // Sharing text
  if (share_info_->extras.has_value() &&
      share_info_->extras->contains(kIntentExtraText)) {
    apps::IntentPtr share_intent = apps_util::MakeShareIntent(
        share_info_->extras->at(kIntentExtraText), share_info_->title);
    share_intent->mime_type = share_info_->mime_type;
    return share_intent;
  }
  return nullptr;
}

apps::IntentPtr
NearbyShareSessionImpl::ConvertShareIntentInfoToMonikerFileIntent() {
  std::vector<std::string> mime_types;
  std::vector<GURL> file_paths;

  std::vector<apps::IntentFilePtr> files;
  for (const auto& file_info : *share_info_->files) {
    absl::optional<fusebox::Moniker> moniker =
        ConvertToMoniker(profile_, file_info->content_uri);
    if (!moniker.has_value()) {
      return nullptr;
    }
    GURL moniker_url = net::FilePathToFileURL(
        base::FilePath(fusebox::MonikerMap::GetFilename(moniker.value())));
    apps::IntentFilePtr file = std::make_unique<apps::IntentFile>(moniker_url);
    file->mime_type = file_info->mime_type;
    file->file_name = base::SafeBaseName::Create(file_info->name);
    files.push_back(std::move(file));
    shared_monikers_.push_back(moniker.value());
  }

  apps::IntentPtr intent = std::make_unique<apps::Intent>(
      files.size() == 1 ? apps_util::kIntentActionSend
                        : apps_util::kIntentActionSendMultiple);
  intent->files = std::move(files);
  intent->share_title = share_info_->title;

  return intent;
}

void NearbyShareSessionImpl::OnPreparedDirectory(base::File::Error result) {
  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
  DCHECK(arc_window_);
  DCHECK_GT(file_handler_->GetTotalSizeOfFiles(), 0u);

  DVLOG(1) << __func__;
  if (result == base::File::FILE_ERROR_NO_SPACE) {
    LOG(ERROR) << "Not enough disk space to proceed with sharing.";
    // Calculate required space and then show the LowDiskSpace Dialog
    backend_task_runner_->PostTaskAndReplyWithResult(
        FROM_HERE,
        base::BindOnce(&CalculateRequiredSpace,
                       file_handler_->GetShareDirectory(),
                       file_handler_->GetTotalSizeOfFiles()),
        base::BindOnce(&NearbyShareSessionImpl::OnShowLowDiskSpaceDialog,
                       weak_ptr_factory_.GetWeakPtr()));
    return;
  }

  // TODO(b/191232168): Figure out why PrepareDirectoryTask is flaky. Ignoring
  // the error seem to always work otherwise will sometimes return error.
  PLOG_IF(WARNING, result != base::File::FILE_OK)
      << "Prepare Directory was not successful";

  file_handler_->StartPreparingFiles(
      /*started_callback=*/base::BindOnce(
          &NearbyShareSessionImpl::OnFileStreamingStarted,
          weak_ptr_factory_.GetWeakPtr()),
      /*completed_callback=*/
      base::BindOnce(&NearbyShareSessionImpl::ShowNearbyShareBubbleInArcWindow,
                     weak_ptr_factory_.GetWeakPtr()),
      /*update_callback=*/
      base::BindRepeating(&NearbyShareSessionImpl::OnProgressBarUpdate,
                          weak_ptr_factory_.GetWeakPtr()));
}

void NearbyShareSessionImpl::OnNearbyShareBubbleShown(
    sharesheet::SharesheetResult result) {
  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);

  if (VLOG_IS_ON(1)) {
    switch (result) {
      case sharesheet::SharesheetResult::kSuccess:
        VLOG(1) << "OnNearbyShareBubbleShown: SUCCESS";
        break;
      case sharesheet::SharesheetResult::kCancel:
        VLOG(1) << "OnNearbyShareBubbleShown: CANCEL";
        break;
      case sharesheet::SharesheetResult::kErrorAlreadyOpen:
        VLOG(1) << "OnNearbyShareBubbleShown: ALREADY OPEN";
        break;
      default:
        VLOG(1) << "OnNearbyShareBubbleShown: UNKNOWN";
    }
  }
  if (result != sharesheet::SharesheetResult::kSuccess) {
    ShowErrorDialog();
  }
}

void NearbyShareSessionImpl::OnFileStreamingStarted() {
  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
  DCHECK(arc_window_);
  DCHECK(file_handler_);

  DVLOG(1) << __func__;
  // Only show the progress bar if total files size is greater than
  // |kShowProgressBarMinSizeInBytes|, otherwise minimize unnecessary
  // UI step as the file streaming time should be < 1 second.
  if (file_handler_->GetTotalSizeOfFiles() > kShowProgressBarMinSizeInBytes) {
    const bool is_multiple_files = file_handler_->GetNumberOfFiles() > 1;
    progress_bar_view_ =
        std::make_unique<ProgressBarDialogView>(is_multiple_files);
    ProgressBarDialogView::Show(arc_window_, progress_bar_view_.get());

    // Keep updating the progress bar if the interval timer elapsed to update
    // the user on the file streaming progress.
    progress_bar_update_timer_.Start(
        FROM_HERE, kProgressBarUpdateInterval, this,
        &NearbyShareSessionImpl::OnProgressBarIntervalElapsed);
  }
}

void NearbyShareSessionImpl::ShowNearbyShareBubbleInArcWindow(
    absl::optional<base::File::Error> result) {
  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
  DCHECK(arc_window_);

  DVLOG(1) << __func__;

  // If the progress bar is visible at this point, stop the update interval
  // timer so that we can show the Nearby Share bubble.
  if (progress_bar_update_timer_.IsRunning()) {
    progress_bar_update_timer_.Stop();
  }

  // Close any overlay and respective child views that may still be shown.
  progress_bar_view_.reset();
  NearbyShareOverlayView::CloseOverlayOn(arc_window_);

  // Only applicable if sharing files.
  if (result.has_value() && result.value() != base::File::FILE_OK) {
    LOG(ERROR) << "Failed to complete file streaming with error: "
               << base::File::ErrorToString(result.value());
    UpdateNearbyShareFileStreamError(result.value());
    ShowErrorDialog();
    return;
  }

  auto intent = ConvertShareIntentInfoToIntent();

  if (!intent) {
    LOG(ERROR) << "No share info found.";
    ShowErrorDialog();
    return;
  }

  sharesheet::SharesheetService* sharesheet_service =
      sharesheet::SharesheetServiceFactory::GetForProfile(profile_);
  if (!sharesheet_service) {
    LOG(ERROR) << "Cannot find sharesheet service.";
    ShowErrorDialog();
    return;
  }

  base::FilePath share_path;
  if (file_handler_) {
    share_path = file_handler_->GetShareDirectory();
  }

  sharesheet::DeliveredCallback delivered_callback =
      base::BindOnce(&NearbyShareSessionImpl::OnNearbyShareBubbleShown,
                     weak_ptr_factory_.GetWeakPtr());
  sharesheet::CloseCallback close_callback =
      base::BindOnce(&NearbyShareSessionImpl::OnNearbyShareClosed,
                     weak_ptr_factory_.GetWeakPtr());
  sharesheet::ActionCleanupCallback cleanup_callback = base::BindOnce(
      &DeleteFilesAndMonikers, share_path, std::move(shared_monikers_));

  if (test_sharesheet_callback_) {
    test_sharesheet_callback_.Run(arc_window_, std::move(intent),
                                  sharesheet::LaunchSource::kArcNearbyShare,
                                  std::move(delivered_callback),
                                  std::move(close_callback),
                                  std::move(cleanup_callback));
    return;
  }

  sharesheet_service->ShowNearbyShareBubbleForArc(
      arc_window_, std::move(intent), sharesheet::LaunchSource::kArcNearbyShare,
      std::move(delivered_callback), std::move(close_callback),
      std::move(cleanup_callback));
}

void NearbyShareSessionImpl::OnTimerFired() {
  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);

  // TODO(b/191232397): Handle error case.
  LOG(ERROR) << "ARC window didn't get initialized within "
             << kWindowInitializationTimeout.InSeconds() << " second(s)";
  UpdateNearbyShareWindowFound(false);
  CleanupSession(/*should_cleanup_files=*/true);
}

void NearbyShareSessionImpl::OnProgressBarIntervalElapsed() {
  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);

  DVLOG(1) << __func__;
  if (progress_bar_view_) {
    progress_bar_view_->UpdateInterpolatedProgressBarValue();
  }
}

void NearbyShareSessionImpl::OnProgressBarUpdate(double value) {
  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);

  DVLOG(1) << "OnProgressBarUpdate with value: " << value;
  if (progress_bar_view_) {
    // Only show value if there is forward progress.
    if (value > progress_bar_view_->GetProgressBarValue()) {
      progress_bar_view_->UpdateProgressBarValue(value);
    }
  }
}

void NearbyShareSessionImpl::CleanupSession(bool should_cleanup_files) {
  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);

  DVLOG(1) << __func__;
  if (should_cleanup_files) {
    DestroySharedMonikers(shared_monikers_);
  }

  // PrepareDirectoryTask must first relinquish ownership of |share_path|.
  prepare_directory_task_.reset();
  if (file_handler_) {
    base::FilePath share_path = file_handler_->GetShareDirectory();
    // Delete any file descriptor handles for files that were created during
    // the session and owned by |file_handler_|. Even if handles are released,
    // the physical files remain until DeletePathAndFiles is called.
    file_handler_.reset();
    if (should_cleanup_files) {
      VLOG(1) << "Deleting session files including base path: " << share_path;
      // Delete any files and the top level share directory with the same
      // |backend_task_runner_| that is used for all file IO operations.
      // Make sure |session_finished_callback_| is not run until the
      // |backend_task_runner_| is no longer in use.
      backend_task_runner_->PostTaskAndReply(
          FROM_HERE, base::BindOnce(&DeletePathAndFiles, share_path),
          base::BindOnce(&NearbyShareSessionImpl::FinishSession,
                         weak_ptr_factory_.GetWeakPtr()));
      return;
    }
  }
  FinishSession();
}

void NearbyShareSessionImpl::ShowErrorDialog() {
  DCHECK(arc_window_);

  DVLOG(1) << __func__;
  ErrorDialogView::Show(arc_window_,
                        base::BindOnce(&NearbyShareSessionImpl::CleanupSession,
                                       weak_ptr_factory_.GetWeakPtr(),
                                       /*should_cleanup_files=*/true));
}

void NearbyShareSessionImpl::FinishSession() {
  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
  DCHECK(session_instance_);

  DVLOG(1) << __func__;
  // Stop timers and destroy any lingering UI surfaces or observers.
  arc_window_observation_.Reset();
  env_observation_.Reset();
  if (window_initialization_timer_.IsRunning()) {
    window_initialization_timer_.Stop();
  }
  if (progress_bar_update_timer_.IsRunning()) {
    progress_bar_update_timer_.Stop();
  }
  progress_bar_view_.reset();
  aura::Window* const arc_window = GetArcWindow(task_id_);
  if (arc_window) {
    NearbyShareOverlayView::CloseOverlayOn(arc_window);
  }

  // Cleanup the session on Android side.
  session_instance_->OnNearbyShareViewClosed();
  // Delete the session object by task ID from the ArcNearbyShareBridge map.
  if (session_finished_callback_) {
    VLOG(1) << "Deleting session with task ID: " << task_id_;
    std::move(session_finished_callback_).Run(task_id_);
  }
}

void NearbyShareSessionImpl::OnShowLowDiskSpaceDialog(
    int64_t required_disk_space) {
  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
  DCHECK_GT(required_disk_space, 0);

  DVLOG(1) << "OnCalculateRequiredSpace required_disk_space: "
           << required_disk_space;
  LowDiskSpaceDialogView::Show(
      arc_window_, file_handler_->GetNumberOfFiles(), required_disk_space,
      base::BindOnce(&NearbyShareSessionImpl::OnLowStorageDialogClosed,
                     weak_ptr_factory_.GetWeakPtr()));
}

void NearbyShareSessionImpl::OnLowStorageDialogClosed(
    bool should_open_storage_settings) {
  if (should_open_storage_settings) {
    chrome::SettingsWindowManager::GetInstance()->ShowOSSettings(
        profile_, chromeos::settings::mojom::kStorageSubpagePath);
  }
  CleanupSession(/*should_cleanup_files=*/true);
}

}  // namespace arc


text:
@interface AppleMapsLinkBuilder : NSObject <MapLinkBuilder>

@end


text:
<?php

/**
 * SystemJob store for table: system_job */

namespace Octo\System\Store;

use b8\Database\Query;
use b8\Database;
use Octo;

/**
 * SystemJob Store
 */
class SystemJobStore extends Base\SystemJobStoreBase
{
	public function getNextJob()
    {
        $query = new Query('\Octo\System\Model\SystemJob');
        $query->select('*')->from('system_job')->order('run_date', 'ASC')->limit(1);

        if ($query->execute()) {
            $job = $query->fetch();

            if ($job->getRunDate() <= new \DateTime()) {
                return $job;
            }
        }

        return null;
    }
}


text:
using System.Linq;
using Raven.Client.Indexes;
using Triage.Api.Domain.Messages;
using Triage.Api.Domain.Messages.Aggregates;
using Triage.Persistence.Context;

namespace Triage.Persistence.Indexes
{
    public interface IErrorMessagesBySourceIndex : IDbIndex
    {
    }

    public class ErrorMessagesBySourceIndex : AbstractIndexCreationTask<ErrorMessage, ErrorMessagesBySource>, IErrorMessagesBySourceIndex
    {
        public override string IndexName { get { return Persistence.Indexes.IndexName.ErrorMessagesBySouce.ToString(); } }

        public ErrorMessagesBySourceIndex()
        {

            Map = docs => from doc in docs
                .Where(message => message.Type == MessageType.Error)
                select new
                {
                    LastestErrorId = doc.Id,
                    doc.Title,
                    doc.StackTrace,
                    Date = doc.Date.Date,
                    Hour = doc.Date.Hour,
                    Count = 1
                };

            Reduce = results => from result in results
                group result by new
                {
                    result.StackTrace,
                    result.Date,
                    result.Hour
                }
                into agg
                let lastError = agg.Last()
                select new
                {
                    lastError.LastestErrorId,
                    lastError.Title,
                    agg.Key.StackTrace,
                    agg.Key.Date,
                    agg.Key.Hour,
                    Count = agg.Sum(x => x.Count)
                };
        }
    }

}


text:
var parseopts = {};

/**
 * @constructor
 * Parses a list of command-line args into a key/value object of
 * options and an array of positional commands.
 *
 * @param {Array} opts A list of options
 *
 * Examples:
 *  [
 *    { full: 'foo'
 *    , abbr: 'f'
 *    , args: true
 *    , canon: 'foo'
 *    }
 *  , { full: 'bar'
 *    , abbr: ['b', 'x']
 *    , args: false
 *    , canon: 'bar'
 *  }
 * ]
 */
parseopts.Parser = function (opts) {
  var self = this
    , key
    , value;

  this.cmds = []; // Positional commands parsed from args
  this.opts = {}; // A key/value object of matching options parsed from args

  // Data structures used for parsing
  this.reg = [];
  this.canonicalOpts = {};
  this.shortOpts = {};
  this.longOpts = {};

  opts.forEach(function (value) {
    // Create the canonical
    self.canonicalOpts[value.canon] = {
      canon: value.canon
    , args: value.args
    };
    // Create short and long aliases that all point to the same canonical
    ['full', 'abbr'].forEach(function (k) {
      var v = value[k]
        , keyType = k == 'full' ?
              'longOpts' : 'shortOpts';
      v = Array.isArray(v) ? v : [v]; // Handle single vals or arrays of them
      v.forEach(function (o) {
        self[keyType][o] = self.canonicalOpts[value.canon];
      });
    });
  });

  this.reg = opts;
};

parseopts.Parser.prototype = new function () {

  /**
   * Parses an array of arguments into options and positional commands
   * Any matcthing opts end up in a key/value object keyed by the 'canon'
   * name of the option. Any args that aren't passed as options end up in
   * an array of positional commands.
   * Any options passed without a value end up with a value of null
   * in the key/value object of options
   * If the user passes options that are not defined in the list passed
   * to the constructor, they will be silently ignored
   * @param {Array} args The command-line args to parse
   */
  this.parse = function (args) {
    var cmds = []
      , opts = {}
      , arg
      , argObj
      , canonArgName
      , argItems;

    while (args.length) {
      arg = args.shift();

      // Full option name
      if (arg.indexOf('--') === 0) {
        argItems = arg.split('=');
        argObj = this.longOpts[argItems[0].substr(2)];

        if (argObj) {
          // Args included a space instead of usual = value
          if (argItems.length === 1) {
            canonArgName = argObj.canon;

            if (!argObj.args) {
              opts[canonArgName] = true;
            } else {
              // If no argument is given for this option then set it's value to true
              if(!args[0] || (args[0].indexOf('-') == 0) || (args[0].indexOf('--') == 0)) {
                opts[canonArgName] = true;
              } else {
                opts[canonArgName] = args.shift();
              }
            }
          }
          else {
            canonArgName = argObj.canon;

            // If the opt doesn't take args then set value to true
            if (!argObj.args) {
              opts[canonArgName] = true;
            } else {
              opts[canonArgName] = argItems[1] || true;
            }
          }
        }
        else {
          // Silently ignore unknown options
        }
      }
      // Short option name
      else if (arg.indexOf('-') === 0) {
        // Get arg from list of options
        argObj = this.shortOpts[arg.substr(1)];

        // If argument exists
        if (argObj) {
          canonArgName = argObj.canon; // Get canon name

          // If the option doesn't rake arguments then set value to true
          if(!argObj.args) {
            opts[canonArgName] = true;
          } else {
            // If no argument is given for this option then set it's value to true
            if(!args[0] || (args[0].indexOf('-') == 0) || (args[0].indexOf('--') == 0)) {
              opts[canonArgName] = true;
            } else {
              opts[canonArgName] = args.shift();
            }
          }
        } else throw new Error('Unknown option "' + arg + '"');
      }
      // Assume command name
      else cmds.push(arg);
    }

    this.cmds = cmds;
    this.opts = opts;
  };

};

module.exports = parseopts;


text:
template<typename BUDom, typename TDDom>
extern void inter_run (crab::cg_impl::z_cg_t* cg,
		       bool run_liveness,
		       unsigned widening,
		       unsigned narrowing,
		       unsigned jump_set_size,
		       bool enable_stats);

#endif


text:
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>system_error</title>
<link rel="stylesheet" href="../../boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.75.2">
<link rel="home" href="../../index.html" title="Asio">
<link rel="up" href="../reference.html" title="Reference">
<link rel="prev" href="system_category.html" title="system_category">
<link rel="next" href="system_error/code.html" title="system_error::code">

system_error

        The system_error
        class is used to represent system conditions that prevent the library from
        operating correctly.

class system_error :
  public std::exception

        Member
        Functions

<colgroup>
<col>
<col>
</colgroup>

                  Name

                  Description

                  code

                  Get the error code associated with the exception.

                  operator=

                  Assignment operator.

                  system_error

                  Construct with an error code.

                  Construct with an error code and context.

                  Copy constructor.

                  what

                  Get a string representation of the exception.

                  ~system_error

                  Destructor.

        Requirements

        Header: asio/system_error.hpp

        Convenience header: asio.hpp

Copyright © 2003-2013 Christopher M. Kohlhoff

        Distributed under the Boost Software License, Version 1.0. (See accompanying
        file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)


text:
<!doctype html>
<html lang="en" ng-app="myApp">
	<head>
		<meta charset="utf-8">
		<title>RestMS v.03</title>
		<link href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet">
		<link rel="stylesheet/less" href="less/style.less" />
		<script src="js/less/less-1.5.0.min.js"></script>
	</head>
	<body>
		<div ng-view></div>
		<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.4/angular.min.js"></script>
		<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.4/angular-route.min.js"></script>
		<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.4/angular-resource.min.js"></script>
		<script src="js/app.js"></script>
		<script src="js/services.js"></script>
		<script src="js/controllers.js"></script>
		<script src="js/filters.js"></script>
		<script src="js/directives.js"></script>
		<script src="js/ui/ui-bootstrap-tpls-0.6.0-SNAPSHOT.min.js"></script>
		<script src="js/angular-file-upload/angular-file-upload.min.js"></script>
	</body>
</html>