text:
namespace device {
namespace cbor_extract {

namespace {

using internal::Type;

static_assert(sizeof(StepOrByte<void>) == 1,
              "things should fit into a single byte");

const bool kTrue = true;
const bool kFalse = false;

constexpr uint8_t CBORTypeToBitfield(const cbor::Value::Type type) {
  const unsigned type_u = static_cast<unsigned>(type);
  if (type_u >= 8) {
    __builtin_unreachable();
  }
  return 1u << type_u;
}

// ASSERT_TYPE_IS asserts that the type of |a| is |b|. This is used to ensure
// that the documented output types for elements of |Type| are correct.
#define ASSERT_TYPE_IS(a, b)                                                \
  static_assert(                                                            \
      std::is_same<decltype(&a), decltype(reinterpret_cast<b*>(0))>::value, \
      "types need updating");

class Extractor {
 public:
  Extractor(base::span<const void*> outputs,
            base::span<const StepOrByte<void>> steps)
      : outputs_(outputs), steps_(steps) {}

  bool ValuesFromMap(const cbor::Value::MapValue& map) {
    for (;;) {
      // steps_[] emits a CHECK, and we don't want the code-size hit. Thus
      // bounds are DCHECKed but then steps_.data() is dereferenced.
      DCHECK_LT(step_i_, steps_.size());
      const internal::Step step = steps_.data()[step_i_++].step;
      const Type value_type = static_cast<Type>(step.value_type);
      if (value_type == Type::kStop) {
        return true;
      }

      DCHECK_LT(step_i_, steps_.size());
      const uint8_t key_or_string_indicator = steps_.data()[step_i_++].u8;
      cbor::Value::MapValue::const_iterator map_it;
      if (key_or_string_indicator == StepOrByte<void>::STRING_KEY) {
        DCHECK_LT(step_i_, steps_.size());
        std::string key(&steps_.data()[step_i_].c);
        step_i_ += key.size() + 1;
        map_it = map.find(cbor::Value(std::move(key)));
      } else {
        map_it = map.find(
            cbor::Value(static_cast<int64_t>(key_or_string_indicator)));
      }

      const void** output = nullptr;
      if (value_type != Type::kMap) {
        DCHECK_LT(step.output_index, outputs_.size());
        output = &outputs_.data()[step.output_index];
      }

      if (map_it == map.end()) {
        if (step.required) {
          return false;
        }
        if (output) {
          *output = nullptr;
        }
        continue;
      }

      // kExpectedCBORTypes is an array of bitmaps of acceptable types for each
      // |Type|.
      static constexpr uint8_t kExpectedCBORTypes[] = {
          // kBytestring
          CBORTypeToBitfield(cbor::Value::Type::BYTE_STRING),
          // kString
          CBORTypeToBitfield(cbor::Value::Type::STRING),
          // kBoolean
          CBORTypeToBitfield(cbor::Value::Type::SIMPLE_VALUE),
          // kInt
          CBORTypeToBitfield(cbor::Value::Type::NEGATIVE) |
              CBORTypeToBitfield(cbor::Value::Type::UNSIGNED),
          // kMap
          CBORTypeToBitfield(cbor::Value::Type::MAP),
          // kArray
          CBORTypeToBitfield(cbor::Value::Type::ARRAY),
          // kValue
          0xff,
      };

      const cbor::Value& value = map_it->second;
      const unsigned cbor_type_u = static_cast<unsigned>(value.type());
      const unsigned value_type_u = static_cast<unsigned>(value_type);
      DCHECK(value_type_u < base::size(kExpectedCBORTypes));
      if (cbor_type_u >= 8 ||
          (kExpectedCBORTypes[value_type_u] & (1u << cbor_type_u)) == 0) {
        return false;
      }

      switch (value_type) {
        case Type::kBytestring:
          ASSERT_TYPE_IS(value.GetBytestring(), const std::vector<uint8_t>);
          *output = &value.GetBytestring();
          break;
        case Type::kString:
          ASSERT_TYPE_IS(value.GetString(), const std::string);
          *output = &value.GetString();
          break;
        case Type::kBoolean:
          switch (value.GetSimpleValue()) {
            case cbor::Value::SimpleValue::TRUE_VALUE:
              *output = &kTrue;
              break;
            case cbor::Value::SimpleValue::FALSE_VALUE:
              *output = &kFalse;
              break;
            default:
              return false;
          }
          break;
        case Type::kInt:
          ASSERT_TYPE_IS(value.GetInteger(), const int64_t);
          *output = &value.GetInteger();
          break;
        case Type::kMap:
          if (!ValuesFromMap(value.GetMap())) {
            return false;
          }
          break;
        case Type::kArray:
          ASSERT_TYPE_IS(value.GetArray(), const std::vector<cbor::Value>);
          *output = &value.GetArray();
          break;
        case Type::kValue:
          *output = &value;
          break;
        case Type::kStop:
          return false;
      }
    }

    return true;
  }

 private:
  base::span<const void*> outputs_;
  base::span<const StepOrByte<void>> steps_;
  size_t step_i_ = 0;
};

}  // namespace

namespace internal {

bool Extract(base::span<const void*> outputs,
             base::span<const StepOrByte<void>> steps,
             const cbor::Value::MapValue& map) {
  DCHECK(steps[steps.size() - 1].step.value_type ==
         static_cast<uint8_t>(Type::kStop));
  Extractor extractor(outputs, steps);
  return extractor.ValuesFromMap(map);
}

}  // namespace internal

bool ForEachPublicKeyEntry(
    const cbor::Value::ArrayValue& array,
    const cbor::Value& key,
    base::RepeatingCallback<bool(const cbor::Value&)> callback) {
  const cbor::Value type_key("type");
  const std::string public_key("public-key");

  for (const cbor::Value& value : array) {
    if (!value.is_map()) {
      return false;
    }
    const cbor::Value::MapValue& map = value.GetMap();
    const auto type_it = map.find(type_key);
    if (type_it == map.end() || !type_it->second.is_string()) {
      return false;
    }
    if (type_it->second.GetString() != public_key) {
      continue;
    }

    const auto value_it = map.find(key);
    if (value_it == map.end() || !callback.Run(value_it->second)) {
      return false;
    }
  }

  return true;
}

}  // namespace cbor_extract
}  // namespace device


text:
/* Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.activiti.rest.dmn.service.api.repository;

import org.activiti.dmn.api.DecisionTable;

/**
 * @author Yvo Swillens
 */
public class DecisionTableResponse {

  protected String id;
  protected String url;
  protected String category;
  protected String name;
  protected String key;
  protected String description;
  protected int version;
  protected String resourceName;
  protected String deploymentId;
  protected String tenantId;

  public DecisionTableResponse(DecisionTable decisionTable) {
    setId(decisionTable.getId());
    setCategory(decisionTable.getCategory());
    setName(decisionTable.getName());
    setKey(decisionTable.getKey());
    setDescription(decisionTable.getDescription());
    setVersion(decisionTable.getVersion());
    setResourceName(decisionTable.getResourceName());
    setDeploymentId(decisionTable.getDeploymentId());
    setTenantId(decisionTable.getTenantId());
  }

  public String getId() {
    return id;
  }

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

  public String getUrl() {
    return url;
  }

  public void setUrl(String url) {
    this.url = url;
  }

  public String getCategory() {
    return category;
  }

