text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <title>...</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="What's for Lunch">
    <meta name="keywords" content="lunch finder, lunch inspiration">
    <meta name="author" content="@bnguyensn">

    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Open+Sans">
    <link href="https://fonts.googleapis.com/css?family=Gentium+Basic" rel="stylesheet">
    <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">


text:
from numbers import Integral
import warnings

from pyarrow.lib import Table
import pyarrow._orc as _orc
from pyarrow.fs import _resolve_filesystem_and_path

class ORCFile:
    """
    Reader interface for a single ORC file

    Parameters
    ----------
    source : str or pyarrow.NativeFile
        Readable source. For passing Python file objects or byte buffers,
        see pyarrow.io.PythonFileInterface or pyarrow.io.BufferReader.
    """

    def __init__(self, source):
        self.reader = _orc.ORCReader()
        self.reader.open(source)

    @property
    def metadata(self):
        """The file metadata, as an arrow KeyValueMetadata"""
        return self.reader.metadata()

    @property
    def schema(self):
        """The file schema, as an arrow schema"""
        return self.reader.schema()

    @property
    def nrows(self):
        """The number of rows in the file"""
        return self.reader.nrows()

    @property
    def nstripes(self):
        """The number of stripes in the file"""
        return self.reader.nstripes()

    @property
    def file_version(self):
        """Format version of the ORC file, must be 0.11 or 0.12"""
        return self.reader.file_version()

    @property
    def software_version(self):
        """Software instance and version that wrote this file"""
        return self.reader.software_version()

    @property
    def compression(self):
        """Compression codec of the file"""
        return self.reader.compression()

    @property
    def compression_size(self):
        """Number of bytes to buffer for the compression codec in the file"""
        return self.reader.compression_size()

    @property
    def writer(self):
        """Name of the writer that wrote this file.
        If the writer is unknown then its Writer ID
        (a number) is returned"""
        return self.reader.writer()

    @property
    def writer_version(self):
        """Version of the writer"""
        return self.reader.writer_version()

    @property
    def row_index_stride(self):
        """Number of rows per an entry in the row index or 0
        if there is no row index"""
        return self.reader.row_index_stride()

    @property
    def nstripe_statistics(self):
        """Number of stripe statistics"""
        return self.reader.nstripe_statistics()

    @property
    def content_length(self):
        """Length of the data stripes in the file in bytes"""
        return self.reader.content_length()

    @property
    def stripe_statistics_length(self):
        """The number of compressed bytes in the file stripe statistics"""
        return self.reader.stripe_statistics_length()

    @property
    def file_footer_length(self):
        """The number of compressed bytes in the file footer"""
        return self.reader.file_footer_length()

    @property
    def file_postscript_length(self):
        """The number of bytes in the file postscript"""
        return self.reader.file_postscript_length()

    @property
    def file_length(self):
        """The number of bytes in the file"""
        return self.reader.file_length()

    def _select_names(self, columns=None):
        if columns is None:
            return None

        schema = self.schema
        names = []
        for col in columns:
            if isinstance(col, Integral):
                col = int(col)
                if 0 <= col < len(schema):
                    col = schema[col].name
                    names.append(col)
                else:
                    raise ValueError("Column indices must be in 0 <= ind < %d,"
                                     " got %d" % (len(schema), col))
            else:
                return columns

        return names

    def read_stripe(self, n, columns=None):
        """Read a single stripe from the file.

        Parameters
        ----------
        n : int
            The stripe index
        columns : list
            If not None, only these columns will be read from the stripe. A
            column name may be a prefix of a nested field, e.g. 'a' will select
            'a.b', 'a.c', and 'a.d.e'

        Returns
        -------
        pyarrow.RecordBatch
            Content of the stripe as a RecordBatch.
        """
        columns = self._select_names(columns)
        return self.reader.read_stripe(n, columns=columns)

    def read(self, columns=None):
        """Read the whole file.

        Parameters
        ----------
        columns : list
            If not None, only these columns will be read from the file. A
            column name may be a prefix of a nested field, e.g. 'a' will select
            'a.b', 'a.c', and 'a.d.e'

        Returns
        -------
        pyarrow.Table
            Content of the file as a Table.
        """
        columns = self._select_names(columns)
        return self.reader.read(columns=columns)

_orc_writer_args_docs = """file_version : {"0.11", "0.12"}, default "0.12"
    Determine which ORC file version to use.
    `Hive 0.11 / ORC v0 <https://orc.apache.org/specification/ORCv0/>`_
    is the older version
    while `Hive 0.12 / ORC v1 <https://orc.apache.org/specification/ORCv1/>`_
    is the newer one.
batch_size : int, default 1024
    Number of rows the ORC writer writes at a time.
stripe_size : int, default 64 * 1024 * 1024
    Size of each ORC stripe in bytes.
compression : string, default 'uncompressed'
    The compression codec.
    Valid values: {'UNCOMPRESSED', 'SNAPPY', 'ZLIB', 'LZ4', 'ZSTD'}
    Note that LZ0 is currently not supported.
compression_block_size : int, default 64 * 1024
    Size of each compression block in bytes.
compression_strategy : string, default 'speed'
    The compression strategy i.e. speed vs size reduction.
    Valid values: {'SPEED', 'COMPRESSION'}
row_index_stride : int, default 10000
    The row index stride i.e. the number of rows per
    an entry in the row index.
padding_tolerance : double, default 0.0
    The padding tolerance.
dictionary_key_size_threshold : double, default 0.0
    The dictionary key size threshold. 0 to disable dictionary encoding.
    1 to always enable dictionary encoding.
bloom_filter_columns : None, set-like or list-like, default None
    Columns that use the bloom filter.
bloom_filter_fpp : double, default 0.05
    Upper limit of the false-positive rate of the bloom filter.
"""

class ORCWriter:
    __doc__ = """
Writer interface for a single ORC file

Parameters
----------
where : str or pyarrow.io.NativeFile
    Writable target. For passing Python file objects or byte buffers,
    see pyarrow.io.PythonFileInterface, pyarrow.io.BufferOutputStream
    or pyarrow.io.FixedSizeBufferWriter.
{}
""".format(_orc_writer_args_docs)

    is_open = False

    def __init__(self, where, *,
                 file_version='0.12',
                 batch_size=1024,
                 stripe_size=64 * 1024 * 1024,
                 compression='uncompressed',
                 compression_block_size=65536,
                 compression_strategy='speed',
                 row_index_stride=10000,
                 padding_tolerance=0.0,
                 dictionary_key_size_threshold=0.0,
                 bloom_filter_columns=None,
                 bloom_filter_fpp=0.05,
                 ):
        self.writer = _orc.ORCWriter()
        self.writer.open(
            where,
            file_version=file_version,
            batch_size=batch_size,
            stripe_size=stripe_size,
            compression=compression,
            compression_block_size=compression_block_size,
            compression_strategy=compression_strategy,
            row_index_stride=row_index_stride,
            padding_tolerance=padding_tolerance,
            dictionary_key_size_threshold=dictionary_key_size_threshold,
            bloom_filter_columns=bloom_filter_columns,
            bloom_filter_fpp=bloom_filter_fpp
        )
        self.is_open = True

    def __del__(self):
        self.close()

    def __enter__(self):
        return self

    def __exit__(self, *args, **kwargs):
        self.close()

    def write(self, table):
        """
        Write the table into an ORC file. The schema of the table must
        be equal to the schema used when opening the ORC file.

        Parameters
        ----------
        table : pyarrow.Table
            The table to be written into the ORC file
        """
        assert self.is_open
        self.writer.write(table)

    def close(self):
        """
        Close the ORC file
        """
        if self.is_open:
            self.writer.close()
            self.is_open = False

def read_table(source, columns=None, filesystem=None):
    filesystem, path = _resolve_filesystem_and_path(source, filesystem)
    if filesystem is not None:
        source = filesystem.open_input_file(path)

    if columns is not None and len(columns) == 0:
        result = ORCFile(source).read().select(columns)
    else:
        result = ORCFile(source).read(columns=columns)

    return result

read_table.__doc__ = """
Read a Table from an ORC file.

Parameters
----------
source : str, pyarrow.NativeFile, or file-like object
    If a string passed, can be a single file name. For file-like objects,
    only read a single file. Use pyarrow.BufferReader to read a file
    contained in a bytes or buffer-like object.
columns : list
    If not None, only these columns will be read from the file. A column
    name may be a prefix of a nested field, e.g. 'a' will select 'a.b',
    'a.c', and 'a.d.e'. If empty, no columns will be read. Note
    that the table will still have the correct num_rows set despite having
    no columns.
filesystem : FileSystem, default None
    If nothing passed, paths assumed to be found in the local on-disk
    filesystem.
"""

def write_table(table, where, *,
                file_version='0.12',
                batch_size=1024,
                stripe_size=64 * 1024 * 1024,
                compression='uncompressed',
                compression_block_size=65536,
                compression_strategy='speed',
                row_index_stride=10000,
                padding_tolerance=0.0,
                dictionary_key_size_threshold=0.0,
                bloom_filter_columns=None,
                bloom_filter_fpp=0.05):
    if isinstance(where, Table):
        warnings.warn(
            "The order of the arguments has changed. Pass as "
            "'write_table(table, where)' instead. The old order will raise "
            "an error in the future.", FutureWarning, stacklevel=2
        )
        table, where = where, table
    with ORCWriter(
        where,
        file_version=file_version,
        batch_size=batch_size,
        stripe_size=stripe_size,
        compression=compression,
        compression_block_size=compression_block_size,
        compression_strategy=compression_strategy,
        row_index_stride=row_index_stride,
        padding_tolerance=padding_tolerance,
        dictionary_key_size_threshold=dictionary_key_size_threshold,
        bloom_filter_columns=bloom_filter_columns,
        bloom_filter_fpp=bloom_filter_fpp
    ) as writer:
        writer.write(table)

write_table.__doc__ = """
Write a table into an ORC file.

Parameters
----------
table : pyarrow.lib.Table
    The table to be written into the ORC file
where : str or pyarrow.io.NativeFile
    Writable target. For passing Python file objects or byte buffers,
    see pyarrow.io.PythonFileInterface, pyarrow.io.BufferOutputStream
    or pyarrow.io.FixedSizeBufferWriter.
{}
""".format(_orc_writer_args_docs)

redpajama_set_name: RedPajamaGithub


text:
require "tsd_metrics/json_formatting_sink"
require "json"
require "json-schema"
require 'timecop'
require 'time'

describe "JsonFormattingSink" do
  let(:outputStreamMock) do
    mock = double()
  end
  let(:minimalStruct) do
    {
      gauges: {
        "myGauge" => [{value: 4}]
      },
      timers: {
        "myGauge" => [{value: 427297}]
      },
      counters: {
        "myCounter" => [{value: 16238}, {value: 948}]
      },
      annotations: {
        "myAnnotation" => "Nevermore, quoth the Raven",
        initTimestamp: Time.parse("2014-11-02T03:33:38.000Z"),
        finalTimestamp: Time.parse("2014-11-02T03:33:40.838Z")
      }
    }
  end

  let(:zeroSampleStruct) do
    {
      gauges: {
      },
      timers: {
      },
      counters: {
      },
      annotations: {
        initTimestamp: 1393037729.0,
        finalTimestamp: 1393037735.0
      }
    }
  end
  let(:receiver) { JsonFormattingSink.new(outputStreamMock) }

  def captureOutput(metricStructMock)
    json = nil
    allow(outputStreamMock).to receive(:write) do |outputJson|
      json = outputJson
    end
    receiver.receive(metricStructMock)
    json
  end

  it "contains all the metric data" do

    jsonString = captureOutput(double(minimalStruct))
    expect(jsonString).to include("427297")
    expect(jsonString).to include("16238")
    expect(jsonString).to include("948")
    expect(jsonString).to include('"Nevermore, quoth the Raven"')
    expect(jsonString).to include('"2014-11-02T03:33:38.000Z"')
    expect(jsonString).to include('"2014-11-02T03:33:40.838Z"')

  end

  it "includes the time as ISO8601 in UTC" do
    timeString = '"2014-11-02T03:33:38.000Z"'
    Timecop.freeze(Time.parse(timeString))

    jsonString = captureOutput(double(minimalStruct))
    expect(jsonString).to include(timeString)
    Timecop.return
  end

  it "conforms to the JSON schema" do
    jsonString = captureOutput(double(minimalStruct))
    JSON::Validator.validate!("../doc/query-log-schema-2e.json", jsonString)
  end

  it "does not output anything when no samples are present" do
    expect(outputStreamMock).to_not receive(:write)
    receiver.receive(double(zeroSampleStruct))
  end
end


