text:
var currentTab;

var insertListAtCursor = function (myField, myValue, number) {
  if (myField[0].selectionStart || myField[0].selectionStart == '0') {
    var startPos = myField[0].selectionStart;
    var endPos = myField[0].selectionEnd;
    var selection;
    var value;
    if (endPos > startPos) {
      selection = myField.val().substring(startPos, endPos);
    }
    var insertvalue = "";
    if (selection) {
      var lines = selection.split('\n');
      for (var i = 0; i < lines.length; i++) {
        if (number == 'numbered') {
          insertvalue += (i + 1) + ".";
        }
        else if (number == 'bulleted') {
          insertvalue += "-";
        }
        else if (number == 'blockquote') {
          insertvalue += "> ";
        }
        insertvalue += " " + lines[i];
        if (i < lines.length) {
          insertvalue += "\n";
        }
      }
      value = myField.val().substring(0, startPos) + insertvalue + myField.val().substring(endPos, myField.val().length);
      myField.val(value);
      myField[0].selectionEnd = myField.selectionStart = startPos + insertvalue.length;
      return;
    }
  }

  var lines = myValue.split('\n');
  for (var i = 0; i < lines.length; i++) {
    if (number == 'numbered') {
      insertvalue += (i + 1) + ".";
    }
    else if (number == 'bulleted') {
      insertvalue += "-";
    }
    else if (number == 'blockquote') {
      insertvalue += ">";
    }
    insertvalue += " " + lines[i];
    if (i < lines.length) {
      insertvalue += "\n";
    }
  }
  value = myField.val() + '\n' + insertvalue;
  myField.val(value);
};

var insertSourcecodeAtCursor = function (myField) {
  if (myField[0].selectionStart || myField[0].selectionStart == '0') {
    var startPos = myField[0].selectionStart;
    var endPos = myField[0].selectionEnd;
    var selection;
    var value;
    if (endPos > startPos) {
      selection = myField.val().substring(startPos, endPos);
    }
    var insertvalue = "```\n";
    if (selection) {
      insertvalue += selection + '\n```';
    }
    else {
      insertvalue += 'code text' + '\n```\n';
    }
    value = myField.val().substring(0, startPos) + insertvalue + myField.val().substring(endPos, myField.val().length);
    myField.val(value);
    myField[0].selectionEnd = myField.selectionStart = startPos + insertvalue.length;
    return;
  }
  var insertvalue = "```\n";
  insertvalue += 'code text' + '\n```\n';
  value = myField.val() + '\n' + insertvalue;
  myField.val(value);
};

var datasetCommentsComponent = null;
var insertAtCursor = function (myField, myValue, newline) {
  if (myField[0].selectionStart || myField[0].selectionStart == '0') {
    var startPos = myField[0].selectionStart;
    var endPos = myField[0].selectionEnd;
    var value;
    if (newline) {
      value = myField.val().substring(0, startPos) + '\n' +
          myValue + myField.val().substring(endPos, myField.val().length);
    }
    else {
      value = myField.val().substring(0, startPos) +
          myValue + myField.val().substring(endPos, myField.val().length);
    }

    myField.val(value);
    myField[0].selectionEnd = myField.selectionStart = startPos + myValue.length;
  } else {
    var value;
    if (newline) {
      value = myField.val() + '\n' + myValue;
    }
    else {
      value = myField.val() + myValue;
    }

    myField.val(value);
  }
};

var insertImageAtCursor = function (myField, param) {
  if (myField[0].selectionStart || myField[0].selectionStart == '0') {
    var startPos = myField[0].selectionStart;
    var endPos = myField[0].selectionEnd;
    var selection;
    var value;
    if (endPos > startPos) {
      selection = myField.val().substring(startPos, endPos);
    }
    var insertvalue = "";
    if (selection && selection.length > 0 &&
        (selection.substr(0, 7) == 'http://' || selection.substr(0, 7) == 'https:/')) {
      if (param == 'image') {
        insertvalue = "[alt text](" + selection + ")";
      }
      else {
        insertvalue = "[" + selection + "](" + selection + ")";
      }

    }
    else {
      if (param == 'image') {
        insertvalue = "![alt text](http://path/to/img.jpg)";
      }
      else {
        insertvalue = "[example link](http://example.com/)";
      }

    }
    value = myField.val().substring(0, startPos) + insertvalue + myField.val().substring(endPos, myField.val().length);
    myField.val(value);
    myField[0].selectionEnd = myField.selectionStart = startPos + insertvalue.length;
    return;
  }
  if (param == 'image') {
    insertvalue = "![alt text](http://path/to/img.jpg)";
  }
  else {
    insertvalue = "[example link](http://example.com/)";
  }
  value = myField.val() + '\n' + insertvalue;
  myField.val(value);
};

var updatePreview = function () {
  var text = $("#datasetSchemaComment-write > textarea").val()
  $("#datasetSchemaComment-preview").html(marked(text))
}
var g;
var svg;
var l;

function initializeColumnTreeGrid() {
  $('#json-table').treegrid();
}
function initializeDependsTreeGrid() {
  $('#depends-table').treegrid();
}

function initializeReferencesTreeGrid() {
  $('#references-table').treegrid();
}

function formatValue(key, value) {
  switch (key) {
    case 'modification_time':
    case 'begin_date':
    case 'lumos_process_time':
    case 'end_date':
    case 'oracle_time':
      if (value < 0)
        return value
      var obj = value;
      try {
        obj = new Date(value).toISOString();
      }
      catch (err) {
        console.log("Invalid date for " + key + " : " + value);
      }
      return obj;
      break;
    case 'dumpdate':
      var y = value.substring(0, 4)
      var mm = value.substring(4, 6)
      var d = value.substring(6, 8)
      var h = value.substring(8, 10)
      var m = value.substring(10, 12)
      var s = value.substring(12, 14)
      return y + '-' + mm + '-' + d + ' ' + h + ':' + m + ':' + s
      break;
    default:
      return value;
  }
}

function convertPropertiesToArray(properties) {
  var propertyArray = [];
  if (properties) {
    for (var key in properties) {
      if ((key.toLowerCase() != 'elements') && (key.toLowerCase() != 'view_depends_on')) {
        var isSelectController = false;
        if (key.toLowerCase() == 'view_expanded_text' || key.toLowerCase() == 'viewSqlText') {
          isSelectController = true;
        }
        else {
          isSelectController = false;
        }
        if (typeof properties[key] !== 'object') {
          if (key == 'connectionURL' && properties[key]) {
            var list = properties[key].split(',');
            if (list && list.length > 0) {
              propertyArray.push({
                'isSelectController': isSelectController,
                'key': key, 'value': JsonHuman.format(list)
              });
            }
            else {
              propertyArray.push({
                'isSelectController': isSelectController,
                'key': key, 'value': properties[key]
              });
            }
          }
          else {
            var value = formatValue(key, properties[key]);
            if (!value && !(value === 0))
              value = 'NULL';
            propertyArray.push({
              'isSelectController': isSelectController,
              'key': key, 'value': value
            });
          }
        }
        else {
          propertyArray.push({
            'isSelectController': isSelectController,
            'key': key, 'value': JsonHuman.format(properties[key])
          });
        }

      }
    }
  }
  return propertyArray;
}
var datasetController = null;
var flowsController = null;
var metricsController = null;

var update = function (param) {
  if (param && param.name) {
    var name = param.name;
    var val = param.value;
    var metricId = param.pk;
    var url = '/api/v1/metrics/' + metricId + '/update';
    var method = 'POST';
    var token = $("#csrfToken").val().replace('/', '');
    var data = {"csrfToken": token};
    data[name] = val;
    $.ajax({
      url: url,
      method: method,
      headers: {
        'Csrf-Token': token
      },
      dataType: 'json',
      data: data
    }).done(function (data, txt, xhr) {
      if (data && data.status && data.status == "success") {
        console.log('Done.')
      }
      else {
        console.log('Failed.')
      }
    }).fail(function (xhr, txt, err) {
      Notify.toast("Failed to update data", "Metric Update Failure", "error")
    })
  }

}
function initializeXEditable(id,
                             description,
                             dashboardName,
                             sourceType,
                             grain,
                             displayFactor,
                             displayFactorSym) {
  $.fn.editable.defaults.mode = 'inline';

  //below code is a walk around for xeditable and ember integration issue

  $('.xeditable').editable("disable");
  $('.xeditable').editable("destroy");

  $('#metricdesc').text(description);
  $('#metricdesc').editable({
    pk: id,
    value: description,
    url: update
  });

  $('#dashboardname').text(dashboardName);
  $('#dashboardname').editable({
    pk: id,
    value: dashboardName,
    url: update
  });

  $('#sourcetype').text(sourceType);
  $('#sourcetype').editable({
    pk: id,
    value: sourceType,
    url: update
  });

  $('#metricgrain').text(grain);
  $('#metricgrain').editable({
    pk: id,
    value: grain,
    url: update
  });

  $('#displayfactor').text(displayFactor);
  $('#displayfactor').editable({
    pk: id,
    value: displayFactor,
    url: update
  });

  $('#displayfactorsym').text(displayFactorSym);
  $('#displayfactorsym').editable({
    pk: id,
    value: displayFactorSym,
    url: update
  });
}
function updateActiveTab() {
  var obj = $("#mainnavbar .nav").find(".active");
  if (obj && obj.length > 0) {
    var text = obj[0].innerText;
    if (text && text.indexOf(currentTab) != -1) {
      return;
    }
  }
  if (obj) {
    obj.removeClass("active");
  }

  if (currentTab == 'Metrics') {
    $('#menutabs a:eq(1)').tab("show");
    $('#metriclink').addClass("active");

  }
  else if (currentTab == 'Flows') {
    $('#menutabs a:last').tab("show");
    $('#flowlink').addClass("active");
  }
  else {
    $('#menutabs a:first').tab("show");
    $('#datasetlink').addClass("active");
  }
}

var scrollToTreeNode = function () {
  $("#tabSplitter").scrollTo($('.fancytree-focused'), 800)
}
function highlightResults(result, index, keyword) {
  var content = result[index].schema;
  if (keyword)
    keyword = keyword.replace("+", "").replace("-", "");
  var query = new RegExp("(" + keyword + ")", "gim");
  var i = content.indexOf(keyword);
  var len = content.length;
  if (len > 500) {
    if ((len - i) < 500) {
      content = content.substring((len - 500), len);
    }
    else {
      content = content.substring(i, 500 + i);
    }
  }
  var newContent = content.replace(query, "$1");
  result[index].schema = newContent;
  var urn = result[index].urn;
  if (urn) {
    var newUrn = urn.replace(query, "$1");
    result[index].urn = newUrn;
  }
};

var genBreadcrumbs = function(urn) {
  var breadcrumbs = []
  var b = urn.split('/')
  b.shift();
  for(var i = 0; i < b.length; i++) {
    var updatedUrn = "/metadata/dashboard/" + b[i]
    if(i === 0)
    {

      breadcrumbs.push({title: b[i], urn: updatedUrn})
    }
    else
    {
      breadcrumbs.push({title: b[i], urn: updatedUrn})
    }
  }
  return breadcrumbs
}


text:
package org.spongepowered.asm.mixin;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import org.spongepowered.asm.mixin.gen.Accessor;

/**
 * Use in conjunction with {@link Final} or {@link Accessor} to indicate that
 * whilst a target field is final in the target class, mutation within the mixin
 * is intentional.
 *
 *
Applying this annotation has the effect of removing the <tt>final</tt>
 * modifier from the target field in order to avoid illegal access errors when a
 * shadow visible outside the mixin class (eg. to derived or package-local
 * mixins) is mutated. It also permits the mutation on Java runtimes which also
 * check for mutation of <tt>private</tt> final variables (JRE 9 and later).

 */