  public void setCategory(String category) {
    this.category = category;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public String getKey() {
    return key;
  }

  public void setKey(String key) {
    this.key = key;
  }

  public String getDescription() {
    return description;
  }

  public void setDescription(String description) {
    this.description = description;
  }

  public int getVersion() {
    return version;
  }

  public void setVersion(int version) {
    this.version = version;
  }

  public String getResourceName() {
    return resourceName;
  }

  public void setResourceName(String resourceName) {
    this.resourceName = resourceName;
  }

  public String getDeploymentId() {
    return deploymentId;
  }

  public void setDeploymentId(String deploymentId) {
    this.deploymentId = deploymentId;
  }

  public String getTenantId() {
    return tenantId;
  }

  public void setTenantId(String tenantId) {
    this.tenantId = tenantId;
  }
}

redpajama_set_name: RedPajamaGithub


text:
(function() {
  var PrettyPrinter, colors, moment, options, pad, wrap,
    __indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

  wrap = require('wordwrap')(8, 80);

  pad = require('wordwrap')(2, 100);

  moment = require('moment');

  colors = require('colors');

  options = require('./format-options');

  PrettyPrinter = (function() {
    var dash, newline, seperator;

    function PrettyPrinter() {}

    colors.setTheme({
      success: "green",
      error: "red",
      log: "white",
      low: "green",
      medium: "yellow",
      high: "magenta",
      crit: "red"
    });

    PrettyPrinter.prototype.prettyPrintList = function(issue, detail) {
      var _ref, _ref1;
      process.stdout.write(issue.key.log.bold);
      if (issue.fields.summary == null) {
        issue.fields.summary = "None";
      }
      dash();
      process.stdout.write(issue.fields.summary.log);
      if (detail) {
        if (issue.fields.issuetype != null) {
          process.stdout.write("Type:".log.bold);
          if (_ref = issue.fields.issuetype.name, __indexOf.call(options.bad_types, _ref) >= 0) {
            process.stdout.write(pad(issue.fields.issuetype.name).high);
          } else {
            process.stdout.write(pad(issue.fields.issuetype.name).low);
          }
        }
        newline();
        process.stdout.write("Status:".log.bold);
        if (_ref1 = issue.fields.status.name, __indexOf.call(options.bad_statuses, _ref1) >= 0) {
          process.stdout.write(pad(issue.fields.status.name).red);
        } else {
          process.stdout.write(pad(issue.fields.status.name).green);
        }
        newline();
        process.stdout.write("Assigned To:".log.bold);
        process.stdout.write(pad(issue.fields.assignee.name).log);
        newline();
      }
      return newline();
    };

    PrettyPrinter.prototype.prettyPrintIssue = function(issue, detail) {
      var dt, txt, _ref, _ref1, _ref2, _ref3, _ref4;
      newline();
      seperator().yellow;
      newline();
      process.stdout.write("Issue:".log.bold);
      process.stdout.write(pad(issue.key).log.bold);
      if (issue.fields.summary == null) {
        issue.fields.summary = "None";
      }
      dash();
      process.stdout.write(issue.fields.summary.log);
      newline();
      if (detail) {
        if (issue.fields.description != null) {
          process.stdout.write("Description:".log.bold);
          newline();
          txt = issue.fields.description.slice(0, 300);
          process.stdout.write(wrap(txt).log);
          if (txt.length > 300) {
            newline();
            process.stdout.write(pad("..."));
          }
          newline();
        }
        if (issue.fields.issuetype != null) {
          process.stdout.write("Type:".log.bold);
          if (_ref = issue.fields.issuetype.name, __indexOf.call(options.bad_types, _ref) >= 0) {
            process.stdout.write(pad(issue.fields.issuetype.name).high);
          } else {
            process.stdout.write(pad(issue.fields.issuetype.name).low);
          }
          newline();
        }
        process.stdout.write("Status:".log.bold);
        if (_ref1 = issue.fields.status.name, __indexOf.call(options.bad_statuses, _ref1) >= 0) {
          process.stdout.write(pad(issue.fields.status.name).red);
        } else {
          process.stdout.write(pad(issue.fields.status.name).green);
        }
        newline();
        process.stdout.write("Priority:".log.bold);
        if (_ref2 = issue.fields.priority.name, __indexOf.call(options.med_priority, _ref2) >= 0) {
          process.stdout.write(pad(issue.fields.priority.name).medium);
        } else if (_ref3 = issue.fields.priority.name, __indexOf.call(options.high_priority, _ref3) >= 0) {
          process.stdout.write(pad(issue.fields.priority.name).high);
        } else if (_ref4 = issue.fields.priority.name, __indexOf.call(options.critical_priority, _ref4) >= 0) {
          process.stdout.write(pad(issue.fields.priority.name).crit);
        } else {
          process.stdout.write(pad(issue.fields.priority.name).low);
        }
        newline();
        process.stdout.write("Assigned To:".log.bold);
        process.stdout.write(pad(issue.fields.assignee.name).log);
        newline();
        process.stdout.write("Reporter:".log.bold);
        process.stdout.write(pad(issue.fields.reporter.name).log);
        newline();
        process.stdout.write("Created On:".log.bold);
        dt = moment(issue.fields.created).format("MM/D/YYYY h:mm:ss a");
        process.stdout.write(pad(dt));
        newline();
        process.stdout.write("Updated On:".log.bold);
        dt = moment(issue.fields.updated).format("MM/D/YYYY h:mm:ss a");
        process.stdout.write(pad(dt));
        newline();
      }
      return newline();
    };

    PrettyPrinter.prototype.prettyPrintIssueTypes = function(issueType, index) {
      if (issueType.subtask === false) {
        process.stdout.write(issueType.id.log.bold);
        dash();
        process.stdout.write(issueType.name);
        if (issueType.description.length > 0) {
          dash();
          process.stdout.write(issueType.description);
        }
        return newline();
      }
    };

    PrettyPrinter.prototype.prettyPrintTransition = function(transition, index) {
      process.stdout.write(transition.id);
      dash();
      process.stdout.write(transition.name);
      return newline();
    };

    PrettyPrinter.prototype.prettyPrintProject = function(project) {
      var key;
      key = project.key;
      while (key.length < 12) {
        key = ' ' + key;
      }
      process.stdout.write(project.key);
      dash();
      process.stdout.write(project.name);
      return newline();
    };

    PrettyPrinter.prototype.prettyPrintError = function(message) {
      process.stdout.write(message.error);
      return newline();
    };

    PrettyPrinter.prototype.prettyPrintSuccess = function(message) {
      process.stdout.write(message.success);
      return newline();
    };

    PrettyPrinter.prototype.prettyPrintLog = function(message) {
      process.stdout.write(message.log);
      return newline();
    };

    newline = function() {
      return process.stdout.write("\n");
    };

    dash = function() {
      return process.stdout.write(" - ");
    };

    seperator = function() {
      var i, txt, _i;
      txt = "";
      for (i = _i = 1; _i <= 80; i = ++_i) {
        txt += "*";
      }
      return process.stdout.write(txt);
    };

    return PrettyPrinter;

  })();

  module.exports = {
    PrettyPrinter: PrettyPrinter
  };

}).call(this);


text:
package org.hisp.dhis.sms.task;

import java.util.List;

import org.hisp.dhis.i18n.I18n;
import org.hisp.dhis.scheduling.TaskId;
import org.hisp.dhis.sms.SmsSender;
import org.hisp.dhis.system.notification.Notifier;
import org.hisp.dhis.user.User;
import org.springframework.beans.factory.annotation.Autowired;

public class SendSmsTask
    implements Runnable
{
    @Autowired
    private SmsSender smsSender;

    @Autowired
    private Notifier notifier;

    // -------------------------------------------------------------------------
    // Input & Output
    // -------------------------------------------------------------------------

    private String smsSubject;

    private String text;

    private User currentUser;

    private List<User> recipientsList;

    private String message = "success";

    private TaskId taskId;

    // -------------------------------------------------------------------------
    // I18n
    // -------------------------------------------------------------------------

    private I18n i18n;

    public void setI18n( I18n i18n )
    {
        this.i18n = i18n;
    }

    @Override
    public void run()
    {
        notifier.notify( taskId, "Sending SMS" );
        message = smsSender.sendMessage( smsSubject, text, currentUser, recipientsList, false );
        notifier.notify( taskId, "All Message Sent" );
    }

    public String getSmsSubject()
    {
        return smsSubject;
    }

    public void setSmsSubject( String smsSubject )
    {
        this.smsSubject = smsSubject;
    }

    public String getText()
    {
        return text;
    }

    public void setText( String text )
    {
        this.text = text;
    }

    public User getCurrentUser()
    {
        return currentUser;
    }

    public void setCurrentUser( User currentUser )
    {
        this.currentUser = currentUser;
    }

    public List<User> getRecipientsList()
    {
        return recipientsList;
    }

    public void setRecipientsList( List<User> recipientsList )
    {
        this.recipientsList = recipientsList;
    }

    public String getMessage()
    {
        return message;
    }

    public void setMessage( String message )
    {
        this.message = message;
    }

    public TaskId getTaskId()
    {
        return taskId;
    }

    public void setTaskId( TaskId taskId )
    {
        this.taskId = taskId;
    }

    public I18n getI18n()
    {
        return i18n;
    }

}


text:
import React from "react";
import { Provider } from "react-redux";

// $FlowExpectedError
<Provider />; // missing store


text:
<?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
 * tests for PMA_sanitize()
 *
 * @package PhpMyAdmin-test
 */

/*
 * Include to test
 */
require_once 'libraries/sanitizing.lib.php';
require_once 'libraries/url_generating.lib.php';
require_once 'libraries/core.lib.php';
require_once 'libraries/Util.class.php';

class PMA_sanitize_test extends PHPUnit_Framework_TestCase
{
    /**
     * Setup various pre conditions
     *
     * @return void
     */
    function setUp()
    {
        $_SESSION[' PMA_token '] = 'token';
    }

    /**
     * Tests for proper escaping of XSS.
     *
     * @return void
     */
    public function testXssInHref()
    {
        $this->assertEquals(
            '[a@javascript:alert(\'XSS\');@target]link',
            PMA_sanitize('[a@javascript:alert(\'XSS\');@target]link[/a]')
        );
    }

    /**
     * Tests correct generating of link redirector.
     *
     * @return void
     */
    public function testLink()
    {
        unset($GLOBALS['server']);
        unset($GLOBALS['lang']);
        unset($GLOBALS['collation_connection']);
        $this->assertEquals(
            'link',
            PMA_sanitize('[a@https://www.phpmyadmin.net/@target]link[/a]')
        );
    }

    /**
     * Tests links to documentation.
     *
     * @return void
     */
    public function testDoc()
    {
        $this->assertEquals(
            'doclink',
            PMA_sanitize('[doc@foo]doclink[/doc]')
        );
    }

    /**
     * Tests link target validation.
     *
     * @return void
     */
    public function testInvalidTarget()
    {
        $this->assertEquals(
            '[a@./Documentation.html@INVALID9]doc',
            PMA_sanitize('[a@./Documentation.html@INVALID9]doc[/a]')
        );
    }

    /**
     * Tests XSS escaping after valid link.
     *
     * @return void
     */
    public function testLinkDocXss()
    {
        $this->assertEquals(
            '[a@./Documentation.html" onmouseover="alert(foo)"]doc',
            PMA_sanitize('[a@./Documentation.html" onmouseover="alert(foo)"]doc[/a]')
        );
    }

    /**
     * Tests proper handling of multi link code.
     *
     * @return void
     */
    public function testLinkAndXssInHref()
    {
        $this->assertEquals(
            'doc[a@javascript:alert(\'XSS\');@target]link',
            PMA_sanitize('[a@https://docs.phpmyadmin.net/]doc[/a][a@javascript:alert(\'XSS\');@target]link[/a]')
        );
    }

    /**
     * Test escaping of HTML tags
     *
     * @return void
     */
    public function testHtmlTags()
    {
        $this->assertEquals(
            '<div onclick="">',
            PMA_sanitize('
')
        );
    }

    /**
     * Tests basic BB code.
     *
     * @return void
     */
    public function testBBCode()
    {
        $this->assertEquals(
            'strong',
            PMA_sanitize('[strong]strong[/strong]')
        );
    }

    /**
     * Tests output escaping.
     *
     * @return void
     */
    public function testEscape()
    {
        $this->assertEquals(
            '<strong>strong</strong>',
            PMA_sanitize('[strong]strong[/strong]', true)
        );
    }

    /**
     * Test for PMA_sanitizeFilename
     *
     * @return void
     */
    public function testSanitizeFilename()
    {
        $this->assertEquals(
            'File_name_123',
            PMA_sanitizeFilename('File_name 123')
        );
    }
}
?>


text:
using namespace std;

class CudaPipeline: public PipelineBase{

	static HANDLE pipelineMutex;
	static map<string, CudaPipeline *> cudaPipeMap;

	// private data
	void * privdata;
	int privdata_size;
public:
	// static functions
	static int do_register(const char * provider, CudaPipeline * pipe);
	static void do_unregister(const char * provider);
	static CudaPipeline * lookup(const char * provider);

	CudaPipeline(int privdata_size = 0);
	~CudaPipeline();

	static void Release();

	// from parent class
	//virtual struct pooldata * allocate_data();
	//virtual void release_data(struct pooldata * data);
	virtual struct pooldata * datapool_init(int n, int datasize);
	struct pooldata * datapool_init(int n, IDirect3DDevice9 * device);
	virtual struct pooldata * datapool_free(struct pooldata * head);
};

#endif


text:
typedef struct XbeHeader {
	uint32_t magic;
	uint8_t signature[256];
	uint32_t base, soh, soi, soih;
	uint32_t timedate, certaddr, numsects, secthdrs, flags;
	uint32_t oep, tls;
	uint32_t stack_commit, heap_reserve, heap_commit, pe_base;
	uint32_t pe_soi, pe_csum, pe_timedate;
	uint32_t debug_pathname, debug_filename, debug_ufilename;
	uint32_t thunk, imports, numvers, libvers, kvers, xapivers;
	uint32_t logoaddr, logosize;
} XbeHeader_t;

typedef struct XbeSection {
	uint32_t flags, vaddr, vsize, raddr, rsize;
	uint32_t nameaddr, nameref, headref, tailref;
	uint8_t digest[20];
} XbeSection_t;

typedef struct XbeTLS {
	uint32_t data_start, data_end, index, callback;
	uint32_t zero_fill, characteristics;
} XbeTLS_t;


text:
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
require 'ruby-jmeter'

test do
  threads count: 10 do
    visit name: 'Google Search', url: 'http://google.com/?hl=en&tbo=d&sclient=psy-ab&q=flood.io&oq=flood.io'
  end
end.run(path: '/usr/share/jmeter-2.13/bin/', gui: true)


text:
// Copyright 2010 Google Inc. All Rights Reserved.

package com.crawljax.util;

import com.google.common.collect.Lists;
import org.custommonkey.xmlunit.Difference;
import org.junit.Assert;
import org.junit.Test;

import java.util.List;

/**
 * Test the usage of the Helper.getDifferences.
 *
 * @author slenselink@google.com (Stefan Lenselink)
 */
public class XmlUnitDifferenceTest {