text:
namespace asmjit {

// ============================================================================
// [asmjit::Assembler - Construction / Destruction]
// ============================================================================

Assembler::Assembler(Runtime* runtime) :
  CodeGen(runtime),
  _buffer(NULL),
  _end(NULL),
  _cursor(NULL),
  _trampolineSize(0),
  _comment(NULL),
  _unusedLinks(NULL) {}

Assembler::~Assembler() {
  reset(true);
}

// ============================================================================
// [asmjit::Assembler - Clear / Reset]
// ============================================================================

void Assembler::reset(bool releaseMemory) {
  // CodeGen members.
  _baseAddress = kNoBaseAddress;
  _instOptions = 0;
  _error = kErrorOk;

  _baseZone.reset(releaseMemory);

  // Assembler members.
  if (releaseMemory && _buffer != NULL) {
    ASMJIT_FREE(_buffer);
    _buffer = NULL;
    _end = NULL;
  }

  _cursor = _buffer;
  _trampolineSize = 0;

  _comment = NULL;
  _unusedLinks = NULL;

  _labelList.reset(releaseMemory);
  _relocList.reset(releaseMemory);
}

// ============================================================================
// [asmjit::Assembler - Buffer]
// ============================================================================

Error Assembler::_grow(size_t n) {
  size_t capacity = getCapacity();
  size_t after = getOffset() + n;

  // Overflow.
  if (n > IntUtil::maxUInt<uintptr_t>() - capacity)
    return setError(kErrorNoHeapMemory);

  // Grow is called when allocation is needed, so it shouldn't happen, but on
  // the other hand it is simple to catch and it's not an error.
  if (after <= capacity)
    return kErrorOk;

  if (capacity < kMemAllocOverhead)
    capacity = kMemAllocOverhead;
  else
    capacity += kMemAllocOverhead;

  do {
    size_t oldCapacity = capacity;

    if (capacity < kMemAllocGrowMax)
      capacity *= 2;
    else
      capacity += kMemAllocGrowMax;

    // Overflow.
    if (oldCapacity > capacity)
      return setError(kErrorNoHeapMemory);
  } while (capacity - kMemAllocOverhead < after);

  capacity -= kMemAllocOverhead;
  return _reserve(capacity);
}

Error Assembler::_reserve(size_t n) {
  size_t capacity = getCapacity();
  if (n <= capacity)
    return kErrorOk;

  uint8_t* newBuffer;
  if (_buffer == NULL)
    newBuffer = static_cast<uint8_t*>(ASMJIT_ALLOC(n));
  else
    newBuffer = static_cast<uint8_t*>(ASMJIT_REALLOC(_buffer, n));

  if (newBuffer == NULL)
    return setError(kErrorNoHeapMemory);

  size_t offset = getOffset();

  _buffer = newBuffer;
  _end = _buffer + n;
  _cursor = newBuffer + offset;

  return kErrorOk;
}

// ============================================================================
// [asmjit::Assembler - Label]
// ============================================================================

Error Assembler::_registerIndexedLabels(size_t index) {
  size_t i = _labelList.getLength();
  if (index < i)
    return kErrorOk;

  if (_labelList._grow(index - i) != kErrorOk)
    return setError(kErrorNoHeapMemory);

  LabelData data;
  data.offset = -1;
  data.links = NULL;

  do {
    _labelList.append(data);
  } while (++i < index);

  return kErrorOk;
}

Error Assembler::_newLabel(Label* dst) {
  dst->_label.op = kOperandTypeLabel;
  dst->_label.size = 0;
  dst->_label.id = OperandUtil::makeLabelId(static_cast<uint32_t>(_labelList.getLength()));

  LabelData data;
  data.offset = -1;
  data.links = NULL;

  if (_labelList.append(data) != kErrorOk)
    goto _NoMemory;
  return kErrorOk;

_NoMemory:
  dst->_label.id = kInvalidValue;
  return setError(kErrorNoHeapMemory);
}

LabelLink* Assembler::_newLabelLink() {
  LabelLink* link = _unusedLinks;

  if (link) {
    _unusedLinks = link->prev;
  }
  else {
    link = _baseZone.allocT<LabelLink>();
    if (link == NULL)
      return NULL;
  }

  link->prev = NULL;
  link->offset = 0;
  link->displacement = 0;
  link->relocId = -1;

  return link;
}

Error Assembler::bind(const Label& label) {
  // Get label data based on label id.
  uint32_t index = label.getId();
  LabelData* data = getLabelData(index);

  // Label can be bound only once.
  if (data->offset != -1)
    return setError(kErrorLabelAlreadyBound);

#if !defined(ASMJIT_DISABLE_LOGGER)
  if (_logger) {
    StringBuilderT<256> sb;
    sb.setFormat("L%u:", index);

    size_t binSize = 0;
    if ((_logger->getOptions() & (1 << kLoggerOptionBinaryForm)) == 0)
      binSize = kInvalidIndex;

    LogUtil::formatLine(sb, NULL, binSize, 0, 0, _comment);
    _logger->logString(kLoggerStyleLabel, sb.getData(), sb.getLength());
  }
#endif // !ASMJIT_DISABLE_LOGGER

  Error error = kErrorOk;
  size_t pos = getOffset();

  LabelLink* link = data->links;
  LabelLink* prev = NULL;

  while (link) {
    intptr_t offset = link->offset;

    if (link->relocId != -1) {
      // Handle RelocData - We have to update RelocData information instead of
      // patching the displacement in LabelData.
      _relocList[link->relocId].data += static_cast<Ptr>(pos);
    }
    else {
      // Not using relocId, this means that we are overwriting a real
      // displacement in the binary stream.
      int32_t patchedValue = static_cast<int32_t>(
        static_cast<intptr_t>(pos) - offset + link->displacement);

      // Size of the value we are going to patch. Only BYTE/DWORD is allowed.
      uint32_t size = getByteAt(offset);
      ASMJIT_ASSERT(size == 1 || size == 4);

      if (size == 4) {
        setInt32At(offset, patchedValue);
      }
      else {
        ASMJIT_ASSERT(size == 1);
        if (IntUtil::isInt8(patchedValue))
          setByteAt(offset, static_cast<uint8_t>(patchedValue & 0xFF));
        else
          error = kErrorIllegalDisplacement;
      }
    }

    prev = link->prev;
    link = prev;
  }

  // Chain unused links.
  link = data->links;
  if (link) {
    if (prev == NULL)
      prev = link;

    prev->prev = _unusedLinks;
    _unusedLinks = link;
  }

  // Set as bound (offset is zero or greater and no links).
  data->offset = pos;
  data->links = NULL;

  if (error != kErrorOk)
    return setError(error);

  _comment = NULL;
  return error;
}

// ============================================================================
// [asmjit::Assembler - Embed]
// ============================================================================

Error Assembler::embed(const void* data, uint32_t size) {
  if (getRemainingSpace() < size) {
    Error error = _grow(size);
    if (error != kErrorOk)
      return setError(error);
  }

  uint8_t* cursor = getCursor();
  ::memcpy(cursor, data, size);
  setCursor(cursor + size);

#if !defined(ASMJIT_DISABLE_LOGGER)
  if (_logger)
    _logger->logBinary(kLoggerStyleData, data, size);
#endif // !ASMJIT_DISABLE_LOGGER

  return kErrorOk;
}

// ============================================================================
// [asmjit::Assembler - Reloc]
// ============================================================================

size_t Assembler::relocCode(void* dst, Ptr baseAddress) const {
  if (baseAddress == kNoBaseAddress)
    baseAddress = hasBaseAddress() ? getBaseAddress() : static_cast<Ptr>((uintptr_t)dst);
  else if (getBaseAddress() != baseAddress)
    return 0;

  return _relocCode(dst, baseAddress);
}

// ============================================================================
// [asmjit::Assembler - Make]
// ============================================================================

void* Assembler::make() {
  // Do nothing on error condition or if no instruction has been emitted.
  if (_error != kErrorOk || getCodeSize() == 0)
    return NULL;

  void* p;
  Error error = _runtime->add(&p, this);

  if (error != kErrorOk)
    setError(error);

  return p;
}

// ============================================================================
// [asmjit::Assembler - Emit (Helpers)]
// ============================================================================

#define NA noOperand

Error Assembler::emit(uint32_t code) {
  return _emit(code, NA, NA, NA, NA);
}

Error Assembler::emit(uint32_t code, const Operand& o0) {
  return _emit(code, o0, NA, NA, NA);
}

Error Assembler::emit(uint32_t code, const Operand& o0, const Operand& o1) {
  return _emit(code, o0, o1, NA, NA);
}

Error Assembler::emit(uint32_t code, const Operand& o0, const Operand& o1, const Operand& o2) {
  return _emit(code, o0, o1, o2, NA);
}

Error Assembler::emit(uint32_t code, int o0) {
  return _emit(code, Imm(o0), NA, NA, NA);
}

Error Assembler::emit(uint32_t code, const Operand& o0, int o1) {
  return _emit(code, o0, Imm(o1), NA, NA);
}

Error Assembler::emit(uint32_t code, const Operand& o0, const Operand& o1, int o2) {
  return _emit(code, o0, o1, Imm(o2), NA);
}

Error Assembler::emit(uint32_t code, const Operand& o0, const Operand& o1, const Operand& o2, int o3) {
  return _emit(code, o0, o1, o2, Imm(o3));
}

Error Assembler::emit(uint32_t code, int64_t o0) {
  return _emit(code, Imm(o0), NA, NA, NA);
}

Error Assembler::emit(uint32_t code, const Operand& o0, int64_t o1) {
  return _emit(code, o0, Imm(o1), NA, NA);
}

Error Assembler::emit(uint32_t code, const Operand& o0, const Operand& o1, int64_t o2) {
  return _emit(code, o0, o1, Imm(o2), NA);
}

Error Assembler::emit(uint32_t code, const Operand& o0, const Operand& o1, const Operand& o2, int64_t o3) {
  return _emit(code, o0, o1, o2, Imm(o3));
}

#undef NA

} // asmjit namespace

// [Api-End]
#include "../apiend.h"


text:
namespace blink {

class ExceptionState;
class ExecutionContext;
class V8UnionCSSStyleValueOrString;

class CORE_EXPORT StylePropertyMap : public StylePropertyMapReadOnlyMainThread {
  DEFINE_WRAPPERTYPEINFO();

 public:
  StylePropertyMap(const StylePropertyMap&) = delete;
  StylePropertyMap& operator=(const StylePropertyMap&) = delete;

  void set(const ExecutionContext* execution_context,
           const String& property_name,
           const HeapVector<Member<V8UnionCSSStyleValueOrString>>& values,
           ExceptionState& exception_state);
  void append(const ExecutionContext* execution_context,
              const String& property_name,
              const HeapVector<Member<V8UnionCSSStyleValueOrString>>& values,
              ExceptionState& exception_state);
  void remove(const ExecutionContext*,
              const String& property_name,
              ExceptionState&);
  void clear();

 protected:
  virtual void SetProperty(CSSPropertyID, const CSSValue&) = 0;
  virtual bool SetShorthandProperty(CSSPropertyID,
                                    const String&,
                                    SecureContextMode) = 0;
  virtual void SetCustomProperty(const AtomicString&, const CSSValue&) = 0;
  virtual void RemoveProperty(CSSPropertyID) = 0;
  virtual void RemoveCustomProperty(const AtomicString&) = 0;
  virtual void RemoveAllProperties() = 0;

  StylePropertyMap() = default;
};

}  // namespace blink

#endif  // THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSSOM_STYLE_PROPERTY_MAP_H_


text:
package game.network;

public class CPlacedWallResponse extends CPointerLocationResponse {

    CPlacedWallResponse(int time_step, short player_id, int x, int y) {
        super(time_step, player_id, x, y);
    }

    @Override
    //Modify to add game class type as input and implementation.
    public void process() {
        if(CNetworkConstants.TESTING){
            System.out.println("Action: "+CNetworkConstants.PLACED_WALL+"Received Response.");
        }
    }
}


text:
angular.module('ngForge').provider('$forgeSegmentio', function() {
  'use strict';

  return {
    $get: [
      '$injector', '$q', '$forge', '$forgeLogger', 'ngForgeUtils', function($injector, $q, $forge, $forgeLogger, ngForgeUtils) {
        var forgeSegmentioDummy;
        forgeSegmentioDummy = {
          identify: function(userId, traits, success, error) {
            $forgeLogger.debug("identify");
            return typeof success === "function" ? success() : void 0;
          },
          track: function(event, properties, success, error) {
            $forgeLogger.debug("track");
            return typeof success === "function" ? success() : void 0;
          },
          screen: function(view, properties, success, error) {
            $forgeLogger.debug("screen");
            return typeof success === "function" ? success() : void 0;
          }
        };
        return ngForgeUtils.liftObject($forge.dummy ? forgeSegmentioDummy : forge.segmentio);
      }
    ]
  };
});


text:
var me = {
    fetch: [

        function(fetched_elts) {
            return '/api/3.0/users/details.json';
        }

    ],
    params: {},
    fields: {
        alias: function(me) {
            return me.response.username;
        },
        name: function(me) {
            return me.response.name;
        },
        bio: function(me) {
            return me.response.about;
        },
        location: function(me) {
            return me.response.location;
        },
        avatar: function(me) {
            if (me.response && me.response.avatar && me.response.avatar.large)
                return me.response.avatar.large.permalink;
            else
                return undefined;
        }
    }
};
module.exports = me;