@Target({ ElementType.METHOD, ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
public @interface Mutable {

}

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class Error : PageBase
{
    #region Constructor

    public Error()
    {
        // wire page events
        this.Init += new EventHandler(Error_Init);
    }

    #endregion

    #region Events

    protected void Error_Init(object sender, EventArgs e)
    {
        Title = "Error - Regex Storm";
    }

    #endregion
}


text:
package org.apache.druid.query.dimension;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.base.Preconditions;
import org.apache.druid.common.config.NullHandling;
import org.apache.druid.java.util.common.StringUtils;
import org.apache.druid.query.filter.DimFilterUtils;
import org.apache.druid.segment.DimensionSelector;
import org.apache.druid.segment.IdMapping;

import java.nio.ByteBuffer;
import java.util.regex.Pattern;

/**
 *
 */
public class RegexFilteredDimensionSpec extends BaseFilteredDimensionSpec
{

  private static final byte CACHE_TYPE_ID = 0x2;

  private final String pattern;

  private final Pattern compiledRegex;

  public RegexFilteredDimensionSpec(
      @JsonProperty("delegate") DimensionSpec delegate,
      @JsonProperty("pattern") String pattern //rows not matching the pattern will be discarded
  )
  {
    super(delegate);
    this.pattern = Preconditions.checkNotNull(pattern, "pattern must not be null");
    this.compiledRegex = Pattern.compile(pattern);
  }

  @JsonProperty
  public String getPattern()
  {
    return pattern;
  }

  @Override
  public DimensionSelector decorate(final DimensionSelector selector)
  {
    if (selector == null) {
      return null;
    }

    final int selectorCardinality = selector.getValueCardinality();
    if (selectorCardinality < 0 || !selector.nameLookupPossibleInAdvance()) {
      return new PredicateFilteredDimensionSelector(
          selector,
          input -> {
            String val = NullHandling.nullToEmptyIfNeeded(input);
            return val != null && compiledRegex.matcher(val).matches();
          }
      );
    }

    final IdMapping.Builder builder = IdMapping.Builder.ofUnknownCardinality();
    for (int i = 0; i < selectorCardinality; i++) {
      String val = NullHandling.nullToEmptyIfNeeded(selector.lookupName(i));
      if (val != null && compiledRegex.matcher(val).matches()) {
        builder.addForwardMapping(i);
      }
    }

    return new ForwardingFilteredDimensionSelector(selector, builder.build());
  }

  @Override
  public byte[] getCacheKey()
  {
    byte[] delegateCacheKey = delegate.getCacheKey();
    byte[] regexBytes = StringUtils.toUtf8(pattern);
    return ByteBuffer.allocate(2 + delegateCacheKey.length + regexBytes.length)
                     .put(CACHE_TYPE_ID)
                     .put(delegateCacheKey)
                     .put(DimFilterUtils.STRING_SEPARATOR)
                     .put(regexBytes)
                     .array();
  }

  @Override
  public DimensionSpec withDimension(String newDimension)
  {
    return new RegexFilteredDimensionSpec(delegate.withDimension(newDimension), pattern);
  }

  @Override
  public boolean equals(Object o)
  {
    if (this == o) {
      return true;
    }
    if (o == null || getClass() != o.getClass()) {
      return false;
    }

    RegexFilteredDimensionSpec that = (RegexFilteredDimensionSpec) o;

    if (!delegate.equals(that.delegate)) {
      return false;
    }
    return pattern.equals(that.pattern);
  }

  @Override
  public int hashCode()
  {
    int result = delegate.hashCode();
    result = 31 * result + pattern.hashCode();
    return result;
  }

  @Override
  public String toString()
  {
    return "RegexFilteredDimensionSpec{" +
           "pattern='" + pattern + '\'' +
           '}';
  }
}


text:
@interface StringPlaceholderViewController ()

@end

@implementation StringPlaceholderViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];

//    _tableView.placeHolderContent = @"No.";
    _tableView.indicatorViewEnabled = YES;
}
@end


text:
class OFFS
  class FeatureDisabled < RuntimeError; end
  class UndefinedFlagError < RuntimeError; end
  class AlreadyInitializedError < StandardError; end
end


text:
package com.github.keaume.amigo.fragment;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.app.Fragment;

import com.github.keaume.amigo.AmigoApplication;
import com.github.keaume.amigo.service.AbstractObdService;
import com.github.keaume.amigo.service.BluetoothObdService;
import com.github.keaume.amigo.service.ObdDataRecordingService;
import timber.log.Timber;

public class ServiceConnectionFragment extends Fragment {

    private Context applicationContext;

    private AbstractObdService obdConnectionService;
    private final ServiceConnection obdConnectionServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName className, IBinder binder) {
            Timber.d(className.toString(), " service is bound");
            obdConnectionService = ((AbstractObdService.AbstractObdServiceBinder) binder).getService();
            if (AmigoApplication.getPreferenceBoolean(SettingsFragment.CONNECT_ON_STARTUP_KEY, false)) {
                obdConnectionService.startObdConnection();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName className) {
            Timber.d(className.toString(), " service is unbound");
            obdConnectionService = null;
        }
    };

    private ObdDataRecordingService obdDataRecordingService;
    private final ServiceConnection obdDataRecordingServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName className, IBinder binder) {
            Timber.d(className.toString(), " service is bound");
            obdDataRecordingService = ((ObdDataRecordingService.ObdDataRecordingServiceBinder) binder).getService();
            obdDataRecordingService.setIsObdConnectionActive(isObdConnectionActive());
        }

        @Override
        public void onServiceDisconnected(ComponentName className) {
            Timber.d(className.toString(), " service is unbound");
            obdDataRecordingService = null;
            bindObdDataRecordingService();
        }
    };

    @Override
    public void onAttach(Context context) {
        Timber.d("onAttach called");
        super.onAttach(context);
        if (applicationContext == null) {
            applicationContext = context.getApplicationContext();
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        Timber.d("onCreate called");
        super.onCreate(savedInstanceState);
        setRetainInstance(true);
        bindObdConnectionService();
        bindObdDataRecordingService();
    }

    @Override
    public void onDestroy() {
        Timber.d("onDestroy called");
        super.onDestroy();
        if (obdDataRecordingService != null) {
            unbindObdDataRecordingService();
        }
        if (obdConnectionService != null) {
            unbindObdConnectionService();
        }
    }

    public void startObdConnection() {
        if (obdConnectionService != null) {
            obdConnectionService.startObdConnection();
        }
    }

    public void stopObdConnection() {
        if (obdConnectionService != null) {
            obdConnectionService.stopObdConnection(false);
        }
    }

    public boolean isObdConnectionActive() {
        return obdConnectionService != null && obdConnectionService.isConnectionActive();
    }

    public long getCurrentSessionId() {
        if (obdConnectionService != null) {
            return obdConnectionService.getCurrentSessionId();
        } else {
            return 0L;
        }
    }

    public String getCurrentVin() {
        if (obdConnectionService != null) {
            return obdConnectionService.getCurrentVIN();
        } else {
            return "";
        }
    }

    private void bindObdConnectionService() {
        if (obdConnectionService == null) {
            Timber.d("Binding OBD connection service");

            Intent obdConnectionServiceIntent;
            // String selectedInterfaceType = sharedPrefs.getString(SettingsFragment.OBD_INTERFACE_TYPE_KEY, getString(R.string.interface_type_preference_default));

            // For now only BT interfaces, USB maybe in the future
            // if (selectedInterfaceType == getString(R.string.interface_type_preference_default)) {
            //     obdConnectionServiceIntent = new Intent(this, BluetoothObdService.class);
            // } else if (...) {
            //     ...
            // }

            // Use me for local testing...
            //obdConnectionServiceIntent = new Intent(this, MockObdService.class);

            obdConnectionServiceIntent = new Intent(applicationContext, BluetoothObdService.class);
            applicationContext.bindService(obdConnectionServiceIntent, obdConnectionServiceConnection, Context.BIND_AUTO_CREATE);
        }
    }

    private void unbindObdConnectionService() {
        if (obdConnectionService != null) {
            Timber.d("Unbinding OBD connection service");
            applicationContext.unbindService(obdConnectionServiceConnection);
            obdConnectionService = null;
        }
    }

    private void bindObdDataRecordingService() {
        if (obdDataRecordingService == null) {
            Timber.d("Binding OBD data recording service");
            Intent obdDataRecordingServiceIntent;
            obdDataRecordingServiceIntent = new Intent(applicationContext, ObdDataRecordingService.class);
            applicationContext.bindService(obdDataRecordingServiceIntent, obdDataRecordingServiceConnection, Context.BIND_AUTO_CREATE);
        }
    }

    private void unbindObdDataRecordingService() {
        if (obdDataRecordingService != null) {
            Timber.d("Unbinding OBD data recording service");
            applicationContext.getApplicationContext().unbindService(obdDataRecordingServiceConnection);
            obdDataRecordingService = null;
        }
    }
}


text:
Run with:
```bash
node eg/spark-io-blink.js
```

```javascript
var five = require("johnny-five");
var Spark = require("spark-io");

var board = new five.Board({
  io: new Spark({
    token: process.env.SPARK_TOKEN,
    deviceId: process.env.SPARK_DEVICE_ID
  })
});

board.on("ready", function() {
  var pin = "A7";
  var led = new five.Led(pin);

  led.strobe(500);

  // this.repl.inject({
  //   led: led
  // });
});

```

## License
Copyright (c) 2012-2013 Rick Waldron <waldron.rick@gmail.com>
Licensed under the MIT license.
Copyright (c) 2014 The Johnny-Five Contributors
Licensed under the MIT license.


text:
using namespace std;
using namespace lomse;
using namespace UnitTest;

const char* basefilename(const char* fullfilename)
{
    const char* onlyFilenamePosix = strrchr(fullfilename, '/');
    const char* onlyFilenameWin = strrchr(fullfilename, '\\');
    const char* basename = std::max(onlyFilenamePosix, onlyFilenameWin) + 1;
    return basename;
}

class MyTestReporterStdout : public UnitTest::TestReporterStdout
{
public:
    MyTestReporterStdout(bool verbose) : m_verbose(verbose) {}

    void ReportTestStart(TestDetails const& test) override
    {
        if (m_verbose)
        {
            printf("%s / %s / %s\n", basefilename(test.filename), test.suiteName, test.testName);
        }
    }

    void ReportFailure(TestDetails const& test, char const* failure) override
    {
        if (m_verbose)
        {
            printf("    Failure at line %d: %s\n", test.lineNumber, failure);
        }
        else
        {
            printf("%s(%d): Failure in %s / %s: %s\n",
                basefilename(test.filename), test.lineNumber, test.suiteName, test.testName, failure);
        }
    }

    void ReportSummary(int totalTestCount, int failedTestCount,
        int failureCount, float secondsElapsed) override
    {
        if (failureCount > 0)
            printf("\nFailure: %d out of %d tests failed (%d failures).\n", failedTestCount, totalTestCount, failureCount);
        else
            printf("\nSuccess: %d tests passed.\n", totalTestCount);

        printf("Test time: %.2f seconds.\n", secondsElapsed);
    }

private:
    bool m_verbose;
    string m_lastFailed;
};

bool TestMatches(TestDetails const& test, const string& name)
{
    return name == test.suiteName || name == test.testName ||
        name == basefilename(test.filename);
}

int main(int argc, char** argv)
{
    //invoke without arguments to run all tests:
    //  testlib
    //
    //invoke with arguments to run a single test:
    //  testlib MyTestName
    //
    //or single suite:
    //  testlib MySuite
    //
    //or single filename:
    //  testlib filename.cpp
    //
    //exclude Test/Suite/filename:
    //  testlib -MyTestNameOrSuiteNameOrFilename
    //
    //verbose output:
    //  testlib -v
    //  testlib --verbose
    //  testlib -v MyTestName
    //  testlib -v MySuite
    //  testlib -v filename.cpp

    cout << "Lomse version " << LibraryScope::get_version_long_string()
         << ". Library tests runner." << endl << endl;

    cout << "Lomse build date: " << LibraryScope::get_build_date() << endl;
    cout << "Path for tests scores: '" << TESTLIB_SCORES_PATH << "'" << endl;
    cout << "Tests fonts path: '" << TESTLIB_FONTS_PATH << "'" << endl;
    cout << "Lomse fonts path: '" << LOMSE_FONTS_PATH << "'" << endl << endl;

    bool verbose = argc > 1 && (!strcmp(argv[1], "--verbose") || !strcmp(argv[1], "-v"));
    int nextArg = verbose ? 2 : 1;

    MyTestReporterStdout reporter(verbose);
    UnitTest::TestRunner runner(reporter);

    int nErrors = 0;

    if (argc > nextArg)
    {
        cout << "Running some tests " << endl << endl;

        //run only matching tests
        nErrors = runner.RunTestsIf(Test::GetTestList(), nullptr,
            [nextArg, argc, argv](Test* p)
            {
                bool hasPositiveArgs = false;
                bool positiveMatch = false;
                bool negativeMatch = false;
                for (int i = nextArg ; i < argc ; ++i)
                {
                    const char* arg = argv[i];
                    bool negative = arg[0] == '-';
                    negativeMatch |= negative && TestMatches(p->m_details, arg + 1);
                    positiveMatch |= !negative && TestMatches(p->m_details, arg);
                    hasPositiveArgs |= !negative;
                }
                return (!hasPositiveArgs || positiveMatch) && !negativeMatch;
            }
            , 0);
    }
    else
    {
        cout << "Running all tests" << endl << endl;
        nErrors = runner.RunTestsIf(Test::GetTestList(), nullptr, True(), 0);
    }

    #if defined WIN32 || defined _WIN32
        _CrtDumpMemoryLeaks();
    #endif

    return nErrors;
}