	@Test
	public void testEmptyDOMs() {
		String left = "";
		String right = "";
		List<Difference> l = DomUtils.getDifferences(left, right);
		Assert.assertEquals(0, l.size());
	}

	@Test
	public void testSameIdenticalDOMs() {
		String left = "<abc></abc>";
		String right = "<abc></abc>";
		List<Difference> l = DomUtils.getDifferences(left, right);
		Assert.assertEquals(0, l.size());
	}

	@Test
	public void testSameDOMsAttributesSame() {
		String left = "<abc><def value='bla'/></abc>";
		String right = "<abc><def value='bla'/></abc>";
		List<Difference> l = DomUtils.getDifferences(left, right);
		Assert.assertEquals(0, l.size());
	}

	@Test
	public void testSameDOMsAttributesFiltered() {
		String left = "<abc><def value='bla123'/></abc>";
		String right = "<abc><def value='bla'/></abc>";
		List<Difference> l = DomUtils.getDifferences(left, right, Lists.newArrayList("value"));
		Assert.assertEquals(0, l.size());
	}

}


text:
package grpc

import (
	"context"
	"net"

	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/peer"
	"google.golang.org/grpc/status"

	"github.com/scionproto/scion/go/lib/addr"
	"github.com/scionproto/scion/go/lib/metrics"
	"github.com/scionproto/scion/go/lib/snet"
	gpb "github.com/scionproto/scion/go/pkg/proto/gateway"
)

// Advertiser returns a list of IP prefixes to advertise.
type Advertiser interface {
	AdvertiseList(from, to addr.IA) []*net.IPNet
}

// IPPrefixServer serves IP prefix requests.
type IPPrefixServer struct {
	// LocalIA is the IA of the local AS.
	LocalIA addr.IA
	// Advertiser is the advertiser used to get the list of prefixes to advertise.
	Advertiser Advertiser
	// PrefixesAdvertised reports the number of IP prefixes advertised. If nil, no  metrics are
	// reported.
	PrefixesAdvertised metrics.Gauge
}

func (s IPPrefixServer) Prefixes(ctx context.Context,
	req *gpb.PrefixesRequest) (*gpb.PrefixesResponse, error) {

	remote, ok := peer.FromContext(ctx)
	if !ok {
		return nil, status.Error(codes.InvalidArgument, "peer required")
	}
	udp, ok := remote.Addr.(*snet.UDPAddr)
	if !ok {
		return nil, status.Error(codes.InvalidArgument, "SCION peer required")
	}
	prefixes := s.Advertiser.AdvertiseList(s.LocalIA, udp.IA)
	metrics.GaugeSet(metrics.GaugeWith(s.PrefixesAdvertised,
		"remote_isd_as", udp.IA.String()), float64(len(prefixes)))

	pb := make([]*gpb.Prefix, 0, len(prefixes))
	for _, prefix := range prefixes {
		ones, bits := prefix.Mask.Size()
		if bits == 0 {
			continue
		}
		pb = append(pb, &gpb.Prefix{
			Prefix: canonicalIP(prefix.IP),
			Mask:   uint32(ones),
		})
	}
	return &gpb.PrefixesResponse{
		Prefixes: pb,
	}, nil
}

func canonicalIP(ip net.IP) net.IP {
	if v4 := ip.To4(); v4 != nil {
		return v4
	}
	return ip
}


text:
import DOMTest from './DOMTest';
import lang from './lang';

/**
 *
 * @param {Section} section
 * @constructor
 * @class DOMSection
 * @extends {DOMTest}
 * @property {boolean}     collapsed
 * @property {HTMLElement} dom
 * @property {Section}     test
 */
var DOMSection                                = function DOMSection(section) {
   DOMTest.call(this, section);
   this.section = section;
};

/**
 * Build the DOM of the section
 */
DOMSection.prototype.buildDOM                 = function buildDOM(collapsed) {
   DOMTest.prototype.buildDOM.call(this, collapsed);
};

/**
 *
 */
DOMSection.prototype.destroy                  = function destroy() {
   DOMTest.prototype.destroy.apply(this, arguments);
};

/**
 * @returns {Array.<DOMSection|DOMTest>}
 */
DOMSection.prototype.getChildTests            = function getTests() {
   var /** @type {Array.<DOMSection|DOMTest>} */ domTests
     , /** @type {number}                     */ t
     , /** @type {Array.<TestUnit|Section>}   */ tests;

   tests = this.test.getTests();

   domTests = [];

   for (t in tests) {

      if (tests[t].getDOM() !== undefined)
         domTests.push(tests[t].getDOM());
      else
         domTests.push(new DOMTest(tests[t]));
   }

   return domTests;
};

/**
 * Return the DOM of the template
 * @param {boolean} [collapsed=false]
 * @returns {HTMLElement}
 */
DOMSection.prototype.getDOM                   = function getDOM(collapsed) {
   collapsed = collapsed === undefined ? this.collapsed : !!collapsed;

   if (this.dom === undefined || collapsed !== this.collapsed)
      this.buildDOM(collapsed);

   return this.dom;
};

/**
 *
 * @returns {Object}
 */
DOMSection.prototype.getTemplateData          = function () {

   var /** @type {number} */ duration
     , /** @type {number} */ endTime
     , /** @type {number} */ startTime;

   startTime = this.section.getStartTime();
   endTime   = this.section.getEndTime();

   if (endTime !== undefined)
      duration = endTime - startTime;

   return { collapsed      : this.collapsed
          , totalFails     : this.section.countFailedTests()
          , totalSuccesses : this.section.countSuccessfulTests()
          , totalTests     : this.section.countTotalTests()
          , description    : this.section.getDescription()
          , duration       : duration
          , endTime        : common.time2string(endTime)
          , lang           : lang.section
          , startTime      : common.time2string(startTime)
          , success        : this.section.isSuccessful()
          , title          : this.section.getTitle()};
};

/**
 *
 * Lang values :
 *    - startDate
 *    - endDate
 *    - duration
 *    - second
 *    - countTotal
 *    - countSuccess
 *    - countFail
 *    - yes
 *    - no
 *
 * @typedef {Object} SectionTemplateData
 * @property {string}  description  - Description of the section
 * @property {number}  countTotal   - Total number of tests
 * @property {number}  countSuccess - Total number of successful tests
 * @property {number}  countFail    - Total number of failed tests
 * @property {string}  duration     - Duration (in second) of the total execution time
 * @property {string}  endDate      - End date of the latest test of the section
 * @property {string}  startDate    - Date of the first test
 * @property {boolean} success      - If true, then all the test of the section was successful. False otherwise
 * @property {string}  title        - Title of the section
 */

/**
 *
 * @returns {string}
 */
DOMSection.prototype.getTemplate              = function getTemplate() {
   return      '
'
            +     ''
            +        '
{{title}}
'
            +        '
{{description}}
'
            +        '
{{totalFails}}
'
            +        '
{{totalSuccesses}}
'
            +        '
{{totalTests}}
'
            +        '
{{totalSuccesses}}/{{totalTests}}
'
            +        '{{#toDoList}}
{{.}}
{{/toDoList}}'
            +        '{{#comments}}
{{.}}
{{/comments}}'
            +     ''
            +     '

'
            +     '

'
            + '
';
};

export default DOMSection;


text:
package alert

import (
	"github.com/libopenstorage/openstorage/api"
)

// AlertInstance is a singleton which should be used to raise/clear alert
type alertInstance struct {
	NodeID    string
	ClusterID string
	Version   string
	kva       AlertClient
}

// Singleton AlertInstance
var inst *alertInstance

// Clear clears an alert
func (ai *alertInstance) Clear(resourceType api.ResourceType, alertID int64) error {
	return ai.kva.Clear(resourceType, alertID)
}

// Alarm raises an alert with severity : ALARM
func (ai *alertInstance) Alarm(alertType int64, msg string, resourceType api.ResourceType, resourceID string) (int64, error) {
	alert, err := ai.raiseAlert(alertType, msg, resourceType, resourceID, api.SeverityType_SEVERITY_TYPE_ALARM)
	return alert.Id, err
}

// Notify raises an alert with severity : NOTIFY
func (ai *alertInstance) Notify(alertType int64, msg string, resourceType api.ResourceType, resourceID string) (int64, error) {
	alert, err := ai.raiseAlert(alertType, msg, resourceType, resourceID, api.SeverityType_SEVERITY_TYPE_NOTIFY)
	return alert.Id, err
}

// Warn raises an alert with severity : WARNING
func (ai *alertInstance) Warn(alertType int64, msg string, resourceType api.ResourceType, resourceID string) (int64, error) {
	alert, err := ai.raiseAlert(alertType, msg, resourceType, resourceID, api.SeverityType_SEVERITY_TYPE_WARNING)
	return alert.Id, err
}

// EnumerateByResource enumerates alerts of the specific resourceType
func (ai *alertInstance) EnumerateByResource(resourceType api.ResourceType) ([]*api.Alert, error) {
	filter := api.Alert {
		Resource: resourceType,
	}
	return ai.kva.Enumerate(&filter)
}

// Alert :  Keeping this function for backward compatibility until we remove all calls to this function
func (ai *alertInstance) Alert(name string, msg string) error {
	// Do nothing
	return nil
}

// Sets the new singleton alert instance
func newAlertInstance(nodeID, clusterID, version string, kva AlertClient) {
	inst = &alertInstance{
		NodeID:    nodeID,
		ClusterID: clusterID,
		Version:   version,
		kva:       kva,
	}
}

// Instance returns the singleton AlertInstance
func instance() *alertInstance {
	return inst
}

func (ai *alertInstance) raiseAlert(alertType int64, msg string, resourceType api.ResourceType, resourceID string, severity api.SeverityType) (*api.Alert, error) {
	alert := api.Alert{
		AlertType:  alertType,
		Resource:   resourceType,
		ResourceId: resourceID,
		Severity:   severity,
		Message:    msg,
	}
	err := ai.kva.Raise(&alert)
	return &alert, err
}


text:
var jsface = require('jsface');
var packageVersion = require('../../package.json').version;

/**
 * @name Globals
 * @namespace
 * @classdesc Globals to be used throught Newman.
 */
var Globals = jsface.Class({
	$singleton: true,

	newmanVersion: packageVersion,

	/**
	 * Used to add the Globals used through out the app
	 * @param {Object} requestJSON Request JSON.
	 * @param {Object} options Newman Options.
	 */
	addEnvironmentGlobals: function(requestJSON, options) {
		this.requestJSON = requestJSON;
		this.envJson = options.envJson || {};
		this.iterationNumber = 1;
		this.outputFile = options.outputFile || '';
		this.testReportFile = options.testReportFile || '';
		this.globalJson = options.globalJSON || [];
        this.dataJson = [];
		this.stopOnError = options.stopOnError;
		this.noColor = options.noColor;
		this.asLibrary = options.asLibrary;
		this.strictSSL = options.strictSSL || true;
		this.exitCode=0;
		this.updateMessage="";
		this.folder = options.folderName || false;
		this.iterationCount = options.iterationCount || 1;
		this.html = options.html || false;
		this.responseEncoding = options.responseEncoding;
	}
});

module.exports = Globals;


text:
#ifndef NGX_HTTP_LUA_CONTROL_H
#define NGX_HTTP_LUA_CONTROL_H

#include "ngx_http_lua_common.h"

void ngx_http_lua_inject_control_api(ngx_log_t *log, lua_State *L);

#endif /* NGX_HTTP_LUA_CONTROL_H */


text:
package com.yarolegovich.discretescrollview.transform;

import android.support.annotation.IntDef;
import android.view.View;

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

/**
 * Created by yarolegovich on 03.03.2017.
 */

public class Pivot {