text:
<?php

namespace PSX\Framework\Tests\Schema;

use PSX\Framework\Schema\File;
use PSX\Framework\Test\SchemaTestCase;

/**
 * FileTest
 *
 * @author  Christoph Kappestein <christoph.kappestein@gmail.com>
 * @license http://www.apache.org/licenses/LICENSE-2.0
 * @link    http://phpsx.org
 */
class FileTest extends SchemaTestCase
{
    protected function getSchema()
    {
        return File::class;
    }

    protected function getExpect()
    {
        return <<<'JSON'
{
    "definitions": {
        "File": {
            "description": "File upload provided through a multipart\/form-data post",
            "type": "object",
            "properties": {
                "name": {
                    "type": "string"
                },
                "type": {
                    "type": "string"
                },
                "size": {
                    "type": "integer"
                },
                "tmp_name": {
                    "type": "string"
                },
                "error": {
                    "type": "integer"
                }
            }
        }
    },
    "$ref": "File"
}
JSON;
    }
}


text:
<!DOCTYPE HTML>

   <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
   <meta name="Author" content="Eric S. Raymond">
   <meta name="Description" content="gpsd is a utility that can listen to a GPS or AIS receiver and re-publish the positional data in a simpler format.">
   <meta name="Keywords" content="GPS, translator, GIS">
   <meta name="Revised" content="9 April 2015">
   <meta name="robots" content="index,follow">

   <meta name="verify-v1" content="kb4f3qxJPMaOltYTpJHnvbnteza1PHO4EhrRIfcq2gk=">
   <title>GPSd — Put your GPS on the net!</title>
   <link rel="stylesheet" href="main.css" type="text/css">

How We Engineer For High Reliability.

    Home

    News

    Downloads

    Mailing lists

    Documentation

    FAQ

    Screenshots

    Recipes

    Other GPSDs

    Hardware

    For GPS Vendors

    Wish List

    Hall of Shame

    Troubleshooting Guide

    Hacker's Guide

    References

    Application Compatibility
    History

    Future

GPSD has an exceptionally low defect rate.  Our first Coverity scan, in March 2007, turned up
only 2 errors in over 22KLOC; our second, in May 2012, turned up just
13 errors in 72KLOC, all on rarely-used code paths.  Though the
software is very widely deployed on multiple platforms, we often go
for months between new tracker bugs.

Here's how that's done:

We have an extensive suite of unit tests and regression tests

GPSD has around 100 unit tests and regression tests, including sample
device output for almost every sensor type we support. We've put a lot of
effort into making the tests easy and fast to run so they can be run
often. This makes it actively difficult for random code changes to
break our device drivers without somebody noticing.

Which isn't to say those drivers can't be wrong, just that the ways
they can be wrong are constrained to be through either:

 a protocol-spec-level misunderstanding of what the driver is
supposed to be doing, or

 an implementation bug somewhere in the program's
state space that is obscure and difficult to reach.

Our first Coverity run only turned up two driver bugs - static
buffer overruns in methods for changing the device's reporting
protocol and line speed that escaped notice because they can't be
checked in our test harnesses but only on a live device.

This is also why Coverity didn't find defects on commonly-used code
paths. If there'd been any, the regression tests probably would have
smashed them out long ago. A great deal of boring, grubby, finicky
work went into getting our test framework in shape, but it has paid
off hugely.

We use every fault scanner we can lay our hands on.

We regulary apply Coverity, cppcheck,
and scan-build.
We've as yet been unable to eliminate all scan-build warnings, but we
require the code to audit clean under all the other tools on each
release.

We used to use splint, until
we found that we couldn't replicate the results of splint runs
reliably in different Linux distributions. Also, far and away the biggest
pain in the ass to use. You have to drop cryptic, cluttery magic
comments all over your source to pass hints to splint and suppress its
extremely voluminous and picky output. We have retired in favor of more
modern analyzers.

cppcheck is much newer and much less prone to false
positives. Likewise scan-build. But here's what experience tells us:
each of these tools finds overlapping but different sets of
bugs. Coverity is, by reputation at least, capable enough that it
might dominate one or more of them - but why take chances? Best to use
all and constrain the population of undiscovered bugs into as
small a fraction of the state space as we can.