text:
import yaml, os, mysql.connector, json
from tqdm import tqdm
from datetime import datetime
from pprint import pprint

class ConfigNotFoundError(Exception): pass

def read_yaml(filename):
    """

    :param filename:
    :return:
    """
    if not os.path.isfile(filename):
        raise ConfigNotFoundError("Could not find the file with the name: %s" % filename)

    yaml_doc = {}

    with open(filename, 'r') as f:
        yaml_doc = yaml.load(f)

    return yaml_doc

print "---=== IlliniBoard.com User Converter ===---"
config = read_yaml('db_config.yml')
db_config = config.get('database').get('development')

user_data = json.loads(open("_User.json").read())

user_list = user_data['results']
print "User List Size: %d" % len(user_list)

for user in tqdm(user_list):
    try:
        db_conn = mysql.connector.connect(**db_config)
        cursor = db_conn.cursor()
        query = ("INSERT INTO user (username, password, created_on, email_address, registration_ip_address, \
                  avatar_url, is_validated) VALUES (%s, %s, %s, %s, %s, %s, %s)")
        try:
            avatar_url = user['avatar_url']
        except KeyError:
            avatar_url = None

        try:
            registration_ip_address = user['registration_ip_address']
        except KeyError:
            registration_ip_address = "from_import"

        try:
            email = user['email']
        except KeyError:
            email = None
        created_on_time = datetime.strptime(user['createdAt'], "%Y-%m-%dT%H:%M:%S.%fZ")
        user_data = (user['username'], user['bcryptPassword'], created_on_time.strftime("%Y-%m-%d %H:%M:%S"),
                     email, registration_ip_address, avatar_url, 1)
        cursor.execute(query, user_data)
    except mysql.connector.Error as error:
        print "[save_user_in_db] :: error number=%s" % error.errno
        print "[save_user_in_db] :: error=%s" % error
    else:
        db_conn.commit()
        cursor.close()
        db_conn.close()

print "Users Saved."


text:
package com.pivotal.gemfirexd.internal.iapi.services.locks;

import com.pivotal.gemfirexd.internal.iapi.services.locks.Latch;
import com.pivotal.gemfirexd.internal.iapi.services.locks.Lockable;
import com.pivotal.gemfirexd.internal.iapi.services.locks.VirtualLockTable;
import com.pivotal.gemfirexd.internal.iapi.services.sanity.SanityManager;

import java.util.Hashtable;

public class ShExLockable implements Lockable
{

	public ShExLockable()
	{
	}

	/** @see Lockable#lockerAlwaysCompatible */
	public boolean lockerAlwaysCompatible()
	{
		return true;
	}

	/** @see Lockable#requestCompatible */
	public boolean requestCompatible(Object requestedQualifier,
											Object grantedQualifier)
	{
		if (SanityManager.DEBUG)
		{
			if (!(requestedQualifier instanceof ShExQual))
				SanityManager.THROWASSERT(
				"requestedQualifier is a " +
				requestedQualifier.getClass().getName() +
				"instead of a ShExQual.");

			if (!(grantedQualifier instanceof ShExQual))
				SanityManager.THROWASSERT(
				"grantedQualifier is a " +
				grantedQualifier.getClass().getName() +
				"instead of a ShExQual.");
		}

		ShExQual requested = (ShExQual) requestedQualifier;
		ShExQual granted = (ShExQual) grantedQualifier;

		return (requested.getLockState() == ShExQual.SHARED) &&
				(granted.getLockState() == ShExQual.SHARED);
	}

	/** @see Lockable#lockEvent */
	public void lockEvent(Latch lockInfo)
	{
		if (SanityManager.DEBUG)
		{
			if (!(lockInfo.getQualifier() instanceof ShExQual))
				SanityManager.THROWASSERT("qualifier is a " + lockInfo.getQualifier().getClass().getName() +
				"instead of a ShExQual.");
		}
	}

	/** @see Lockable#unlockEvent */
	public void unlockEvent(Latch lockInfo)
	{
		if (SanityManager.DEBUG)
		{
			if (!(lockInfo.getQualifier() instanceof ShExQual))
				SanityManager.THROWASSERT("qualifier is a " + lockInfo.getQualifier().getClass().getName() +
				"instead of a ShExQual.");
		}
	}

    /**
     * This lockable want to participate in the Virtual LockTable
     * when we want to print LATCH information.
     * Any lockable object which DOES NOT want to participate should
     * override this function.
     */
	public boolean lockAttributes(int flag, Hashtable attributes)
	{
        if((flag & VirtualLockTable.SHEXLOCK) == 0)
            return false;
        // No containerId, but need something in there so it can print
		attributes.put(VirtualLockTable.CONTAINERID, new Long(-1) );

		attributes.put(VirtualLockTable.LOCKNAME, this.toString() );

		attributes.put(VirtualLockTable.LOCKTYPE, "ShExLockable");

		return true;
	}

}


text:
/**
 * Generated by Scrooge
 *   version: ?
 *   rev: ?
 *   built at: ?
 */
#import <Foundation/Foundation.h>

#import "ApacheThrift/TBase.h"
#import "TFNTwitterThriftGoldResponseUnion.h"

@interface TFNTwitterThriftGoldResponse : NSObject <TBase, NSCoding>

@property (nonatomic) int32_t statusCode;
@property (nonatomic, readonly) BOOL statusCodeIsSet;

@property (nonatomic) TFNTwitterThriftGoldResponseUnion* responseUnion;
@property (nonatomic, readonly) BOOL responseUnionIsSet;

- (instancetype)initWithStatusCode:(int32_t)statusCode responseUnion:(TFNTwitterThriftGoldResponseUnion*)responseUnion;
- (void)read:(id<TProtocol>)inProtocol;
- (void)write:(id<TProtocol>)outProtocol;

@end


text:
\documentclass[Screen16to9,17pt]{foils}
\usepackage{zencurity-slides}

\externaldocument{system-security-exercises}
\selectlanguage{english}

\begin{document}

\mytitlepage
{4. Integrity and Availability Policies}
{KEA Kompetence Computer Systems Security \the\year}

\slide{Plan for today}

\begin{list1}
\item Subjects
\begin{list2}
\item Accuracy vs disclosure
\item The Biba Model
\item Clark-Wilson Integrity Model
\item Trust models
\item Deadlocks
\item Availability and flooding attacks
\item Protection against TCP Synfloods
\end{list2}
\item Exercises
\begin{list2}
\item Databases - discussion about Relational Database Management System RDBMS Model and NoSQL
\item SYN flooding exercise
\end{list2}
\end{list1}

\slide{Reading Summary}

\begin{list1}
\item Bishop chapter 6: Integrity Policies
\item Bishop chapter 7: Availability Policies
\item TCP Synfloods - an old yet current problem, and improving pf's response to it, Henning Brauer, BSDCan 2017
\end{list1}

\slide{Accuracy vs disclosure}

Lipner five commercial requirements:
\begin{list2}
\item[1.] Users will not write their own programs, but use existing
  production software.
\item[2.] Programmers develop and test applications on a nonproduction system, possibly using contrived data.
\item[3.] Moving applications from development to production requires a special process.
\item[4.] This process must be controlled and audited.
\item[5.] Managers and auditors must have access to system state and system logs
\end{list2}