    public static final int AXIS_X = 0;
    public static final int AXIS_Y = 1;

    private static final int PIVOT_CENTER = -1;
    private static final int PIVOT_MAX = -2;

    private int axis;
    private int pivotPoint;

    public Pivot(@Axis int axis, int pivotPoint) {
        this.axis = axis;
        this.pivotPoint = pivotPoint;
    }

    public void setOn(View view) {
        if (axis == AXIS_X) {
            switch (pivotPoint) {
                case PIVOT_CENTER:
                    view.setPivotX(view.getWidth() * 0.5f);
                    break;
                case PIVOT_MAX:
                    view.setPivotX(view.getWidth());
                    break;
                default:
                    view.setPivotX(pivotPoint);
                    break;
            }
            return;
        }

        if (axis == AXIS_Y) {
            switch (pivotPoint) {
                case PIVOT_CENTER:
                    view.setPivotY(view.getHeight() * 0.5f);
                    break;
                case PIVOT_MAX:
                    view.setPivotY(view.getHeight());
                    break;
                default:
                    view.setPivotY(pivotPoint);
                    break;
            }
        }
    }

    @Axis
    public int getAxis() {
        return axis;
    }

    public enum X {
        LEFT {
            @Override
            public Pivot create() {
                return new Pivot(AXIS_X, 0);
            }
        },
        CENTER {
            @Override
            public Pivot create() {
                return new Pivot(AXIS_X, PIVOT_CENTER);
            }
        },
        RIGHT {
            @Override
            public Pivot create() {
                return new Pivot(AXIS_X, PIVOT_MAX);
            }
        };

        public abstract Pivot create();
    }

    public enum Y {
        TOP {
            @Override
            public Pivot create() {
                return new Pivot(AXIS_Y, 0);
            }
        },
        CENTER {
            @Override
            public Pivot create() {
                return new Pivot(AXIS_Y, PIVOT_CENTER);
            }
        },
        BOTTOM {
            @Override
            public Pivot create() {
                return new Pivot(AXIS_Y, PIVOT_MAX);
            }
        };

        public abstract Pivot create();
    }

    @IntDef({AXIS_X, AXIS_Y})
    @Retention(RetentionPolicy.SOURCE)
    public @interface Axis{
    }
}


text:
/**
 *  Include guard
 */
#pragma once

/**
 *  Set up namespace
 */
namespace AMQP {

/**
 *  Class definition
 */
class TcpState
{
protected:
    /**
     *  Parent object that constructed the state
     *  @var TcpParent
     */
    TcpParent *_parent;

protected:
    /**
     *  Protected constructor
     *  @param  parent      The parent object
     *  @param  handler     User-supplied handler class
     */
    TcpState(TcpParent *parent) :
        _parent(parent) {}

    /**
     *  Protected "copy" constructor
     *  @param  state       Original TcpState object
     */
    TcpState(const TcpState *state) :
        _parent(state->_parent) {}

public:
    /**
     *  Virtual destructor
     */
    virtual ~TcpState() = default;

    /**
     *  The filedescriptor of this connection
     *  @return int
     */
    virtual int fileno() const { return -1; }

    /**
     *  The number of outgoing bytes queued on this connection.
     *  @return size_t
     */
    virtual std::size_t queued() const { return 0; }

    /**
     *  Is this a closed / dead state?
     *  @return bool
     */
    virtual bool closed() const { return false; }

    /**
     *  Process the filedescriptor in the object
     *
     *  This method should return the handler object that will be responsible for
     *  all future readable/writable events for the file descriptor, or nullptr
     *  if the underlying connection object has already been destructed by the
     *  user and it would be pointless to set up a new handler.
     *
     *  @param  monitor     Monitor that can be used to check if the tcp connection is still alive
     *  @param  fd          The filedescriptor that is active
     *  @param  flags       AMQP::readable and/or AMQP::writable
     *  @return             New implementation object
     */
    virtual TcpState *process(const Monitor &monitor, int fd, int flags)
    {
        // default implementation does nothing and preserves same implementation
        return this;
    }

    /**
     *  Send data over the connection
     *  @param  buffer      Buffer to send
     *  @param  size        Size of the buffer
     */
    virtual void send(const char *buffer, size_t size)
    {
        // default does nothing
    }

    /**
     *  Gracefully start closing the connection
     */
    virtual void close() {}

    /**
     *  Install max-frame size
     *  @param  heartbeat   suggested heartbeat
     */
    virtual void maxframe(size_t maxframe) {}
};

/**
 *  End of namespace
 */
}


text:
namespace ui {

static IMEBridge* g_ime_bridge = NULL;

// An implementation of IMEBridge.
class IMEBridgeImpl : public IMEBridge {
 public:
#if defined(OS_CHROMEOS)
  IMEBridgeImpl()
      : input_context_handler_(NULL),
        engine_handler_(NULL),
        current_input_context_(ui::TEXT_INPUT_TYPE_NONE,
                               ui::TEXT_INPUT_MODE_DEFAULT,
                               0),
        candidate_window_handler_(NULL) {}
#else
  IMEBridgeImpl()
      : input_context_handler_(NULL),
        engine_handler_(NULL),
        current_input_context_(ui::TEXT_INPUT_TYPE_NONE,
                               ui::TEXT_INPUT_MODE_DEFAULT,
                               0) {}
#endif

  ~IMEBridgeImpl() override {}

  // IMEBridge override.
  IMEInputContextHandlerInterface* GetInputContextHandler() const override {
    return input_context_handler_;
  }

  // IMEBridge override.
  void SetInputContextHandler(
      IMEInputContextHandlerInterface* handler) override {
    input_context_handler_ = handler;
  }

  // IMEBridge override.
  void SetCurrentEngineHandler(IMEEngineHandlerInterface* handler) override {
    engine_handler_ = handler;
  }

  // IMEBridge override.
  IMEEngineHandlerInterface* GetCurrentEngineHandler() const override {
    return engine_handler_;
  }

  // IMEBridge override.
  void SetCurrentInputContext(
      const IMEEngineHandlerInterface::InputContext& input_context) override {
    current_input_context_ = input_context;
  }

  // IMEBridge override.
  const IMEEngineHandlerInterface::InputContext& GetCurrentInputContext()
      const override {
    return current_input_context_;
  }

#if defined(OS_CHROMEOS)
  // IMEBridge override.
  void SetCandidateWindowHandler(
      chromeos::IMECandidateWindowHandlerInterface* handler) override {
    candidate_window_handler_ = handler;
  }

  // IMEBridge override.
  chromeos::IMECandidateWindowHandlerInterface* GetCandidateWindowHandler()
      const override {
    return candidate_window_handler_;
  }
#endif

 private:
  IMEInputContextHandlerInterface* input_context_handler_;
  IMEEngineHandlerInterface* engine_handler_;
  IMEEngineHandlerInterface::InputContext current_input_context_;

#if defined(OS_CHROMEOS)
  chromeos::IMECandidateWindowHandlerInterface* candidate_window_handler_;
#endif

  DISALLOW_COPY_AND_ASSIGN(IMEBridgeImpl);
};

///////////////////////////////////////////////////////////////////////////////
// IMEBridge
IMEBridge::IMEBridge() {}

IMEBridge::~IMEBridge() {}

// static.
void IMEBridge::Initialize() {
  if (!g_ime_bridge)
    g_ime_bridge = new IMEBridgeImpl();
}

// static.
void IMEBridge::Shutdown() {
  delete g_ime_bridge;
  g_ime_bridge = NULL;
}

// static.
IMEBridge* IMEBridge::Get() {
  return g_ime_bridge;
}

}  // namespace ui


text:
package edu.stanford.nlp.international.arabic.pipeline;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

import edu.stanford.nlp.trees.Tree;
import edu.stanford.nlp.trees.TreeReader;
import edu.stanford.nlp.trees.TreeReaderFactory;
import edu.stanford.nlp.trees.TreeTransformer;
import edu.stanford.nlp.trees.international.arabic.ArabicTreeReaderFactory;
import edu.stanford.nlp.trees.tregex.TregexPattern;
import edu.stanford.nlp.trees.tregex.tsurgeon.Tsurgeon;
import edu.stanford.nlp.trees.tregex.tsurgeon.TsurgeonPattern;
import edu.stanford.nlp.util.Pair;

/**
 * Makes ATB trees consistent with ArabicTreebankLanguagePack. Specifically, it removes
 * sentence-initial punctuation, and constraints sentence-final punctuation to be one of
 * [.!?].
 * <p>
 * Also cleans up some of the headlines, and other weirdly tokenized sentences.
 *
 * @author Spence Green
 *
 */
public class ATBCorrector implements TreeTransformer {

  private static final boolean DEBUG = false;

  private final List<Pair<TregexPattern,TsurgeonPattern>> ops;

  public ATBCorrector() {
    ops = loadOps();
  }