We also use valgrind to check
for memory leaks, though this is not expected to turn up bugs (and
doesn't) due to our no-dynamic-allocation house
rule.

We are methodical and merciless

Neither magic or genius is required to get defect densities as
low as GPSD's. It's more a matter of sheer bloody-minded persistence -
the willingness to do the up-front work required to apply and
discipline fault scanners, write test harnesses, and automate your
verification process so you can run a truly rigorous validation with
the push of a button.

Many more projects could do this than do. And many more projects
should.


text:
package tunnelRunner;

import java.awt.AWTException;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.geom.Rectangle2D;
import java.util.Arrays;

import javax.swing.JPanel;
import javax.swing.Timer;

import utilityClasses.*;

public class TunnelPanel extends JPanel implements ActionListener, KeyListener {

	private boolean UpPressed = false;
	private boolean DownPressed = false;

	private boolean startGame = true;
	private boolean playing = false;
	private boolean endGame = false;
	private boolean nameEnter = false;
	private boolean highScores = false;

	private ScoreInfo scores = new ScoreInfo("tunnel");

	private int holeX = 500;
	private int holeY = 220;

	private String pName = "";
	private Character letter;

	private int widthOfHole = 5;
	private int holeNumber = 500 / widthOfHole;
	private int holeSize = 150;

	private int[] holesX = new int[holeNumber];
	private int[] holesY = new int[holeNumber];

	/*
	 * private int[] holesX = { 500, 500 + (15), 500 + (15) * 2, 500 + (15) * 3,
	 * 500 + (15) * 4, 500 + (15) * 5, 500 + (15) * 6, 500 + (15) * 7, 500 +
	 * (15) * 8, 500 + (15) * 9, 500 + (15) * 10, 500 + (15) * 11, 500 + (15) *
	 * 12, 500 + (15) * 13, 500 + (15) * 14, 500 + (15) * 15};
	 *
	 * private int[] holesY = { 220, 230, 240, 230, 240, 230, 220, 230, 240,
	 * 230, 240, 230, 220, 230, 240, 250};
	 */
	private int ballX = 20;
	private int ballY = 40;
	private int deltaX = 0;
	private int deltaY = 0;
	private int diameter = 15;
	private int buffer = 0;

	private int ballSpeed = 5;
	private int origBallSpeed = ballSpeed;
	private int holeSpeed = 5;
	private int origHoleSpeed = holeSpeed;

	private int timeSplit = 0;
	private int timeSeconds = 0;
	private boolean paused = false;

	public TunnelPanel() {

		for (int i = 0; i < holesX.length; i++) {
			holesX[i] = 500 + widthOfHole * i;
			holesY[i] = randomY(i);

		}
		setBackground(Color.BLACK);

		setFocusable(true);
		addKeyListener(this);

		Timer timer = new Timer(1000 / 60, this);
		timer.start();

	}

	public void actionPerformed(ActionEvent e) {

		// ifStarted();
		moves();

	}

	public void moves() {

		if (playing) {
			int nextBallX = ballX + deltaX;
			int nextBallY = ballY + deltaY;

			int leftX = ballX + deltaX;
			int rightX = ballX + deltaX + diameter;
			int topY = ballY + deltaY;
			int bottomY = ballY + deltaY + diameter;

			Color topLeftColor = getColor(leftX + buffer, topY + buffer);
			Color topRightColor = getColor(rightX - buffer, topY + buffer);
			Color bottomLeftColor = getColor(leftX + buffer, bottomY - buffer);
			Color bottomRightColor = getColor(rightX - buffer, bottomY - buffer);

			// System.out.println(topRightColor.toString() + "   ");

			if (topLeftColor.equals(Color.WHITE)
					|| topRightColor.equals(Color.WHITE)
					|| bottomLeftColor.equals(Color.WHITE)
					|| bottomRightColor.equals(Color.WHITE)) {
				playing = false;
				// endGame = true;
				nameEnter = true;

			}

			if (UpPressed) {
				deltaY = -ballSpeed;
			} else if (DownPressed) {
				deltaY = ballSpeed;
			} else {
				deltaY = 0;
			}

			for (int i = 0; i < holesX.length; i++) {

				if (holesX[i] <= 0) {
					holesX[i] = 500 + holesX[i];
					holesY[i] = randomY(i);

				}

				holesX[i] -= holeSpeed;

			}

			timeSplit++;
			if (timeSplit == 60) {
				timeSplit = 0;
				timeSeconds++;
			}

			// holeSpeed = (int) (timeSeconds / 10) + 4;

			if (ballY + deltaY + diameter > 0)
				ballY += deltaY;

			// int ballSpeedChange = (int) (timeSeconds / 10);
			// System.out.println(ballSpeed);

		}
		repaint();

	}

	public void paintComponent(Graphics g) {

		super.paintComponent(g);
		g.setColor(Color.WHITE);

		if (startGame) {

			g.setFont(new Font("Joystix", Font.BOLD, 40));
			CenteredText.draw("TUNNEL", 150, g);
			// g.drawString("HOLE IN THE", 60, 210);
			CenteredText.draw("RUNNER", 200, g);
			// g.drawString("WALL", 180, 260);
			g.setFont(new Font("Joystix", Font.BOLD, 20));

			CenteredText.draw("Press Enter to", 300, g);
			// g.drawString("Press Enter to", 120, 300);
			CenteredText.draw("Start", 330, g);
			// g.drawString("Start", 200, 330);

		} else if (playing || paused) {

			// g.fillRect(holeX, holeY + 100, 15, 500 - holeY - 100);

			/*
			 * g.fillRect(leftX, topY, 1, 1); g.fillRect(leftX, bottomY, 1, 1);
			 * g.fillRect(rightX, topY, 1, 1); g.fillRect(rightX, bottomY, 1,
			 * 1);
			 */

			for (int i = 0; i < holesX.length; i++) {

				g.setColor(Color.WHITE);
				g.fillRect(holesX[i], 0, widthOfHole, 500);
				g.setColor(Color.BLACK);

				g.fillRect(holesX[i], holesY[i], widthOfHole, holeSize);
			}
			g.setColor(Color.WHITE);

			g.fillOval(ballX, ballY, diameter, diameter);

			g.setColor(Color.BLACK);
			g.setFont(new Font("Joystix", Font.BOLD, 20));
			FontMetrics f = g.getFontMetrics();
			int w = f.stringWidth(String.valueOf(timeSeconds));
			int h = f.getAscent();

			g.fillRect(3, 3, w + 3, h);

			g.setColor(Color.WHITE);
			g.setFont(new Font("Joystix", Font.BOLD, 20));
			g.drawString(String.valueOf(timeSeconds), 5, 20);

			if (paused) {
				g.setFont(new Font("Joystix", Font.BOLD, 60));
				CenteredText.draw("Paused", 200, g);
			}

		} else if (endGame) {

			g.setColor(Color.WHITE);
			g.setFont(new Font("Joystix", Font.BOLD, 20));
			g.drawString(String.valueOf(timeSeconds), 5, 20);

			g.setFont(new Font("Joystix", Font.BOLD, 60));
			g.setColor(Color.WHITE);
			CenteredText.draw("You Lose!", 170, g);
			// g.drawString("You Lose!", 50, 270);

			g.setFont(new Font("Joystix", Font.BOLD, 26));

			CenteredText.draw("Enter to Restart", 320, g);
			// g.drawString("Enter to Restart", 80, 400);

		} else if (nameEnter) {

			scores.enterName(g, 500, 500, timeSeconds, pName);

		} else if (highScores) {

			//scores.setScores(timeSeconds, pName);
			scores.drawScores(g);
		}

	}

	public void keyTyped(KeyEvent e) {
		// TODO Auto-generated method stub

	}

	public void keyPressed(KeyEvent e) {

		if (e.getKeyCode() == KeyEvent.VK_UP) {
			UpPressed = true;

		} else if (e.getKeyCode() == KeyEvent.VK_DOWN) {
			DownPressed = true;

		}  else if (e.getKeyLocation() == KeyEvent.KEY_LOCATION_STANDARD) {

			if (nameEnter) {
				if (pName.length() < 10) {
					letter = e.getKeyChar();

					letter = Character.toUpperCase(letter);
					pName = pName.concat(letter.toString());
				}
			}
		}
	}

	public void keyReleased(KeyEvent e) {

		if (e.getKeyCode() == KeyEvent.VK_UP) {
			UpPressed = false;

		} else if (e.getKeyCode() == KeyEvent.VK_DOWN) {
			DownPressed = false;

		} else if (e.getKeyCode() == KeyEvent.VK_ENTER) {

			if (endGame) {
				holeX = 500;
				for (int i = 0; i < holesX.length; i++) {
					holesX[i] = 500 + (widthOfHole) * i;
					holesY[i] = randomY(i);
				}
				holeSpeed = origHoleSpeed;
				ballSpeed = origBallSpeed;
				timeSplit = 0;
				timeSeconds = 0;
				startGame = false;
				playing = true;
				nameEnter = false;
				highScores = false;
				endGame = false;
				pName = "";

			} else if (nameEnter) {
				nameEnter = false;
				highScores = true;
				scores.setScores(timeSeconds, pName);

			} else if (highScores) {

				highScores = false;
				endGame = true;
			} else {
			startGame = false;
			playing = true;
			}
		}

	}

	public int randomY(int i) {
		// System.out.println(((int) (Math.random() * 6)) * 80);
		/*
		 * int firstX = holesX[0]; holesX[0] = holesX[1]; holesX[1] = holesX[2];
		 * holesX[2] = firstX;
		 *
		 * int firstY = holesY[0]; holesY[0] = holesY[1]; holesY[1] = holesY[2];
		 * holesY[2] = firstY;
		 */
		if (i == 0)
			i = holesY.length - 1;
		int prevHole = holesY[i - 1];
		int wayPrevHole = prevHole;
		/*
		 * try { if (i - 30 < 0) { i = 124 - i; } wayPrevHole = holesY[i]; }
		 * catch (ArrayIndexOutOfBoundsException e) {
		 *
		 * }
		 */
		// && Math.abs(randNum - wayPrevHole) > 60
		int randNum = ((int) (Math.random() * 300));
		while (Math.abs(randNum - prevHole) > 20) {
			randNum = ((int) (Math.random() * 300));
		}
		return randNum;

	}

	public static Color getColor(int x, int y) {
		try {
			// System.out.print("(" + x + ", " + y + ")  ");
			return new Robot().getPixelColor(x, y + 40);
		} catch (AWTException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return Color.BLACK;
		}
	}

}


text:
#include <common.h>
#include <linux/compat.h>
#include <asm/io.h>
#include <malloc.h>
#include <spi.h>
#include <asm/arch/clk.h>

/* SSP chip registers */
struct ssp_regs {
	u32 cr0;
	u32 cr1;
	u32 data;
	u32 sr;
	u32 cpsr;
	u32 imsc;
	u32 ris;
	u32 mis;
	u32 icr;
	u32 dmacr;
};

/* CR1 register defines  */
#define SSP_CR1_SSP_ENABLE 0x0002

/* SR register defines  */
#define SSP_SR_TNF 0x0002
/* SSP status RX FIFO not empty bit */
#define SSP_SR_RNE 0x0004

/* lpc32xx spi slave */
struct lpc32xx_spi_slave {
	struct spi_slave slave;
	struct ssp_regs *regs;
};

static inline struct lpc32xx_spi_slave *to_lpc32xx_spi_slave(
	struct spi_slave *slave)
{
	return container_of(slave, struct lpc32xx_spi_slave, slave);
}

/* spi_init is called during boot when CONFIG_CMD_SPI is defined */
void spi_init(void)
{
	/*
	 *  nothing to do: clocking was enabled in lpc32xx_ssp_enable()
	 * and configuration will be done in spi_setup_slave()
	*/
}

/* the following is called in sequence by do_spi_xfer() */

struct spi_slave *spi_setup_slave(uint bus, uint cs, uint max_hz, uint mode)
{
	struct lpc32xx_spi_slave *lslave;

	/* we only set up SSP0 for now, so ignore bus */

	if (mode & SPI_3WIRE) {
		error("3-wire mode not supported");
		return NULL;
	}

	if (mode & SPI_SLAVE) {
		error("slave mode not supported\n");
		return NULL;
	}

	if (mode & SPI_PREAMBLE) {
		error("preamble byte skipping not supported\n");
		return NULL;
	}

	lslave = spi_alloc_slave(struct lpc32xx_spi_slave, bus, cs);
	if (!lslave) {
		printf("SPI_error: Fail to allocate lpc32xx_spi_slave\n");
		return NULL;
	}

	lslave->regs = (struct ssp_regs *)SSP0_BASE;

	/*
	 * 8 bit frame, SPI fmt, 500kbps -> clock divider is 26.
	 * Set SCR to 0 and CPSDVSR to 26.
	 */

	writel(0x7, &lslave->regs->cr0); /* 8-bit chunks, SPI, 1 clk/bit */
	writel(26, &lslave->regs->cpsr); /* SSP clock = HCLK/26 = 500kbps */
	writel(0, &lslave->regs->imsc); /* do not raise any interrupts */
	writel(0, &lslave->regs->icr); /* clear any pending interrupt */
	writel(0, &lslave->regs->dmacr); /* do not do DMAs */
	writel(SSP_CR1_SSP_ENABLE, &lslave->regs->cr1); /* enable SSP0 */
	return &lslave->slave;
}

void spi_free_slave(struct spi_slave *slave)
{
	struct lpc32xx_spi_slave *lslave = to_lpc32xx_spi_slave(slave);

	debug("(lpc32xx) spi_free_slave: 0x%08x\n", (u32)lslave);
	free(lslave);
}

int spi_claim_bus(struct spi_slave *slave)
{
	/* only one bus and slave so far, always available */
	return 0;
}

int spi_xfer(struct spi_slave *slave, unsigned int bitlen,
	const void *dout, void *din, unsigned long flags)
{
	struct lpc32xx_spi_slave *lslave = to_lpc32xx_spi_slave(slave);
	int bytelen = bitlen >> 3;
	int idx_out = 0;
	int idx_in = 0;
	int start_time;

	start_time = get_timer(0);
	while ((idx_out < bytelen) || (idx_in < bytelen)) {
		int status = readl(&lslave->regs->sr);
		if ((idx_out < bytelen) && (status & SSP_SR_TNF))
			writel(((u8 *)dout)[idx_out++], &lslave->regs->data);
		if ((idx_in < bytelen) && (status & status & SSP_SR_RNE))
			((u8 *)din)[idx_in++] = readl(&lslave->regs->data);
		if (get_timer(start_time) >= CONFIG_LPC32XX_SSP_TIMEOUT)
			return -1;
	}
	return 0;
}

void spi_release_bus(struct spi_slave *slave)
{
	/* do nothing */
}


text:
<?xml version="1.0" encoding="utf-8"?>

<!--
 Copyright 2020 The Android Open Source Project

 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.
-->

<resources>
    <!-- The primary custom color corresponding to CarColor#PRIMARY -->
    <attr name="carColorPrimary" format="color" />
    <!-- The dark-variant primary custom color corresponding to CarColor#PRIMARY -->
    <attr name="carColorPrimaryDark" format="color" />
    <!-- The secondary custom color corresponding to CarColor#SECONDARY -->
    <attr name="carColorSecondary" format="color" />
    <!-- The dark-variant secondary custom color corresponding to CarColor#SECONDARY -->
    <attr name="carColorSecondaryDark" format="color" />
    <!-- The layout for usage in background of requesting permissions on the phone -->
    <attr name="carPermissionActivityLayout" format="reference" />
</resources>


text:
// This is a part of the Microsoft Foundation Classes C++ library.
// Copyright (C) Microsoft Corporation
// All rights reserved.
//
// This source code is only intended as a supplement to the
// Microsoft Foundation Classes Reference and related
// electronic documentation provided with the library.
// See these sources for detailed information regarding the
// Microsoft Foundation Classes product.

#include "stdafx.h"

#ifdef _DEBUG

#endif

#define new DEBUG_NEW

/////////////////////////////////////////////////////////////////////////////
// COleDocObjectItem

IMPLEMENT_DYNAMIC(COleDocObjectItem, COleClientItem)

BEGIN_INTERFACE_MAP(COleDocObjectItem, COleClientItem)
	INTERFACE_PART(COleDocObjectItem, IID_IOleDocumentSite, OleDocumentSite)
END_INTERFACE_MAP()

COleDocObjectItem::COleDocObjectItem(COleDocument* pContainerDoc)
	: COleClientItem(pContainerDoc)
{
	m_pHelpPopupMenu = NULL;
	m_pActiveView = NULL;
	m_pIPrint = NULL;
	m_bInHelpMenu = FALSE;
}

COleDocObjectItem::~COleDocObjectItem()
{
	if (m_pHelpPopupMenu != NULL)
		m_pHelpPopupMenu->RemoveMenu(0, MF_BYPOSITION);
	delete m_pHelpPopupMenu;
}

/////////////////////////////////////////////////////////////////////////////
// IOleDocumentSite interface

STDMETHODIMP_(ULONG) COleDocObjectItem::XOleDocumentSite::AddRef()
{
	METHOD_PROLOGUE_EX(COleDocObjectItem, OleDocumentSite)
	return pThis->ExternalAddRef();
}

STDMETHODIMP_(ULONG) COleDocObjectItem::XOleDocumentSite::Release()
{
	METHOD_PROLOGUE_EX(COleDocObjectItem, OleDocumentSite)
	return pThis->ExternalRelease();
}

STDMETHODIMP COleDocObjectItem::XOleDocumentSite::QueryInterface(
	REFIID iid, LPVOID* ppvObj)
{
	METHOD_PROLOGUE_EX(COleDocObjectItem, OleDocumentSite)
	return pThis->ExternalQueryInterface(&iid, ppvObj);
}

STDMETHODIMP COleDocObjectItem::XOleDocumentSite::ActivateMe(
	LPOLEDOCUMENTVIEW pViewToActivate)
{
	METHOD_PROLOGUE_EX(COleDocObjectItem, OleDocumentSite)

	LPOLEDOCUMENT lpDocument;
	LPOLECLIENTSITE lpClientSite = pThis->GetClientSite();
	LPOLEINPLACESITE lpInPlaceSite =
		(LPOLEINPLACESITE) pThis->GetInterface(&IID_IOleInPlaceSite);

	if (lpClientSite == NULL || lpInPlaceSite == NULL)
		return E_FAIL;

	// if we've gotten a NULL view, we're to create one ourselves

	if (pViewToActivate == NULL)
	{
		// if we already have a view, we can simply activate it

		if (pThis->m_pActiveView != NULL && pThis->m_pView != NULL)
		{
			pThis->ActivateAndShow();
			return NOERROR;
		}

		ASSERT(pThis->m_lpObject != NULL);
		if (pThis->m_lpObject == NULL)
			return E_FAIL;

		lpDocument = QUERYINTERFACE(pThis->m_lpObject, IOleDocument);
		if (lpDocument == NULL)
			return E_FAIL;

		if (FAILED(
			lpDocument->CreateView(lpInPlaceSite, NULL, 0, &pViewToActivate)))
		{
			lpDocument->Release();
		return E_OUTOFMEMORY;
		}

		// we're done with the document pointer
		lpDocument->Release();
	}
	else if (pThis->m_pActiveView != NULL && pThis->m_pActiveView == pViewToActivate)
	{
		// we already own this view, so no need to addref
		// simply make it visible and resize it

		pThis->ActivateAndShow();
		return NOERROR;
	}
	else
	{
		// set the in-place site
		pViewToActivate->SetInPlaceSite(lpInPlaceSite);
		pViewToActivate->AddRef();
	}

	// it must've created
	ASSERT(pThis->m_pView != NULL);

	// if we had an old one, release it
	if (pThis->m_pActiveView != NULL)
	{
		pThis->m_pActiveView->Show(FALSE);
		pThis->m_pActiveView->UIActivate(FALSE);
		pThis->m_pActiveView->Release();

		if (pThis->m_pIPrint != (IPrint*) -1 && pThis->m_pIPrint != NULL)
			pThis->m_pIPrint->Release();
		pThis->m_pIPrint = NULL;
	}

	// remember it for later
	pThis->m_pActiveView = pViewToActivate;

	// activate and position it
	pThis->ActivateAndShow();

	return NOERROR;
}

/////////////////////////////////////////////////////////////////////////////
// IOleDocumentSite implementation helper

void COleDocObjectItem::ActivateAndShow()
{
	// set up toolbars and menus for the object
	m_pActiveView->UIActivate(TRUE);

	// set the window size, avoiding new toolbars
	RECT rc;
	m_pView->GetClientRect(&rc);
	m_pActiveView->SetRect(&rc);

	// make everything visible
	m_pActiveView->Show(TRUE);

	return;
}

void COleDocObjectItem::OnGetItemPosition(CRect& rPosition)
{
	ASSERT_VALID(this);
	ASSERT(AfxIsValidAddress(&rPosition, sizeof(RECT)));

	// doc objects [almost] always in the exact rect of the view
	ASSERT_VALID(m_pView);
	m_pView->GetClientRect(&rPosition);
}

LPOLEDOCUMENTVIEW COleDocObjectItem::GetActiveView() const
{
	return m_pActiveView;
}

void COleDocObjectItem::Release(OLECLOSE dwCloseOption)
{
	RELEASE(m_pActiveView);
	if (m_pIPrint != (IPrint*) -1)
		RELEASE(m_pIPrint);
	COleClientItem::Release(dwCloseOption);
}

HRESULT COleDocObjectItem::ExecCommand(DWORD nCmdID,
	DWORD nCmdExecOpt /* = OLECMDEXECOPT_DONTPROMPTUSER */,
	const GUID* pguidCmdGroup /* = NULL */)
{
	LPOLECOMMANDTARGET lpCt = QUERYINTERFACE(m_lpObject, IOleCommandTarget);
	HRESULT hr = E_NOTIMPL;

	if (lpCt != NULL)
		hr = lpCt->Exec(pguidCmdGroup, nCmdID, nCmdExecOpt, NULL, NULL);

	RELEASE(lpCt);
	return hr;
}

HRESULT COleDocObjectItem::QueryCommand(ULONG nCmdID,
			DWORD* pdwStatus,
			OLECMDTEXT* pCmdText /*=NULL*/,
			const GUID* pguidCmdGroup /*=NULL*/)
{
	LPOLECOMMANDTARGET lpCt = QUERYINTERFACE(m_lpObject, IOleCommandTarget);
	HRESULT hr = E_NOTIMPL;

	if (lpCt != NULL)
	{
		OLECMD cmd;
		cmd.cmdID = nCmdID;
		cmd.cmdf = 0;
		hr = lpCt->QueryStatus(pguidCmdGroup, 1, &cmd, pCmdText);
		if (hr == S_OK)
			*pdwStatus = cmd.cmdf;
	}

	RELEASE(lpCt);
	return hr;
}

BOOL COleDocObjectItem::SupportsIPrint()
{
	// did someone already ask? -1 means we know it doesn't,
	// non-NULL means we know it does (and we point at it)
	// NULL means we don't know

	if (m_pIPrint == NULL)
	{
		// QI for it
		m_pIPrint = QUERYINTERFACE(m_lpObject, IPrint);

		if (m_pIPrint == NULL)
		{
			// if the server isn't running, we'll need to
			// start it in order to print

			if (FAILED(::OleRun(m_lpObject)))
				m_pIPrint = (IPrint*) -1;
			else
				m_pIPrint = QUERYINTERFACE(m_lpObject, IPrint);
		}
	}

	return (m_pIPrint != NULL && m_pIPrint != (IPrint*) -1);
}

BOOL COleDocObjectItem::GetPageCount(LPLONG pnFirstPage, LPLONG pcPages)
{
	if (!SupportsIPrint())
		return FALSE;

	// The proxy in DOCOBJ.DLL is broken; it doesn't allow
	// NULL parameters to IPrint::GetPageInfo(), even though the spec
	// says it should.

	LONG lPages;
	LONG lFirstPage;

	HRESULT hr = m_pIPrint->GetPageInfo(&lFirstPage, &lPages);

	if (pnFirstPage != NULL)
		*pnFirstPage = lFirstPage;
	if (pcPages != NULL)
		*pcPages = lPages;

	if (SUCCEEDED(hr))
		return TRUE;
	else
		return FALSE;
}

CMenu* COleDocObjectItem::GetHelpMenu(UINT& nPosition)
{
	CFrameWnd* pFrame = m_pView->GetTopLevelFrame();
	ENSURE(pFrame);
	CMenu* pMenuFrame = CMenu::FromHandle(pFrame->m_hMenuDefault);

	if (pMenuFrame != NULL)
		nPosition = pMenuFrame->GetMenuItemCount() -1;

	return pMenuFrame;
}

void COleDocObjectItem::OnInsertMenus(CMenu* pMenuShared,
	LPOLEMENUGROUPWIDTHS lpMenuWidths)
{
	ASSERT_VALID(this);
	ASSERT_VALID(pMenuShared);
	ASSERT(AfxIsValidAddress(lpMenuWidths, sizeof(OLEMENUGROUPWIDTHS)));

	// initialize the group widths array
	lpMenuWidths->width[0] = 1;
	lpMenuWidths->width[2] = 0;
	lpMenuWidths->width[4] = 0;
	lpMenuWidths->width[1] = lpMenuWidths->width[1] == 0xFFFFFFFF ? 0 : lpMenuWidths->width[1];
	lpMenuWidths->width[3] = lpMenuWidths->width[3] == 0xFFFFFFFF ? 0 : lpMenuWidths->width[3];
	lpMenuWidths->width[5] = lpMenuWidths->width[5] == 0xFFFFFFFF ? 0 : lpMenuWidths->width[5];

	// get menu from document template
	CDocTemplate* pTemplate = GetDocument()->GetDocTemplate();
	HMENU hMenuOLE = pTemplate->m_hMenuInPlace;

	// only copy the popups if there is a menu loaded
	if (hMenuOLE == NULL)
		return;

	UINT nItem;
	CMenu* pMenuFrame = GetHelpMenu(nItem);

	if (pMenuFrame != NULL)
	{
		CString strHelpMenuName;
		int nSeparator = pMenuFrame->GetMenuString(nItem,
				strHelpMenuName, MF_BYPOSITION);
		if (nSeparator == 0)
		{
			TRACE(traceOle, 0, "Error: COleDocObjectItem::OnInsertMenus() found no help menu!\n");
			return;
		}

		CString strTearOffName;
		strTearOffName.Format(_T("%s %s"), AfxGetAppName(), strHelpMenuName);
		strTearOffName.Remove('&');

		// get the normal frame menu
		int nCount = pMenuFrame->GetMenuItemCount();
		HMENU hMenu = GetSubMenu(pMenuFrame->m_hMenu, nCount-1);

		// clean up old menu and allocate a new one
		if (m_pHelpPopupMenu == NULL)
		{
			m_pHelpPopupMenu = new CMenu;

			// create new sub-popup menu and add container's Help tearoff
			// then add help menu from main window
			m_pHelpPopupMenu->CreateMenu();
			m_pHelpPopupMenu->InsertMenu((UINT) -1, MF_BYPOSITION | MF_POPUP,
				(DWORD_PTR)hMenu, strTearOffName);
		}

		pMenuShared->InsertMenu((unsigned int)-1, MF_BYPOSITION | MF_POPUP,
			(UINT_PTR) m_pHelpPopupMenu->m_hMenu, strHelpMenuName);

		// tell the object we added our Help menu
		lpMenuWidths->width[5] = 1;
	}

	// insert our menu items and adjust group widths array
	AfxMergeMenus(pMenuShared->GetSafeHmenu(), hMenuOLE,
		&lpMenuWidths->width[0], 0, TRUE);
}

void COleDocObjectItem::OnRemoveMenus(CMenu *pMenuShared)
{
	int cItemsShared = pMenuShared->GetMenuItemCount();
	if (cItemsShared != 0)
	{
		CMenu *pMenuHelp = pMenuShared->GetSubMenu(cItemsShared - 1);

		if(pMenuHelp)
		{
			int cItemsHelp = pMenuHelp->GetMenuItemCount();

			int nItem;
			//remove everything but our help popup!
			for (nItem = 1;nItem<cItemsHelp; nItem++)
			{
				pMenuHelp->DeleteMenu(nItem, MF_BYPOSITION);
			}
		}

		pMenuShared->RemoveMenu(cItemsShared - 1, MF_BYPOSITION);
	}

	// get menu from document template
	COleClientItem::OnRemoveMenus(pMenuShared);
}

BOOL COleDocObjectItem::OnPreparePrinting(CView* pCaller,
	CPrintInfo* pInfo, BOOL bPrintAll)
{
	LONG lDocObjectPages = 0;

	CDocument* pDoc = pCaller->GetDocument();
	COleDocument* pOleDoc = DYNAMIC_DOWNCAST(COleDocument, pDoc);
	if (pOleDoc == NULL)
		return FALSE;

	POSITION pos = pOleDoc->GetStartPosition();
	while (pos != NULL)
	{
		COleClientItem* pItem = pOleDoc->GetNextClientItem(pos);
		COleDocObjectItem* pDocItem =
			DYNAMIC_DOWNCAST(COleDocObjectItem, pItem);
		if (pDocItem == NULL)
			continue;

		// if this isn't the view, continue
		if (!bPrintAll)
		{
			if (pItem->m_pView == NULL ||
				 pItem->m_pView->m_hWnd != pCaller->m_hWnd)
				continue;
		}

		if (pDocItem->SupportsIPrint())
		{
			LONG lThisObjectPages;
			if (pDocItem->GetPageCount(NULL, &lThisObjectPages))
				lDocObjectPages += lThisObjectPages;
			pInfo->m_bDocObject = TRUE;
		}
		else
			lDocObjectPages++;

		if (!bPrintAll)
			break;
	}

	if (lDocObjectPages > 0)
	{
		UINT nMaxPage = pInfo->GetMaxPage();

		// set the page count; increment it if previously set
		if (nMaxPage == 0xFFFF)
			pInfo->SetMaxPage(lDocObjectPages);
		else
			pInfo->SetMaxPage(nMaxPage + lDocObjectPages);
		pInfo->m_bDocObject = TRUE;
	}

	if (pInfo->m_bDocObject)
	{
		// we can't show the "selection" button for DocObjects
		pInfo->m_pPD->m_pd.Flags |= PD_NOSELECTION;

		// if it's a doc object, and we're printing all, then we
		// shouldn't show the selection
		if (bPrintAll)
			pInfo->m_pPD->m_pd.Flags |= PD_NOPAGENUMS;
	}

	return TRUE;
}

void COleDocObjectItem::OnPrint(CView* pCaller, CPrintInfo* pInfo,
	BOOL bPrintAll)
{
	// Note that this function ignores pInfo->m_nCurPage, and will always
	// print the whole range of pages in the CPrintInfo object. That's
	// because DocObjects don't support any mechanism to _continue_
	// printing to an existing print job.

	CDocument* pDoc = pCaller->GetDocument();
	COleDocument* pOleDoc = DYNAMIC_DOWNCAST(COleDocument, pDoc);
	if (pOleDoc == NULL)
		return;

	POSITION pos = pOleDoc->GetStartPosition();
	while (pos != NULL)
	{
		COleClientItem* pItem = pOleDoc->GetNextClientItem(pos);
		COleDocObjectItem* pDocItem = DYNAMIC_DOWNCAST(COleDocObjectItem, pItem);
		if (pDocItem == NULL)
			continue;

		// if this isn't the view, continue
		if (!bPrintAll)
		{
			if (pItem->m_pView == NULL || pItem->m_pView->m_hWnd != pCaller->m_hWnd)
				continue;
		}

		HRESULT hrThisPage = E_UNEXPECTED;

		if (pDocItem->SupportsIPrint())
		{
			DVTARGETDEVICE* pTargetDevice = NULL;
			LPDEVNAMES lpDevNames = NULL;
			LPDEVMODE lpDevMode = NULL;

			lpDevNames = (LPDEVNAMES) GlobalLock(pInfo->m_pPD->m_pd.hDevNames);
			if (lpDevNames != NULL)
			{
				lpDevMode = (LPDEVMODE) GlobalLock(pInfo->m_pPD->m_pd.hDevMode);
				if (lpDevMode != NULL)
				{
					pTargetDevice = _AfxOleCreateTargetDevice(lpDevNames, lpDevMode);
					if (pTargetDevice != NULL)
					{
						PAGESET* pps = (PAGESET*) CoTaskMemAlloc(sizeof(PAGESET));
						if (pps != NULL)
						{
							pps->cbStruct = sizeof(PAGESET);
							ASSERT((pps->cbStruct % 4) == 0);
							pps->fOddPages = TRUE;
							pps->fEvenPages = TRUE;
							pps->cPageRange = 1;
							pps->rgPages[0].nFromPage = pInfo->GetFromPage();
							pps->rgPages[0].nToPage = pInfo->GetToPage();

							LONG lLastPage = pps->rgPages[0].nFromPage;
							LONG lPagesPrinted;

							DWORD dwFlags = PRINTFLAG_RECOMPOSETODEVICE;

							if (pInfo->m_pPD->m_pd.Flags & PD_PRINTTOFILE)
								dwFlags |= PRINTFLAG_PRINTTOFILE;

							hrThisPage = pDocItem->m_pIPrint->Print(dwFlags,
									&pTargetDevice, &pps, NULL, NULL,
									pInfo->m_nCurPage, &lPagesPrinted,
									&lLastPage);

							if (!SUCCEEDED(hrThisPage))
								TRACE(traceOle, 0, "IPrint::Print() returned %8.8X\n", hrThisPage);
							CoTaskMemFree(pps);
						}
						CoTaskMemFree(pTargetDevice);
					}
					GlobalUnlock(pInfo->m_pPD->m_pd.hDevMode);
				}
				GlobalUnlock(pInfo->m_pPD->m_pd.hDevNames);
			}
		}
		else
		{
			// try through IOleCommandTarget

			hrThisPage = pDocItem->ExecCommand(OLECMDID_PRINT);
			if (!SUCCEEDED(hrThisPage))
				TRACE(traceOle, 0, "IOleCommandTarget::Exec() returned %8.8X\n", hrThisPage);
		}
	}

	return;
}

HRESULT COleDocObjectItem::DoDefaultPrinting(CView *pCaller, CPrintInfo *pInfo)
{
	ENSURE_VALID(pCaller);
	ENSURE_ARG(pInfo != NULL);
	COleDocObjectItem* pDocItem = NULL;
	HRESULT hr = E_FAIL;
	CDocument* pDoc = pCaller->GetDocument();
	COleDocument* pOleDoc = DYNAMIC_DOWNCAST(COleDocument, pDoc);
	if (pOleDoc == NULL)
		return hr;

	POSITION pos = pOleDoc->GetStartPosition();
	while (pos != NULL)
	{
		COleClientItem* pItem = pOleDoc->GetNextClientItem(pos);
		pDocItem = DYNAMIC_DOWNCAST(COleDocObjectItem, pItem);
		if (pDocItem != NULL)
			break;
	}

	if (!pDocItem)
		return hr;

	IOleCommandTarget *pCmdTarget = NULL;
	if (pDocItem && pDocItem->m_lpObject)
	{
		if (S_OK == (hr = pDocItem->m_lpObject->QueryInterface(IID_IOleCommandTarget,
			(void**)&pCmdTarget)))
		{

			OLECMD cmd;
			cmd.cmdID = pInfo->m_bPreview ? OLECMDID_PRINTPREVIEW : OLECMDID_PRINT;

			if (S_OK == (hr = pCmdTarget->QueryStatus(NULL, 1, &cmd, NULL)))
			{
				if ((cmd.cmdf & (OLECMDF_SUPPORTED|OLECMDF_ENABLED))
					== (OLECMDF_SUPPORTED|OLECMDF_ENABLED))
				{
					hr = pCmdTarget->Exec(NULL, cmd.cmdID, OLECMDEXECOPT_PROMPTUSER,
						NULL, NULL);
					if (hr == OLECMDERR_E_CANCELED || hr == S_OK)
						hr = S_OK;
				}
			}
			pCmdTarget->Release();
		}
	}
	return hr;
}

BEGIN_OLECMD_MAP(COleDocObjectItem, COleClientItem)
END_OLECMD_MAP()

BOOL COleDocObjectItem::OnCmdMsg(UINT nID, int nCode, void* pExtra, AFX_CMDHANDLERINFO* pHandlerInfo)
{
	if (m_pView && m_pView->OnCmdMsg(nID, nCode, pExtra, pHandlerInfo))
		return TRUE;
	return COleClientItem::OnCmdMsg(nID, nCode, pExtra, pHandlerInfo);
}


text:
from .myqt import QT
import pyqtgraph as pg

import time
import os
from collections import OrderedDict
import pickle
import webbrowser
from pprint import pprint

from ..dataio import DataIO
from ..datasource import data_source_classes
from .tools import get_dict_from_group_param, ParamDialog, MethodDialog #, open_dialog_methods
from  ..datasets import datasets_info, download_dataset

from ..catalogueconstructor import CatalogueConstructor
from ..cataloguetools import apply_all_catalogue_steps
from ..autoparams import get_auto_params_for_catalogue, get_auto_params_for_peelers
from .cataloguewindow import CatalogueWindow
from ..peeler import Peeler
from .peelerwindow import PeelerWindow
from .initializedatasetwindow import InitializeDatasetWindow
from .probegeometryview import ProbeGeometryView
from ..export import export_list
from ..tools import open_prb
from ..report import generate_report
from ..cltools import HAVE_PYOPENCL
from .gpuselector import GpuSelector

from . import icons

from . import gui_params

try:
    import ephyviewer
    HAVE_EPHYVIEWER = True
except:
    HAVE_EPHYVIEWER = False

error_box_msg = """
This is the raw Python error.
Unfortunatly, this is sometimes not so usefull for user...
Please send it to https://github.com/tridesclous/tridesclous/issues.

{}
"""
class MainWindow(QT.QMainWindow):
    def __init__(self, parent=None):
        QT.QMainWindow.__init__(self, parent=parent)

        self.setWindowIcon(QT.QIcon(':/main_icon.png'))

        self.dataio = None
        #~ self.catalogueconstructor = None

        self.resize(800, 800)

        appname = 'tridesclous'
        settings_name = 'settings'
        self.settings = QT.QSettings(appname, settings_name)

        self.create_actions_and_menu()

        w = QT.QWidget()
        self.setCentralWidget(w)
        mainlayout  = QT.QVBoxLayout()
        w.setLayout(mainlayout)

        self.label_info = QT.QLabel('Nothing loaded')
        mainlayout.addWidget(self.label_info)

        mainlayout.addStretch()

        self.open_windows = []

        self.win_viewer = None
        self.probe_viewer = None

        self.dialog_fullchain_params = ParamDialog(gui_params.fullchain_params, parent=self)
        self.dialog_method_features = MethodDialog(gui_params.features_params_by_methods, parent=self,
                        title='Which feature method ?', selected_method='peak_max')
        self.dialog_method_cluster = MethodDialog(gui_params.cluster_params_by_methods, parent=self,
                        title='Which cluster method ?', selected_method = 'sawchaincut')

        self.dialog_method_peeler = MethodDialog(gui_params.peeler_params_by_methods, parent=self,
                    title='Peeler engine')

        if HAVE_PYOPENCL:
            self.dialog_gpuselector = GpuSelector(settings=self.settings)

    def create_actions_and_menu(self):

        self.toolbar = QT.QToolBar(orientation=QT.Vertical)
        self.toolbar.setToolButtonStyle(QT.Qt.ToolButtonTextUnderIcon)
        self.addToolBar(QT.TopToolBarArea, self.toolbar)
        self.toolbar.setIconSize(QT.QSize(60, 40))

        self.toolbar2 = QT.QToolBar(orientation=QT.Vertical)
        self.toolbar2.setToolButtonStyle(QT.Qt.ToolButtonTextUnderIcon)
        self.addToolBar(QT.LeftToolBarArea, self.toolbar2)
        self.toolbar2.setIconSize(QT.QSize(60, 40))

        self.file_menu = self.menuBar().addMenu(self.tr("File"))

        do_open = QT.QAction('&Open', self, shortcut = "Ctrl+O", icon=QT.QIcon(":document-open.svg"))
        do_open.triggered.connect(self.open_dialog)
        self.file_menu.addAction(do_open)
        self.toolbar.addAction(do_open)

        do_init = QT.QAction('&Initialize dataset', self, shortcut = "Ctrl+I", icon=QT.QIcon(":document-new.svg"))
        do_init.triggered.connect(self.initialize_dataset_dialog)
        self.file_menu.addAction(do_init)
        self.toolbar.addAction(do_init)

        self.recetly_opened_menu = self.file_menu.addMenu('Recently opened')
        self._refresh_recetly_opened()

        self.dw_dataset_menu = self.file_menu.addMenu('Download test datasets')
        for name in datasets_info:
            act = self.dw_dataset_menu.addAction(name)
            act.name = name
            act.triggered.connect(self.do_download_dataset)

        self.toolbar.addSeparator()

        if HAVE_EPHYVIEWER:
            open_viewer = QT.QAction('&Preview raw signals', self, icon=QT.QIcon(":ephyviewer.png"))
            open_viewer.triggered.connect(self.open_ephyviewer)
            self.toolbar.addAction(open_viewer)

        open_probe_viewer = QT.QAction('&Probe geometry', self, icon=QT.QIcon(":probe-geometry.svg"))
        open_probe_viewer.triggered.connect(self.open_probe_viewer)
        self.toolbar.addAction(open_probe_viewer)

        self.toolbar.addSeparator()

        do_check_prb = QT.QAction('Check PRB file', self, ) # icon=QT.QIcon(":document-export.svg"))
        do_check_prb.triggered.connect(self.check_prb_file)
        self.file_menu.addAction(do_check_prb)

        if HAVE_PYOPENCL:
            do_open_gpuselector = QT.QAction('Default OpenCL (GPU) selector', self)
            do_open_gpuselector.triggered.connect(self.open_gpuselector)
            self.file_menu.addAction(do_open_gpuselector)

        self.toolbar.addSeparator()

        do_refresh = QT.QAction(u'Refresh', self,checkable = False, icon=QT.QIcon(":/view-refresh.svg"))
        do_refresh.triggered.connect(self.refresh_with_reload)
        self.toolbar.addAction(do_refresh)

        do_export_spikes = QT.QAction('Export spikes', self,  icon=QT.QIcon(":document-export.svg"))
        do_export_spikes.triggered.connect(self.export_spikes)
        self.toolbar.addAction(do_export_spikes)
        self.file_menu.addAction(do_export_spikes)

        do_generate_report = QT.QAction('Generate report', self,  icon=QT.QIcon(":kwrite.svg"))
        do_generate_report.triggered.connect(self.generate_report)
        self.toolbar.addAction(do_generate_report)
        self.file_menu.addAction(do_generate_report)

        self.toolbar.addSeparator()

        help_act = QT.QAction('Help', self,checkable = False, icon=QT.QIcon(":main_icon.png"))
        help_act.triggered.connect(self.open_webbrowser_help)
        self.toolbar.addAction(help_act)

        # Toolbar2
        self.toolbar2.addWidget(QT.QLabel('<b>Steps</b>'))

        self.toolbar2.addWidget(QT.QLabel('Select chanel group:'))
        self.combo_chan_grp = QT.QComboBox()
        self.toolbar2.addWidget(self.combo_chan_grp)
        self.combo_chan_grp.currentIndexChanged .connect(self.on_chan_grp_change)

        do_init_cataloguewin = QT.QAction('Initialize Catalogue', self, icon=QT.QIcon(":autocorrection.svg"))
        do_init_cataloguewin.triggered.connect(self.initialize_catalogue)
        self.toolbar2.addAction(do_init_cataloguewin)

        do_open_cataloguewin = QT.QAction('Open CatalogueWindow', self,  icon=QT.QIcon(":catalogwinodw.png"))
        do_open_cataloguewin.triggered.connect(self.open_cataloguewin)
        self.toolbar2.addAction(do_open_cataloguewin)

        do_run_peeler = QT.QAction('Run Peeler', self,  icon=QT.QIcon(":configure-shortcuts.svg"))
        do_run_peeler.triggered.connect(self.run_peeler)
        self.toolbar2.addAction(do_run_peeler)

        do_open_peelerwin = QT.QAction('Open PeelerWindow', self,  icon=QT.QIcon(":peelerwindow.png"))
        do_open_peelerwin.triggered.connect(self.open_peelerwin)
        self.toolbar2.addAction(do_open_peelerwin)

    def open_webbrowser_help(self):
        url = "http://tridesclous.readthedocs.io"
        webbrowser.open(url, new=2)

    def warn(self, text, title='Error in tridesclous'):
        mb = QT.QMessageBox.warning(self, title,text,
                QT.QMessageBox.Ok ,
                QT.QMessageBox.NoButton)

    def errorToMessageBox(self, e):
        self.warn(error_box_msg.format(e))

    def refresh_info(self):
        txt = self.dataio.__repr__()
        txt += '\n\n'
        #~ print('refresh_info', self.chan_grps)
        for chan_grp in self.chan_grps:
            catalogueconstructor = CatalogueConstructor(dataio=self.dataio, chan_grp=chan_grp)
            txt += catalogueconstructor.__repr__()
            txt += '\n'

        self.label_info.setText(txt)

    def open_dialog(self):
        fd = QT.QFileDialog(fileMode=QT.QFileDialog.DirectoryOnly, acceptMode=QT.QFileDialog.AcceptOpen)
        #~ fd.setNameFilters(['Hearingloss setup (*.json)', 'All (*)'])
        fd.setViewMode( QT.QFileDialog.Detail )
        if fd.exec_():
            dirname = fd.selectedFiles()[0]
            print(dirname)

            if DataIO.check_initialized(dirname):
                self._open_dataio(dirname)

    def _refresh_recetly_opened(self):
        self.recetly_opened_menu.clear()
        for dirname in self.recently_opened():
            act = self.recetly_opened_menu.addAction(str(dirname))
            act.dirname = dirname
            act.triggered.connect(self.do_open_recent)

    def do_open_recent(self):
        self._open_dataio(self.sender().dirname)

    def recently_opened(self):
        value = self.settings.value('recently_opened')
        if value is None:
            recently_opened = []
        else:
            try:
                if type(value) == str:
                    #bug on some qt
                    value = value.encode('ascii')
                recently_opened = pickle.loads(value)
                if type(recently_opened) != list:
                    recently_opened = []
            except:
                recently_opened = []
        return recently_opened

    def do_download_dataset(self):
        name = self.sender().name
        fd = QT.QFileDialog(fileMode=QT.QFileDialog.DirectoryOnly, acceptMode=QT.QFileDialog.AcceptOpen)
        fd.setViewMode( QT.QFileDialog.Detail )
        if fd.exec_():
            localdir = os.path.join(fd.selectedFiles()[0], name)
            if os.path.exists(localdir):
                return
            os.mkdir(localdir)
            localdir, filenames, params = download_dataset(name, localdir=localdir)

            dirname = os.path.join(localdir, 'tdc_'+name)
            dataio = DataIO(dirname=dirname)
            dataio.set_data_source(type='RawData', filenames=filenames, **params)

            self._open_dataio( dirname)

    def refresh_with_reload(self):
        if self.dataio is None:
            return

        self.dataio = DataIO(dirname=self.dataio.dirname)
        self.refresh_info()

    def _open_dataio(self, dirname):
        recently_opened =self.recently_opened()
        if dirname not in recently_opened:
            recently_opened = [dirname] + recently_opened
            recently_opened = recently_opened[:5]
            self.settings.setValue('recently_opened', pickle.dumps(recently_opened))
            self._refresh_recetly_opened()

        for win in self.open_windows:
            win.close()
        self.open_windows = []

        self.dataio = DataIO(dirname=dirname)

        self.combo_chan_grp.blockSignals(True)
        self.combo_chan_grp.clear()
        self.combo_chan_grp.addItems([str(k) for k in self.dataio.channel_groups.keys()] + ['ALL'])
        self.combo_chan_grp.blockSignals(False)
        self.on_chan_grp_change()

        # set auto params catalogue
        params = get_auto_params_for_catalogue(self.dataio, chan_grp=self.chan_grps[0])
        d = dict(params)
        for k in ('feature_method', 'feature_kargs', 'cluster_method', 'cluster_kargs'):
            d.pop(k)
        self.dialog_fullchain_params.set(d)
        self.dialog_method_features.set_method(params['feature_method'], params['feature_kargs'])
        self.dialog_method_cluster.set_method(params['cluster_method'], params['cluster_kargs'])

        # TODO clean_cluster

        # set auto params peeler
        params = get_auto_params_for_peelers(self.dataio, chan_grp=self.chan_grps[0])
        d = dict(params)
        engine = d.pop('engine')
        self.dialog_method_peeler.set_method(engine, d)

    def release_closed_windows(self):
        for win in list(self.open_windows):
            if not win.isVisible():
                self.open_windows.remove(win)

    def close_window_chan_grp(self, chan_grp):
        for win in list(self.open_windows):
            if win.controller.chan_grp == chan_grp:
                win.close()
                self.open_windows.remove(win)

    #~ @property
    #~ def chan_grp(self):
        #~ txt = self.combo_chan_grp.currentText()
        #~ if txt == 'ALL':
            #~ # take the first
            #~ chan_grp = list(self.dataio.channel_groups.keys())[0]
        #~ else:
            #~ chan_grp = int(txt)
        #~ return chan_grp

    @property
    def chan_grps(self):
        txt = self.combo_chan_grp.currentText()
        if txt == 'ALL':
            # take the first
            chan_grps = list(self.dataio.channel_groups.keys())
        else:
            chan_grps = [int(txt)]
        return chan_grps

    def on_chan_grp_change(self, index=None):
        #~ self.catalogueconstructor = CatalogueConstructor(dataio=self.dataio, chan_grp=self.chan_grp)
        self.refresh_info()

        # this set a the a by default method depending the number of channels
        n = self.dataio.nb_channel(chan_grp=self.chan_grps[0])
        if 1<=n<9:
            feat_method = 'global_pca'
        else:
            feat_method = 'peak_max'
        self.dialog_method_features.param_method['method'] = feat_method

    def initialize_dataset_dialog(self):
        init_dia = InitializeDatasetWindow(parent=self)
        if init_dia.exec_():
            self._open_dataio(init_dia.dirname_created)

    def initialize_catalogue(self):

        if  self.dataio is None:
            return

        self.release_closed_windows()
        for chan_grp in self.chan_grps:
            self.close_window_chan_grp(chan_grp)

        self.refresh_with_reload()

        if not self.dialog_fullchain_params.exec_():
            return
        if not self.dialog_method_features.exec_():
            return
        if not self.dialog_method_cluster.exec_():
            return

        params = {}
        params.update(self.dialog_fullchain_params.get())
        params['memory_mode'] = 'memmap'
        #~ pprint(params)

        method, d = self.dialog_method_features.get()
        params['feature_method'] = method
        params['feature_kargs'] = d

        method, d = self.dialog_method_cluster.get()
        params['cluster_method'] = method
        params['cluster_kargs'] = d

        #~ #TODO dialog for that
        #~ params['clean_cluster'] = False
        #~ params['clean_cluster_kargs'] = {}

        for chan_grp in self.chan_grps:
            print('### chan_grp', chan_grp, ' ###')

            #~ try:
            if 1:
                catalogueconstructor = CatalogueConstructor(dataio=self.dataio, chan_grp=chan_grp)
                apply_all_catalogue_steps(catalogueconstructor, params, verbose=True)

            #~ except Exception as e:
                #~ print(e)
                #~ self.errorToMessageBox(e)

        self.refresh_info()

    def open_cataloguewin(self):
        if self.dataio is None: return
        if len(self.chan_grps) != 1: return

        #~ try:
        if True:
            catalogueconstructor = CatalogueConstructor(dataio=self.dataio, chan_grp=self.chan_grps[0])
            win = CatalogueWindow(catalogueconstructor)
            win.setWindowTitle(self.dataio.channel_group_label(chan_grp=self.chan_grps[0]))
            win.show()
            self.open_windows.append(win)
        #~ except Exception as e:
            #~ print(e)
            #~ self.errorToMessageBox(e)

    def run_peeler(self):
        if self.dataio is None: return

        #TODO find something better when several segment
        #~ lengths = [ self.dataio.datasource.get_segment_shape(i)[0] for i in range(self.dataio.nb_segment)]
        #~ max_duration = max(lengths)/self.dataio.sample_rate

        total_duration = sum(self.dataio.get_segment_length(seg_num=seg_num) / self.dataio.sample_rate for seg_num in range(self.dataio.nb_segment))

        for m in self.dialog_method_peeler.methods:
            self.dialog_method_peeler.all_params[m]['duration'] = total_duration

        #~ dia = ParamDialog(gui_params.peeler_params)
        #~ dia.resize(450, 500)

        #~ if not dia.exec_():
            #~ return
        #~ d = dia.get()

        if not self.dialog_method_peeler.exec_():
            return
        engine, d = self.dialog_method_peeler.get()
        #~ print('run_peeler')
        #~ print(engine)
        #~ print(d)
        d['engine'] = engine

        #~ duration = d['duration'] if d['limit_duration'] else None
        #~ d.pop('limit_duration')
        duration = d.pop('duration')
        print('duration', duration)

        errors = []
        for chan_grp in self.chan_grps:
            try:
            #~ if True:
                initial_catalogue = self.dataio.load_catalogue(chan_grp=chan_grp)
                if initial_catalogue is None:
                    txt =  """chan_grp{}
Catalogue do not exists, please do:
    1. Initialize Catalogue (if not done)
    2. Open CatalogueWindow
    3. Make catalogue for peeler
                    """.format(chan_grp)
                    errors.append(txt)
                    continue

                pprint(d)
                peeler = Peeler(self.dataio)
                peeler.change_params(catalogue=initial_catalogue, **d)

                t1 = time.perf_counter()
                peeler.run(duration=duration)
                t2 = time.perf_counter()
                print('peeler.run_loop', t2-t1)

            except Exception as e:
                print(e)
                error = """chan_grp{}\n{}""".format(chan_grp, e)
                errors.append(error)

        for error in errors:
            self.errorToMessageBox(error)

    def open_peelerwin(self):
        if self.dataio is None: return

        if len(self.chan_grps) != 1:
            return

        try:
            initial_catalogue = self.dataio.load_catalogue(chan_grp=self.chan_grps[0])
            win = PeelerWindow(dataio=self.dataio, catalogue=initial_catalogue)
            win.show()
            self.open_windows.append(win)
        except Exception as e:
            print(e)
            self.errorToMessageBox(e)

    def open_ephyviewer(self):
        if self.win_viewer is not None:
            self.win_viewer.close()
            self.win_viewer = None

        if self.dataio  is None:
            return
        if not hasattr(self.dataio.datasource, 'rawios'):
            return

        sources = ephyviewer.get_sources_from_neo_rawio(self.dataio.datasource.rawios[0])

        self.win_viewer = ephyviewer.MainViewer()

        for i, sig_source in enumerate(sources['signal']):
            view = ephyviewer.TraceViewer(source=sig_source, name='signal {}'.format(i))
            view.params['scale_mode'] = 'same_for_all'
            view.params['display_labels'] = True
            view.auto_scale()
            if i==0:
                self.win_viewer.add_view(view)
            else:
                self.win_viewer.add_view(view, tabify_with='signal {}'.format(i-1))

        self.win_viewer.show()

    def open_probe_viewer(self):
        if self.dataio is None:
            return

        if self.probe_viewer is not None:
            self.probe_viewer.close()
            self.probe_viewer = None

        self.probe_viewer = ProbeGeometryView(channel_groups=self.dataio.channel_groups, parent=self)
        self.probe_viewer.setWindowFlags(QT.Qt.Window)
        self.probe_viewer.show()

    def export_spikes(self):
        if self.dataio is None:
            return

        possible_formats = [e.ext for e in export_list]
        params = [
            {'name': 'format', 'type': 'list', 'limits':possible_formats},
            {'name': 'split_by_cluster', 'type': 'bool', 'value':False},
            {'name': 'use_cell_label', 'type': 'bool', 'value':True},
        ]
        dialog = ParamDialog(params, parent=self)
        if not dialog.exec_():
            return
        p = dialog.get()
        self.dataio.export_spikes(export_path=None,
                split_by_cluster=p['split_by_cluster'],  use_cell_label=p['use_cell_label'], formats=p['format'])

    def generate_report(self):
        if self.dataio is None:
            return
        generate_report(self.dataio)

    def check_prb_file(self):
        fd = QT.QFileDialog(fileMode=QT.QFileDialog.AnyFile, acceptMode=QT.QFileDialog.AcceptOpen)
        fd.setNameFilters(['Probe geometry (*.PRB, *.prb)', 'All (*)'])
        fd.setViewMode( QT.QFileDialog.Detail )
        if fd.exec_():
            prb_filename = fd.selectedFiles()[0]
            #~ print(prb_filename)
            try:
                channel_groups = open_prb(prb_filename)
                self.probe_viewer = ProbeGeometryView(channel_groups=channel_groups, parent=self)
            except:
                self.warn('Error in PRB')
                return
            self.probe_viewer.setWindowFlags(QT.Qt.Window)
            self.probe_viewer.show()

    def open_gpuselector(self):
        if not HAVE_PYOPENCL:
            return
        if not self.dialog_gpuselector.exec_():
            return
        self.dialog_gpuselector.apply_cl_setting()


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/html; charset=utf-8" />
  <meta http-equiv="Content-Style-Type" content="text/css" />
  <meta name="generator" content="pandoc" />
  <title>Corona Docs: API > Libraries > display > newLine</title>
  <meta name="revised" content="14-Nov-2013" />
  <meta name="description" content="Whether you're new to Corona or want to take your app to the next level, we've got a wealth of resources for you including extensive documentation, API reference, sample code, and videos.  API > Libraries > display > newLine" />

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

SDK APIs

Enterprise APIs

Plugins

Guides

Tutorials

Corona Resources ▹

  <form action="http://www.google.com/cse" id="cse-search-box">
  <input type="hidden" name="cx" value="009283852522218786394:g40gqt2m6rq" />
  <input type="hidden" name="ie" value="UTF-8" />
  <input type="text" name="q" id="q" autocomplete="off" size="40" style="width:150px;float:left" />
  <input type="submit" name="sa" value="Search" style="float:right; font-size: 13px;" />
  </form>

display.newLine()

Overview

Gotchas

Syntax

parentGroup (optional)

x1, y1 (required)

x2, y2 (required)

Example

Ξ  ▸  API  ▸  Libraries  ▸  display  ▸  newLine

display.newLine()

Type
Function

Library
display.*

Return value
LineObject

Revision
Current Public Release (2013.2076)

Keywords
lines, vector

Sample code
/CoronaSDK/SampleCode/Graphics/Polylines

See also
display.setDefault()
object.width
object:append()

Overview

Draw a line from one point to another. Optionally, append points to the end of the line.

Gotchas

Currently display.newLine() objects do not support touch events (case #3803).

By default, the fill color is white (rgb 255, 255, 255). The default color can be changed using display.setDefault().

Syntax

display.newLine( [parentGroup,] x1, y1, x2, y2 )

parentGroup (optional)

DisplayObject (group). Specify an optional display group in which to insert the line. Uses the current stage (as returned from display.getCurrentStage()) if not specified.

x1, y1 (required)

Numbers. Coordinates of the beginning of the line.

x2, y2 (required)

Numbers. Coordinates of the end of the line.

Example

local star = display.newLine( 200,90, 227,165 )
star:append( 305,165, 243,216, 265,290, 200,245, 135,290, 157,215, 95,165, 173,165, 200,90 )
star:setColor( 255, 102, 102, 255 )
star.width = 3

© 2013 Corona Labs Inc. All Rights Reserved. (Last updated: 14-Nov-2013)

Help us help you! Give us feedback on this page:

Love it

Like it, but...

Hate it


text:
require_relative '../../../../automated_init'

context "Message" do
  context "Metadata" do
    context "Correlated" do
      context "Entity Stream Input" do
        context "Entity Correlation Stream Name" do
          metadata = Controls::Metadata.example

          metadata.correlation_stream_name = 'someStream-123'

          context "Correlation Stream Name Is the Stream Name" do
            test "Is correlated" do
              assert(metadata.correlated?('someStream-123'))
            end
          end

          context "Correlation Stream Name Is Not the Stream Name" do
            test "Is not correlated" do
              refute(metadata.correlated?("a#{SecureRandom.hex}-123"))
            end
          end
        end
      end
    end
  end
end


text:
package com.google.cloud.websecurityscanner.v1beta.samples;

// [START websecurityscanner_v1beta_generated_WebSecurityScanner_GetFinding_Findingname_sync]
import com.google.cloud.websecurityscanner.v1beta.Finding;
import com.google.cloud.websecurityscanner.v1beta.FindingName;
import com.google.cloud.websecurityscanner.v1beta.WebSecurityScannerClient;

public class SyncGetFindingFindingname {

  public static void main(String[] args) throws Exception {
    syncGetFindingFindingname();
  }

  public static void syncGetFindingFindingname() throws Exception {
    // This snippet has been automatically generated and should be regarded as a code template only.
    // It will require modifications to work:
    // - It may require correct/in-range values for request initialization.
    // - It may require specifying regional endpoints when creating the service client as shown in
    // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
    try (WebSecurityScannerClient webSecurityScannerClient = WebSecurityScannerClient.create()) {
      FindingName name = FindingName.of("[PROJECT]", "[SCAN_CONFIG]", "[SCAN_RUN]", "[FINDING]");
      Finding response = webSecurityScannerClient.getFinding(name);
    }
  }
}
// [END websecurityscanner_v1beta_generated_WebSecurityScanner_GetFinding_Findingname_sync]


text:
from django.conf.urls import url

from api.nodes import views
from website import settings

urlpatterns = [
    # Examples:
    # url(r'^$', 'api.views.home', name='home'),
    # url(r'^blog/', include('blog.urls')),
    url(r'^$', views.NodeList.as_view(), name=views.NodeList.view_name),
    url(r'^(?P<node_id>\w+)/$', views.NodeDetail.as_view(), name=views.NodeDetail.view_name),
    url(r'^(?P<node_id>\w+)/contributors/$', views.NodeContributorsList.as_view(), name=views.NodeContributorsList.view_name),
    url(r'^(?P<node_id>\w+)/contributors/(?P<user_id>\w+)/$', views.NodeContributorDetail.as_view(), name=views.NodeContributorDetail.view_name),
    url(r'^(?P<node_id>\w+)/children/$', views.NodeChildrenList.as_view(), name=views.NodeChildrenList.view_name),
    url(r'^(?P<node_id>\w+)/forks/$', views.NodeForksList.as_view(), name=views.NodeForksList.view_name),
    url(r'^(?P<node_id>\w+)/files/$', views.NodeProvidersList.as_view(), name=views.NodeProvidersList.view_name),
    url(r'^(?P<node_id>\w+)/files/providers/(?P<provider>\w+)/?$', views.NodeProviderDetail.as_view(), name=views.NodeProviderDetail.view_name),
    url(r'^(?P<node_id>\w+)/files/(?P<provider>\w+)(?P<path>/(?:.*/)?)$', views.NodeFilesList.as_view(), name=views.NodeFilesList.view_name),
    url(r'^(?P<node_id>\w+)/files/(?P<provider>\w+)(?P<path>/.+[^/])$', views.NodeFileDetail.as_view(), name=views.NodeFileDetail.view_name),
    url(r'^(?P<node_id>\w+)/comments/$', views.NodeCommentsList.as_view(), name=views.NodeCommentsList.view_name),
    url(r'^(?P<node_id>\w+)/logs/$', views.NodeLogList.as_view(), name=views.NodeLogList.view_name),
    url(r'^(?P<node_id>\w+)/node_links/$', views.NodeLinksList.as_view(), name=views.NodeLinksList.view_name),
    url(r'^(?P<node_id>\w+)/node_links/(?P<node_link_id>\w+)/', views.NodeLinksDetail.as_view(), name=views.NodeLinksDetail.view_name),
    url(r'^(?P<node_id>\w+)/wikis/$', views.NodeWikiList.as_view(), name=views.NodeWikiList.view_name),
    url(r'^(?P<node_id>\w+)/institutions/$', views.NodeInstitutionsList.as_view(), name=views.NodeInstitutionsList.view_name),
    url(r'^(?P<node_id>\w+)/relationships/institutions/$', views.NodeInstitutionsRelationship.as_view(), name=views.NodeInstitutionsRelationship.view_name),
]

# Routes only active in local/staging environments
if settings.DEV_MODE:
    urlpatterns.extend([
        url(r'^(?P<node_id>\w+)/registrations/$', views.NodeRegistrationsList.as_view(), name=views.NodeRegistrationsList.view_name),

        url(r'^(?P<node_id>\w+)/draft_registrations/$', views.NodeDraftRegistrationsList.as_view(), name=views.NodeDraftRegistrationsList.view_name),
        url(r'^(?P<node_id>\w+)/draft_registrations/(?P<draft_id>\w+)/$', views.NodeDraftRegistrationDetail.as_view(), name=views.NodeDraftRegistrationDetail.view_name),

        # Custom citations
        url(r'^(?P<node_id>\w+)/citations/$', views.NodeAlternativeCitationsList.as_view(), name=views.NodeAlternativeCitationsList.view_name),
        url(r'^(?P<node_id>\w+)/citations/(?P<citation_id>\w+)/$', views.NodeAlternativeCitationDetail.as_view(), name=views.NodeAlternativeCitationDetail.view_name),
    ])


text:
namespace IdentityBase.Actions.Account
{
    public class ChangeEmailConfirmViewModel
    {
        public string Email { get; set; }

        public string Key { get; set; }

        public string ReturnUrl { get; set; }
    }
}


text:
module Match
  class Runner
    attr_accessor :changes_to_commit
    attr_accessor :spaceship

    def run(params)
      FastlaneCore::PrintTable.print_values(config: params,
                                         hide_keys: [:workspace],
                                             title: "Summary for match #{Fastlane::VERSION}")

      UI.error("Enterprise profiles are currently not officially supported in _match_, you might run into issues") if Match.enterprise?

      params[:workspace] = GitHelper.clone(params[:git_url], params[:shallow_clone], skip_docs: params[:skip_docs], branch: params[:git_branch])
      self.spaceship = SpaceshipEnsure.new(params[:username]) unless params[:readonly]

      if params[:app_identifier].kind_of?(Array)
        app_identifiers = params[:app_identifier]
      else
        app_identifiers = params[:app_identifier].to_s.split(/\s*,\s*/).uniq
      end

      # Verify the App ID (as we don't want 'match' to fail at a later point)
      if spaceship
        app_identifiers.each do |app_identifier|
          spaceship.bundle_identifier_exists(username: params[:username], app_identifier: app_identifier)
        end
      end

      # Certificate
      cert_id = fetch_certificate(params: params)
      spaceship.certificate_exists(username: params[:username], certificate_id: cert_id) if spaceship

      # Provisioning Profiles
      app_identifiers.each do |app_identifier|
        loop do
          break if fetch_provisioning_profile(params: params,
                                      certificate_id: cert_id,
                                      app_identifier: app_identifier)
        end
      end

      # Done
      if self.changes_to_commit and !params[:readonly]
        message = GitHelper.generate_commit_message(params)
        GitHelper.commit_changes(params[:workspace], message, params[:git_url], params[:git_branch])
      end

      # Print a summary table for each app_identifier
      app_identifiers.each do |app_identifier|
        TablePrinter.print_summary(app_identifier: app_identifier, type: params[:type])
      end

      UI.success "All required keys, certificates and provisioning profiles are installed 🙌".green
    rescue Spaceship::Client::UnexpectedResponse, Spaceship::Client::InvalidUserCredentialsError, Spaceship::Client::NoUserCredentialsError => ex
      UI.error("An error occured while verifying your certificates and profiles with the Apple Developer Portal.")
      UI.error("If you already have your certificates stored in git, you can run `match` in readonly mode")
      UI.error("to just install the certificates and profiles without accessing the Dev Portal.")
      UI.error("To do so, just pass `readonly: true` to your match call.")
      raise ex
    ensure
      GitHelper.clear_changes
    end

    def fetch_certificate(params: nil)
      cert_type = Match.cert_type_sym(params[:type])

      certs = Dir[File.join(params[:workspace], "certs", cert_type.to_s, "*.cer")]
      keys = Dir[File.join(params[:workspace], "certs", cert_type.to_s, "*.p12")]

      if certs.count == 0 or keys.count == 0
        UI.important "Couldn't find a valid code signing identity in the git repo for #{cert_type}... creating one for you now"
        UI.crash!("No code signing identity found and can not create a new one because you enabled `readonly`") if params[:readonly]
        cert_path = Generator.generate_certificate(params, cert_type)
        self.changes_to_commit = true
      else
        cert_path = certs.last
        UI.message "Installing certificate..."

        if FastlaneCore::CertChecker.installed?(cert_path)
          UI.verbose "Certificate '#{File.basename(cert_path)}' is already installed on this machine"
        else
          Utils.import(cert_path, params[:keychain_name], password: params[:keychain_password])
        end

        # Import the private key
        # there seems to be no good way to check if it's already installed - so just install it
        Utils.import(keys.last, params[:keychain_name], password: params[:keychain_password])

        # Get and print info of certificate
        info = Utils.get_cert_info(cert_path)
        TablePrinter.print_certificate_info(cert_info: info)
      end

      return File.basename(cert_path).gsub(".cer", "") # Certificate ID
    end

    # @return [String] The UUID of the provisioning profile so we can verify it with the Apple Developer Portal
    def fetch_provisioning_profile(params: nil, certificate_id: nil, app_identifier: nil)
      prov_type = Match.profile_type_sym(params[:type])

      profile_name = [Match::Generator.profile_type_name(prov_type), app_identifier].join("_").gsub("*", '\*') # this is important, as it shouldn't be a wildcard
      base_dir = File.join(params[:workspace], "profiles", prov_type.to_s)
      profiles = Dir[File.join(base_dir, "#{profile_name}.mobileprovision")]

      # Install the provisioning profiles
      profile = profiles.last

      if params[:force_for_new_devices] && !params[:readonly]
        params[:force] = device_count_different?(profile: profile) unless params[:force]
      end

      if profile.nil? or params[:force]
        if params[:readonly]
          all_profiles = Dir.entries(base_dir).reject { |f| f.start_with? "." }
          UI.error "No matching provisioning profiles found for '#{profile_name}'"
          UI.error "A new one cannot be created because you enabled `readonly`"
          UI.error "Provisioning profiles in your repo for type `#{prov_type}`:"
          all_profiles.each { |p| UI.error "- '#{p}'" }
          UI.error "If you are certain that a profile should exist, double-check the recent changes to your match repository"
          UI.user_error! "No matching provisioning profiles found and can not create a new one because you enabled `readonly`. Check the output above for more information."
        end
        profile = Generator.generate_provisioning_profile(params: params,
                                                       prov_type: prov_type,
                                                  certificate_id: certificate_id,
                                                  app_identifier: app_identifier)
        self.changes_to_commit = true
      end

      FastlaneCore::ProvisioningProfile.install(profile)

      parsed = FastlaneCore::ProvisioningProfile.parse(profile)
      uuid = parsed["UUID"]

      if spaceship && !spaceship.profile_exists(username: params[:username], uuid: uuid)
        # This profile is invalid, let's remove the local file and generate a new one
        File.delete(profile)
        self.changes_to_commit = true
        return nil
      end

      Utils.fill_environment(Utils.environment_variable_name(app_identifier: app_identifier,
                                                                       type: prov_type),
                             uuid)

      # TeamIdentifier is returned as an array, but we're not sure why there could be more than one
      Utils.fill_environment(Utils.environment_variable_name_team_id(app_identifier: app_identifier,
                                                                               type: prov_type),
                             parsed["TeamIdentifier"].first)

      Utils.fill_environment(Utils.environment_variable_name_profile_name(app_identifier: app_identifier,
                                                                                type: prov_type),
                             parsed["Name"])

      return uuid
    end

    def device_count_different?(profile: nil)
      if profile
        parsed = FastlaneCore::ProvisioningProfile.parse(profile)
        uuid = parsed["UUID"]
        portal_profile = Spaceship.provisioning_profile.all.detect { |i| i.uuid == uuid }

        if portal_profile
          profile_device_count = portal_profile.devices.count
          portal_device_count = Spaceship.device.all.count
          return portal_device_count != profile_device_count
        end
      end
      return false
    end
  end
end