Available from\\ {\footnotesize\link{https://csrc.nist.gov/CSRC/media/Publications/conference-paper/1982/05/24/proceedings-5th-seminar-dod-computer-security-initiative/documents/1982-5th-seminar-proceedings.pdf}}

\slide{Separation of duty ns function}

\begin{quote}
{\bf Separation of duties} (SoD; also known as Segregation of Duties) is the concept of having more than one person required to complete a task. In business the separation by sharing of more than one individual in one single task is an internal control intended to prevent fraud and error.
\end{quote}

Quote from \url{https://en.wikipedia.org/wiki/Separation_of_duties}

\begin{quote}
{\bf Separation of function}. Developers do not develop new programs on production systems because of the potential threat to production data.
\end{quote}
\emph{Computer Security}, Matt Bishop, 2019

Danish: Funktionsadskillelse

%\slide{Auditing}

\slide{The Biba Model}

Ken Biba (1977) proposed three different integrity access control
policies.

\begin{list2}
\item[1] The Low Water Mark Integrity Policy
\item[2] The Ring Policy
\item[3] Strict Integrity
\item All assume that we associate integrity labels with subjects and
objects, analogous to clearance levels in BLP.
\item Only Strict Integrity had much continuing influence. It is the one
typically referred to as the "Biba Model" or "Biba Integrity."
\end{list2}

% https://www.cs.utexas.edu/~byoung/cs361/syllabus361.html
% https://www.cs.utexas.edu/~byoung/cs361/lecture21.pdf

Example page 178 mentions that this was implemented in FreeBSD

\slide{Lipners Integrity Matrix Model}

\hlkimage{15cm}{lipner-model-levels.png}

\emph{Non-Discretionary Controls for Commercial Applications}, Steven B. Lipner, IEEE Symposium on Security and Privacy, and Fifth Seminar on the DoD Computer Security Initiative, 1982

\slide{Lipners Integrity Matrix Model}

\hlkimage{20cm}{lipner-1982.png}

\emph{Non-Discretionary Controls for Commercial Applications}, Steven B. Lipner, IEEE Symposium on Security and Privacy, and Fifth Seminar on the DoD Computer Security Initiative, 1982

\slide{Lipners Integrity Matrix Model}

\hlkimage{20cm}{lipner-with-integrity.png}

\emph{Non-Discretionary Controls for Commercial Applications}, Steven B. Lipner, IEEE Symposium on Security and Privacy, and Fifth Seminar on the DoD Computer Security Initiative, 1982

% \slide{One source of truth}
% Maybe later

\slide{Clark-Wilson Integrity Model}

A {\bf well-formed transaction} from one consistent state to another consistent state.

\begin{list2}
\item Constrained Data Items: CDIs are the objects whose
integrity is protected
\item Unconstrained Data Items: UDIs are objects not covered by
the integrity policy
\item Transformation Procedures: TPs are the only procedures
allowed to modify CDIs, or take arbitrary user input and
create new CDIs. Designed to take the system from one valid
state to another.
\item Integrity Verification Procedures: IVPs are procedures
meant to verify maintainance of integrity of CDIs.
\end{list2}

\emph{A Comparison of Commercial and Military Computer Security Policies},
David D. Clark and David R. Wilson, 1987

\slide{Clark-Wilson rules}

\begin{list22}
\item[Certification rule 1] —When an IVP is executed, it must ensure the CDIs are valid.
\item[Certification rule 2] —For some associated set of CDIs, a TP must transform those CDIs from one valid state to another.
Since we must make sure that these TPs are certified to operate on a particular CDI, we must have E1 and E2.

\item[Enforcement rule 1] —System must maintain a list of certified relations and ensure only TPs certified to run on a CDI change that CDI.
\item[Enforcement rule 2] —System must associate a user with each TP and set of CDIs. The TP may access the CDI on behalf of the user if it is "legal".
\item[Enforcement rule 3] -The system must authenticate the identity of each user attempting to execute a TP.
This requires keeping track of triples (user, TP, {CDIs}) called "allowed relations".

\item[Certification rule 3] —Allowed relations must meet the requirements of "separation of duty".
We need authentication to keep track of this.

\item[Certification rule 4] —All TPs must append to a log enough information to reconstruct the operation.
When information enters the system it need not be trusted or constrained (i.e. can be a UDI). We must deal with this appropriately.

\item[Certification rule 5] —Any TP that takes a UDI as input may only perform valid transactions for all possible values of the UDI. The TP will either accept (convert to CDI) or reject the UDI.
Finally, to prevent people from gaining access by changing qualifications of a TP:

\item[Enforcement rule 4] —Only the certifier of a TP may change the list of entities associated with that TP.
\end{list22}

\slide{Clark-Wilson Integrity Model}

\begin{quote}
The model uses a three-part relationship of subject/program/object (where program is interchangeable with transaction) known as a triple or an access control triple. Within this relationship, subjects do not have direct access to objects. Objects can only be accessed through programs
\end{quote}

\emph{A Comparison of Commercial and Military Computer Security Policies},
David D. Clark and David R. Wilson, 1987

See also
\url{https://en.wikipedia.org/wiki/Clark%E2%80%93Wilson_model}

%\slide{Trust models}
% Removed not so important for us

\slide{Availability Policies}

\begin{list1}
\item An availability policy ensures that a resource or service can be accessed in some way in a timely fashion
\item Often expressed as \emph{quality of service}
\item Denial of service occurs when this resource or service becomes unavailable
\end{list1}

\slide{Relational Database Management System RDBMS}

\hlkimage{7cm}{RDBMS_structure.png}

\begin{list1}
\item Relational Database Management System RDBMS is a common database architecture
\item Common examples MS-SQL, MySQL/MariaDB, PostgreSQL
\item Picture: By Scifipete - Own work, CC BY-SA 3.0,\\ \url{https://commons.wikimedia.org/w/index.php?curid=11506013}
\item \url{https://en.wikipedia.org/wiki/Relational_database#RDBMS}
\end{list1}

\slide{PostgreSQL security}
\hlkimage{15cm}{postgresql-security.png}

Feature overview security features in PostgreSQL\\
\url{https://www.postgresql.org/about/featurematrix/#security}

\slide{Deadlocks}

\begin{list1}
\item {\bf Definition 7-1} A \emph{deadlock} is a state in which some set of processes block, each waiting for another process in the set to take some action.
\begin{list2}
\item[1.] The resource is not shared (mutual exclusion)
\item[2.] An entity must hold the resource and block, waiting until another resource becomes available (hold and wait)
\item[3.] A resource being help cannot be released (no preemption)
\item[4.] A set of entities must be holding resources such that each entity is waiting for a resource held by another entity in the set (circular wait)
\end{list2}
\item Often found in Relational Database Systems, if two processes want to update two tables, and each one has a write lock on one table, waiting for the write lock on the other
\item See also \link{https://en.wikipedia.org/wiki/Deadlock}
\end{list1}

\slide{Common Discusssion}

Databases - discussion about Relational Database Management System RDBMS Model and NoSQL databases, which ones do you and your company use?

\slide{Fairness and starvation}

\begin{list1}
\item Fairness policy prevents starvation, often rephrased as - process will make progress
\item If one process gets all resources, memory, cpu, network the others will starve - not have enough resources to progress
\item Compare to old operating systems Windows 3 / Mac OS 9\\
Cooperative multitasking vs pre-emptive multitasking
\end{list1}

\slide{Availability and Network flooding attacks}

\begin{list2}
\item Our book spends some time on SYN and other flooding attacks
\item SYN flood is the most basic and very common on the internet towards 80/tcp and 443/tcp
\item ICMP and UDP flooding are the next targets
\item Supporting litterature is TCP Synfloods - an old yet current problem, and improving pf's response to it, Henning Brauer, BSDCan 2017
\item All of them try to use up some resources
\begin{list2}
\item Memory space in specific sections of the kernel, TCP state, firewalls state, number of concurrent sessions/connections
\item interrupt processing of packets - packets per second
\item CPU processing in firewalls, pps
\item CPU processing in server software
\item Bandwidth - megabits per second mbps
\end{list2}
\end{list2}

There is a presentation about DDoS protection with low level technical measures to implement at\\
{\footnotesize \link{https://github.com/kramse/security-courses/tree/master/presentations/network/introduction-ddos-testing}}

\exercise{ex:syn-flood-101}

\slidenext

\end{document}


text:
<!doctype html>

    <meta charset="utf-8"/>
    <meta name="viewport"
          content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-touch-fullscreen" content="yes">
    <title>line pointer demo</title>
    <link rel="stylesheet" href="http://a.tbcdn.cn/s/kissy/1.3.0rc/css/dpl/??base-min.css"/>
    <link rel="stylesheet" href="http://a.tbcdn.cn/s/kissy/1.3.0rc/??button/assets/dpl-min.css"/>

        请画出 3 条两两相交的直线穿过 4 个点

    <button class="ks-button" id="redo">重来</button>

    <canvas id="canvas" width="600" height="600">
        请不要使用 ie < 9
    </canvas>


text:
package com.baidubce.services.ses.model;

import com.fasterxml.jackson.annotation.JsonProperty;

/**
 * The token model object. It was contained by @link{DkimAttrModelTokenModel}.
 */
public class TokenModel {
    /**
     * The id of token.
     */
    private String id;
    /**
     * The private key of token.
     */
    @JsonProperty("private_key")
    private String privateKey;
    /**
     * The public key of token.
     */
    @JsonProperty("public_key")
    private String publicKey;
    /**
     * The selector of token.
     */
    private String selector;
    /**
     * The CName of token.
     */
    private String cname;
    /**
     * The DNS record name of token.
     */
    @JsonProperty("dns_record_name")
    private String dnsRecordName;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getPrivateKey() {
        return privateKey;
    }

    public void setPrivateKey(String privateKey) {
        this.privateKey = privateKey;
    }

    public String getPublicKey() {
        return publicKey;
    }

    public void setPublicKey(String publicKey) {
        this.publicKey = publicKey;
    }

    public String getSelector() {
        return selector;
    }

    public void setSelector(String selector) {
        this.selector = selector;
    }

    public String getCname() {
        return cname;
    }

    public void setCname(String cname) {
        this.cname = cname;
    }

    public String getDnsRecordName() {
        return dnsRecordName;
    }

    public void setDnsRecordName(String dnsRecordName) {
        this.dnsRecordName = dnsRecordName;
    }

    @Override
    public String toString() {
        return "TokenModel [id=" + id + ", privateKey=" + privateKey + ", publicKey=" + publicKey + ", selector="
                + selector + ", cname=" + cname + ", dnsRecordName=" + dnsRecordName + "]";
    }

}


text:
package com.marklogic.xcc.types.impl;

import java.math.BigDecimal;
import java.math.BigInteger;

import com.marklogic.xcc.types.ValueType;
import com.marklogic.xcc.types.XSDouble;

public class XsDoubleImpl extends AbstractStringItem implements XSDouble {
    private final Double value;
    private final BigDecimal bigDecimalValue;
    private final NumberFormatException formatException;

    public XsDoubleImpl(String bodyString) {
        super(ValueType.XS_DOUBLE, bodyString);

        this.value = Double.valueOf(scrubbedFloatValue(bodyString));

        BigDecimal tmpBigDecimal = null;
        NumberFormatException tmpEx = null;

        try {
            tmpBigDecimal = new BigDecimal(bodyString);
        } catch (NumberFormatException e) {
            // Double value parsed, must be NaN or +-INF, leave as null
            tmpEx = e;
        }

        this.bigDecimalValue = tmpBigDecimal;
        this.formatException = tmpEx;
    }

    public XsDoubleImpl(Object value) {
        super(ValueType.XS_DOUBLE, value.toString());

        if ((value instanceof Integer) || (value instanceof Long) || (value instanceof Double)
                || (value instanceof Float) || (value instanceof BigDecimal) || (value instanceof BigInteger)
                || (value instanceof String)) {
            this.value = new Double(value.toString());

            BigDecimal tmpBigDecimal = null;
            NumberFormatException tmpEx = null;

            try {
                tmpBigDecimal = new BigDecimal(value.toString());
            } catch (NumberFormatException e) {
                tmpEx = e;
            }

            this.bigDecimalValue = tmpBigDecimal;
            this.formatException = tmpEx;
        } else {
            throw new IllegalArgumentException("Cannot construct XSDouble from " + value.getClass().getName());
        }
    }

    public Double asDouble() {
        return (value);
    }

    public double asPrimitiveDouble() {
        return value.doubleValue();
    }

    public BigDecimal asBigDecimal() {
        if (bigDecimalValue == null) {
            throw formatException;
        }

        return bigDecimalValue;
    }
}


text:
enum VisionClass
{
	None,
	Color_box,
	Calibration,
	Test,
};

const CString VisionClass[] = {"None", "Color_box", "Calibration", "Test"};

// CVisionTab ´ëÈ »óÀÚÀÔ´Ï´Ù.

class CVisionTab : public CDialogEx
{
	DECLARE_DYNAMIC(CVisionTab)

public:
	CVisionTab(CWnd* pParent = NULL);   // Ç¥ÁØ »ý¼ºÀÚÀÔ´Ï´Ù.
	virtual ~CVisionTab();

// ´ëÈ »óÀÚ µ¥ÀÌÅÍÀÔ´Ï´Ù.
	enum { IDD = IDD_VISION };

private:
	// ÀÛ¾÷ ¾²·¹µå
	CWinThread* pThread;
	CWinThread* pThreadIP;

private:
	CDib*	pBufColor;
	CDib*	pBufDepth;
	CDib*	pColor;
	CDib*	pDepth;
	CDib*	pColorClip;
	CDib*	pDepthClip;

	UINT	m_visionMode;
	// intrincsic Matrix K
	MatrixXd K;

	// Staubli matching matrix
	MatrixXd M_st;

	UINT m_binThres;

public:
	CKinectConnection	kinect;
	CLargeText			m_FrameRate;
	CLargeText			m_FrameRateIP;
	CPoint				m_ClipCenter;
	CPoint				m_GlobalCenter;

	bool clip;

	// Àӽà º¯¼ö ~~~~~
	bool m_flag;	// TODO
	CDib* pTestImage;	// TODO

	CImageDisp	m_DispRGB;
	CImageDisp	m_DispDepth;
	CImageDisp	m_imgProcess;
	CRect		m_ClipRect;
	CButton		m_ImgClipBtn;
	Coordi		m_cbWorldPoint[NUMBOX];	// World point of each color boxes, To send
	ViaPoint	m_calibPoint;

	static HANDLE m_updateEvent;
	static HANDLE m_GetCimgEvent;
	static HANDLE m_GetDimgEvent;
	static HANDLE m_Mutex;

	CRITICAL_SECTION cs;
	CCriticalSection g_CS;

	CEvent g_event;

protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV Áö¿øÀÔ´Ï´Ù.

private:
	static UINT ThreadUpdateKinectImage(LPVOID pParam);
	static UINT ThreadImageProcessing(LPVOID pParam);
	void CalcTime();
	void CalcTimeIP();

	DECLARE_MESSAGE_MAP()

public:
	void updateColorStream();
	void updateDepthStream();
	void doingImageProcess();

	CDib* GetColorImage();
	CDib* GetDepthImage();
	CDib* GetColorClipImage(RECT *pRect);
	CDib* GetDepthClipImage(RECT *pRect);

	//// Vision Algorithm implementation ----------------------
	CDib*			ColorBoxRecog(CDib* pImg);
	TargetObject	CellPhonePartRecog(CDib* pImg);

public:
	virtual BOOL OnInitDialog();
	afx_msg void OnBnClickedClipimage();

	CComboBox		m_Combo_VisionClass;
	afx_msg void	OnCbnSelchangeVisionclasscombo();
	afx_msg void	OnBnClickedDoCalib();
	CImageDisp		m_testView;
	CListCtrl		m_CalibList;

	UINT			GetVisionMode();

	afx_msg void OnBnClickedClearCalib();
	CSpinButtonCtrl m_SpinBin;
	afx_msg void OnDeltaposSpinBinarization(NMHDR *pNMHDR, LRESULT *pResult);
};


text:
Mode Replié et Déplié
===========================

Les tâches peuvent être affichées sur le Tableau en mode Replié ou Déplié.
Basculer d'un mode à l'autre peut être fait à l'aide du raccourci clavier **"s"** ou en utilisant le menu déroulant sur la gauche.

Mode Replié
--------------
![Tâches repliées](http://kanboard.net/screenshots/documentation/board-collapsed-mode.png)

- Si la tâche est affectée à quelqu'un, les initiales de la personne sont affichées à côté du numéro de la tâche.
- Si le titre de la tâche est trop long, mettez le curseur de la souris au-dessus de la tâche pour voir une boite flottante avec le titre entier.

Mode Déplié
-------------

![Tâches dépliées](http://kanboard.net/screenshots/documentation/board-expanded-mode.png)


text:
#ifndef BLOCK_WRITER_H_
#define BLOCK_WRITER_H_

#include <cstddef>
#include <cstdint>

#include "bit_stream.h"
#include "block.h"
#include "constants.h"

class BlockWriter {
public:
    BlockWriter(const ZjumpBlock& block);

    ZjumpErrorCode Write(const size_t allocated_size,
                         uint8_t* stream,
                         size_t* stream_size);

private:
    const ZjumpBlock &block_;

    ZjumpErrorCode WriteBwtMetadata(BitStreamWriter* writer);

    ZjumpErrorCode WriteHuffmanTree(BitStreamWriter* writer);

    ZjumpErrorCode WriteLiterals(BitStreamWriter* writer);

    ZjumpErrorCode WriteJumpSequences(BitStreamWriter* writer);
};

#endif // BLOCK_WRITER_H_


text:
DEFINE_string(trusted_user_acl, "",
    "Comma-separated list of trusted users who may access the cluster "
    "without being authorized against fine-grained permissions.");
TAG_FLAG(trusted_user_acl, sensitive);

using std::string;
using std::vector;

namespace kudu {
namespace master {

AuthzProvider::AuthzProvider() {
  vector<string> acls = strings::Split(FLAGS_trusted_user_acl, ",", strings::SkipEmpty());
  std::move(acls.begin(), acls.end(), std::inserter(trusted_users_, trusted_users_.end()));
}

bool AuthzProvider::IsTrustedUser(const string& user) const {
  return ContainsKey(trusted_users_, user);
}

} // namespace master
} // namespace kudu


text:
package com.navercorp.pinpoint.plugin.activemq.client.field.getter;

import java.net.Socket;

/**
 * @author HyunGil Jeong
 */
public interface SocketGetter {
    Socket _$PINPOINT$_getSocket();
}


text:
package OpenResty::Limits;

use strict;
use warnings;
use base 'Exporter';

our @EXPORT = qw(
    $MODEL_LIMIT
    $VIEW_LIMIT
    $FEED_LIMIT
    $ROLE_LIMIT
    $ACTION_LIMIT
    $ACTION_PARAM_LIMIT
    $COLUMN_LIMIT
    $RECORD_LIMIT
    $INSERT_LIMIT
    $POST_LEN_LIMIT
    $MAX_SELECT_LIMIT
    $PASSWORD_MIN_LEN
    $VIEW_MAX_LEN
    $ACTION_MAX_LEN
    $ACTION_CMD_COUNT_LIMIT
    $ACTION_REC_DEPTH_LIMIT
);

our $MODEL_LIMIT = 40;
our $VIEW_LIMIT = 100;
our $FEED_LIMIT = 100;
our $ROLE_LIMIT = 100;
our $COLUMN_LIMIT = 40;
our $ACTION_LIMIT = 40;
our $ACTION_PARAM_LIMIT = 100;
our $INSERT_LIMIT = 20;
our $RECORD_LIMIT = 200;
our $POST_LEN_LIMIT = 1_000_000; # 1 MB
our $MAX_SELECT_LIMIT = 200;
our $PASSWORD_MIN_LEN = 6;
our $VIEW_MAX_LEN = 5_000; # 5 KB
our $ACTION_MAX_LEN = 5_000; # 5 KB
our $ACTION_CMD_COUNT_LIMIT = 20;
our $ACTION_REC_DEPTH_LIMIT = 3;

1;
__END__

=head1 NAME

OpenResty::Limits - Various contraints used in the OpenResty server

=head1 SYNOPSIS

    use OpenResty::Limits;

    print join("\n",
        $MODEL_LIMIT,
        $VIEW_LIMIT,
        $FEED_LIMIT,
        $ROLE_LIMIT,
        $COLUMN_LIMIT,
        $RECORD_LIMIT,
        $INSERT_LIMIT,
        $POST_LEN_LIMIT,
        $MAX_SELECT_LIMIT,
        $PASSWORD_MIN_LEN,
        $VIEW_MAX_LEN,
        $ACTION_MAX_LEN,
        $ACTION_CMD_COUNT_LIMIT,
        $ACTION_REC_DEPTH_LIMIT,
    );

=head1 DESCRIPTION

This module defines various constants which limits the resources each OpenResty account could use, like the number of different objects (models, rows, views, and  etc.).

These constants are not truly constants. Some of them could be overridden by some config options specified in F<etc/site_openresty.conf>. So different servers may have (very) different limitations.

=head1 VARIABLES

=over

=item C<$MODEL_LIMIT>

Model count limit in an account, default 40.

Controlled by config file option C<frontend.model_limit>.

=item C<$VIEW_LIMIT>

View count limit in an account, default 100.

=item C<$FEED_LIMIT>

Feed count limit in an account, default 100.

=item C<$ROLE_LIMIT>

Role count limit in an account, default 100.

=item C<$COLUMN_LIMIT>

Column count limit in a model, default 40.

Controlled by config file option C<frontend.column_limit>.

=item C<$RECORD_LIMIT>

Row count limit in a model, default 200.

Controlled by config file option C<frontend.row_limit>.

=item C<$INSERT_LIMIT>

Maximal number of rows inserted in a single POST request, default 20.

Controlled by config file option C<frontend.bulk_insert_limit>.

=item C<$POST_LEN_LIMIT>

Content length limit for a POST/PUT request, default 1_000_000 (1 MB).

Controlled by config file option C<frontend.post_len_limit>.

=item C<$MAX_SELECT_LIMIT>

Maximal number of rows returned by a unlimited query, default 200.

=item C<$PASSWORD_MIN_LEN>

Minimum length for the password of a role, default 6 chars.

=item C<$VIEW_MAX_LEN>

The maximal length of a view definition, default 5_000 (5 KB).

=item C<$ACTION_MAX_LEN>

The maximal length of an action definition, default 5_000 (5 KB).

=item C<$ACTION_CMD_COUNT_LIMIT>

Maximal number of commands in a single action's definition, default 5

=item C<$ACTION_REC_DEPTH_LIMIT>

The maximal depth of recursive action calls, default 3.

=back

=head1 AUTHOR

Yichun Zhang (agentzh) C<< <agentzh@gmail.com> >>

=head1 SEE ALSO

L<OpenResty::Config>, L<OpenResty>, L<OpenResty::Spec::Overview>.


text:
package com.vav.Common.Sorting;

/**
 * Created by Vaibhav on 4/9/2017.
 */
public class Partitioning {
    static int arr[] = {4,3,2,1};
    public static void main(String arg[]){
       // mergeSort.mergeSort(arr);

        int partition = partitionIt(0,arr.length-1,arr.length/2);
        System.out.println("Partition:"+partition);
        for (int i=0;i<arr.length;i++){
            System.out.print(arr[i]+ ", ");
        }

    }

    private static int partitionIt(int start, int end, int partition) {
        int left = start-1;
        int right = end+1;
        while (true) {
            while (left < right && arr[++left] < arr[partition]) ;
            while (right > left && arr[--right] > arr[partition]) ;
            if(left>=right){
                break;
            }else{
                swap(left,right);
            }
        }

        return arr[partition];
    }

    private static void swap(int one, int two) {
        int temp=arr[one];
        arr[one]=arr[two];
        arr[two]=temp;
    }

}


text:
namespace darkfeed
{
/// @defgroup time
/// @brief primitives for dealing with market timestamps
/// @ingroup types

/// @brief A timestamp broken out in civil format
/// @ingroup time
struct CivilTime {
    std::uint16_t year; ///< gregorian year (eg; 2016)
    std::uint8_t month; ///< calendar month (1= January, 2=February, ...)
    std::uint8_t day;; ///< day of month (starting at 1)
    std::uint8_t hour; ///< hour of day (0 = midnight, 23=11PM)
    std::uint8_t minute; ///< minute of hour
    std::uint8_t second; ///< second of minute
    std::uint32_t nanosecond; ///< nanosecond offset past second
    std::uint8_t dow; ///< day of week (0 = Sunday, 1 = Monday, etc.)
    std::uint16_t doy; ///< day of year (0-365)
    std::int8_t offset; ///< hours offset from UTC
    bool dst; ///< whether DST was active at timezone

    CivilTime(); ///< default constructor
};

/// @brief A high resolution (nanosecond) timestamp with easy civil time conversion
/// @ingroup time
struct Timestamp {
    std::time_t ts; ///< Internal representation of time in UTC
    std::uint32_t ns; ///< Nanosecond offset
    std::int8_t offset;      ///< UTC offset of source time (including DST if active) in HOURS
    bool dst;        ///< Whether DST was active at this location and time (automatically set if timezone is specified)

 public:
    /// @brief Default constructor
    Timestamp();
    /// @brief Full constructor
    /// @param unix Seconds since the unix epoch
    /// @param nano nanoseconds past the unix timestamp
    /// @param utc_offset number of hours + or - GMT
    /// @param dst_status whether DST is active for this timestamp
    /// @return
    Timestamp(std::time_t epoch, std::uint32_t nano = 0, std::int8_t utc_offset = 0, bool dst_status = false);
    /// @brief Construct from ISO 8601 timestamp or FIX timestamp (both at UTC)
    /// @param s the string to process
    /// @return
    Timestamp(const std::string &s);
    /// @brief Construct from a CivilTime object
    /// @param c The CivilTime object to use
    Timestamp(const CivilTime & c);
    /// @brief Constructor from flatbuffers timestamp
    /// @param t The flatbuffers timestamp

    /// @brief Populate timestamp with current host timestamp
    void now();

    bool operator<(const Timestamp &t) const
    {
        return (ts < t.ts) || ((ts == t.ts) && (ns < t.ns));
    }

    bool operator<=(const Timestamp &t) const
    {
        return (ts < t.ts) || ((ts == t.ts) && (ns <= t.ns));
    }

    bool operator>(const Timestamp &t) const
    {
        return (ts > t.ts) || ((ts == t.ts) && (ns > t.ns));
    }

    bool operator>=(const Timestamp &t) const
    {
        return (ts > t.ts) || ((ts == t.ts) && (ns >= t.ns));
    }

    bool operator==(const Timestamp &t) const
    {
        return (ts == t.ts) && (ns == t.ns);
    }

    bool operator!=(const Timestamp &t) const
    {
        return !((ts == t.ts) && (ns == t.ns));
    }

    /// @brief Compares using only dates (not intraday aware)
    /// @param t
    /// @return
    bool operator<<(const Timestamp &t) const
    {
        auto ct1 = get_utc_civiltime();
        auto ct2 = t.get_utc_civiltime();

        return ct1.year * 365 + ct1.doy < ct2.year * 365 + ct2.doy;

    }

    /// @brief Compares using only dates (not intraday aware)
    /// @param t
    /// @return
    bool operator>>(const Timestamp &t) const
    {
        auto ct1 = get_utc_civiltime();
        auto ct2 = t.get_utc_civiltime();

        return ct1.year * 365 + ct1.doy > ct2.year * 365 + ct2.doy;

    }

    /// @brief returns civil time breakdown using supplied offsets/DST
    /// @return
    CivilTime get_civiltime() const;
    /// @brief returns civil time breakdown at UTC
    /// @return
    CivilTime get_utc_civiltime() const;

    /// @brief whether date is NYSE/NASDAQ market holiday
    /// @return
    bool is_holiday() const;
    /// @brief whether date falls on the weekend
    /// @return
    bool is_weekend() const;

    /// @brief returns timestamp as ISO 8601 formatted timestamp (at origin UTC offset)
    /// @return
    std::string iso8601() const;
    /// @brief returns date in ISO 8601 format (at origin UTC offset)
    /// @return
    std::string iso8601Date() const;
    /// @brief return timestamp as ISO 8601 formatted timestamp at UTC
    /// @return
    std::string iso8601UTC() const;
    /// @brief return date in ISO 8601 format (at UTC)
    /// @return
    std::string iso8601DateUTC() const;
    /// @brief return FIX >= 4.2 compatible UTC timestamp
    /// @return
    std::string FIX() const;
};
} // darkfeed


text:
@class NewsBlurAppDelegate;
@class ProfileBadge;

@interface UserProfileViewController : UIViewController
<UITableViewDataSource, UITableViewDelegate, ASIHTTPRequestDelegate> {
    NewsBlurAppDelegate *appDelegate;

    UILabel *followingCount;
    UILabel *followersCount;
    ProfileBadge *profileBadge;
    UITableView *profileTable;
    NSArray *activitiesArray;
    NSString *activitiesUsername;
    NSDictionary *userProfile;
}

@property (nonatomic) NewsBlurAppDelegate *appDelegate;
@property (nonatomic) ProfileBadge *profileBadge;
@property (nonatomic) UITableView *profileTable;
@property (nonatomic) NSArray *activitiesArray;
@property (nonatomic) NSString *activitiesUsername;
@property (nonatomic) NSDictionary *userProfile;
@property (nonatomic) ASIHTTPRequest *request;

- (void)getUserProfile;
- (void)requestFinished:(ASIHTTPRequest *)request;
- (void)requestFailed:(ASIHTTPRequest *)request;
- (void)doCancelButton;

@end


text:
package org.apache.drill;

import org.apache.drill.categories.OperatorTest;
import org.apache.drill.categories.SqlTest;
import org.junit.Test;
import org.junit.experimental.categories.Category;

@Category({SqlTest.class, OperatorTest.class})
public class TestCorrelation extends PlanTestBase {
  static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(TestCorrelation.class);

  @Test  // DRILL-2962
  public void testScalarAggCorrelatedSubquery() throws Exception {
    String query = "select count(*) as cnt from cp.`tpch/nation.parquet` n1 "
      + " where n1.n_nationkey  > (select avg(n2.n_regionkey) * 4 from cp.`tpch/nation.parquet` n2 "
      + " where n1.n_regionkey = n2.n_nationkey)";

    testBuilder()
      .sqlQuery(query)
      .ordered()
      .baselineColumns("cnt")
      .baselineValues((long) 17)
      .build()
      .run();
  }

  @Test  // DRILL-2949
  public void testScalarAggAndFilterCorrelatedSubquery() throws Exception {
    String query = "select count(*) as cnt from cp.`tpch/nation.parquet` n1, "
      + " cp.`tpch/region.parquet` r1 where n1.n_regionkey = r1.r_regionkey and "
      + " r1.r_regionkey < 3 and "
      + " n1.n_nationkey  > (select avg(n2.n_regionkey) * 4 from cp.`tpch/nation.parquet` n2 "
      + " where n1.n_regionkey = n2.n_nationkey)";

    testBuilder()
      .sqlQuery(query)
      .ordered()
      .baselineColumns("cnt")
      .baselineValues((long) 11)
      .build()
      .run();
  }

}


text:
using WebBlocks.Types.DataContracts;

namespace WebBlocks.Types.Models
{
    public class MediaGallery : Entity
    {
        public string Title { get; set; }

        public override string DisplayName()
        {
            return Title;
        }
    }
}


text:
namespace base {

// Make sure our Whence mappings match the system headers.
COMPILE_ASSERT(File::FROM_BEGIN   == SEEK_SET &&
               File::FROM_CURRENT == SEEK_CUR &&
               File::FROM_END     == SEEK_END, whence_matches_system);

namespace {

#if defined(OS_BSD) || defined(OS_MACOSX) || defined(OS_NACL)
typedef struct stat stat_wrapper_t;
static int CallFstat(int fd, stat_wrapper_t *sb) {
  base::ThreadRestrictions::AssertIOAllowed();
  return fstat(fd, sb);
}
#else
typedef struct stat64 stat_wrapper_t;
static int CallFstat(int fd, stat_wrapper_t *sb) {
  base::ThreadRestrictions::AssertIOAllowed();
  return fstat64(fd, sb);
}
#endif

// NaCl doesn't provide the following system calls, so either simulate them or
// wrap them in order to minimize the number of #ifdef's in this file.
#if !defined(OS_NACL)
static bool IsOpenAppend(PlatformFile file) {
  return (fcntl(file, F_GETFL) & O_APPEND) != 0;
}

static int CallFtruncate(PlatformFile file, int64 length) {
  return HANDLE_EINTR(ftruncate(file, length));
}

static int CallFsync(PlatformFile file) {
  return HANDLE_EINTR(fsync(file));
}

static int CallFutimes(PlatformFile file, const struct timeval times[2]) {
#ifdef __USE_XOPEN2K8
  // futimens should be available, but futimes might not be
  // http://pubs.opengroup.org/onlinepubs/9699919799/

  timespec ts_times[2];
  ts_times[0].tv_sec  = times[0].tv_sec;
  ts_times[0].tv_nsec = times[0].tv_usec * 1000;
  ts_times[1].tv_sec  = times[1].tv_sec;
  ts_times[1].tv_nsec = times[1].tv_usec * 1000;

  return futimens(file, ts_times);
#else
  return futimes(file, times);
#endif
}

static File::Error CallFctnlFlock(PlatformFile file, bool do_lock) {
  struct flock lock;
  lock.l_type = F_WRLCK;
  lock.l_whence = SEEK_SET;
  lock.l_start = 0;
  lock.l_len = 0;  // Lock entire file.
  if (HANDLE_EINTR(fcntl(file, do_lock ? F_SETLK : F_UNLCK, &lock)) == -1)
    return File::OSErrorToFileError(errno);
  return File::FILE_OK;
}
#else  // defined(OS_NACL)

static bool IsOpenAppend(PlatformFile file) {
  // NaCl doesn't implement fcntl. Since NaCl's write conforms to the POSIX
  // standard and always appends if the file is opened with O_APPEND, just
  // return false here.
  return false;
}

static int CallFtruncate(PlatformFile file, int64 length) {
  NOTIMPLEMENTED();  // NaCl doesn't implement ftruncate.
  return 0;
}

static int CallFsync(PlatformFile file) {
  NOTIMPLEMENTED();  // NaCl doesn't implement fsync.
  return 0;
}

static int CallFutimes(PlatformFile file, const struct timeval times[2]) {
  NOTIMPLEMENTED();  // NaCl doesn't implement futimes.
  return 0;
}

static File::Error CallFctnlFlock(PlatformFile file, bool do_lock) {
  NOTIMPLEMENTED();  // NaCl doesn't implement flock struct.
  return File::FILE_ERROR_INVALID_OPERATION;
}
#endif  // defined(OS_NACL)

}  // namespace

// NaCl doesn't implement system calls to open files directly.
#if !defined(OS_NACL)
// TODO(erikkay): does it make sense to support FLAG_EXCLUSIVE_* here?
void File::InitializeUnsafe(const FilePath& name, uint32 flags) {
  base::ThreadRestrictions::AssertIOAllowed();
  DCHECK(!IsValid());
  DCHECK(!(flags & FLAG_ASYNC));

  int open_flags = 0;
  if (flags & FLAG_CREATE)
    open_flags = O_CREAT | O_EXCL;

  created_ = false;

  if (flags & FLAG_CREATE_ALWAYS) {
    DCHECK(!open_flags);
    open_flags = O_CREAT | O_TRUNC;
  }

  if (flags & FLAG_OPEN_TRUNCATED) {
    DCHECK(!open_flags);
    DCHECK(flags & FLAG_WRITE);
    open_flags = O_TRUNC;
  }

  if (!open_flags && !(flags & FLAG_OPEN) && !(flags & FLAG_OPEN_ALWAYS)) {
    NOTREACHED();
    errno = EOPNOTSUPP;
    error_details_ = FILE_ERROR_FAILED;
    return;
  }

  if (flags & FLAG_WRITE && flags & FLAG_READ) {
    open_flags |= O_RDWR;
  } else if (flags & FLAG_WRITE) {
    open_flags |= O_WRONLY;
  } else if (!(flags & FLAG_READ) &&
             !(flags & FLAG_WRITE_ATTRIBUTES) &&
             !(flags & FLAG_APPEND) &&
             !(flags & FLAG_OPEN_ALWAYS)) {
    NOTREACHED();
  }

  if (flags & FLAG_TERMINAL_DEVICE)
    open_flags |= O_NOCTTY | O_NDELAY;

  if (flags & FLAG_APPEND && flags & FLAG_READ)
    open_flags |= O_APPEND | O_RDWR;
  else if (flags & FLAG_APPEND)
    open_flags |= O_APPEND | O_WRONLY;

  COMPILE_ASSERT(O_RDONLY == 0, O_RDONLY_must_equal_zero);

  int mode = S_IRUSR | S_IWUSR;
#if defined(OS_CHROMEOS)
  mode |= S_IRGRP | S_IROTH;
#endif

  int descriptor = HANDLE_EINTR(open(name.value().c_str(), open_flags, mode));

  if (flags & FLAG_OPEN_ALWAYS) {
    if (descriptor < 0) {
      open_flags |= O_CREAT;
      if (flags & FLAG_EXCLUSIVE_READ || flags & FLAG_EXCLUSIVE_WRITE)
        open_flags |= O_EXCL;   // together with O_CREAT implies O_NOFOLLOW

      descriptor = HANDLE_EINTR(open(name.value().c_str(), open_flags, mode));
      if (descriptor >= 0)
        created_ = true;
    }
  }

  if (descriptor >= 0 && (flags & (FLAG_CREATE_ALWAYS | FLAG_CREATE)))
    created_ = true;

  if ((descriptor >= 0) && (flags & FLAG_DELETE_ON_CLOSE))
    unlink(name.value().c_str());

  if (descriptor >= 0)
    error_details_ = FILE_OK;
  else
    error_details_ = File::OSErrorToFileError(errno);

  file_ = descriptor;
}
#endif  // !defined(OS_NACL)

bool File::IsValid() const {
  return file_ >= 0;
}

PlatformFile File::TakePlatformFile() {
  PlatformFile file = file_;
  file_ = kInvalidPlatformFileValue;
  return file;
}

void File::Close() {
  if (!IsValid())
    return;

  base::ThreadRestrictions::AssertIOAllowed();
  if (!IGNORE_EINTR(close(file_)))
    file_ = kInvalidPlatformFileValue;
}

int64 File::Seek(Whence whence, int64 offset) {
  base::ThreadRestrictions::AssertIOAllowed();
  DCHECK(IsValid());
  if (file_ < 0 || offset < 0)
    return -1;

  return lseek(file_, static_cast<off_t>(offset), static_cast<int>(whence));
}

int File::Read(int64 offset, char* data, int size) {
  base::ThreadRestrictions::AssertIOAllowed();
  DCHECK(IsValid());
  if (size < 0)
    return -1;

  int bytes_read = 0;
  int rv;
  do {
    rv = HANDLE_EINTR(pread(file_, data + bytes_read,
                            size - bytes_read, offset + bytes_read));
    if (rv <= 0)
      break;

    bytes_read += rv;
  } while (bytes_read < size);

  return bytes_read ? bytes_read : rv;
}

int File::ReadAtCurrentPos(char* data, int size) {
  base::ThreadRestrictions::AssertIOAllowed();
  DCHECK(IsValid());
  if (size < 0)
    return -1;

  int bytes_read = 0;
  int rv;
  do {
    rv = HANDLE_EINTR(read(file_, data, size));
    if (rv <= 0)
      break;

    bytes_read += rv;
  } while (bytes_read < size);

  return bytes_read ? bytes_read : rv;
}

int File::ReadNoBestEffort(int64 offset, char* data, int size) {
  base::ThreadRestrictions::AssertIOAllowed();
  DCHECK(IsValid());

  return HANDLE_EINTR(pread(file_, data, size, offset));
}

int File::ReadAtCurrentPosNoBestEffort(char* data, int size) {
  base::ThreadRestrictions::AssertIOAllowed();
  DCHECK(IsValid());
  if (size < 0)
    return -1;

  return HANDLE_EINTR(read(file_, data, size));
}

int File::Write(int64 offset, const char* data, int size) {
  base::ThreadRestrictions::AssertIOAllowed();

  if (IsOpenAppend(file_))
    return WriteAtCurrentPos(data, size);

  DCHECK(IsValid());
  if (size < 0)
    return -1;

  int bytes_written = 0;
  int rv;
  do {
    rv = HANDLE_EINTR(pwrite(file_, data + bytes_written,
                             size - bytes_written, offset + bytes_written));
    if (rv <= 0)
      break;

    bytes_written += rv;
  } while (bytes_written < size);

  return bytes_written ? bytes_written : rv;
}

int File::WriteAtCurrentPos(const char* data, int size) {
  base::ThreadRestrictions::AssertIOAllowed();
  DCHECK(IsValid());
  if (size < 0)
    return -1;

  int bytes_written = 0;
  int rv;
  do {
    rv = HANDLE_EINTR(write(file_, data, size));
    if (rv <= 0)
      break;

    bytes_written += rv;
  } while (bytes_written < size);

  return bytes_written ? bytes_written : rv;
}

int File::WriteAtCurrentPosNoBestEffort(const char* data, int size) {
  base::ThreadRestrictions::AssertIOAllowed();
  DCHECK(IsValid());
  if (size < 0)
    return -1;

  return HANDLE_EINTR(write(file_, data, size));
}

int64 File::GetLength() {
  DCHECK(IsValid());

  stat_wrapper_t file_info;
  if (CallFstat(file_, &file_info))
    return false;

  return file_info.st_size;
}

bool File::SetLength(int64 length) {
  base::ThreadRestrictions::AssertIOAllowed();
  DCHECK(IsValid());
  return !CallFtruncate(file_, length);
}

bool File::Flush() {
  base::ThreadRestrictions::AssertIOAllowed();
  DCHECK(IsValid());
  return !CallFsync(file_);
}

bool File::SetTimes(Time last_access_time, Time last_modified_time) {
  base::ThreadRestrictions::AssertIOAllowed();
  DCHECK(IsValid());

  timeval times[2];
  times[0] = last_access_time.ToTimeVal();
  times[1] = last_modified_time.ToTimeVal();

  return !CallFutimes(file_, times);
}

bool File::GetInfo(Info* info) {
  DCHECK(IsValid());

  stat_wrapper_t file_info;
  if (CallFstat(file_, &file_info))
    return false;

  info->is_directory = S_ISDIR(file_info.st_mode);
  info->is_symbolic_link = S_ISLNK(file_info.st_mode);
  info->size = file_info.st_size;

#if defined(OS_LINUX)
  const time_t last_modified_sec = file_info.st_mtim.tv_sec;
  const int64 last_modified_nsec = file_info.st_mtim.tv_nsec;
  const time_t last_accessed_sec = file_info.st_atim.tv_sec;
  const int64 last_accessed_nsec = file_info.st_atim.tv_nsec;
  const time_t creation_time_sec = file_info.st_ctim.tv_sec;
  const int64 creation_time_nsec = file_info.st_ctim.tv_nsec;
#elif defined(OS_ANDROID)
  const time_t last_modified_sec = file_info.st_mtime;
  const int64 last_modified_nsec = file_info.st_mtime_nsec;
  const time_t last_accessed_sec = file_info.st_atime;
  const int64 last_accessed_nsec = file_info.st_atime_nsec;
  const time_t creation_time_sec = file_info.st_ctime;
  const int64 creation_time_nsec = file_info.st_ctime_nsec;
#elif defined(OS_MACOSX) || defined(OS_IOS) || defined(OS_BSD)
  const time_t last_modified_sec = file_info.st_mtimespec.tv_sec;
  const int64 last_modified_nsec = file_info.st_mtimespec.tv_nsec;
  const time_t last_accessed_sec = file_info.st_atimespec.tv_sec;
  const int64 last_accessed_nsec = file_info.st_atimespec.tv_nsec;
  const time_t creation_time_sec = file_info.st_ctimespec.tv_sec;
  const int64 creation_time_nsec = file_info.st_ctimespec.tv_nsec;
#else
  // TODO(gavinp): Investigate a good high resolution option for OS_NACL.
  const time_t last_modified_sec = file_info.st_mtime;
  const int64 last_modified_nsec = 0;
  const time_t last_accessed_sec = file_info.st_atime;
  const int64 last_accessed_nsec = 0;
  const time_t creation_time_sec = file_info.st_ctime;
  const int64 creation_time_nsec = 0;
#endif

  info->last_modified =
      base::Time::FromTimeT(last_modified_sec) +
      base::TimeDelta::FromMicroseconds(last_modified_nsec /
                                        base::Time::kNanosecondsPerMicrosecond);
  info->last_accessed =
      base::Time::FromTimeT(last_accessed_sec) +
      base::TimeDelta::FromMicroseconds(last_accessed_nsec /
                                        base::Time::kNanosecondsPerMicrosecond);
  info->creation_time =
      base::Time::FromTimeT(creation_time_sec) +
      base::TimeDelta::FromMicroseconds(creation_time_nsec /
                                        base::Time::kNanosecondsPerMicrosecond);
  return true;
}

File::Error File::Lock() {
  return CallFctnlFlock(file_, true);
}

File::Error File::Unlock() {
  return CallFctnlFlock(file_, false);
}

// Static.
File::Error File::OSErrorToFileError(int saved_errno) {
  switch (saved_errno) {
    case EACCES:
    case EISDIR:
    case EROFS:
    case EPERM:
      return FILE_ERROR_ACCESS_DENIED;
#if !defined(OS_NACL)  // ETXTBSY not defined by NaCl.
    case ETXTBSY:
      return FILE_ERROR_IN_USE;
#endif
    case EEXIST:
      return FILE_ERROR_EXISTS;
    case ENOENT:
      return FILE_ERROR_NOT_FOUND;
    case EMFILE:
      return FILE_ERROR_TOO_MANY_OPENED;
    case ENOMEM:
      return FILE_ERROR_NO_MEMORY;
    case ENOSPC:
      return FILE_ERROR_NO_SPACE;
    case ENOTDIR:
      return FILE_ERROR_NOT_A_DIRECTORY;
    default:
#if !defined(OS_NACL)  // NaCl build has no metrics code.
      UMA_HISTOGRAM_SPARSE_SLOWLY("PlatformFile.UnknownErrors.Posix",
                                  saved_errno);
#endif
      return FILE_ERROR_FAILED;
  }
}

void File::SetPlatformFile(PlatformFile file) {
  DCHECK_EQ(file_, kInvalidPlatformFileValue);
  file_ = file;
}

}  // namespace base


text:
package org.hawkular.metrics.core.service.metrics;

import static java.util.Arrays.asList;
import static java.util.Collections.emptyMap;
import static java.util.Collections.singletonList;

import static org.hawkular.metrics.core.service.DataAccessImpl.DPART;
import static org.hawkular.metrics.core.service.TimeUUIDUtils.getTimeUUID;
import static org.hawkular.metrics.model.AvailabilityType.ADMIN;
import static org.hawkular.metrics.model.AvailabilityType.DOWN;
import static org.hawkular.metrics.model.AvailabilityType.UNKNOWN;
import static org.hawkular.metrics.model.AvailabilityType.UP;
import static org.hawkular.metrics.model.MetricType.AVAILABILITY;
import static org.joda.time.DateTime.now;
import static org.joda.time.Days.days;
import static org.joda.time.Hours.hours;
import static org.testng.Assert.assertEquals;

import java.nio.ByteBuffer;
import java.util.List;

import org.hawkular.metrics.core.service.DelegatingDataAccess;
import org.hawkular.metrics.core.service.Order;
import org.hawkular.metrics.model.AvailabilityType;
import org.hawkular.metrics.model.DataPoint;
import org.hawkular.metrics.model.Metric;
import org.hawkular.metrics.model.MetricId;
import org.hawkular.metrics.model.Tenant;
import org.joda.time.DateTime;
import org.joda.time.Duration;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

import com.datastax.driver.core.BatchStatement;
import com.datastax.driver.core.PreparedStatement;
import com.google.common.collect.ImmutableMap;

import rx.Observable;

public class AvailabilityITest extends BaseMetricsITest {

    protected PreparedStatement insertAvailabilityDateWithTimestamp;

    @BeforeClass
    public void initClass() {
        super.initClass();

        insertAvailabilityDateWithTimestamp = session.prepare(
                "INSERT INTO data (tenant_id, type, metric, dpart, time, availability) " +
                        "VALUES (?, ?, ?, ?, ?, ?) " +
                        "USING TTL ? AND TIMESTAMP ?");
    }

    @Test
    public void addAvailabilityForMultipleMetrics() throws Exception {
        DateTime start = now().minusMinutes(10);
        DateTime end = start.plusMinutes(8);
        String tenantId = "test-tenant";

        metricsService.createTenant(new Tenant(tenantId), false).toBlocking().lastOrDefault(null);

        Metric<AvailabilityType> m1 = new Metric<>(new MetricId<>(tenantId, AVAILABILITY, "m1"), asList(
                new DataPoint<>(start.plusSeconds(10).getMillis(), UP),
                new DataPoint<>(start.plusSeconds(20).getMillis(), DOWN)));
        Metric<AvailabilityType> m2 = new Metric<>(new MetricId<>(tenantId, AVAILABILITY, "m2"), asList(
                new DataPoint<>(start.plusSeconds(15).getMillis(), DOWN),
                new DataPoint<>(start.plusSeconds(30).getMillis(), UP)));
        Metric<AvailabilityType> m3 = new Metric<>(new MetricId<>(tenantId, AVAILABILITY, "m3"));

        metricsService.addDataPoints(AVAILABILITY, Observable.just(m1, m2, m3)).toBlocking().lastOrDefault(null);

        List<DataPoint<AvailabilityType>> actual = metricsService.findDataPoints(m1.getMetricId(),
                start.getMillis(), end.getMillis(), 0, Order.ASC).toList().toBlocking().last();
        assertEquals(actual, m1.getDataPoints(), "The availability data does not match expected values");

        actual = metricsService.findDataPoints(m2.getMetricId(), start.getMillis(), end.getMillis(), 0, Order.ASC)
                .toList().toBlocking().last();
        assertEquals(actual, m2.getDataPoints(), "The availability data does not match expected values");

        actual = metricsService.findDataPoints(m3.getMetricId(), start.getMillis(), end.getMillis(), 0, Order.DESC)
                .toList().toBlocking().last();
        assertEquals(actual.size(), 0, "Did not expect to get back results since there is no data for " + m3);

        Metric<AvailabilityType> m4 = new Metric<>(new MetricId<>(tenantId, AVAILABILITY, "m4"), emptyMap(), 24,
                asList(
                        new DataPoint<>(start.plusMinutes(2).getMillis(), UP),
                        new DataPoint<>(end.plusMinutes(2).getMillis(), UP)));
        metricsService.createMetric(m4, false).toBlocking().lastOrDefault(null);

        metricsService.addDataPoints(AVAILABILITY, Observable.just(m4)).toBlocking().lastOrDefault(null);

        actual = metricsService.findDataPoints(m4.getMetricId(), start.getMillis(), end.getMillis(), 0, Order.DESC)
                .toList().toBlocking().last();
        Metric<AvailabilityType> expected = new Metric<>(m4.getMetricId(), emptyMap(), 24,
                singletonList(new DataPoint<>(start.plusMinutes(2).getMillis(), UP)));
        assertEquals(actual, expected.getDataPoints(), "The availability data does not match expected values");

        assertMetricIndexMatches(tenantId, AVAILABILITY, asList(
                new Metric<>(m1.getMetricId(), 7),
                new Metric<>(m2.getMetricId(), 7),
                new Metric<>(m4.getMetricId(), 24)));
    }

    @Test
    public void findDistinctAvailabilities() throws Exception {
        DateTime end = now();
        DateTime start = end.minusMinutes(20);
        String tenantId = "tenant1";
        MetricId<AvailabilityType> metricId = new MetricId<>("tenant1", AVAILABILITY, "A1");

        metricsService.createTenant(new Tenant(tenantId), false).toBlocking().lastOrDefault(null);

        Metric<AvailabilityType> metric = new Metric<>(metricId, asList(
                new DataPoint<>(start.getMillis(), UP),
                new DataPoint<>(start.plusMinutes(1).getMillis(), DOWN),
                new DataPoint<>(start.plusMinutes(2).getMillis(), DOWN),
                new DataPoint<>(start.plusMinutes(3).getMillis(), UP),
                new DataPoint<>(start.plusMinutes(4).getMillis(), DOWN),
                new DataPoint<>(start.plusMinutes(5).getMillis(), UP),
                new DataPoint<>(start.plusMinutes(6).getMillis(), UP),
                new DataPoint<>(start.plusMinutes(7).getMillis(), UNKNOWN),
                new DataPoint<>(start.plusMinutes(8).getMillis(), UNKNOWN),
                new DataPoint<>(start.plusMinutes(9).getMillis(), DOWN),
                new DataPoint<>(start.plusMinutes(10).getMillis(), ADMIN),
                new DataPoint<>(start.plusMinutes(11).getMillis(), UP)));

        metricsService.addDataPoints(AVAILABILITY, Observable.just(metric)).toBlocking().lastOrDefault(null);

        List<DataPoint<AvailabilityType>> actual = metricsService.findAvailabilityData(metricId,
                start.getMillis(), end.getMillis(), true, 0, Order.ASC).toList().toBlocking().lastOrDefault(null);

        List<DataPoint<AvailabilityType>> expected = asList(
                metric.getDataPoints().get(0),
                metric.getDataPoints().get(1),
                metric.getDataPoints().get(3),
                metric.getDataPoints().get(4),
                metric.getDataPoints().get(5),
                metric.getDataPoints().get(7),
                metric.getDataPoints().get(9),
                metric.getDataPoints().get(10),
                metric.getDataPoints().get(11));

        assertEquals(actual, expected, "The availability data does not match the expected values");
    }

    @Test
    public void verifyTTLsSetOnAvailabilityData() throws Exception {
        DateTime start = now().minusMinutes(10);

        metricsService.createTenant(new Tenant("t1"), false).toBlocking().lastOrDefault(null);
        metricsService.createTenant(
                new Tenant("t2", ImmutableMap.of(AVAILABILITY, 14)), false).toBlocking().lastOrDefault(null);

        VerifyTTLDataAccess verifyTTLDataAccess = new VerifyTTLDataAccess(dataAccess);

        metricsService.setDataAccess(verifyTTLDataAccess);
        metricsService.setDataAccess(verifyTTLDataAccess);

        List<DataPoint<AvailabilityType>> dataPoints = asList(
                new DataPoint<>(start.getMillis(), UP),
                new DataPoint<>(start.plusMinutes(1).getMillis(), DOWN),
                new DataPoint<>(start.plusMinutes(2).getMillis(), DOWN));
        Metric<AvailabilityType> m1 = new Metric<>(new MetricId<>("t1", AVAILABILITY, "m1"), dataPoints);

        addAvailabilityDataInThePast(m1, days(2).toStandardDuration());

        verifyTTLDataAccess.setAvailabilityTTL(days(14).toStandardSeconds().getSeconds());
        Metric<AvailabilityType> m2 = new Metric<>(new MetricId<>("t2", AVAILABILITY, "m2"),
                singletonList(new DataPoint<>(start.plusMinutes(5).getMillis(), UP)));

        addAvailabilityDataInThePast(m2, days(5).toStandardDuration());

        metricsService.createTenant(new Tenant("t3", ImmutableMap.of(AVAILABILITY, 24)), false)
                .toBlocking()
                .lastOrDefault(null);
        verifyTTLDataAccess.setAvailabilityTTL(hours(24).toStandardSeconds().getSeconds());
        Metric<AvailabilityType> m3 = new Metric<>(new MetricId<>("t3", AVAILABILITY, "m3"),
                singletonList(new DataPoint<>(start.getMillis(), UP)));

        metricsService.addDataPoints(AVAILABILITY, Observable.just(m3)).toBlocking();
    }

    private void addAvailabilityDataInThePast(Metric<AvailabilityType> metric, final Duration duration)
            throws Exception {
        try {
            metricsService.setDataAccess(new DelegatingDataAccess(dataAccess) {
                @Override
                public Observable<Integer> insertAvailabilityData(Metric<AvailabilityType> m, int ttl) {
                    int actualTTL = ttl - duration.toStandardSeconds().getSeconds();
                    long writeTime = now().minus(duration).getMillis() * 1000;
                    BatchStatement batchStatement = new BatchStatement(BatchStatement.Type.UNLOGGED);
                    for (DataPoint<AvailabilityType> a : m.getDataPoints()) {
                        batchStatement.add(insertAvailabilityDateWithTimestamp.bind(m.getMetricId().getTenantId(),
                                AVAILABILITY.getCode(), m.getMetricId().getName(), DPART,
                                getTimeUUID(a.getTimestamp()),
                                getBytes(a), actualTTL, writeTime));
                    }
                    return rxSession.execute(batchStatement).map(resultSet -> batchStatement.size());
                }
            });
            metricsService.addDataPoints(AVAILABILITY, Observable.just(metric));
        } finally {
            metricsService.setDataAccess(dataAccess);
        }
    }

    private ByteBuffer getBytes(DataPoint<AvailabilityType> dataPoint) {
        return ByteBuffer.wrap(new byte[] { dataPoint.getValue().getCode() });
    }
}


text:
<?php

class Twig_Node_Expression_Binary_Matches extends Twig_Node_Expression_Binary
{

    public function compile( Twig_Compiler $compiler )
    {

        $compiler
            ->raw( 'preg_match(' )
            ->subcompile( $this->getNode( 'right' ) )
            ->raw( ', ' )
            ->subcompile( $this->getNode( 'left' ) )
            ->raw( ')' );
    }

    public function operator( Twig_Compiler $compiler )
    {

        return $compiler->raw( '' );
    }
}


text:
external help file: AzureAutomationTools.PackageManagement-help.xml
online version:
schema: 2.0.0
---

# Get-AatPackagePath

## SYNOPSIS
Gets the package path for the working package.

## SYNTAX

```
Get-AatPackagePath [<CommonParameters>]
```

## DESCRIPTION
Gets the package path for the working package.

## EXAMPLES

### Example 1: Get the package path
```PowerShell
PS C:\> Get-AatPackagePath
C:\aat-package-examples\example-1
```

## PARAMETERS

### CommonParameters
This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see about_CommonParameters (http://go.microsoft.com/fwlink/?LinkID=113216).

## INPUTS

### None

## OUTPUTS

### System.Object

## NOTES

## RELATED LINKS


text:
package net.logvv.raven.utils;

import net.logvv.raven.common.exception.ExceptionLevel;
import net.logvv.raven.common.exception.ExceptionMessage;

public class ExceptionUtils
{
	/** 日志记录器 */
	/** 网页换行 */
	private static final String newLine = "
";

	/** html字体颜色模板 */
	private static final String colorTemplate = "%s%s%s";

	public ExceptionUtils()
	{

	}

	/** 获取异常堆栈异常信息 */
	public static String getStackTraceMsg(Throwable e)
	{
		if (null == e){
			return "";
		}

		StackTraceElement[] messages = e.getStackTrace();
		StringBuilder exceptionMsg = new StringBuilder(2000);
		exceptionMsg.append(bold(e.toString())).append(newLine);
		int length = messages.length;
		exceptionMsg.append("");
		for (int i = 0; i < length; i++)
		{
			exceptionMsg.append("at " + messages[i].toString()).append(newLine);
		}
		exceptionMsg.append("");

		return exceptionMsg.toString();
	}

	/** 生成异常信息实体类*/
	public static ExceptionMessage generateExceptionMsg(String phoneNumber, String productCode, String versionName, String clientType,
			ExceptionLevel exceptionLevel,String operationDesc, String exceptionMsg)
	{
		ExceptionMessage exceptionMsgObj = new ExceptionMessage();
		exceptionMsgObj.setPhoneNumber(null == phoneNumber ? "NONE" : phoneNumber);
		exceptionMsgObj.setExceptionLevel(null == exceptionLevel ? ExceptionLevel.CRITICAL : exceptionLevel);
		exceptionMsgObj.setExceptionMessage(null == exceptionMsg ? "Unkown Exception" : exceptionMsg);
		exceptionMsgObj.setProductCode(null == productCode ? "" : productCode);
		exceptionMsgObj.setClientType(null == clientType ? "SERVER" : clientType);
		exceptionMsgObj.setUserOperationDesc(null == operationDesc ? "" : operationDesc);
		exceptionMsgObj.setVersionName(null == versionName ? "" : versionName);
		return exceptionMsgObj;
	}

	private static String bold(String str)
	{
		return String.format(colorTemplate, "", str, "");
	}
}


text:
from setuptools import setup, find_packages

version = {}
with open("emotioncf/version.py") as f:
    exec(f.read(), version)

with open('requirements.txt') as f:
    requirements = f.read().splitlines()

extra_setuptools_args = dict(
    tests_require=['pytest']
)

setup(
    name="emotioncf",
    version=version['__version__'],
    description='A Python package for performing Collaborative Filtering on sparse emotion ratings',
    maintainer='Luke Chang',
    maintainer_email='luke.j.chang@dartmouth.edu',
    url='http://github.com/ljchang/emotionCF',
    install_requires=requirements,
    packages=find_packages(exclude=['emotioncf/tests']),
    license='MIT',
    keywords = ['emotion', 'collaborative filtering', 'recommender','machine-learning'],
    classifiers = [
        "Programming Language :: Python :: 2.7",
        "Programming Language :: Python :: 3.6",
        "Operating System :: OS Independent",
        "Intended Audience :: Science/Research",
        "License :: OSI Approved :: MIT License"
    ],
    **extra_setuptools_args
)


text:
using System;
using System.Collections.Generic;

namespace WilliamsonFamily.Models.Blog
{
    public interface IBlogList
    {
        IEnumerable<IBlog> BlogEntries { get; }
        int PageCount { get; }
        int PageIndex { get; }
    }
}


text:
namespace _14.Labyrinth
{
    using System;
    using System.Collections;
    using System.Collections.Generic;

    public class Program
    {
        public static void Main()
        {
            //Test labyrinth
            char[,] labyrinth =
                                 {
                {'0', '0', '0', 'x', '0', 'x'},
                {'0', 'x', '0', 'x', '0', 'x'},
                {'0', '*', 'x', '0', 'x', '0'},
                {'0', 'x', '0', '0', '0', '0'},
                {'0', '0', '0', 'x', 'x', '0'},
                {'0', '0', '0', 'x', '0', 'x'}
            };

            Position player = new Position { Row = 2, Column = 1 };
            int[,] resultMoves = new int[labyrinth.GetLength(0), labyrinth.GetLength(1)];
            Queue<QueueItem> queue = new Queue<QueueItem>();

            HashSet<Position> visited = new HashSet<Position>();

            queue.Enqueue(new QueueItem { Position = player, Value = 0 });
            visited.Add(player);

            while (queue.Count != 0)
            {
                var cell = queue.Dequeue();

                if (OutOfField(cell.Position, labyrinth))
                {
                    continue;
                }

                Position up = new Position { Row = cell.Position.Row - 1, Column = cell.Position.Column };
                Position down = new Position { Row = cell.Position.Row + 1, Column = cell.Position.Column };
                Position left = new Position { Column = cell.Position.Column - 1, Row = cell.Position.Row };
                Position right = new Position { Column = cell.Position.Column + 1, Row = cell.Position.Row };

                VisiteCell(labyrinth, up, visited, cell.Value + 1, queue, resultMoves);
                VisiteCell(labyrinth, down, visited, cell.Value + 1, queue, resultMoves);
                VisiteCell(labyrinth, left, visited, cell.Value + 1, queue, resultMoves);
                VisiteCell(labyrinth, right, visited, cell.Value + 1, queue, resultMoves);
            }

            char[,] resultLabyrinth = new char[labyrinth.GetLength(0), labyrinth.GetLength(1)];

            //Print the result
            for (var i = 0; i < resultMoves.GetLength(0); i++)
            {
                for (var j = 0; j < resultMoves.GetLength(1); j++)
                {
                    if (labyrinth[i, j] == 'x')
                    {
                        Console.Write(" X ");
                    }
                    else
                        if (labyrinth[i, j] == '*')
                    {
                        Console.Write(" * ");
                    }
                    else
                    {
                        if (resultMoves[i, j] == 0)
                        {
                            Console.Write(" U ");
                        }
                        else
                        {
                            Console.Write(" " + resultMoves[i, j] + " ");
                        }
                    }
                }

                Console.WriteLine();
            }
        }

        private static void VisiteCell(char[,] labyrinth, Position visiteCellAtPosition, HashSet<Position> visited, int cellValue, Queue<QueueItem> queue, int[,] resultMovesCount)
        {
            if (!OutOfField(visiteCellAtPosition, labyrinth)
                    && labyrinth[visiteCellAtPosition.Row, visiteCellAtPosition.Column] != 'x'
                    && !visited.Contains(visiteCellAtPosition))
            {
                queue.Enqueue(new QueueItem { Position = visiteCellAtPosition, Value = cellValue });
                resultMovesCount[visiteCellAtPosition.Row, visiteCellAtPosition.Column] = cellValue;
                visited.Add(visiteCellAtPosition);
            }
        }

        private static bool OutOfField(Position cellPosition, char[,] labyrinth)
        {
            if (cellPosition.Column < 0 ||
                cellPosition.Column > labyrinth.GetLength(1) - 1 ||
                cellPosition.Row < 0 ||
                cellPosition.Row > labyrinth.GetLength(0) - 1)
            {
                return true;
            }

            return false;
        }
    }
}


text:
/*Navigation*/
.navbar {
      margin-bottom: 0;
      background-color: #2d83bc;
      z-index: 9999;
      border: 0;
      font-size: 12px !important;
      line-height: 1.42857143 !important;
      letter-spacing: 4px;
      border-radius: 0;
      font-family: 'Raleway', serif;
  }
  .navbar .navbar-brand {
      letter-spacing: 0;
  }
  .navbar li a, .navbar .navbar-brand {
      color: #fff !important;
  }
  .navbar-nav li a:hover, .navbar-nav li.active a {
      color: #2d83bc !important;
      background-color: #fff !important;
  }
  .navbar-default .navbar-toggle {
      border-color: transparent;
      color: #fff !important;
  }

nav .navbar-header span {
    background: #fff;
}

@media only screen and (max-width: 767px) {
    .navbar-brand {
        margin-left: 10px;
    }

    #myNavbar ul li {
        margin-left: 10px;
    }

    .navbar-toggle {
        margin-right: 15px;
    }
}


text:
<?php
# $Id$
# Testing PHPlot - Bad data range with SetPlotAreaWorld
# See the script named below for details
$subtitle = 'Xmax<Data_Min, Xmin unset'; // Subtitle for plot
$spaw = array(NULL, 20, 20, 200); // Args to SetPlotAreaWorld
require 'error-SetPlotAreaWorld.php';


text:
  Author: "Younes Zakaria"
  Description: "A dark and techy theme, with a blue background and bright, neon-like colors."
  FileName: "SpaceRave.tmTheme"
  ID: "SpaceRave"
  Title: "Space Rave"
  layout: theme
---


text:
<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;

/* @var $this yii\web\View */
/* @var $model app\models\ApplyActivity */
/* @var $form yii\widgets\ActiveForm */
?>

    <?php $form = ActiveForm::begin(); ?>

    <?= $form->field($model, 'user_id')->textInput() ?>

    <?= $form->field($model, 'project_id')->textInput() ?>

    <?= $form->field($model, 'created_at')->textInput() ?>

        <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>

    <?php ActiveForm::end(); ?>