  private List<Pair<TregexPattern, TsurgeonPattern>> loadOps() {
    List<Pair<TregexPattern,TsurgeonPattern>> ops = new ArrayList<Pair<TregexPattern,TsurgeonPattern>>();

    String line = null;
    try {
      BufferedReader br = new BufferedReader(new StringReader(editStr));
      List<TsurgeonPattern> tsp = new ArrayList<TsurgeonPattern>();
      while ((line = br.readLine()) != null) {
        if (DEBUG) System.err.print("Pattern is " + line);
        TregexPattern matchPattern = TregexPattern.compile(line);
        if (DEBUG) System.err.println(" [" + matchPattern + "]");
        tsp.clear();
        while (continuing(line = br.readLine())) {
          TsurgeonPattern p = Tsurgeon.parseOperation(line);
          if (DEBUG) System.err.println("Operation is " + line + " [" + p + "]");
          tsp.add(p);
        }
        if ( ! tsp.isEmpty()) {
          TsurgeonPattern tp = Tsurgeon.collectOperations(tsp);
          ops.add(new Pair<TregexPattern,TsurgeonPattern>(matchPattern, tp));
        }
      } // while not at end of file
    } catch (IOException ioe) {
      ioe.printStackTrace();
    }

    return ops;
  }

  private static boolean continuing(String str) {
    return str != null && ! str.matches("\\s*");
  }

  public Tree transformTree(Tree t) {
    return Tsurgeon.processPatternsOnTree(ops, t);
  }

  /**
   * The Tsurgeon patterns
   */
  private static final String editStr =

    //Delete sentence-initial punctuation
    ("@PUNC=punc <: __ >>, (/^S/ > @ROOT) \n"
        + "prune punc\n"
        + "\n") +

    //Delete sentence-initial punctuation (again)
    ("@PUNC=punc <: __ >>, (/^S/ > @ROOT) \n"
        + "prune punc\n"
        + "\n") +

    //Delete sentence final punctuation that is preceded by punctuation (first time)
    ("@PUNC=punc >>- (/^S/ > @ROOT) <: __ $, @PUNC \n"
        + "prune punc\n"
        + "\n") +

    //Delete sentence final punctuation that is preceded by punctuation (second time)
    ("@PUNC=punc >>- (/^S/ > @ROOT) <: __ $, @PUNC \n"
        + "prune punc\n"
        + "\n") +

    //Convert remaining sentence-final punctuation to . if it is not [.!?]
    ("@PUNC=pos >>- (/^S/ > @ROOT) <: /[^\\.\\?!]/=term !$, @PUNC \n"
        + "relabel pos PUNC\n"
        + "relabel term /./\n"
        + "\n") +

    //Delete medial, sentence-final punctuation
//    ("@PUNC=punc <: /[!\\.\\?]+/ $. __\n"
//        + "prune punc\n"
//        + "\n") +

    //Now move the sentence-final mark under the top-level node
    ("@PUNC=punc <: /^[\\.!\\?]+$/ >>- (/^S/ > @ROOT <- __=sfpos) !> (/^S/ > @ROOT)\n"
        + "move punc $- sfpos\n"
        + "\n");

    //For those trees that lack a sentence-final punc, add one.
//    ("/^[^\\.!\\?]$/ >>- (__ > @ROOT <- __=loc) <: __\n"
//        + "insert (PUNC .) $- loc\n"
//        + "\n");

  /**
   * @param args
   */
  public static void main(String[] args) {
    if(args.length != 1) {
      System.err.println("Usage: java " + ATBCorrector.class.getName() + " filename\n");
      System.exit(-1);
    }

    TreeTransformer tt = new ATBCorrector();

    File f = new File(args[0]);
    try {

      BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(f), "UTF-8"));
      TreeReaderFactory trf = new ArabicTreeReaderFactory.ArabicRawTreeReaderFactory();
      TreeReader tr = trf.newTreeReader(br);

      int nTrees = 0;
      for(Tree t; (t = tr.readTree()) != null;nTrees++) {
        Tree fixedT = tt.transformTree(t);
        System.out.println(fixedT.toString());
      }

      tr.close();

      System.err.printf("Wrote %d trees%n",nTrees);

    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();

    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}


text:
/* Test that #pragma GCC visibility affects class members. */
/* { dg-do compile } */
/* { dg-require-visibility "" } */
/* { dg-final { scan-hidden "_ZN3Foo6methodEv" } } */

#pragma GCC visibility push(hidden)
class Foo
{
  void method();
};
#pragma GCC visibility pop

void Foo::method() { }


text:
from django.core.management.base import NoArgsCommand
from articles.models import Article, Tag

class Command(NoArgsCommand):
    help = """Converts our old categories into tags"""

    def handle_noargs(self, **opts):
        from django.db import connection

        c = connection.cursor()

        for article in Article.objects.all():
            c.execute("""SELECT c.slug
FROM articles_article_categories aac
JOIN articles_category c
ON aac.category_id = c.id
WHERE aac.article_id=%s""", (article.id,))

            names = [row[0] for row in c.fetchall()]
            tags = [Tag.objects.get_or_create(name=t)[0] for t in names]
            article.tags = tags
            article.save()


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.11"/>
<title>V8 API Reference Guide for node.js v8.9.4: v8_inspector::V8InspectorClient Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

V8 API Reference Guide for node.js v8.9.4

Main Page

Related Pages

Namespaces

Classes

Files

Examples

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Class List

Class Index

Class Hierarchy

Class Members

v8_inspector

V8InspectorClient

Public Types |
Public Member Functions |
List of all members

v8_inspector::V8InspectorClient Class Reference

Public Types

typedef void(* 	TimerCallback) (void *)

Public Member Functions

virtual void 	runMessageLoopOnPause (int contextGroupId)

virtual void 	quitMessageLoopOnPause ()

virtual void 	runIfWaitingForDebugger (int contextGroupId)

virtual void 	muteMetrics (int contextGroupId)

virtual void 	unmuteMetrics (int contextGroupId)

virtual void 	beginUserGesture ()

virtual void 	endUserGesture ()

virtual std::unique_ptr< StringBuffer > 	valueSubtype (v8::Local< v8::Value >)

virtual bool 	formatAccessorsAsProperties (v8::Local< v8::Value >)

virtual bool 	isInspectableHeapObject (v8::Local< v8::Object >)

virtual v8::Local< v8::Context > 	ensureDefaultContextInGroup (int contextGroupId)

virtual void 	beginEnsureAllContextsInGroup (int contextGroupId)

virtual void 	endEnsureAllContextsInGroup (int contextGroupId)

virtual void 	installAdditionalCommandLineAPI (v8::Local< v8::Context >, v8::Local< v8::Object >)

virtual void 	consoleAPIMessage (int contextGroupId, v8::Isolate::MessageErrorLevel level, const StringView &message, const StringView &url, unsigned lineNumber, unsigned columnNumber, V8StackTrace *)

virtual v8::MaybeLocal< v8::Value > 	memoryInfo (v8::Isolate *, v8::Local< v8::Context >)

virtual void 	consoleTime (const StringView &title)

virtual void 	consoleTimeEnd (const StringView &title)

virtual void 	consoleTimeStamp (const StringView &title)

virtual void 	consoleClear (int contextGroupId)

virtual double 	currentTimeMS ()

virtual void 	startRepeatingTimer (double, TimerCallback, void *data)

virtual void 	cancelTimer (void *data)

virtual bool 	canExecuteScripts (int contextGroupId)

virtual void 	maxAsyncCallStackDepthChanged (int depth)

The documentation for this class was generated from the following file:

deps/v8/include/v8-inspector.h

<address class="footer">
Generated by

 1.8.11
</address>


text:
__author__ = 'srun'

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()

db_connect_string = 'mysql+mysqldb://root:root@127.0.0.1/ti?charset=utf8'

def getsession():
    engine = create_engine(db_connect_string, echo=True)
    db_session = sessionmaker(bind=engine)
    session = db_session()
    return session

session = getsession()

def underline_to_camel(underline_format):
    camel_format = ''
    if isinstance(underline_format, str):
        for _s_ in underline_format.split('_'):
            camel_format += _s_.capitalize()
    return camel_format

def show(tableName):
    _tableName = underline_to_camel(str(tableName))
    sql = "desc %s " % tableName
    result = session.execute(sql).fetchall()

    # for i in result:
    #     print """%s = Column('%s', String(45))""" % (i[0], i[0])
    new_path_filename = "F:\\sql\\%s.groovy" % _tableName
    f = open(new_path_filename, 'w')
    f.write("class %s { " % _tableName + "\n")

    src_path_filename = "F:\\template\\SysCitysSpec.groovy"
    _text = open(src_path_filename).readlines()
    _text[8] = "@TestFor(%s)\n" % _tableName
    _text[9] = "class %sSpec extends Specification {" % _tableName
    new_src_path_filename = "F:\\src\\%sSpec.groovy" % _tableName
    s = open(new_src_path_filename, 'w')
    s.writelines(_text)

    for i in result:
        a = str(i[1]).split("(")
        if a[0] == "varchar":
            f.write("    %s %s " % ("String", str(i[0]).lower()))
        elif a[0] == "int":
            f.write("    %s %s " % ("Integer", str(i[0]).lower()))
        elif a[0] == "datetime":
            f.write("    %s %s " % ("String", str(i[0]).lower()))
        elif a[0] == "bit":
            f.write("    %s %s " % ("Integer", str(i[0]).lower()))
        elif a[0] == "char":
            f.write("    %s %s " % ("String", str(i[0]).lower()))
        elif a[0] == "text":
            f.write("    %s %s " % ("String", str(i[0]).lower()))
        elif a[0] == "double":
            f.write("    %s %s " % ("Double", str(i[0]).lower()))
        else:
            f.write("    %s %s " % (i[1], str(i[0]).lower()))
        f.write("\n")
    f.write("    static constraints = { \n } \n")
    f.write("}")
    f.close()

tableNames = [
"sys_citys",
"sys_file_group",
"sys_files",
"ti_customer",
"ti_designate_order",
"ti_designate_order_products",
"ti_flow_path_terms",
"ti_installation_team",
"ti_installed_flow_path",
"ti_installed_progress_adjunct_history",
"ti_installed_progress_exception_history",
"ti_installed_progress_submission_history",
"ti_installed_progress_submission_terms",
"ti_order_products",
"ti_partner",
"ti_partner_contract",
"ti_product_series",
"ti_resource_partner_settlement_history",
"ti_resources_products",
"ti_submission_order",
"ti_worker",
"ti_worker_designate_history",
"ti_wechatmediatasks"]

# for j in session.execute("show tables").fetchall():
#     show(j[0])
for j in tableNames:
    show(j)

# show("ti_worker")

# print str("IsMySql").lower()


text:
```javascript
const Tournesol = require( 'tournesol' );
const Lcrud = require( 'tournesol' ).Lcrud;
const Lab = require( 'lab' );
const lab = exports.lab = Lab.script();

const Server = require( 'A Hapi server' ); // require the hapi server to test or build it within the test file.

const definition = {
        title: 'Title of the test with value of {pre.half1} + {input.itemId}',
        pre: [
            {
                assign: 'half1',
                name: 'half1 ( = 5)',
                method: function ( reply ) {

                    // no err
                    reply( null, 5 );
                }
            }
        ],
        paramSets: [
            {
                titleComplement: 'hello mommy',
                input: {
                    itemId: 5
                },
                output: {
                    statusCode: 200
                }
            },
            {
                input: {
                    itemId: 10
                },
                output: {
                    statusCode: 404
                }
            }
        ],
        inject: function ( pre, input ) {

            const request = new Lcrud( '/items', null, null );
            return request.get( null, null, input.itemId + pre.half1 );
        }
    };

    Tournesol.runTests(definition, Server, lab);
```

is equivalent to:

```javascript
const Lcrud = require( 'tournesol' ).Lcrud;
const Lab = require( 'lab' );
const lab = exports.lab = Lab.script();
const Server = require( 'A Hapi server' );
const Code = require( 'code' );

lab.test( 'Title of the test with value of half1 ( = 5) + 5 | hello mommy', (done) => {

    const getHalf1 = function (callback){

        callback( null, 5 );
    };

    const itemId = 5;

    const request = new Lcrud( '/items', null, null );

    getHalf1( (err, half1) => {

        if (err){
            done(err);
        }

        Server.inject( request.get( null, null, itemId + half1 ), ( response ) => {

            Code.expect(response.statusCode).to.equal(200);
            done();
        } );
    });
});

lab.test( 'Title of the test with value of half1 ( = 5) + 5', (done) => {

    const getHalf1 = function (callback){

        callback( null, 5 );
    };

    const itemId = 10;

    const request = new Lcrud( '/items', null, null );

    getHalf1( (err, half1) => {

        if (err){
            done(err);
        }

        Server.inject( request.get( null, null, itemId + half1 ), ( response ) => {

            Code.expect(response.statusCode).to.equal(404);
            done();
        } );
    });
});
```
## Details

The `runTests` function takes 3 arguments:

* `definition`: an object described later.
* `Server`: a Hapi server.
* `lab`: a `Lab.script()` object.

### Definition format

```javascript
{
        title: 'Title of the test with value of {pre.half1} + {input.itemId}', // The values between { } will be replaced by their actual values
        pre: [ // A list of methods to run before each test
            {
                assign: 'half1', // The result of this will be available as pre.half1
                name: 'half1 ( = 5)', // The name to put in the title
                method: function ( reply ) { // The method

                    // no err
                    reply( null, 5 ); // reply(err, result), if an error is present here, the test will fail with the list of all errors raised by pre-methods
                }
            }
        ],
        paramSets: [ // Each element of this list is a test
            {
                titleComplement: 'hello mommy', // Optional: if a complement is given, the title of the test will be '<rendered title> | complemnet'
                input: { // items that will be available in a 'input' variable
                    itemId: 5 // input.itemId = 5
                },
                output: {
                    statusCode: 200, // Expected statusCode for this test
                    payload: function (code, payload){ // Optional: the response.payload can be tested with this, arguments are: (code, payload) = (and instance of Code, payload parsed as JSON)

                        code.expect(payload.message).to.equal('hello');
                    }
                }
            },
            {
                input: {
                    itemId: 10
                },
                output: {
                    statusCode: 404
                }
            }
        ],
        inject: function ( pre, input ) { // The function which result will be passed to Server.inject

            const request = new Lcrud( '/items', null, null );
            return request.get( null, null, input.itemId + pre.half1 );
        }
    }

```


text:
<?php
use app\models\Parameters;
$Comm = Parameters::find('first');
?>

FAQ

Become a Customer

To become an SiiCrypto customer please click signup. Registration implies you have read and agreed to our Terms of Service.

Fees

We charge <?=$Comm['value']?>% per transaction.

If you buy 1 Bitcoin our fee is <?=$Comm['value']/100?> Bitcoins.

If you sell $100 worth of Bitcoins our fee is <?=$Comm['value']*100?> cent.

Deposits/Withdrawals

For bank wire transfer deposits/withdrawals

Limits

Registered - $2,500 daily.

Verified - 45,000 daily.

Fully verified - $20,000 daily.

All deposits and withdrawals need to be verified and cleared, please see relevant sections when you login.

VERY IMPORTANT: Please make sure to INCLUDE your CUSTOMER REFERENCE with your deposit, which you can find when you complete FUNDING on your account page, so that we can credit your account appropriately.

We cannot be held liable if you send us money with no reference and have not completed a deposit request via your account (though with recorded delivery we can attempt to return any such fiat or solve such matters).

We cannot be held liable if you send us fiat with no reference, no deposit request, and no recorded delivery, and will treat such activity as suspicious and report it to the relevant authorities.

Example Reference:

Account name: silent bob

Reference number: 15828481

Amount: $xxxx

When we receive your funds we verify with your deposit request and credit your SiiCrypto.com account the amount.

Deposits

Once fiat amounts are received your account gets credited the same amount, just the same as doing a bank transfer, without the bank.

Withdrawals

We charge customers the relevant fee that Royal Mail charges to cover the withdrawal amount respectively.

This charge is made to your SiiCrypto.com account.

If you do not have enough to cover the Royal Mail fee in your SiiCrypto.com account then your withdrawal will not be processed and you will be notified via email.

We store all fiat via safety deposit box services.

Time Delays

Transfers are only processed weekdays, barring bank holidays.

It can take us up to 24 hours to verify, confirm and start the process for your withdrawal requests.

It can then take Royal Mail 1-3 days to deliver your withdrawal (we always use 1st Class).

Bitcoin

Bitcoin deposits and withdrawals are subject to the Bitcoin protocol.

Security

SiiCrypto employs two factor authentication (2FA) and time-based one-time password algorithm (TOTP), for login, withdrawals, deposits and settings.

We also require a level of identification for all customers as per our (link) verification page, and run random security checks on accounts. Any information found to be out of date may result in the account in question to be temporarily suspended until such information is suitably updated.

If you have any issues please contact SiiCrypto.com at support@SiiCrypto.com


text:
package org.classdump.luna.env;

import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.FileSystem;

/**
 * The runtime environment used by functions in the standard library.
 *
 *
To obtain instances of this interface, use the utility class {@link RuntimeEnvironments}.

 */
public interface RuntimeEnvironment {

  /**
   * Returns the standard input stream.
   *
   * @return the standard input stream
   */
  InputStream standardInput();

  /**
   * Returns the standard output stream.
   *
   * @return the standard output stream
   */
  OutputStream standardOutput();

  /**
   * Returns the standard error stream.
   *
   * @return the standard output stream
   */
  OutputStream standardError();

  /**
   * Returns the file system.
   *
   * @return the file system
   */
  FileSystem fileSystem();

  /**
   * Returns the value of the environment variable {@code name}, or {@code null} when
   * {@code name} is not defined.
   *
   * @param name the name of the environment variable, must not be {@code null}
   * @return the value of the environment variable {@code name} (possibly {@code null})
   * @throws NullPointerException if {@code name} is {@code null}
   */
  String getEnv(String name);

  /**
   * Returns an approximation of the CPU time used by this program in seconds.
   *
   * @return an approximation of the CPU time used by this program in seconds
   * @throws UnsupportedOperationException if this operation is not supported by the runtime
   * environment
   */
  double getCpuTime();

}


text:
import { NavigationActions } from 'react-navigation';
import React, { Component } from 'react';
import { Image, Alert, Text, View, StyleSheet, ScrollView } from 'react-native';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { List } from 'immutable';
import UserItem from '../components/UserItem';
import AppButton from '../components/AppButton';
import { setCurrentUser, setFeedbackId } from '../state/UserState';
import { toggleIsLoading } from '../state/SessionState';
import { setAuthenticationToken } from '../utils/authentication';
import { setText, setAudio } from '../state/HemmoState';
import { post } from '../utils/api';
import {
  getSizeByWidth,
  getSizeByHeight,
  getImage,
  getFontSize,
} from '../services/graphics';

const styles = StyleSheet.create({
  container: {
    flex: 1,
    height: null,
    width: null,
    backgroundColor: '#fff',
  },
  firstUseScreen: {
    justifyContent: 'center',
    alignItems: 'center',
  },
  userContainer: {
    flexDirection: 'column',
    marginTop: getFontSize(3),
  },
  firstUseContainer: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
  },
  scrollContainer: {
    alignItems: 'center',
  },
  settingsButton: {
    position: 'absolute',
    bottom: getFontSize(2),
    left: getFontSize(2),
  },
  bubbleText: {
    alignSelf: 'center',
    textAlign: 'center',
    fontFamily: 'ComicNeue-Bold',
    color: '#000',
    fontSize: getFontSize(1.8),
    margin: getFontSize(3),
  },
  hemmo: {},
  bubbleTextTitle: {
    fontSize: getFontSize(2.3),
    margin: 5,
  },
  userName: {
    fontFamily: 'Roboto-Regular',
    color: '#000',
    fontSize: getFontSize(2.5),
  },
});

const phrases = require('../data/phrases.json');

const mapStateToProps = state => ({
  users: state.getIn(['user', 'users']),
});

const mapDispatchToProps = dispatch => ({
  setCurrentUser: user => dispatch(setCurrentUser(user)),
  setFeedbackId: id => dispatch(setFeedbackId(id)),
  toggleIsLoading: loading => dispatch(toggleIsLoading(loading)),
  setText: text => dispatch(setText(text)),
  setAudio: audio => dispatch(setAudio(audio)),
  pushRoute: route =>
    dispatch(NavigationActions.navigate({ routeName: route })),
});

@connect(mapStateToProps, mapDispatchToProps)
export default class HomeViewContainer extends Component {
  static propTypes = {
    setCurrentUser: PropTypes.func.isRequired,
    setFeedbackId: PropTypes.func.isRequired,
    toggleIsLoading: PropTypes.func.isRequired,
    pushRoute: PropTypes.func.isRequired,
    users: PropTypes.instanceOf(List).isRequired,
  };

  state = {
    isLoginModalOpen: false,
    showBubble: true,
    firstUseScreenIndex: 0,
  };

  openLogin = () => {
    this.props.pushRoute('Login');
  };

  startSession = async user => {
    this.props.toggleIsLoading(true);

    try {
      await setAuthenticationToken(user.get('token'));

      const result = await post('/app/feedback', { activities: [], moods: [] });

      this.props.setCurrentUser(user);
      this.props.setFeedbackId(result.id);
      this.props.toggleIsLoading(false);
      this.props.pushRoute('FeedbackMenu');
    } catch (error) {
      console.log(error);
      this.props.toggleIsLoading(false);

      await this.props.setAudio(phrases.check_connection.audio);
      Alert.alert('Hmm, jokin meni pieleen.', phrases.check_connection.text, [
        { text: 'OK', onPress: () => this.props.setAudio('') },
      ]);
    }
  };

  renderSettingsButton = () =>
    <View style={styles.settingsButton}>
      <AppButton
        background="settings"
        onPress={this.openLogin}
        width={getSizeByWidth('settings', 0.15).width}
      />
    </View>;

  renderUsers = users =>
    users.size > 0 ? this.renderUserIcons(users) : this.renderEmptyIcon();

  renderUserIcons = users =>
    users.map((user, key) =>
      <UserItem
        key={key}
        name={this.renderUserName(user.get('name'))}
        index={key}
        empty={false}
        startJourney={() => this.startSession(user)}
        image={user.get('image')}
      />,
    );

  renderEmptyIcon = () =>
    <UserItem name={this.renderUserName('Nimi')} key={0} index={0} empty />;

  renderUserName = name =>
    <Text ellipsizeMode="tail" numberOfLines={1} style={styles.userName}>
      {name}
    </Text>;

  // Texts should be put into separate file at some point
  renderBubbleText = () => {
    if (this.state.firstUseScreenIndex === 0) {
      return (
        <View>
          <Text style={[styles.bubbleText, styles.bubbleTextTitle]}>
            Tervetuloa Hemmoon!
          </Text>
          <Text style={styles.bubbleText}>
            Ensimmäinen askel on käyttäjätilin luominen lapselle. Tämä vaatii
            PeLa:n työntekijän tunnukset.
          </Text>
        </View>
      );
    }

    return (
      <Text style={styles.bubbleText}>
        Luodaksesi tilin lapselle, paina alla olevaa nappia ja kirjaudu sisään.
      </Text>
    );
  };

  switchScreen = () => {
    this.setState({
      firstUseScreenIndex: 1 - this.state.firstUseScreenIndex,
    });
  };

  renderFirstUseScreens = () => {
    const firstScreen = this.state.firstUseScreenIndex === 0;

    return (
      <View style={styles.firstUseScreen}>
        <View style={styles.bubble}>
          <AppButton
            background="bubble_down"
            onPress={this.switchScreen}
            contentContainerStyle={{ padding: 30 }}
            width={getSizeByWidth('bubble_down', 0.8).width}
          >
            {this.renderBubbleText()}
          </AppButton>
        </View>
        <Image
          source={getImage(firstScreen ? 'hemmo_big' : 'hemmo_down').normal}
          style={[
            styles.hemmo,
            getSizeByHeight(
              firstScreen ? 'hemmo_big' : 'hemmo_down',
              firstScreen ? 0.4 : 0.4,
            ),
          ]}
        />
      </View>
    );
  };

  render() {
    if (this.props.users.size === 0) {
      return (
        <Image source={getImage('forest').normal} style={styles.container}>
          <View style={styles.firstUseContainer}>
            {this.renderFirstUseScreens()}
          </View>
          {this.renderSettingsButton()}
        </Image>
      );
    }

    return (
      <Image source={getImage('forest').normal} style={styles.container}>
        <ScrollView
          keyboardShouldPersistTaps={'always'}
          overScrollMode={'always'}
          contentContainerStyle={styles.scrollContainer}
        >
          <View style={styles.userContainer}>
            {this.renderUsers(this.props.users)}
          </View>
        </ScrollView>
        {this.renderSettingsButton()}
      </Image>
    );
  }
}


text:
package org.wso2.carbon.identity.captcha.connector.recaptcha;

import org.apache.commons.lang.StringUtils;
import org.wso2.carbon.identity.captcha.connector.CaptchaConnector;
import org.wso2.carbon.identity.captcha.exception.CaptchaClientException;
import org.wso2.carbon.identity.captcha.exception.CaptchaException;
import org.wso2.carbon.identity.captcha.util.CaptchaUtil;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

/**
 * Abstract ReCaptcha Connector.
 */
public abstract class AbstractReCaptchaConnector implements CaptchaConnector {

    @Override
    public boolean verifyCaptcha(ServletRequest servletRequest, ServletResponse servletResponse)
            throws CaptchaException {

        if (((HttpServletRequest) servletRequest).getMethod().equalsIgnoreCase("GET")) {
            throw new CaptchaClientException("reCaptcha response must send in a POST request.");
        }

        String reCaptchaResponse = servletRequest.getParameter("g-recaptcha-response");
        if (StringUtils.isBlank(reCaptchaResponse)) {
            throw new CaptchaClientException("reCaptcha response is not available in the request.");
        }

        return CaptchaUtil.isValidCaptcha(reCaptchaResponse);
    }
}


text:
<!-- Do not edit this file. It is automatically generated by API Documenter. -->

[Home](./index.md) > [puppeteer](./puppeteer.md) > [Protocol](./puppeteer.protocol.md) > [Runtime](./puppeteer.protocol.runtime.md) > [AwaitPromiseRequest](./puppeteer.protocol.runtime.awaitpromiserequest.md) > [generatePreview](./puppeteer.protocol.runtime.awaitpromiserequest.generatepreview.md)

## Protocol.Runtime.AwaitPromiseRequest.generatePreview property

Whether preview should be generated for the result.

<b>Signature:</b>

```typescript
generatePreview?: boolean;
```


text:
#include "cpl_conv.h"
#include "cpl_string.h"
#include "cpl_multiproc.h"

CPL_CVSID("$Id: cpl_findfile.cpp 27044 2014-03-16 23:41:27Z rouault $");

typedef struct
{
    int bFinderInitialized;
    int nFileFinders;
    CPLFileFinder *papfnFinders;
    char **papszFinderLocations;
} FindFileTLS;

/************************************************************************/
/*                      CPLFindFileDeinitTLS()                          */
/************************************************************************/

static void CPLPopFinderLocationInternal(FindFileTLS* pTLSData);
static CPLFileFinder CPLPopFileFinderInternal(FindFileTLS* pTLSData);

static void CPLFindFileFreeTLS(void* pData)
{
    FindFileTLS* pTLSData = (FindFileTLS*) pData;
    if( pTLSData->bFinderInitialized )
    {
        while( pTLSData->papszFinderLocations != NULL )
            CPLPopFinderLocationInternal(pTLSData);
        while( CPLPopFileFinderInternal(pTLSData) != NULL ) {}

        pTLSData->bFinderInitialized = FALSE;
    }
    CPLFree(pTLSData);
}

/************************************************************************/
/*                       CPLGetFindFileTLS()                            */
/************************************************************************/

static FindFileTLS* CPLGetFindFileTLS()
{
    FindFileTLS* pTLSData =
            (FindFileTLS *) CPLGetTLS( CTLS_FINDFILE );
    if (pTLSData == NULL)
    {
        pTLSData = (FindFileTLS*) CPLCalloc(1, sizeof(FindFileTLS));
        CPLSetTLSWithFreeFunc( CTLS_FINDFILE, pTLSData, CPLFindFileFreeTLS );
    }
    return pTLSData;
}

/************************************************************************/
/*                           CPLFinderInit()                            */
/************************************************************************/

static FindFileTLS* CPLFinderInit()

{
    FindFileTLS* pTLSData = CPLGetFindFileTLS();
    if( !pTLSData->bFinderInitialized )
    {
        pTLSData->bFinderInitialized = TRUE;
        CPLPushFileFinder( CPLDefaultFindFile );

        CPLPushFinderLocation( "." );

        if( CPLGetConfigOption( "GDAL_DATA", NULL ) != NULL )
        {
            CPLPushFinderLocation( CPLGetConfigOption( "GDAL_DATA", NULL ) );
        }
        else
        {
#ifdef GDAL_PREFIX
  #ifdef MACOSX_FRAMEWORK
            CPLPushFinderLocation( GDAL_PREFIX "/Resources/gdal" );
  #else
            CPLPushFinderLocation( GDAL_PREFIX "/share/gdal" );
  #endif
#else
            CPLPushFinderLocation( "/usr/local/share/gdal" );
#endif
        }
    }
    return pTLSData;
}

/************************************************************************/
/*                           CPLFinderClean()                           */
/************************************************************************/

void CPLFinderClean()

{
    FindFileTLS* pTLSData = CPLGetFindFileTLS();
    CPLFindFileFreeTLS(pTLSData);
    CPLSetTLS( CTLS_FINDFILE, NULL, FALSE );
}

/************************************************************************/
/*                         CPLDefaultFileFind()                         */
/************************************************************************/

const char *CPLDefaultFindFile( const char *pszClass,
                                const char *pszBasename )

{
    FindFileTLS* pTLSData = CPLGetFindFileTLS();
    int         i, nLocations = CSLCount( pTLSData->papszFinderLocations );

    (void) pszClass;

    for( i = nLocations-1; i >= 0; i-- )
    {
        const char  *pszResult;
        VSIStatBuf  sStat;

        pszResult = CPLFormFilename( pTLSData->papszFinderLocations[i], pszBasename,
                                     NULL );

        if( VSIStat( pszResult, &sStat ) == 0 )
            return pszResult;
    }

    return NULL;
}

/************************************************************************/
/*                            CPLFindFile()                             */
/************************************************************************/

const char *CPLFindFile( const char *pszClass, const char *pszBasename )

{
    int         i;

    FindFileTLS* pTLSData = CPLFinderInit();

    for( i = pTLSData->nFileFinders-1; i >= 0; i-- )
    {
        const char * pszResult;

        pszResult = (pTLSData->papfnFinders[i])( pszClass, pszBasename );
        if( pszResult != NULL )
            return pszResult;
    }

    return NULL;
}

/************************************************************************/
/*                         CPLPushFileFinder()                          */
/************************************************************************/

void CPLPushFileFinder( CPLFileFinder pfnFinder )

{
    FindFileTLS* pTLSData = CPLFinderInit();

    pTLSData->papfnFinders = (CPLFileFinder *)
        CPLRealloc(pTLSData->papfnFinders,  sizeof(void*) * ++pTLSData->nFileFinders);
    pTLSData->papfnFinders[pTLSData->nFileFinders-1] = pfnFinder;
}

/************************************************************************/
/*                          CPLPopFileFinder()                          */
/************************************************************************/

CPLFileFinder CPLPopFileFinderInternal(FindFileTLS* pTLSData)

{
    CPLFileFinder pfnReturn;

    if( pTLSData->nFileFinders == 0 )
        return NULL;

    pfnReturn = pTLSData->papfnFinders[--pTLSData->nFileFinders];

    if( pTLSData->nFileFinders == 0)
    {
        CPLFree( pTLSData->papfnFinders );
        pTLSData->papfnFinders = NULL;
    }

    return pfnReturn;
}

CPLFileFinder CPLPopFileFinder()

{
    return CPLPopFileFinderInternal(CPLFinderInit());
}

/************************************************************************/
/*                       CPLPushFinderLocation()                        */
/************************************************************************/

void CPLPushFinderLocation( const char *pszLocation )

{
    FindFileTLS* pTLSData = CPLFinderInit();

    pTLSData->papszFinderLocations  = CSLAddString( pTLSData->papszFinderLocations,
                                          pszLocation );
}

/************************************************************************/
/*                       CPLPopFinderLocation()                         */
/************************************************************************/

static void CPLPopFinderLocationInternal(FindFileTLS* pTLSData)

{
    int      nCount;

    if( pTLSData->papszFinderLocations == NULL )
        return;

    nCount = CSLCount(pTLSData->papszFinderLocations);
    if( nCount == 0 )
        return;

    CPLFree( pTLSData->papszFinderLocations[nCount-1] );
    pTLSData->papszFinderLocations[nCount-1] = NULL;

    if( nCount == 1 )
    {
        CPLFree( pTLSData->papszFinderLocations );
        pTLSData->papszFinderLocations = NULL;
    }
}

void CPLPopFinderLocation()
{
    CPLPopFinderLocationInternal(CPLFinderInit());
}


text:
Given /^I am running the "([^\"]*)" example$/ do |example_name|
  Dollhouse.launch_from(PROJECT_ROOT + "/examples/#{example_name}")
end

When /^I have deleted "([^\"]*)"$/ do |path|
  FileUtils.rm_rf(File.join(Dollhouse.root, path))
end


text:
using HLife.Mods;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HLife.GameEntities.Props
{
    /// <summary>
    /// Defailt settings for a Prop.
    /// </summary>
    public class PropTemplate
    {
        /// <summary>
        /// Reference name. MUST BE UNIQUE.
        /// </summary>
        public string Name { get; set; }

        /// <summary>
        /// Printable name.
        /// </summary>
        public string DisplayName { get; set; }

        /// <summary>
        /// Path to the image file.
        /// </summary>
        public string Image { get; set; }

        /// <summary>
        /// Description of this Prop.
        /// </summary>
        public string Description { get; set; }

        /// <summary>
        /// Performable Actions.
        /// </summary>
        public List<string> Actions { get; set; }

        /// <summary>
        /// Clerical categories.
        /// </summary>
        public List<string> Categories { get; set; }

        public Mod Source { get; set; }

        public int MaxOccupancy { get; set; }

        /// <summary>
        /// Default constructor.
        /// </summary>
        public PropTemplate()
        {
            this.Name = "{PROP}";
            this.DisplayName = "{PROP}";
            this.Actions = new List<string>();
            this.Categories = new List<string>();
        }
    }
}


text:
package iso20022

// Identification of the party.
type PartyIdentification100 struct {

	// Unique identification of the party.
	Identification *PartyIdentification71Choice `xml:"Id"`

	// Legal entity identification as an alternate identification for a party.
	LEI *LEIIdentifier `xml:"LEI,omitempty"`
}

func (p *PartyIdentification100) AddIdentification() *PartyIdentification71Choice {
	p.Identification = new(PartyIdentification71Choice)
	return p.Identification
}

func (p *PartyIdentification100) SetLEI(value string) {
	p.LEI = (*LEIIdentifier)(&value)
}


text:
package com.fastopencsv;

import java.io.IOException;
import java.nio.CharBuffer;
import java.util.ArrayList;
import java.util.List;

public abstract class AbstractCsvReader implements AutoCloseable {

	protected int bufferSize = 1024 * 1024;
	protected boolean hasNext = true;
	protected CSVParser parser;
	protected int skipLines;
	protected boolean linesSkiped;
	protected CharBuffer buffer;
	protected int positionInBuffer = -1;
	protected long totalCharactersRead = 0;
	protected int charactersRead;
	protected char[] nextLine;

	/**
	 * The default line to start reading.
	 */
	public static final int DEFAULT_SKIP_LINES = 0;

	public static final int[] getNextLineBoundaries(int start, int end,
			CharBuffer characters) {
		int[] returnValue = new int[] { -1, -1 };

		int i = start;
		while (i < end && characters.hasRemaining()) {
			// System.out.println("boundaries " + characters);
			if (characters.get(i) == '\r' || characters.get(i) == '\n') {
				int previousPos = i - 1;
				if (previousPos >= returnValue[0] && returnValue[0] >= 0) {
					// We have already set the first position. Now we have
					// reached the end of this line.
					// Set the second position
					returnValue[1] = previousPos; // TODO
					break;
				} else {
					returnValue[1] = returnValue[0] = i;
					break;
				}

			} else {
				if (returnValue[0] < 0) {
					// We have not set the first position yet and we see a non
					// new
					// line character. This is the first character of the line.
					returnValue[0] = i;
				}
			}
			i++;
		}

		return returnValue;
	}

	/**
	 * Reads the entire file into a List with each element being a String[] of
	 * tokens.
	 *
	 * @return a List of String[], with each String[] representing a line of the
	 *         file.
	 *
	 * @throws IOException
	 *             if bad things happen during the read
	 */
	public List<String[]> readAll() throws IOException {

		List<String[]> allElements = new ArrayList<String[]>();
		while (hasNext) {
			String[] nextLineAsTokens = readNext();
			if (nextLineAsTokens != null)
				allElements.add(nextLineAsTokens);
		}
		return allElements;

	}

	/**
	 * Reads the next line from the buffer and converts to a string array.
	 *
	 * @return a string array with each comma-separated element as a separate
	 *         entry.
	 *
	 * @throws IOException
	 *             if bad things happen during the read
	 */
	public final String[] readNext() throws IOException {
		String[] result = null;
		do {
			nextLine = getNextLine();
			if (!hasNext) {
				return result; // should throw if still pending?
			}
			String[] r = parser.parseLineMulti(nextLine);
			if (r.length > 0) {
				if (result == null) {
					result = r;
				} else {
					String[] t = new String[result.length + r.length];
					System.arraycopy(result, 0, t, 0, result.length);
					System.arraycopy(r, 0, t, result.length, r.length);
					result = t;
				}
			}
		} while (parser.isPending());
		return result;
	}

	/**
	 * Reads the next line from the file.
	 *
	 * @return the next line from the file without trailing newline
	 * @throws IOException
	 *             if bad things happen during the read
	 */
	private final char[] getNextLine() throws IOException {
		if (!this.linesSkiped) {
			for (int i = 0; i < skipLines; i++) {
				readLine();
			}
			this.linesSkiped = true;
		}
		char[] nextLine = readLine();
		if (nextLine == null) {
			hasNext = false;
		}
		return hasNext ? nextLine : null;
	}

	public final char[] getNextLineText() {
		return nextLine;
	}

	protected final char[] readLine() throws IOException {
		boolean foundLine = false;
		char[] returnLine = null;
		char[] partialLine = null;

		while (!foundLine) {
			// System.out.println("readline " + positionInBuffer + " " + new
			// String(buffer));
			if (positionInBuffer < 0 || !buffer.hasRemaining()) {
				// read more data
				charactersRead = read();

				totalCharactersRead += charactersRead;
				positionInBuffer = 0;
			}

			int[] lineBoundaries = getNextLineBoundaries(positionInBuffer,
					charactersRead, buffer);
			int lengthOfLine;
			if (lineBoundaries[0] < 0 && lineBoundaries[1] < 0) {
				// We reached the end of the buffer and did not find a new line.
				// reset positionInBuffer
				// Continue and read in more data
				if (charactersRead < 0) {
					return partialLine;
				}
				positionInBuffer = -1;
				continue;
			} else if (lineBoundaries[1] >= 0) {
				// Newline found
				lengthOfLine = lineBoundaries[1]
						- Math.max(0, lineBoundaries[0]) + 1;
			} else {
				lengthOfLine = charactersRead - lineBoundaries[0];
			}
			/************************************************************************************************
			 * TODO I think this is broken because lineBounardaries[0] is not
			 * taken into account when populating the buffer like it was in
			 * System.arrayCopy
			 *************************************************************************************************/
			if (charactersRead < 0) {
				// We've reached the end of the file
				return partialLine;
			} else if (lineBoundaries[0] >= 0) {

				if (lineBoundaries[1] < 0) {
					// If partialLine is already created, just add to it.
					// TODO this is found below. Break it out as a function or
					// change the if statement?
					if (partialLine == null) {
						partialLine = new char[lengthOfLine];
						buffer.position(lineBoundaries[0]);
						buffer.get(partialLine, 0, lengthOfLine);
						// System.arraycopy(buffer, lineBoundaries[0],
						// partialLine, 0, lengthOfLine);
					} else {
						char[] newPartialLine = new char[lengthOfLine
								+ partialLine.length];
						// TODO do we need two copies?
						System.arraycopy(partialLine, 0, newPartialLine, 0,
								partialLine.length);
						// TODO this does not look right
						buffer.position(lineBoundaries[0]);
						buffer.get(newPartialLine, partialLine.length,
								lengthOfLine);
						// System.arraycopy(buffer, lineBoundaries[0],
						// newPartialLine, partialLine.length, lengthOfLine);
						partialLine = newPartialLine;
					}
					positionInBuffer = -1;
				} else if (lineBoundaries[0] == lineBoundaries[1]
						&& (buffer.get(lineBoundaries[0]) == '\n' || buffer
								.get(lineBoundaries[0]) == '\r')) {
					// Found a new line. If there is a partial line, return it
					// otherwise keep looking.
					// Todo put a better check than this

					positionInBuffer = lineBoundaries[1] + 2;
					if (partialLine != null) {
						return partialLine;
					}

				} else {
					if (partialLine == null) {
						returnLine = new char[lengthOfLine];
						buffer.position(lineBoundaries[0]);
						buffer.get(returnLine, 0, lengthOfLine);
						// System.arraycopy(buffer, lineBoundaries[0],
						// returnLine, 0, lengthOfLine);
					} else {
						returnLine = new char[lengthOfLine + partialLine.length];
						// TODO is this right?
						System.arraycopy(partialLine, 0, returnLine, 0,
								partialLine.length);
						buffer.position(lineBoundaries[0]);
						buffer.get(returnLine, partialLine.length, lengthOfLine);
						// System.arraycopy(buffer, lineBoundaries[0],
						// returnLine, partialLine.length, lengthOfLine);
						partialLine = null;
					}
					positionInBuffer = lineBoundaries[1] + 2;
					return returnLine;
				}
			} else {
				// Keep looping. The only case where I can think of that this
				// would happen is if
				// the buffer is full of new line characters. Hopefully that
				// will never happen.
			}

		}
		return returnLine;
	}

	public AbstractCsvReader() {
		super();
	}

	public final long getTotalCharactersRead() {
		return totalCharactersRead;
	}

	public abstract int read() throws IOException;

	/**
	 * Closes the underlying reader.
	 *
	 * @throws IOException
	 *             if the close fails
	 */
	public abstract void close() throws IOException;

}


text:
package com.android.exchange;

import android.app.Application;

public class Exchange extends Application {
    // TODO Investigate whether this class is needed
}