text:
require File.join(File.dirname(File.dirname(File.dirname(File.expand_path(__FILE__)))), 'spec_helper')
require File.join(File.dirname(File.dirname(File.dirname(File.dirname(File.expand_path(__FILE__))))), 'lib', 'reek', 'source', 'tree_dresser')

include Reek::Source

describe TreeDresser do
  before(:each) do
    @dresser = TreeDresser.new
  end
  it 'maps :if to IfNode' do
    @dresser.extensions_for(:if).should == 'IfNode'
  end
  it 'maps :call to CallNode' do
    @dresser.extensions_for(:call).should == 'CallNode'
  end
end

describe SexpNode do
  context 'format' do
    it 'formats self' do
      @node = s(:self)
      @node.extend(SexpNode)
      @node.format_ruby.should == 'self'
    end
  end

  context 'hash' do
    it 'hashes equal for equal sexps' do
      node1 = ast(:defn, s(:const2, :Fred, :jim), s(:call, :+, s(:lit, 4), :fred))
      node2 = ast(:defn, s(:const2, :Fred, :jim), s(:call, :+, s(:lit, 4), :fred))
      node1.hash.should == node2.hash
    end
    it 'hashes diferent for diferent sexps' do
      node1 = ast(:defn, s(:const2, :Fred, :jim), s(:call, :+, s(:lit, 4), :fred))
      node2 = ast(:defn, s(:const2, :Fred, :jim), s(:call, :+, s(:lit, 3), :fred))
      node1.hash.should_not == node2.hash
    end
  end
end

describe SexpExtensions::DefnNode do
  context 'with no parameters' do
    before :each do
      @node = s(:defn, :hello, s(:args))
      @node.extend(SexpExtensions::DefnNode)
    end
    it 'has no parameters' do
      @node.parameters.should == s(:args)
    end
    it 'has no parameter names' do
      @node.parameter_names.should == s()
    end
    it 'includes outer scope in its full name' do
      @node.full_name('Fred').should == 'Fred#hello'
    end
    it 'includes no marker in its full name with empty outer scope' do
      @node.full_name('').should == 'hello'
    end
  end

  context 'with 1 parameter' do
    before :each do
      @node = s(:defn, :hello, s(:args, :param))
      @node.extend(SexpExtensions::DefnNode)
    end
    it 'has 1 parameter' do
      @node.parameters.should == s(:args, :param)
    end
    it 'has 1 parameter name' do
      @node.parameter_names.should == s(:param)
    end
    it 'includes outer scope in its full name' do
      @node.full_name('Fred').should == 'Fred#hello'
    end
    it 'includes no marker in its full name with empty outer scope' do
      @node.full_name('').should == 'hello'
    end
  end

  context 'with a block' do
    before :each do
      @node = s(:defn, :hello, s(:args, :param, :"&blk"))
      @node.extend(SexpExtensions::DefnNode)
    end
    it 'has 1 parameter' do
      @node.parameters.should == s(:args, :param, :"&blk")
    end
    it 'has 1 parameter name' do
      @node.parameter_names.should == s(:param, :"&blk")
    end
    it 'includes outer scope in its full name' do
      @node.full_name('Fred').should == 'Fred#hello'
    end
    it 'includes no marker in its full name with empty outer scope' do
      @node.full_name('').should == 'hello'
    end
  end

  context 'with 1 defaulted parameter' do
    before :each do
      @node = s(:defn, :hello, s(:args, :param, s(:block, s(:lasgn, :param, s(:array)))))
      @node.extend(SexpExtensions::DefnNode)
    end
    it 'has 1 parameter' do
      @node.parameters.should == s(:args, :param)
    end
    it 'has 1 parameter name' do
      @node.parameter_names.should == s(:param)
    end
    it 'includes outer scope in its full name' do
      @node.full_name('Fred').should == 'Fred#hello'
    end
    it 'includes no marker in its full name with empty outer scope' do
      @node.full_name('').should == 'hello'
    end
  end
end

describe SexpExtensions::DefsNode do
  context 'with no parameters' do
    before :each do
      @node = s(:defs, :obj, :hello, s(:args))
      @node.extend(SexpExtensions::DefsNode)
    end
    it 'has no parameters' do
      @node.parameters.should == s(:args)
    end
    it 'has no parameter names' do
      @node.parameter_names.should == s()
    end
    it 'includes outer scope in its full name' do
      @node.full_name('Fred').should == 'Fred#obj.hello'
    end
    it 'includes no marker in its full name with empty outer scope' do
      @node.full_name('').should == 'obj.hello'
    end
  end

  context 'with 1 parameter' do
    before :each do
      @node = s(:defs, :obj, :hello, s(:args, :param))
      @node.extend(SexpExtensions::DefsNode)
    end
    it 'has 1 parameter' do
      @node.parameters.should == s(:args, :param)
    end
    it 'has 1 parameter name' do
      @node.parameter_names.should == s(:param)
    end
    it 'includes outer scope in its full name' do
      @node.full_name('Fred').should == 'Fred#obj.hello'
    end
    it 'includes no marker in its full name with empty outer scope' do
      @node.full_name('').should == 'obj.hello'
    end
  end

  context 'with a block' do
    before :each do
      @node = s(:defs, :obj, :hello, s(:args, :param, :"&blk"))
      @node.extend(SexpExtensions::DefsNode)
    end
    it 'has 1 parameter' do
      @node.parameters.should == s(:args, :param, :"&blk")
    end
    it 'has 1 parameter name' do
      @node.parameter_names.should == s(:param, :"&blk")
    end
    it 'includes outer scope in its full name' do
      @node.full_name('Fred').should == 'Fred#obj.hello'
    end
    it 'includes no marker in its full name with empty outer scope' do
      @node.full_name('').should == 'obj.hello'
    end
  end

  context 'with 1 defaulted parameter' do
    before :each do
      @node = s(:defs, :obj, :hello, s(:args, :param, s(:block, s(:lasgn, :param, s(:array)))))
      @node.extend(SexpExtensions::DefsNode)
    end
    it 'has 1 parameter' do
      @node.parameters.should == s(:args, :param)
    end
    it 'has 1 parameter name' do
      @node.parameter_names.should == s(:param)
    end
    it 'includes outer scope in its full name' do
      @node.full_name('Fred').should == 'Fred#obj.hello'
    end
    it 'includes no marker in its full name with empty outer scope' do
      @node.full_name('').should == 'obj.hello'
    end
  end
end

describe SexpExtensions::IterNode do
  context 'with no parameters' do
    before :each do
      @node = s(:iter, s(), nil, s())
      @node.extend(SexpExtensions::IterNode)
    end
    it 'has no parameters' do
      @node.parameters.should == []
    end
    it 'has no parameter names' do
      @node.parameter_names.should == []
    end
  end

  context 'with 1 parameter' do
    before :each do
      @node = s(:iter, s(), s(:lasgn, :param), s())
      @node.extend(SexpExtensions::IterNode)
    end
    it 'has 1 parameter' do
      @node.parameters.should == s(:lasgn, :param)
    end
    it 'has 1 parameter name' do
      @node.parameter_names.should == s(:param)
    end
  end

  context 'with 2 parameters' do
    before :each do
      @node = s(:iter, s(), s(:masgn, s(:array, s(:lasgn, :x), s(:lasgn, :y))), s())
      @node.extend(SexpExtensions::IterNode)
    end
    it 'has 1 parameter' do
      @node.parameters.should == s(:masgn, s(:array, s(:lasgn, :x), s(:lasgn, :y)))
    end
    it 'has 1 parameter name' do
      @node.parameter_names.should == [:x, :y]
    end
  end
end

describe SexpExtensions::ModuleNode do
  context 'with a simple name' do
    subject do
      mod = ast(:module, :Fred, nil)
      mod
    end
    its(:name) { should == :Fred }
    its(:simple_name) { should == :Fred }
    its(:text_name) { should == 'Fred' }
    it 'has a simple full_name' do
      subject.full_name('').should == 'Fred'
    end
    it 'has a fq full_name' do
      subject.full_name('Blimey::O::Reilly').should == 'Blimey::O::Reilly::Fred'
    end
  end

  context 'with a scoped name' do
    subject do
      mod = ast(:module, s(:colon2, s(:const, :Foo), :Bar), nil)
      mod
    end
    its(:name) { should == s(:colon2, s(:const, :Foo), :Bar) }
    its(:simple_name) { should == :Bar }
    its(:text_name) { should == 'Foo::Bar' }
    it 'has a simple full_name' do
      subject.full_name('').should == 'Foo::Bar'
    end
    it 'has a fq full_name' do
      subject.full_name('Blimey::O::Reilly').should == 'Blimey::O::Reilly::Foo::Bar'
    end
  end
end


text:
layout: page
title: 'Connect with Bernie'
permalink: /projects/connect-with-bernie/
---

<img src="/img/connectwithbernie.png" alt="Connect with Bernie" />

[Connect with Bernie](http://connect.berniesanders.com/) allows admins of Bernie groups on Facebook or Twitter, as well as general supports of Bernie, to log in with their Facebook or Twitter accounts and receive special updates directly from the campaign to help amplify Bernie's message on social media. The campaign posts timely updates about hashtags, new videos, and more, especially during debate nights and other campaign events.

redpajama_set_name: RedPajamaGithub


text:
{-# LANGUAGE DataKinds                 #-}
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE FlexibleContexts          #-}
{-# LANGUAGE OverloadedStrings         #-}
{-# LANGUAGE RecordWildCards           #-}
{-# LANGUAGE TypeOperators             #-}

module Clicklac.Servant.Response
  (
  -- * 400-499 HTTP responses
    s400
  , s401
  , s403
  , s404
  , s409

  -- * 500-514 HTTP responses
  , s500
  , s503

  -- * Utils
  , encodeErr
  , encodeErr'
  , contentType

  -- * Failure
  , RequestFailure(..)

  -- * Headers
  , Location(..)
  ) where

import Control.Monad.Error.Class
import Data.ByteString (ByteString)
import qualified Data.ByteString.Lazy as BL
import Data.Text (Text)

import Data.Aeson (encode, ToJSON(..), (.=), object)
import Data.ByteString.Conversion.To (ToByteString(..))
import Network.HTTP.Types.Header (hContentType, HeaderName)
import Servant.Server.Internal.ServantErr

import Clicklac.OpFailure (FailureMsg(..))

data RequestFailure
  = UrlNotFound
  | MethodNotAllowed
  | InvalidRequestBody
  | UnsupportedMedia
  | BadRequest
  | InternalError
  | ResourceNotFound
  deriving (Eq, Show)

instance FailureMsg RequestFailure where
  failMsg UrlNotFound           = "Url Not Found"
  failMsg MethodNotAllowed      = "Method Not Allowed"
  failMsg InvalidRequestBody    = "Invalid Request Body"
  failMsg UnsupportedMedia      = "Unsupported Media Type"
  failMsg BadRequest            = "Bad Request"
  failMsg InternalError         = "Internal Error"
  failMsg ResourceNotFound      = "Resource Not Found"

data Err = Err
  { msg    :: !Text
  , reason :: !Text
  } deriving Show

instance ToJSON Err where
  toJSON Err{..} =
    object ["message" .= msg, "reason" .= reason]

data ErrJSON = forall j. ToJSON j =>
  ErrJSON {_code :: !Int, _message :: !Text, _errors :: ![j]}

instance ToJSON ErrJSON where
  toJSON ErrJSON{..} =
    object ["code" .= _code, "message" .= _message, "errors" .= _errors]

-- similiar to https://goo.gl/qSTbGa
newtype ErrJSONRoot = ErrJSONRoot ErrJSON

instance ToJSON ErrJSONRoot where
  toJSON(ErrJSONRoot errJSON) = object ["error" .= errJSON]

encodeErr' :: (FailureMsg fm) => Int -> fm -> BL.ByteString
encodeErr' c fm = encode $
  ErrJSONRoot $ ErrJSON c (failMsg fm) [Err (failMsg fm) (failReason fm)]

encodeErr :: Int -> Text -> Text -> BL.ByteString
encodeErr c m r = encode $ ErrJSONRoot $ ErrJSON c m [Err m r]

s400 :: (FailureMsg fm, MonadError ServantErr m) => Text -> [fm] -> m a
s400 = err 400

s401 :: (FailureMsg fm, MonadError ServantErr m) => Text -> [fm] -> m a
s401 = err 401

s403 :: (FailureMsg fm, MonadError ServantErr m) => Text -> [fm] -> m a
s403 = err 403

s404 :: (FailureMsg fm, MonadError ServantErr m) => Text -> [fm] -> m a
s404 = err 404

s409 :: (FailureMsg fm, MonadError ServantErr m) => Text -> [fm] -> m a
s409 = err 409

s500 :: (FailureMsg fm, MonadError ServantErr m) => Text -> [fm] -> m a
s500 = err 500

s503 :: (FailureMsg fm, MonadError ServantErr m) => Text -> [fm] -> m a
s503 = err 503

err :: (FailureMsg fm, MonadError ServantErr m) => Int -> Text -> [fm] -> m a
err errCode msg errs = throwError $
  case errCode of
    400 -> resp err400
    401 -> resp err401
    403 -> resp err403
    404 -> resp err404
    409 -> resp err409
    500 -> resp err500
    503 -> resp err503
    _   | errCode <= 499 -> resp err400
        | otherwise -> resp err500
 where
   resp fn =
     fn { errBody = encode (ErrJSONRoot $ ErrJSON errCode msg errs')
        , errHeaders = [contentType]
        }
   errs' = foldr (\e a -> Err (failMsg e) (failReason e) : a) [] errs

contentType :: (HeaderName, ByteString)
contentType = (hContentType, "application/json")

newtype Location = Location ByteString

instance ToByteString Location where
  builder (Location x) = builder x


text:
using namespace llvm;
namespace {

struct UstarHeader {
  char Name[100];
  char Mode[8];
  char Uid[8];
  char Gid[8];
  char Size[12];
  char Mtime[12];
  char Checksum[8];
  char TypeFlag;
  char Linkname[100];
  char Magic[6];
  char Version[2];
  char Uname[32];
  char Gname[32];
  char DevMajor[8];
  char DevMinor[8];
  char Prefix[155];
  char Pad[12];
};

class TarWriterTest : public ::testing::Test {};

static UstarHeader create(StringRef Base, StringRef Filename) {
  // Create a temporary file.
  SmallString<128> Path;
  std::error_code EC =
      sys::fs::createTemporaryFile("TarWriterTest", "tar", Path);
  EXPECT_FALSE((bool)EC);

  // Create a tar file.
  Expected<std::unique_ptr<TarWriter>> TarOrErr = TarWriter::create(Path, Base);
  EXPECT_TRUE((bool)TarOrErr);
  std::unique_ptr<TarWriter> Tar = std::move(*TarOrErr);
  Tar->append(Filename, "contents");
  Tar.reset();

  // Read the tar file.
  ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr = MemoryBuffer::getFile(Path);
  EXPECT_TRUE((bool)MBOrErr);
  std::unique_ptr<MemoryBuffer> MB = std::move(*MBOrErr);
  sys::fs::remove(Path);
  return *reinterpret_cast<const UstarHeader *>(MB->getBufferStart());
}

TEST_F(TarWriterTest, Basics) {
  UstarHeader Hdr = create("base", "file");
  EXPECT_EQ("ustar", StringRef(Hdr.Magic));
  EXPECT_EQ("00", StringRef(Hdr.Version, 2));
  EXPECT_EQ("base/file", StringRef(Hdr.Name));
  EXPECT_EQ("00000000010", StringRef(Hdr.Size));
}

TEST_F(TarWriterTest, LongFilename) {
  UstarHeader Hdr1 = create(
      "012345678", std::string(99, 'x') + "/" + std::string(44, 'x') + "/foo");
  EXPECT_EQ("foo", StringRef(Hdr1.Name));
  EXPECT_EQ("012345678/" + std::string(99, 'x') + "/" + std::string(44, 'x'),
            StringRef(Hdr1.Prefix));

  UstarHeader Hdr2 = create(
      "012345678", std::string(99, 'x') + "/" + std::string(45, 'x') + "/foo");
  EXPECT_EQ("foo", StringRef(Hdr2.Name));
  EXPECT_EQ("012345678/" + std::string(99, 'x') + "/" + std::string(45, 'x'),
            StringRef(Hdr2.Prefix));

  UstarHeader Hdr3 = create(
      "012345678", std::string(99, 'x') + "/" + std::string(46, 'x') + "/foo");
  EXPECT_EQ(std::string(46, 'x') + "/foo", StringRef(Hdr3.Name));
  EXPECT_EQ("012345678/" + std::string(99, 'x'), StringRef(Hdr3.Prefix));
}
}


text:
#if !GOOGLE_CUDA
#error This file must only be included when building with Cuda support
#endif

#ifndef TENSORFLOW_CORE_COMMON_RUNTIME_GPU_GPU_DEVICE_H_
#define TENSORFLOW_CORE_COMMON_RUNTIME_GPU_GPU_DEVICE_H_

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

#include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor"
#include "tensorflow/core/common_runtime/device_factory.h"
#include "tensorflow/core/common_runtime/gpu/gpu_event_mgr.h"
#include "tensorflow/core/common_runtime/gpu/gpu_id.h"
#include "tensorflow/core/common_runtime/gpu/gpu_id_manager.h"
#include "tensorflow/core/common_runtime/gpu/gpu_id_utils.h"
#include "tensorflow/core/common_runtime/gpu_device_context.h"
#include "tensorflow/core/common_runtime/local_device.h"
#include "tensorflow/core/common_runtime/scoped_allocator_mgr.h"
#include "tensorflow/core/framework/allocator.h"
#include "tensorflow/core/framework/device_base.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/lib/gtl/inlined_vector.h"
#include "tensorflow/core/platform/mutex.h"
#include "tensorflow/core/platform/stream_executor.h"
#include "tensorflow/core/platform/types.h"
#include "tensorflow/core/public/session_options.h"

namespace tensorflow {

class BaseGPUDevice : public LocalDevice {
 public:
  BaseGPUDevice(const SessionOptions& options, const string& name,
                Bytes memory_limit, const DeviceLocality& locality,
                TfGpuId tf_gpu_id, const string& physical_device_desc,
                Allocator* gpu_allocator, Allocator* cpu_allocator,
                bool sync_every_op, int32 max_streams);

  ~BaseGPUDevice() override;

  // Initialize the device and return the status of initialization.
  Status Init(const SessionOptions& options);

  // GPU devices require the Op Compute method to save a reference to
  // any temporary tensors that are allocated until the Op execution
  // completes.
  bool RequiresRecordingAccessedTensors() const override;

  void ConsumeListOfAccessedTensors(
      DeviceContext* device_context,
      const TensorReferenceVector& tensor_refs) override;

  Status FillContextMap(const Graph* graph,
                        DeviceContextMap* device_context_map) override;

  void Compute(OpKernel* op_kernel, OpKernelContext* context) override;

  Status Sync() override;

  void ComputeAsync(AsyncOpKernel* op_kernel, OpKernelContext* context,
                    AsyncOpKernel::DoneCallback done) override;

  Status MakeTensorFromProto(const TensorProto& tensor_proto,
                             const AllocatorAttributes alloc_attrs,
                             Tensor* tensor) override;

  // The caller owns the returned device.
  PerOpGpuDevice* MakeGpuDevice() override;

  Status ReinitializeGpuDevice(OpKernelContext* context, PerOpGpuDevice* device,
                               DeviceContext* dc,
                               Allocator* allocator) override;

  // Returns the platform GPU id of this device within the native driver system;
  // e.g., for CUDA this is the ordinal of the GPU within the system.
  int gpu_id() const {
    PlatformGpuId platform_gpu_id;
    TF_CHECK_OK(GpuIdManager::TfToPlatformGpuId(tf_gpu_id_, &platform_gpu_id));
    return platform_gpu_id.value();
  }

  // The executor that provides control for the device; e.g., for CUDA this
  // corresponds to the cuda context.
  se::StreamExecutor* executor() const { return executor_; }

  Allocator* GetScopedAllocator(AllocatorAttributes attr,
                                int64 step_id) override;

  ScopedAllocatorMgr* GetScopedAllocatorMgr() const override {
    return scoped_allocator_mgr_.get();
  }

 protected:
  Allocator* gpu_allocator_;  // not owned
  Allocator* cpu_allocator_;  // not owned

  se::StreamExecutor* executor_;  // not owned
  std::unique_ptr<ScopedAllocatorMgr> scoped_allocator_mgr_;

 private:
  struct StreamGroup {
    se::Stream* compute = nullptr;
    se::Stream* host_to_device = nullptr;
    se::Stream* device_to_host = nullptr;
    gtl::InlinedVector<se::Stream*, 4> device_to_device;
  };
  class StreamGroupFactory;

  gtl::InlinedVector<StreamGroup*, 4> streams_;
  mutex scratch_init_mutex_;
  gtl::InlinedVector<char*, 4> scratch_;
  std::vector<GPUDeviceContext*> device_contexts_;
  GpuDeviceInfo* gpu_device_info_ = nullptr;
  mutex trace_mu_;
  TfGpuId tf_gpu_id_;
  const bool sync_every_op_ = false;
  const int32 max_streams_;
  std::unique_ptr<EventMgr> em_;
  std::unique_ptr<thread::ThreadPool> thread_pool_;

  // Initialize scractch buffers used by Eigen.
  Status InitScratchBuffers();

  void ReinitializeDevice(OpKernelContext* context, PerOpGpuDevice* device,
                          int stream_id, Allocator* allocator);

  void ComputeHelper(OpKernel* op_kernel, OpKernelContext* context);

  string ComputeOpKernelDebugString(const OpKernel& op_kernel,
                                    const int& stream_id);

  // This method returns an initialization status, in addition to
  // calling the "done" StatusCallback, if there is a failure to
  // allocate memory or if the tensor "from" is not DMA-copyable.
  // If there is no error prior to enqueueing the copy, an OK status
  // is returned.
  Status MaybeCopyTensorToGPU(const AllocatorAttributes& alloc_attrs,
                              const Tensor& from, Tensor* to,
                              StatusCallback done);
};

class BaseGPUDeviceFactory : public DeviceFactory {
 public:
  Status CreateDevices(const SessionOptions& options, const string& name_prefix,
                       std::vector<Device*>* devices) override;

  struct InterconnectMap {
    // Name of interconnect technology, if known.
    string name;
    // If possible, strength should approximate Gb/sec bandwidth rate.
    // Where architecture-specific subclassing is not done that won't
    // always be possible.  The minimum expectation is that
    // faster links should have a higher value than slower links.
    int32 strength;
    static const int kSameDeviceStrength;
    static const int kStreamExecutorStrength;
    std::set<std::pair<PlatformGpuId, PlatformGpuId>> directed_links;
  };

 protected:
  // Populates *maps with interconnect maps for all local direct access
  // pathways between GPUs.
  virtual Status GetInterconnectMaps(
      const std::vector<PlatformGpuId>& visible_gpu_order,
      se::Platform* gpu_manager, std::vector<InterconnectMap>* maps);

  struct TfGpuIdHash {
    std::size_t operator()(const TfGpuId& id) const noexcept {
      return std::hash<int>{}(id.value());
    }
  };
  typedef std::unordered_map<TfGpuId, DeviceLocality, TfGpuIdHash> LocalityMap;
  // Populates *localities with the DeviceLocality descriptor for
  // every TfGpuId.
  virtual Status GetDeviceLocalities(
      int num_tf_gpus, const std::vector<InterconnectMap>& interconnects,
      LocalityMap* localities);

 private:
  // Creates a BaseGPUDevice associated with 'tf_gpu_id', allocates (strictly)
  // 'memory_limit' bytes of GPU memory to it, and adds it to the 'devices'
  // vector.
  Status CreateGPUDevice(const SessionOptions& options,
                         const string& name_prefix, TfGpuId tf_gpu_id,
                         int64 memory_limit, const DeviceLocality& dev_locality,
                         std::vector<Device*>* devices);

  virtual BaseGPUDevice* CreateGPUDevice(const SessionOptions& options,
                                         const string& name, Bytes memory_limit,
                                         const DeviceLocality& dev_locality,
                                         TfGpuId tf_gpu_id,
                                         const string& physical_device_desc,
                                         Allocator* gpu_allocator,
                                         Allocator* cpu_allocator) = 0;

  // Returns into 'ids' the list of valid platform GPU ids, in the order that
  // they should map to TF GPU ids "/device:GPU:0", "/device:GPU:1", etc,
  // based upon 'visible_gpu_order' which was generated by parsing
  // GPUOptions::visible_device_list which is a comma-separated list of CUDA GPU
  // ids.
  Status GetValidDeviceIds(const std::vector<PlatformGpuId>& visible_gpu_order,
                           std::vector<PlatformGpuId>* ids);

  // visible_gpu_initialized_[platform_gpu_id] is true if visible GPU
  // platform_gpu_id has been initialized by the process.
  std::unordered_map<int, bool> visible_gpu_initialized_;
};

}  // namespace tensorflow

#endif  // TENSORFLOW_CORE_COMMON_RUNTIME_GPU_GPU_DEVICE_H_


text:
ACCEPTED

#### According to
Interim Register of Marine and Nonmarine Genera

#### Published in
Fauna Flora Golfo di Napoli, 37, 83.

#### Original name
null

### Remarks
null


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using RestSharp.Deserializers;
using Newtonsoft.Json;

namespace inBloom_c_sharp_hello_world.Recipes
{
    public class inBloomDeserializer : IDeserializer
    {

        public string DateFormat { get; set; }

        public string Namespace { get; set; }

        public string RootElement  { get; set; }

        public T Deserialize<T>(RestSharp.IRestResponse response)
        {
            return JsonConvert.DeserializeObject<T>(response.Content);
        }
    }
}


text:
using hw.UnitTest;
using Reni.FeatureTest.Helper;
using Reni.FeatureTest.Structure;

namespace Reni.FeatureTest.BlogExamples
{
    [UnitTest]
    [AccessSimple1]
    [TargetSet(@"x: (1, 2); (x; 2) dump_print", "((1, 2), 2)")]
    public sealed class NestedCompound : CompilerTest {}

    [UnitTest]
    [AccessSimple1]
    [NestedCompound]
    [TargetSet(@"x: (4, 8, 15, 16, 23, 42); ('Die Lottozahlen lauten: '; x; 'Wir gratulieren den Gewinnern.') dump_print",
        "(Die Lottozahlen lauten: , (4, 8, 15, 16, 23, 42), Wir gratulieren den Gewinnern.)")]
    public sealed class WikiExamples : CompilerTest {}
}


text:
/**
 * The RDF Model API
 *

 * The core RDF model interfaces are organized in the following hierarchy:
 *

 *
 *

 *        Value          Statement       Model
 *       /     \
 *      /       \
 *   Resource  Literal
 *     /  \
 *    /    \
 *  IRI   BNode
 *

 *

 * An individual RDF triple or statement is represented by the {@link org.eclipse.rdf4j.model.Statement Statement}
 * interface. Collections of RDF statements are represented by the {@link org.eclipse.rdf4j.model.Model Model}
 * interface.
 *

 *

 * Creation of new Model elements ({@link org.eclipse.rdf4j.model.IRI IRI}, {@link org.eclipse.rdf4j.model.Literal
 * Literal}, {@link org.eclipse.rdf4j.model.BNode BNode}, {@link org.eclipse.rdf4j.model.Statement Statement}) is done
 * by means of a {@link org.eclipse.rdf4j.model.ValueFactory ValueFactory}.
 *

 *
 * @see RDF4J model documentation
 */
package org.eclipse.rdf4j.model;


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">
    <link rel="shortcut icon" href="assets/ico/favicon.ico">

    <title>CallHero</title>

    <link href="assets/css/bootstrap.css" rel="stylesheet">

    <link href="assets/css/style.css" rel="stylesheet">
    <link href="assets/css/font-awesome.min.css" rel="stylesheet">
    <link href="assets/js/fancybox/jquery.fancybox.css" rel="stylesheet" />

Team Zeros

      Home
      About
      Services
      Contact

  <form action="/users/2705621411/rules" method="post">

            Name

            <input type="text" class="form-control" name="name"/>

Select Type

              <input type="radio" name="type" value="call">Call

              <input type="radio" name="type" value="text">Text

Trigger

              <input type="radio" name="rule" value="not_in_contacts">Not in contacts

              <input type="radio" name="rule" value="weekday">Weekday

              <input type="radio" name="rule" value="weekend">WeekEnd

              <input type="radio" name="rule" value="custom">Custom(Time)

Action

              <input type="radio" name="action" value="drop1">Drop call

              <input type="radio" name="action" value="drop">Drop call with message

                  Message

                <input type="text" class="form-control" name="message"/>

              <input type="radio" name="action" value="forward">Forward to number

          <button style="border: 1px solid;border-radius: 15px;float:right;" type="submit">Create</button>

  </form>


text:
import Account from './Account'
import Department from './Department'
import ItemBase from './ItemBase'
import UserSubstitute from './UserSubstitute'

export default interface User {
	id: string
	lastName: string
	firstName: string
	email: string | null
	accountLong: string | null
	hasNotification: boolean | null

	accountId: number | null
	departmentId: number | null
	supervisorId: number | null

	requesting?: ItemBase[]
	notifications?: number[]
	groups?: number[]
	account?: Account
	department?: Department
	supervisor?: User
	substitutes?: UserSubstitute[]
	substituting?: UserSubstitute[]

	fullName: string
	memberOf?: string[]
	accountNumber?: string
	departmentName?: string
	supervisorName?: string
	readPerm?: string[]
	writePerm?: string[]
	readGroupPerm?: string[]
	writeGroupPerm?: string[]

	createdAt: Date
	updatedAt: Date
}


text:
data LocalizedData
{
    # culture="en-US"
    ConvertFrom-StringData @'
        RoleNotFoundError        = Please ensure that the PowerShell module for role '{0}' is installed
        RetrievingOU             = Retrieving OU '{0}'.
        UpdatingOU               = Updating OU '{0}'
        DeletingOU               = Deleting OU '{0}'
        CreatingOU               = Creating OU '{0}'
        OUInDesiredState         = OU '{0}' exists and is in the desired state
        OUNotInDesiredState      = OU '{0}' exists but is not in the desired state
        OUExistsButShouldNot     = OU '{0}' exists when it should not exist
        OUDoesNotExistButShould  = OU '{0}' does not exist when it should exist
'@
}

function Get-TargetResource
{
    [CmdletBinding()]
    [OutputType([System.Collections.Hashtable])]
    param
    (
        [parameter(Mandatory)]
        [System.String] $Name,

        [parameter(Mandatory)]
        [System.String] $Path
    )

    Assert-Module -ModuleName 'ActiveDirectory';
    Write-Verbose ($LocalizedData.RetrievingOU -f $Name)
    $ou = Get-ADOrganizationalUnit -Filter { Name -eq $Name } -SearchBase $Path -SearchScope OneLevel -Properties ProtectedFromAccidentalDeletion, Description

    $targetResource = @{
        Name = $Name
        Path = $Path
        Ensure = if ($null -eq $ou) { 'Absent' } else { 'Present' }
        ProtectedFromAccidentalDeletion = $ou.ProtectedFromAccidentalDeletion
        Description = $ou.Description
    }
    return $targetResource

} # end function Get-TargetResource

function Test-TargetResource
{
    [CmdletBinding()]
    [OutputType([System.Boolean])]
    param
    (
        [parameter(Mandatory)]
        [System.String] $Name,

        [parameter(Mandatory)]
        [System.String] $Path,

        [ValidateSet('Present', 'Absent')]
        [System.String]
        $Ensure = 'Present',

        [ValidateNotNull()]
        [System.Management.Automation.PSCredential]
        [System.Management.Automation.CredentialAttribute()]
        $Credential,

        [ValidateNotNull()]
        [System.Boolean] $ProtectedFromAccidentalDeletion = $true,

        [ValidateNotNull()]
        [System.String] $Description = ''
    )

    $targetResource = Get-TargetResource -Name $Name -Path $Path

    if ($targetResource.Ensure -eq 'Present')
    {
        if ($Ensure -eq 'Present')
        {
            ## Organizational unit exists
            if ([System.String]::IsNullOrEmpty($Description)) {
                $isCompliant = (($targetResource.Name -eq $Name) -and
                                    ($targetResource.Path -eq $Path) -and
                                        ($targetResource.ProtectedFromAccidentalDeletion -eq $ProtectedFromAccidentalDeletion))
            }
            else {
                $isCompliant = (($targetResource.Name -eq $Name) -and
                                    ($targetResource.Path -eq $Path) -and
                                        ($targetResource.ProtectedFromAccidentalDeletion -eq $ProtectedFromAccidentalDeletion) -and
                                            ($targetResource.Description -eq $Description))
            }

            if ($isCompliant)
            {
                Write-Verbose ($LocalizedData.OUInDesiredState -f $targetResource.Name)
            }
            else
            {
                Write-Verbose ($LocalizedData.OUNotInDesiredState -f $targetResource.Name)
            }
        }
        else
        {
            $isCompliant = $false
            Write-Verbose ($LocalizedData.OUExistsButShouldNot -f $targetResource.Name)
        }
    }
    else
    {
        ## Organizational unit does not exist
        if ($Ensure -eq 'Present')
        {
            $isCompliant = $false
            Write-Verbose ($LocalizedData.OUDoesNotExistButShould -f $targetResource.Name)
        }
        else
        {
            $isCompliant = $true
            Write-Verbose ($LocalizedData.OUInDesiredState -f $targetResource.Name)
        }
    }

    return $isCompliant

} #end function Test-TargetResource

function Set-TargetResource
{
    [CmdletBinding()]
    param
    (
        [parameter(Mandatory)]
        [System.String] $Name,

        [parameter(Mandatory)]
        [System.String] $Path,

        [ValidateSet('Present', 'Absent')]
        [System.String]
        $Ensure = 'Present',

        [ValidateNotNull()]
        [System.Management.Automation.PSCredential]
        [System.Management.Automation.CredentialAttribute()]
        $Credential,

        [ValidateNotNull()]
        [System.Boolean] $ProtectedFromAccidentalDeletion = $true,

        [ValidateNotNull()]
        [System.String] $Description = ''
    )

    Assert-Module -ModuleName 'ActiveDirectory';
    $targetResource = Get-TargetResource -Name $Name -Path $Path

    if ($targetResource.Ensure -eq 'Present')
    {
        $ou = Get-ADOrganizationalUnit -Filter { Name -eq $Name } -SearchBase $Path -SearchScope OneLevel
        if ($Ensure -eq 'Present')
        {
            Write-Verbose ($LocalizedData.UpdatingOU -f $targetResource.Name)
            $setADOrganizationalUnitParams = @{
                Identity = $ou
                Description = $Description
                ProtectedFromAccidentalDeletion = $ProtectedFromAccidentalDeletion
            }
            if ($Credential)
            {
                $setADOrganizationalUnitParams['Credential'] = $Credential
            }
            Set-ADOrganizationalUnit @setADOrganizationalUnitParams
        }
        else
        {
            Write-Verbose ($LocalizedData.DeletingOU -f $targetResource.Name)
            if ($targetResource.ProtectedFromAccidentalDeletion)
            {
                $setADOrganizationalUnitParams = @{
                    Identity = $ou
                    ProtectedFromAccidentalDeletion = $ProtectedFromAccidentalDeletion
                }
                if ($Credential)
                {
                    $setADOrganizationalUnitParams['Credential'] = $Credential
                }
                Set-ADOrganizationalUnit @setADOrganizationalUnitParams
            }

            $removeADOrganizationalUnitParams = @{
                Identity = $ou
            }
            if ($Credential)
            {
                $removeADOrganizationalUnitParams['Credential'] = $Credential
            }
            Remove-ADOrganizationalUnit @removeADOrganizationalUnitParams
        }
    }
    else
    {
        Write-Verbose ($LocalizedData.CreatingOU -f $targetResource.Name)
        $newADOrganizationalUnitParams = @{
            Name = $Name
            Path = $Path
            Description = $Description
            ProtectedFromAccidentalDeletion = $ProtectedFromAccidentalDeletion
        }
        if ($Credential) {
            $newADOrganizationalUnitParams['Credential'] = $Credential
        }
        New-ADOrganizationalUnit @newADOrganizationalUnitParams
    }

} #end function Set-TargetResource

## Import the common AD functions
$adCommonFunctions = Join-Path -Path (Split-Path -Path $PSScriptRoot -Parent) -ChildPath '\MSFT_xADCommon\MSFT_xADCommon.ps1';
. $adCommonFunctions;

Export-ModuleMember -Function *-TargetResource


text:
package com.fishercoder;

import com.fishercoder.common.utils.CommonUtils;
import com.fishercoder.solutions._861;
import org.junit.BeforeClass;
import org.junit.Test;

import static org.junit.Assert.assertEquals;

public class _861Test {
    private static _861.Solution1 solution1;

    @BeforeClass
    public static void setup() {
        solution1 = new _861.Solution1();
    }

    @Test
    public void test1() {
        assertEquals(39, solution1.matrixScore(CommonUtils.convertLeetCodeIrregularLengths2DArrayInputIntoJavaArray("[0,0,1,1],[1,0,1,0],[1,1,0,0]")));
    }

}


text:
 - **Authors**: Bruno Grande
 - **Research field**: Computational biology / Cancer genomics
 - **Lesson Topic**: This lesson introduces the basics of regular expressions.

## Motivation

We deal with a lot of text in our day-to-day lives, whether at work or at home. In doing so, we often wish to search or otherwise manipulate this text. You can typically achieve this manually if the amount of text isn't too large. However, this approach doesn't readily scale.

This is where regular expressions come in.

Regular expressions—or regex—offer a powerful means for detecting patterns in text. They are also flexible to match anything from the simplest pattern (_e.g._ a simple DNA motif) to the more complex ones (_e.g._ extracting variably formatted phone number from a block of text). You can either do simple searching (_e.g._ using `grep`) or text manipulation (_e.g._ using `sed`).

Once equipped with the knowledge of regular expressions, you'll wonder how you ever got things done without them. This lesson aims to teach you the way to think about regex, giving you a foundation you can then build upon by yourself. To this day, I still use the Internet to search more complex regex patterns. Once you understand the basics, it opens up a whole world of possibilities.

## Setup

1. Open [regexpal.com](http://regexpal.com/).
2. Enable the following options at the top of the page.
    * ^$ match at line breaks
3. Copy the appropriate text in the bottom text box on regexpal.com. See each part below for the example text.
4. Enjoy the lesson!

## Lesson

### Part 1: Basic Patterns

For Parts 1 and 2, we will use the following text. Please copy-paste it into the bottom textbox on regexpal.com.

```text
=== Parts 1 and 2 ===

TACTAGATGACTGCAGAATTCCCGACGTTAAGTACATTACCCCGTCCAGG
GCGCCGTTCAGGATCACGTTACCGCCATAAGATGGGAGGGATCCTTCTTC
TCCGCTGCGCCCACGCCAGTAGTGATTATATATACTCCTATAACCCTTCT
CCGGAGGCGGAAATCCGCCACGAATGAATTCGAGAATGTATTTCCCCGAC
AATCATTATATAGGGGCGCTCCTAAGCTTTTCCACTCGGTTGAGCCTGGT
```

A common technique in molecular biology is to digest or cut DNA with restriction enzymes. You can think of restriction enzymes as DNA scissors that only cut at specific places, depending on their recognition site. There are a great number of commercially available restriction enzymes, each with its own recognition site. I have included a few real and theoretical ones below.

| Restriction Enzyme | Recognition Sequence |
| ------------------ | -------------------- |
| *Eco*RI            | `GAATTC`             |
| *Bam*HI            | `GGATCC`             |
| *Eco*RII           | `CCWGG`              |
| *Boom*HI           | `CTGCNNNN`           |

**Notes**

* W = A or T

* N = A, T, G or C

To search for *Eco*RI cutting sites, you can simply search using the recognition sequencing as the pattern.

```text
GAATTC
```

**Warning:** Regex is case-sensitive. Accordingly, since our DNA sequence is in upper case, the pattern `GAATTC` will work, but not `gaattc`.

This should unveil two *Eco*RI cutting sites. You can do the same for finding *Bam*HI cutting sites.

```text
GGATCC
```

In this case, you should find one *Bam*HI cutting site.

What if you're interested in doing a double digestion, using both *Eco*RI and *Bam*HI. In this case, you want to match either `GAATTC` or `GGATCC`. The "OR" operator in regex is the vertical bar (or pipe), `|`. Hence, here's how you can match all *Eco*RI and *Bam*HI cutting sites.

```text
GAATTC|GGATCC
```

**Warning:** Whitespace in regex matters. Accordingly, if your pattern isn't matching as it should, make sure you don't have spaces or newlines trailing at the end.

Now that we've found all *Eco*RI and *Bam*HI cutting sites, let's do the same for *Eco*RII. In this case, the recognition sequence is `CCWGG`, where W = A or T. If you were to search for `CCWGG`, you will notice that no matches are made. This is because regex isn't aware of the W convention. Instead, it's searching for the actual letter W.

There is a way however to specify a range of possible characters to match. For this, you can use the square braquets notation, `[]`. In this case, you want to match `CC`, followed by either an A or a T, followed by `GG`. In regex, you can express this pattern as follows.

```text
CC[AT]GG
```

This pattern should detect two *Eco*RII cutting sites, one being CCAGG and the other, CCTGG.

If you wanted to detect *all* possible cutting sites, you can add *Eco*RII's recognition sequence to our list from before, namely:

```text
GAATTC|GGATCC|CC[AT]GG
```

----

#### Challenge Question 1

Refer back to the table of restriction enzymes above. Create a pattern to match *Boom*HI cutting sites.

**Hint:** If you notice repetition in your pattern, you should consider using quantifiers. See cheat sheet or jump ahead a little to learn how to use quantifiers.

*Answers to challenge questions are located at the bottom of this lesson.*

----

### Part 2: Quantifiers

For Part 2, we will use the same text as in Part 1 (see above).

A common feature of DNA sequences are repeats, in which a stretch of sequence is repeated a variable number of times. The repeated sequence is usually relatively well defined, but the number of repeats can vary.

The simplest kind of repeat is a stretch of the same nucleotide. For instance, to search for stretches of one or more T's, you may use the plus quantifier, `+`. This quantifier means that the preceding subpattern can be present one or more times. Similar quantifier are the asterisk, `*`, which signifies zero or more times, and the question mark, `?`, which signifies zero or one time.

In this case, matching stretches of one or more T's can be done as follows.

```text
T+
```

You should see a number of matches in the DNA sequence, One wouldn't consider a single T to be a repeat. Let's say we want to search for two or more T's in a row. We may use the general quantifier notation using curly braces, `{}`.

There are various ways of using the curly braces notation.

* **An exact count:** `{3}` would match exactly three occurrences of the preceding subpattern.
* **A bounded range:** `{3,5}` would match three, four or five occurrences.
* **An unbounded range:** `{3,}` would match three or more occurrences.

Hence, in our case, if we wish to match stretches of two or more T's in the DNA sequence, we can achieve this with the following pattern.

```text
T{2,}
```

Now, let's match repeats of the dinucleotide TA. Unfortunately, the pattern `TA{2,}` doesn't work, because the quantifier only applies to the subpattern directly preceding it, namely `A` in this case. This pattern would match ant T following by two or more A's.

To match TA repeats, we need to group the T and A together and apply the quantifier to that group. The parentheses notation, `()`, can be used to this effect. Accordinfly, our pattern becomes:

```text
(TA){2,}
```

As you can see, there are three instances of TA repeats in our example DNA sequence.

----

#### Challenge Question 2

Match all of the phone number formats listed below.

```text
415-555-1234
650-555-2345
(416)555-3456
202 555 4567
4035555678
1 416 555 9292
```

**Hint:** The question mark quantifier, `?`, mentioned earlier could be useful here.

*Answers to challenge questions are located at the bottom of this lesson.*

----

### Part 3: Character Classes

For Part 3, we will use the list of email addresses below. The first section are invalid emails, and the second section are valid emails. We will build our repertoire of regex knowledge in order to be able to only match valid emails (and exclude any invalid ones).

```text
=== Parts 3 and 4 ===

# Valid emails
brunogrande@sfu.ca
BrunoGrande@sfu.ca
Bruno_Grande@sfu.ca
Bruno_Grande1991@sfu.ca
Bruno_Grande.1991@sfu.ca
Bruno_Grande-1991@sfu.ca
Bruno_Grande-1991@engage-sfu.ca
Bruno_Grande.1991@sfu.co.uk

# Invalid emails
bruno grande@sfu.ca
brunogrande@sfuca
brunogrande@-sfu.ca
brunograndesfu.ca
bruno_o'grande@sfu.ca
```

Let's start by focusing on matching the first part of valid emails. For future reference:

```text
brunogrande@sfu.ca
|---------| |----|
     |         `-> Second part
     `-> First part
```

Earlier, we saw that we can match one of many possible characters by using the square braquet notation, `[]`. For instance, if we wish to match a vowel, we could use `[aeiou]`.

But what if we want to match any lower-case letter in the alphabet? The immediately obvious answer would be `[abcdefghijklmnopqrstuvwxyz]`. So, you can match what comes before the @ with:

```text
[abcdefghijklmnopqrstuvwxyz]+
```

Unfortunately, this matches any stretch of lower-case letters (one or more), while we wish to only match the first part of the email addresses.

To accomplish this, we can make use of a very useful feature in regex: boundaries. There are a few ways of matching either line or word boundaries, as follows.

* `^` = Line beginning
* `$` = Line ending
* `\b` = Word boundary

Knowing this, we can review our previous pattern to match any string of lower-case letters starting after the line beginning:

```text
^[abcdefghijklmnopqrstuvwxyz]+
```

However, we, programmers, hate typing. So, there is a shortcut in regex: you can specify ranges in square braquets using the hyphen, `-`. Knowing this, we can rewrite our pattern above as:

```text
^[a-z]+
```

This is obviously much better. Now, what if you wanted to match both lower- and upper-case letters? Well, you can specify more than one range between square braquets:

```text
^[A-Za-z]+
```

Now, with this previous pattern, we notice that we're starting to match email better and better. However, there is an obvious issue now: we need to also match the underscore, as it is a valid character in emails. This can be done by adding it between square braquets alongside the other ranges.

```text
^[A-Za-z_]+
```

And now we need to do the same for digits:

```text
^[A-Za-z_0-9]+
```

Now, as you can imagine, this is a common pattern. We are basically matching typical word characters. In fact, there are a few common patterns for which "shortcuts" were created. Here are the main ones:

* `\w` = `[A-za-z0-9_]` (Word characters)
* `\d` = `[0-9]` (Digits)
* `\s` = `[ \t\r\n\f]` (Whitespace characters)
* `.` = Any character except for the newline (`\n`)

With this, we can shorten our pattern to the following. Notice that we no longer need the square braquets, as they're implied.

```text
^\w+
```

If we look at the email being matched, we continue to make progress. However, the period remains unmatched. However, you will notice that adding a period (`^\w.+`) causes every email to be fully matched. This is because the `+` quantifier applies to the subpattern immediately before, which is the period in this case. This causes the first character to me matched with `\w` and the rest of the emails matched with `.+`.

ThisIn order to match either `\w` or `.`, we need to bring back the square braquets.

```text
^[\w.]+
```

As expected, the emails containing a period are now being fully matched. However, the period (`.`) is supposed to match any character except for the newline. Why isn't it also matching the dash (and the rest of the emails, for that matter)?

Well, because the period is being used between square braquets, it's implied that you don't want to match anything. Otherwise, you wouldn't need the square braquets and would just use the period directly. So, in this case, the period is a literal period (nothing special about it).

**Warning:** However, outside of square braquets, you'll need to escape the period (`\.`) if you wish to specifically match periods.

If we also include the dash, our pattern now becomes:

```text
^[\w.-]+
```

We are now finally matching the first part of every valid emails.

----

#### Challenge Question 3

Now, expand on this pattern to also match the entire emails. Remember: you wish to only match valid emails. Ensure that none of the invalid emails are matched.

**Hint:** A URL (second part of emails, after the @) can consist of alphanumerical characters and dashes. However, a dash cannot be the first character. Also, there needs to be at least one period in a URL. The top-level domain (_e.g._ .com, .ca, .org) can only contain letters (no digits or dashes).

*Answers to challenge questions are located at the bottom of this lesson.*

----

There are a few more character classes available to us in regular expressions.

In addition to the three character classes introduced above (`\d`, `\w`, `\s`), you can also match the "inverse" of any of them by using their upper-case equivalent (`\D`, `\W`, `\S`, respectively).

More formally, here are the equivalents:

* `\D` = `[^0-9]` (Anything except digits)
* `\W` = `[^A-za-z0-9_]` (Anything except word characters)
* `\S` = `[^ \t\r\n\f]` (Anything except whitespace characters)

You'll notice the caret as the first character between square braquets above. Here, it is acting as a special character: it is negating the ranges. For instance, `[^0-9]` matches anything that isn't a digit.

While on the topic of escaping characters, another use of the backslash (`\`) is to refer to whitespace characters. Obviously, you can include a space in a pattern by typing a space (` `). However, for other whitespace characters, there are "visible" equivalents.

* `\t` = Tab
* `\n` = Newline
* `\r` = Carriage return

In the Unix world (including OS X), you will mostly encounter tabs (`\t`) and newlines (`\n`). However, on Windows, a "newline" is often represented as a carriage return followed by a newline (`\r\n`).

**Tip:** If ever you run into issues where everything in a file is on one line or your regex isn't matching newlines properly, it might be due to line endings not being interpreted correctly.

----

#### Challenge Question 4

Create a regex pattern that matches all of the number formats listed below.

```text
3.14529
-255.34
128
1.9e10
123,340.00
```

*Answers to challenge questions are located at the bottom of this lesson.*

----

### Part 4: Capturing

**Warning:** This section is still being developed.

All of the above is useful to search for patterns within a body of text. However, as I alluded to in the Motivation section, regex is also useful for text manipulation in addition to simple searching.

For this Part, we will stick with the same example text as Part 3, but we will store it into a text file. You can create this yourself or download it by right-clicking [this link](https://github.com/sciprog-sfu/sciprog-sfu.github.io/raw/master/lessons/2015-07-21_regex/part_4.txt) and selecting "Save Link As..." (or equivalent, such as "Download Linked File As...").

Open a Bash shell and navigate to the directory where the text file is located, referred to here as part_4.txt.

```bash
cd /path/to/part_4.txt
```

If you print the contents of the file, you should see the following (where `$` is your prompt).

```bash
$ cat part_4.txt
=== Parts 3 and 4 ===

# Valid emails
brunogrande@sfu.ca
BrunoGrande@sfu.ca
Bruno_Grande@sfu.ca
Bruno_Grande1991@sfu.ca
Bruno_Grande.1991@sfu.ca
Bruno_Grande-1991@sfu.ca
Bruno_Grande-1991@engage-sfu.ca
Bruno_Grande.1991@sfu.co.uk

# Invalid emails
bruno grande@sfu.ca
brunogrande@sfuca
brunogrande@-sfu.ca
brunograndesfu.ca
bruno_o'grande@sfu.ca
```

Let's extract the second part (URL portion) of valid emails.

To do this, we can start with the regex pattern developed for Challenge Question 3. We will restrict the contents of the text file to lines that match that pattern using `grep` and pipes (`|`).

```bash
$ cat part_4.txt | grep -P "^[\w.-]+@[A-Za-z0-9][A-Za-z0-9-]+(\.[A-Za-z]+)+$"
brunogrande@sfu.ca
BrunoGrande@sfu.ca
Bruno_Grande@sfu.ca
Bruno_Grande1991@sfu.ca
Bruno_Grande.1991@sfu.ca
Bruno_Grande-1991@sfu.ca
Bruno_Grande-1991@engage-sfu.ca
Bruno_Grande.1991@sfu.co.uk
```

**Warning:** I'm using the `-P` option here so that the regular expression is interpreted as a Perl regular expression. Unfortunately, there are slight variations in how regex is implemented from one tool to the next. The `-P` option prevents us from having to tweak our regex.

Now that we have valid emails, let's extract the URL after the `@` symbol. We can achieve this using a capture group, denoted with parentheses (`()`). You can recall that we have used parentheses earlier today and those too are capture groups.

To extract the second part of the emails, we wrap the subpattern corresponding to the URL, which is basically everything after the `@`. The regex becomes: `^[\w.-]+@([A-Za-z0-9][A-Za-z0-9-]+(\.[A-Za-z]+)+)$`. Notice that we don't include the trailing `$`, as we don't want to capture the line ending.

To do the actual extraction, we can use `sed` or `perl`. We'll use Perl for the simplicity of not having to tweak our regex.

```bash
$ cat part_4.txt | grep -P "^[\w.-]+@[A-Za-z0-9][A-Za-z0-9-]+(\.[A-Za-z]+)+$" | perl -pe 's/^[\w.-]+@([A-Za-z0-9][A-Za-z0-9-]+(\.[A-Za-z]+)+)$/\1/'
sfu.ca
sfu.ca
sfu.ca
sfu.ca
sfu.ca
sfu.ca
engage-sfu.ca
sfu.co.uk
```

## Answers to Challenge Questions

#### Challenge Question 1

Based on what we learned so far, a correct pattern to match *Boom*HI cutting sites would be the following.

```text
CTGC[ATGC][ATGC][ATGC][ATGC]
```

However, we have the same subpattern (`[ATGC]`) being repeated multiple times. In regex, we can use quantifiers to allow subpatterns to be repeated a given number of times using the curly braces notation, `{}`. In this case, we want the `[ATGC]` subpattern to be matched exactly four times.

```text
CTGC[ATGC]{4}
```

#### Challenge Question 2

There are many approaches to solving this challenge. Here's my attempt:

```text
1? ?\(?\d{3}\)?[- ]?\d{3}[- ]?\d{4}
```

#### Challenge Question 3

Starting with our pattern to match the emails' first part, we can match a `@` followed by characters making up a valid URL (`[A-Za-z0-9-]`). However, the first character of the URL cannot be a dash. Hence, the first subpattern after the @ cannot have the dash. Afterwards, you can match any of those characters (including the dash) any number of times.

```text
^[\w.-]+@[A-Za-z0-9][A-Za-z0-9-]+
```

However, the previous pattern doesn't match the periods in the URL. We could add the period in the last range, but this makes it optional. As a result, it matches emails that don't have a period in the email's second part.

To circumvent this issue, we need to specify the period outside of the square braquets (don't forget to escape it), followed by any number of letters.

```text
^[\w.-]+@[A-Za-z0-9][A-Za-z0-9-]+\.[A-Za-z]+
```

This is nearly the solution, but there is still one problem: when the URL has more than one period. The workaround for this is simple though once you notice the pattern: the last part (period followed by letters) can be repeated any number of times. To achieve this pattern in regex, you need to wrap the subpattern you wish to repeat (like with the repeating TA dinucleotide earlier) in parentheses. Then, you may add the quantifier, which is one or more in this case (`+`), and the line ending notation (`$`).

```text
^[\w.-]+@[A-Za-z0-9][A-Za-z0-9-]+(\.[A-Za-z]+)+$
```

And voilà! You are now only matching valid emails.

#### Challenge Question 4

Again, there are multiple ways of solving this challenge. Here's one example solution.

```text
-?(\d+,?)+(\.\d+)?(e\d+)?
```


text:
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.nispok.samples.snackbar.SnackbarSampleActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin">

        <Button
            android:id="@+id/single_line"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Single-line" />

        <Button
            android:id="@+id/single_line_with_action"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Single-line + Action" />

        <Button
            android:id="@+id/multi_line"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Multi-line" />

        <Button
            android:id="@+id/multi_line_with_action"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Multi-line + Action" />

        <Button
            android:id="@+id/no_animation"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="No animation" />

        <Button
            android:id="@+id/event_listener"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Event Listener" />

        <Button
            android:id="@+id/custom_colors"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Custom colors" />

        <Button
            android:id="@+id/unswipeable"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Unswipeable" />

        <Button
            android:id="@+id/indefinite"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Indefinite Duration" />

        <Button
            android:id="@+id/list_example"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="ListView Listener" />

        <Button
            android:id="@+id/recycler_example"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="RecyclerView Listener" />

        <Button
            android:id="@+id/typeface_example"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Custom Typefaces" />

        <Button
            android:id="@+id/navigation_bar_translucent"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Navigation Bar Translucent"/>

        <Button
            android:id="@+id/immersive_mode_example"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Immersive Mode"/>

        <Button
            android:id="@+id/show_in_dialog_example"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Show in Dialog"/>

	    <Button
		    android:id="@+id/single_line_top"
		    android:layout_width="match_parent"
		    android:layout_height="wrap_content"
		    android:text="Single-line Top" />

	    <Button
		    android:id="@+id/single_line_margins"
		    android:layout_width="match_parent"
		    android:layout_height="wrap_content"
		    android:text="Single-line Margins" />

	    <Button
		    android:id="@+id/single_line_shape"
		    android:layout_width="match_parent"
		    android:layout_height="wrap_content"
		    android:text="Custom Shape Touchable" />

	    <Button
		    android:id="@+id/single_line_inside"
		    android:layout_width="match_parent"
		    android:layout_height="wrap_content"
		    android:text="Single-line Inside RelativeLayout" />

	    <Button
		    android:id="@+id/single_line_top_inside"
		    android:layout_width="match_parent"
		    android:layout_height="wrap_content"
		    android:text="Single-line Top Inside LinearLayout" />

	    <RelativeLayout
		    android:id="@+id/view_relative_layout"
		    android:layout_width="match_parent"
		    android:layout_height="100dp"
		    android:orientation="horizontal"
		    android:background="@color/material_deep_teal_500" />

	    <LinearLayout
		    android:id="@+id/view_linear_layout"
		    android:layout_width="match_parent"
		    android:layout_height="100dp"
		    android:orientation="horizontal"
		    android:background="@color/material_deep_teal_200" />

    </LinearLayout>
</ScrollView>


text:
namespace net {
namespace test {

class QuicTestPacketMaker {
 public:
  QuicTestPacketMaker(QuicVersion version, QuicGuid guid);
  ~QuicTestPacketMaker();

  scoped_ptr<QuicEncryptedPacket> MakeRstPacket(
      QuicPacketSequenceNumber num,
      bool include_version,
      QuicStreamId stream_id,
      QuicRstStreamErrorCode error_code);
  scoped_ptr<QuicEncryptedPacket> MakeAckAndRstPacket(
      QuicPacketSequenceNumber num,
      bool include_version,
      QuicStreamId stream_id,
      QuicRstStreamErrorCode error_code,
      QuicPacketSequenceNumber largest_received,
      QuicPacketSequenceNumber least_unacked,
      bool send_feedback);
  scoped_ptr<QuicEncryptedPacket> MakeConnectionClosePacket(
      QuicPacketSequenceNumber num);
  scoped_ptr<QuicEncryptedPacket> MakeAckPacket(
      QuicPacketSequenceNumber sequence_number,
      QuicPacketSequenceNumber largest_received,
      QuicPacketSequenceNumber least_unacked,
      bool send_feedback);
  scoped_ptr<QuicEncryptedPacket> MakeDataPacket(
      QuicPacketSequenceNumber sequence_number,
      QuicStreamId stream_id,
      bool should_include_version,
      bool fin,
      QuicStreamOffset offset,
      base::StringPiece data);
  scoped_ptr<QuicEncryptedPacket> MakeRequestHeadersPacket(
      QuicPacketSequenceNumber sequence_number,
      QuicStreamId stream_id,
      bool should_include_version,
      bool fin,
      const SpdyHeaderBlock& headers);
  scoped_ptr<QuicEncryptedPacket> MakeResponseHeadersPacket(
      QuicPacketSequenceNumber sequence_number,
      QuicStreamId stream_id,
      bool should_include_version,
      bool fin,
      const SpdyHeaderBlock& headers);

  SpdyHeaderBlock GetRequestHeaders(const std::string& method,
                                    const std::string& scheme,
                                    const std::string& path);
  std::string GetRequestString(const std::string& method,
                               const std::string& scheme,
                               const std::string& path);
  SpdyHeaderBlock GetResponseHeaders(const std::string& status);
  std::string GetResponseString(const std::string& status,
                                const std::string& body);

 private:
  scoped_ptr<QuicEncryptedPacket> MakePacket(
      const QuicPacketHeader& header,
      const QuicFrame& frame);

  void InitializeHeader(QuicPacketSequenceNumber sequence_number,
                        bool should_include_version);

  std::string SerializeHeaderBlock(const SpdyHeaderBlock& headers);

  QuicVersion version_;
  QuicGuid guid_;
  SpdyFramer spdy_request_framer_;
  SpdyFramer spdy_response_framer_;
  MockRandom random_generator_;
  QuicPacketHeader header_;
  QuicSpdyCompressor compressor_;

  DISALLOW_COPY_AND_ASSIGN(QuicTestPacketMaker);
};

}  // namespace test
}  // namespace net

#endif  // NET_QUIC_TEST_TOOLS_QUIC_TEST_PACKET_MAKER_H_


text:
package multiverse.tests.marshallingtests;

import multiverse.server.network.*;

public class TestClass7 extends TestClass3 {

    public boolean b;

    public void marshalObject(MVByteBuffer buf) {
        super.marshalObject(buf);
        buf.putByte((byte)(b ? 1 : 0));
    }

    public Object unmarshalObject(MVByteBuffer buf) {
        super.unmarshalObject(buf);
        b = buf.getByte() != 0;
        return this;
    }
}


text:
import warnings

# noinspection PyDeprecation
from .array_connection import (
    connection_from_array,
    connection_from_array_slice,
    cursor_for_object_in_connection,
    cursor_to_offset,
    get_offset_with_default,
    offset_to_cursor,
    SizedSliceable,
)

warnings.warn(
    "The 'arrayconnection' module is deprecated. "
    "Functions should be imported from the top-level package instead.",
    DeprecationWarning,
    stacklevel=2,
)

__all__ = [
    "connection_from_array",
    "connection_from_array_slice",
    "cursor_for_object_in_connection",
    "cursor_to_offset",
    "get_offset_with_default",
    "offset_to_cursor",
    "SizedSliceable",
]


text:
namespace Microsoft.Azure.Management.KeyVault.Models
{

    /// <summary>
    /// Defines values for IdentityType.
    /// </summary>
    public static class IdentityType
    {
        public const string User = "User";
        public const string Application = "Application";
        public const string ManagedIdentity = "ManagedIdentity";
        public const string Key = "Key";
    }
}


text:
package org.neo4j.qa.tooling;

import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.lang.Thread.State;

public class DumpVmInformation
{
    public static void dumpVmInfo( File directory ) throws IOException
    {
        File file = new File( directory, "main-vm-dump-" + System.currentTimeMillis() );
        PrintStream out = null;
        try
        {
            out = new PrintStream( file );
            dumpVmInfo( out );
        }
        finally
        {
            if ( out != null )
                out.close();
        }
    }

    public static void dumpVmInfo( PrintStream out )
    {
        // Find the top thread group
        ThreadGroup topThreadGroup = Thread.currentThread().getThreadGroup();
        while ( topThreadGroup.getParent() != null )
            topThreadGroup = topThreadGroup.getParent();

        // Get all the thread groups under the top.
        ThreadGroup[] allGroups = new ThreadGroup[1000];
        topThreadGroup.enumerate( allGroups, true );

        // Dump the info.
        for ( ThreadGroup group : allGroups )
        {
            if ( group == null )
                break;
            dumpThreadGroupInfo( group, out );
        }
        dumpThreadGroupInfo( topThreadGroup, out );
    }

    public static void dumpThreadGroupInfo( ThreadGroup tg, PrintStream out )
    {
        String parentName = (tg.getParent() == null ? null : tg.getParent().getName());
        // Dump thread group info.
        out.println( "---- GROUP:" + tg.getName() +
                (parentName != null ? " parent:" + parentName : "" ) +
                (tg.isDaemon() ? " daemon" : "" ) +
                (tg.isDestroyed() ? " destroyed" : "" ) +
                " ----" );
        // Dump info for each thread.
        Thread[] allThreads = new Thread[1000];
        tg.enumerate( allThreads, false );
        for ( Thread thread : allThreads )
        {
            if ( thread == null )
                break;
            out.println(
                    "\"" + thread.getName() + "\"" +
                    (thread.isDaemon() ? " daemon" : "") +
            		" prio=" + thread.getPriority() +
            		" tid=" + thread.getId() +
            		" " + thread.getState().name().toLowerCase() );
            out.println( "  " + State.class.getName() + ": " + thread.getState().name() );
            for ( StackTraceElement element : thread.getStackTrace() )
            {
                out.println( "\tat " + element );
            }
        }
    }
}


text:
<?php

namespace Google\Service\Translate;

class LanguageCodePair extends \Google\Model
{
  /**
   * @var string
   */
  public $sourceLanguageCode;
  /**
   * @var string
   */
  public $targetLanguageCode;

  /**
   * @param string
   */
  public function setSourceLanguageCode($sourceLanguageCode)
  {
    $this->sourceLanguageCode = $sourceLanguageCode;
  }
  /**
   * @return string
   */
  public function getSourceLanguageCode()
  {
    return $this->sourceLanguageCode;
  }
  /**
   * @param string
   */
  public function setTargetLanguageCode($targetLanguageCode)
  {
    $this->targetLanguageCode = $targetLanguageCode;
  }
  /**
   * @return string
   */
  public function getTargetLanguageCode()
  {
    return $this->targetLanguageCode;
  }
}

// Adding a class alias for backwards compatibility with the previous class name.
class_alias(LanguageCodePair::class, 'Google_Service_Translate_LanguageCodePair');


text:
/**
 * Module dependencies.
 */
const express = require('express');
const compression = require('compression');
const session = require('express-session');
const bodyParser = require('body-parser');
const logger = require('morgan');
const chalk = require('chalk');
const errorHandler = require('errorhandler');
const lusca = require('lusca');
const dotenv = require('dotenv');
const MongoStore = require('connect-mongo')(session);
const flash = require('express-flash');
const path = require('path');
const mongoose = require('mongoose');
const passport = require('passport');
const expressValidator = require('express-validator');
const expressStatusMonitor = require('express-status-monitor');
const sass = require('node-sass-middleware');
const multer = require('multer');
const dbScheduler = require('./db');
const fs = require('fs');

const upload = multer({ dest: path.join(__dirname, 'uploads') });

/**
 * Load environment variables from .env file, where API keys and passwords are configured.
 */
dotenv.load({ path: '.env' });

/**
 * Controllers (route handlers).
 */
const marketsController = require('./controllers/markets');
const portfolioController = require('./controllers/portfolio');
const strategyController = require('./controllers/strategies');
const homeController = require('./controllers/home');
const userController = require('./controllers/user');
const apiController = require('./controllers/api');
const contactController = require('./controllers/contact');

/**
 * API keys and Passport configuration.
 */
const passportConfig = require('./config/passport');

/**
 * Create Express server.
 */
const app = express();

/**
 * Connect to MongoDB.
 */
mongoose.Promise = global.Promise;
mongoose.connect(process.env.MONGO_HEROKU || process.env.MONGOLAB_URI, { useMongoClient: true });
mongoose.connection.on('error', (err) => {
  console.error(err);
  console.log('%s MongoDB connection error. Please make sure MongoDB is running.', chalk.red('✗'));
  process.exit();
});

/**
 * Express configuration.
 */
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use(expressStatusMonitor());
app.use(compression());
app.use(sass({
  src: path.join(__dirname, 'public'),
  dest: path.join(__dirname, 'public')
}));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(expressValidator());
app.use(session({
  resave: true,
  saveUninitialized: true,
  secret: process.env.SESSION_SECRET,
  store: new MongoStore({
    url: process.env.MONGODB_URI || process.env.MONGOLAB_URI,
    autoReconnect: true,
    clear_interval: 3600
  })
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
app.use((req, res, next) => {
  if (req.path === '/api/upload') {
    next();
  } else {
    lusca.csrf()(req, res, next);
  }
});
app.use(lusca.xframe('SAMEORIGIN'));
app.use(lusca.xssProtection(true));
app.use((req, res, next) => {
  res.locals.user = req.user;
  next();
});
app.use((req, res, next) => {
  // After successful login, redirect back to the intended page
  if (!req.user &&
      req.path !== '/login' &&
      req.path !== '/signup' &&
      !req.path.match(/^\/auth/) &&
      !req.path.match(/\./)) {
    req.session.returnTo = req.path;
  } else if (req.user &&
      req.path === '/account') {
    req.session.returnTo = req.path;
  }
  next();
});
app.use(express.static(path.join(__dirname, 'public'), { maxAge: 31557600000 }));

/**
 * Primary app routes.
 */
app.get('/', homeController.index);
app.get('/markets', marketsController.getMarkets);
app.get('/data', marketsController.getTickData);
app.get('/tick', marketsController.getTickData);
app.get('/portfolio', portfolioController.getPortfolio);
app.get('/strategies', strategyController.getStrategies);
app.post('strategies/create', strategyController.deployStrategy);

// login and account creation
app.get('/login', userController.getLogin);
app.post('/login', userController.postLogin);
app.get('/logout', userController.logout);
app.get('/forgot', userController.getForgot);
app.post('/forgot', userController.postForgot);
app.get('/reset/:token', userController.getReset);
app.post('/reset/:token', userController.postReset);
app.get('/signup', userController.getSignup);
app.post('/signup', userController.postSignup);
app.get('/account', passportConfig.isAuthenticated, userController.getAccount);
app.post('/account/profile', passportConfig.isAuthenticated, userController.postUpdateProfile);
app.post('/account/password', passportConfig.isAuthenticated, userController.postUpdatePassword);
app.post('/account/delete', passportConfig.isAuthenticated, userController.postDeleteAccount);
app.get('/account/unlink/:provider', passportConfig.isAuthenticated, userController.getOauthUnlink);

// other
app.get('/contact', homeController.index);
app.post('/contact', contactController.postContact);

/**
 * API examples routes.
 */
app.get('/api', apiController.getApi);
app.get('/api/stripe', apiController.getStripe);
app.post('/api/stripe', apiController.postStripe);
app.get('/api/facebook', passportConfig.isAuthenticated, passportConfig.isAuthorized, apiController.getFacebook);
app.get('/api/linkedin', passportConfig.isAuthenticated, passportConfig.isAuthorized, apiController.getLinkedin);
app.get('/api/paypal', apiController.getPayPal);
app.get('/api/paypal/success', apiController.getPayPalSuccess);
app.get('/api/paypal/cancel', apiController.getPayPalCancel);
app.get('/api/upload', apiController.getFileUpload);
app.post('/api/upload', upload.single('myFile'), apiController.postFileUpload);

/**
 * OAuth authentication routes. (Sign in)
 */
app.get('/auth/facebook', passport.authenticate('facebook', { scope: ['email', 'public_profile'] }));
app.get('/auth/facebook/callback', passport.authenticate('facebook', { failureRedirect: '/login' }), (req, res) => {
  res.redirect(req.session.returnTo || '/');
});
app.get('/auth/google', passport.authenticate('google', { scope: 'profile email' }));
app.get('/auth/google/callback', passport.authenticate('google', { failureRedirect: '/login' }), (req, res) => {
  res.redirect(req.session.returnTo || '/');
});

/**
 * Error Handler.
 */
app.use(errorHandler());
process.on('unhandledRejection', (reason, p) => {
  console.log('### Unhandled Rejection at: Promise', p, '\n### Reason:', reason);
  // application specific logging, throwing an error, or other logic here
});

/**
 * Update MongoDB and start Express server.
 */
dbScheduler.dbInitializer().then((DBUpdateResolves) => {
  console.log('### DB UPDATES:', DBUpdateResolves);
  console.log('### EXITING...');
  // process.exit(0);
  app.listen(app.get('port'), () => {
    // dbScheduler.dbUpdater();
    console.log('%s App is running at http://localhost:%d in %s mode', chalk.green('✓'), app.get('port'), app.get('env'));
    console.log('  Press CTRL-C to stop\n');
  });
});

module.exports = app;

const http = require('http');

setInterval(() => {
  http.get('http://ostiatrading.herokuapp.com');
}, 300000); // every 5 minutes (300000)


text:
layout: single
property_name: border-left-width
---

    {% include section-nav.html property_name="border-left-width" %}

      #border-left-width

和 border-width 类似,但是只设置左边框。

            默认

          border-left-width: 0;

去掉左边框。

Hello world

          border-left-width: 4px;

可以使用像素值。

Hello world


text:
<?php
return array (
  'Could not extract module!' => 'Nebylo možné rozbalit modul!',
  'Could not fetch module list online! (%error%)' => 'Nebylo možné vypsat seznam modulů! (%error%)',
  'Could not get module info online! (%error%)' => 'Nebylo možné získat informace o modulu! (%error%₎',
  'Download of module failed!' => 'Nebylo možné stáhnout modul!',
  'Module directory %modulePath% is not writeable!' => 'Adresář pro ukládání modulů %modulePath% není zapisovatelný!',
  'Module directory for module %moduleId% already exists!' => 'Adresář modulu %moduleId% již existuje!',
  'Module download failed! (%error%)' => 'Nebylo možné stáhnout modul! (%error%)',
  'No compatible module version found!' => 'Nebyla nalezena žádná kompatibilní verze modulu!',
);


text:
package org.inaturalist.android;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.util.Log;

import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool;
import com.bumptech.glide.load.resource.bitmap.BitmapTransformation;

import java.security.MessageDigest;

public class RotateTransformation extends BitmapTransformation {

    private float rotateRotationAngle = 0f;

    public RotateTransformation(Context context, float rotateRotationAngle) {
        super();

        this.rotateRotationAngle = rotateRotationAngle;
    }
    @Override
    protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
        Matrix matrix = new Matrix();

        matrix.postRotate(rotateRotationAngle);

        return Bitmap.createBitmap(toTransform, 0, 0, toTransform.getWidth(), toTransform.getHeight(), matrix, true);
    }

    @Override
    public void updateDiskCacheKey(MessageDigest messageDigest) {
        messageDigest.update(("rotate12312321" + rotateRotationAngle).getBytes());
    }
}


text:
<?php

namespace Composer\Installer;

use Composer\Composer;
use Composer\IO\IOInterface;
use Composer\Repository\InstalledRepositoryInterface;
use Composer\Package\PackageInterface;
use Composer\Util\Filesystem;
use Composer\Util\Silencer;
use Composer\Util\Platform;

/**
 * Package installation manager.
 *
 * @author Jordi Boggiano <j.boggiano@seld.be>
 * @author Konstantin Kudryashov <ever.zet@gmail.com>
 */
class LibraryInstaller implements InstallerInterface, BinaryPresenceInterface
{
    protected $composer;
    protected $vendorDir;
    protected $binDir;
    protected $downloadManager;
    protected $io;
    protected $type;
    protected $filesystem;
    protected $binCompat;
    protected $binaryInstaller;

    /**
     * Initializes library installer.
     *
     * @param IOInterface     $io
     * @param Composer        $composer
     * @param string          $type
     * @param Filesystem      $filesystem
     * @param BinaryInstaller $binaryInstaller
     */
    public function __construct(IOInterface $io, Composer $composer, $type = 'library', Filesystem $filesystem = null, BinaryInstaller $binaryInstaller = null)
    {
        $this->composer = $composer;
        $this->downloadManager = $composer->getDownloadManager();
        $this->io = $io;
        $this->type = $type;

        $this->filesystem = $filesystem ?: new Filesystem();
        $this->vendorDir = rtrim($composer->getConfig()->get('vendor-dir'), '/');
        $this->binaryInstaller = $binaryInstaller ?: new BinaryInstaller($this->io, rtrim($composer->getConfig()->get('bin-dir'), '/'), $composer->getConfig()->get('bin-compat'), $this->filesystem);
    }

    /**
     * {@inheritDoc}
     */
    public function supports($packageType)
    {
        return $packageType === $this->type || null === $this->type;
    }

    /**
     * {@inheritDoc}
     */
    public function isInstalled(InstalledRepositoryInterface $repo, PackageInterface $package)
    {
        if (!$repo->hasPackage($package)) {
            return false;
        }

        $installPath = $this->getInstallPath($package);

        if (is_readable($installPath)) {
            return true;
        }

        return (Platform::isWindows() && $this->filesystem->isJunction($installPath)) || is_link($installPath);
    }

    /**
     * {@inheritDoc}
     */
    public function install(InstalledRepositoryInterface $repo, PackageInterface $package)
    {
        $this->initializeVendorDir();
        $downloadPath = $this->getInstallPath($package);

        // remove the binaries if it appears the package files are missing
        if (!is_readable($downloadPath) && $repo->hasPackage($package)) {
            $this->binaryInstaller->removeBinaries($package);
        }

        $this->installCode($package);
        $this->binaryInstaller->installBinaries($package, $this->getInstallPath($package));
        if (!$repo->hasPackage($package)) {
            $repo->addPackage(clone $package);
        }
    }

    /**
     * {@inheritDoc}
     */
    public function update(InstalledRepositoryInterface $repo, PackageInterface $initial, PackageInterface $target)
    {
        if (!$repo->hasPackage($initial)) {
            throw new \InvalidArgumentException('Package is not installed: '.$initial);
        }

        $this->initializeVendorDir();

        $this->binaryInstaller->removeBinaries($initial);
        $this->updateCode($initial, $target);
        $this->binaryInstaller->installBinaries($target, $this->getInstallPath($target));
        $repo->removePackage($initial);
        if (!$repo->hasPackage($target)) {
            $repo->addPackage(clone $target);
        }
    }

    /**
     * {@inheritDoc}
     */
    public function uninstall(InstalledRepositoryInterface $repo, PackageInterface $package)
    {
        if (!$repo->hasPackage($package)) {
            throw new \InvalidArgumentException('Package is not installed: '.$package);
        }

        $this->removeCode($package);
        $this->binaryInstaller->removeBinaries($package);
        $repo->removePackage($package);

        $downloadPath = $this->getPackageBasePath($package);
        if (strpos($package->getName(), '/')) {
            $packageVendorDir = dirname($downloadPath);
            if (is_dir($packageVendorDir) && $this->filesystem->isDirEmpty($packageVendorDir)) {
                Silencer::call('rmdir', $packageVendorDir);
            }
        }
    }

    /**
     * {@inheritDoc}
     */
    public function getInstallPath(PackageInterface $package)
    {
        $this->initializeVendorDir();

        $basePath = ($this->vendorDir ? $this->vendorDir.'/' : '') . $package->getPrettyName();
        $targetDir = $package->getTargetDir();

        return $basePath . ($targetDir ? '/'.$targetDir : '');
    }

    /**
     * Make sure binaries are installed for a given package.
     *
     * @param PackageInterface $package Package instance
     */
    public function ensureBinariesPresence(PackageInterface $package)
    {
        $this->binaryInstaller->installBinaries($package, $this->getInstallPath($package), false);
    }

    /**
     * Returns the base path of the package without target-dir path
     *
     * It is used for BC as getInstallPath tends to be overridden by
     * installer plugins but not getPackageBasePath
     *
     * @param  PackageInterface $package
     * @return string
     */
    protected function getPackageBasePath(PackageInterface $package)
    {
        $installPath = $this->getInstallPath($package);
        $targetDir = $package->getTargetDir();

        if ($targetDir) {
            return preg_replace('{/*'.str_replace('/', '/+', preg_quote($targetDir)).'/?$}', '', $installPath);
        }

        return $installPath;
    }

    protected function installCode(PackageInterface $package)
    {
        $downloadPath = $this->getInstallPath($package);
        $this->downloadManager->download($package, $downloadPath);
    }

    protected function updateCode(PackageInterface $initial, PackageInterface $target)
    {
        $initialDownloadPath = $this->getInstallPath($initial);
        $targetDownloadPath = $this->getInstallPath($target);
        if ($targetDownloadPath !== $initialDownloadPath) {
            // if the target and initial dirs intersect, we force a remove + install
            // to avoid the rename wiping the target dir as part of the initial dir cleanup
            if (substr($initialDownloadPath, 0, strlen($targetDownloadPath)) === $targetDownloadPath
                || substr($targetDownloadPath, 0, strlen($initialDownloadPath)) === $initialDownloadPath
            ) {
                $this->removeCode($initial);
                $this->installCode($target);

                return;
            }

            $this->filesystem->rename($initialDownloadPath, $targetDownloadPath);
        }
        $this->downloadManager->update($initial, $target, $targetDownloadPath);
    }

    protected function removeCode(PackageInterface $package)
    {
        $downloadPath = $this->getPackageBasePath($package);
        $this->downloadManager->remove($package, $downloadPath);
    }

    protected function initializeVendorDir()
    {
        $this->filesystem->ensureDirectoryExists($this->vendorDir);
        $this->vendorDir = realpath($this->vendorDir);
    }
}


text:
class GcovUtil

	# check, eg: src#xcp#XcpProcessor.o##..#^#Logger#include#logger#Logger.h.gcov
	# for containing "#^#"
	def GcovUtil.isExternGcovFile(gcovFile)

		return File.basename(gcovFile).index("#^#") != nil
	end

	# extract extern gcof-file, eg: src#xcp#XcpProcessor.o##..#^#Logger#include#logger#Logger.h.gcov
	# to "Logger"
	def GcovUtil.getProjectName(gcovFile)

		if isExternGcovFile(gcovFile) then
			return File.basename(gcovFile).split("##")[1].split("#")[2]
		else
			raise "no extern-gcov: "+gcovFile
		end
	end

	# extract intern gcof-file, eg: src#xcp#XcpProcessor.o##..#include#xcp#XcpPacket.h.gcov
	# to include/xcp/XcpPacket.h
	# extract extern gcof-file, eg: src#xcp#XcpProcessor.o##..#^#Logger#include#logger#Logger.h.gcov
	# to ../Logger/include/logger/Logger.h
	def GcovUtil.getSourcePath(gcovFile)

		return File.basename(gcovFile).split("##")[1].gsub(/\^/, "..").gsub(/\#/, "/").chomp(".gcov").reverse.chomp("/..").reverse
	end

	# extract gcof-file, eg: src#xcp#XcpProcessor.o##..#include#xcp#XcpPacket.h.gcov
	# to src/xcp/XcpProcessor.o
	def GcovUtil.getObjectPath(gcovFile)

		return File.basename(gcovFile).split("##")[0].gsub(/\#/, "/")
	end
end


text:
IF (EXISTS (SELECT *
            FROM INFORMATION_SCHEMA.TABLES
            WHERE TABLE_SCHEMA = '${ohdsiSchema}'
            AND  TABLE_NAME = 'CONCEPT_SET_NEGATIVE_CONTROLS'))
BEGIN
    DROP TABLE [${ohdsiSchema}].[CONCEPT_SET_NEGATIVE_CONTROLS];
END

IF (EXISTS (SELECT *
						FROM sys.objects
					  WHERE name = 'negative_controls_sequence'))
BEGIN
	DROP SEQUENCE ${ohdsiSchema}.negative_controls_sequence;
END

CREATE SEQUENCE ${ohdsiSchema}.negative_controls_sequence;
CREATE TABLE ${ohdsiSchema}.CONCEPT_SET_NEGATIVE_CONTROLS (
    id int NOT NULL DEFAULT (NEXT VALUE FOR ${ohdsiSchema}.negative_controls_sequence),
		evidence_job_id BIGINT NOT NULL,
    source_id INTEGER NOT NULL,
    concept_set_id INTEGER NOT NULL,
    concept_set_name varchar(255) NOT NULL,
		negative_control INTEGER NOT NULL,
    concept_id INTEGER NOT NULL,
    concept_name varchar(255) NOT NULL,
    domain_id varchar(255) NOT NULL,
    sort_order bigint,
    descendant_pmid_cnt BIGINT,
    exact_pmid_cnt BIGINT,
    parent_pmid_cnt BIGINT,
    ancestor_pmid_cnt BIGINT,
    ind_ci INTEGER,
    too_broad INTEGER,
    drug_induced INTEGER,
    pregnancy INTEGER,
    descendant_splicer_cnt BIGINT,
    exact_splicer_cnt BIGINT,
    parent_splicer_cnt BIGINT,
    ancestor_splicer_cnt BIGINT,
    descendant_faers_cnt BIGINT,
    exact_faers_cnt BIGINT,
    parent_faers_cnt BIGINT,
    ancestor_faers_cnt BIGINT,
    user_excluded INTEGER,
    user_included INTEGER,
    optimized_out INTEGER,
    not_prevalent INTEGER
		CONSTRAINT [PK_CONCEPT_SET_NC] PRIMARY KEY CLUSTERED
		 (
			 [id] ASC
		 ) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
);


text:
package cluster

import (
	"flag"

	"golang.org/x/net/context"

	"github.com/vmware/govmomi/govc/cli"
	"github.com/vmware/govmomi/govc/flags"
	"github.com/vmware/govmomi/object"
	"github.com/vmware/govmomi/vim25/types"
)

type create struct {
	*flags.DatacenterFlag

	parent string

	types.ClusterConfigSpecEx
}

func init() {
	cli.Register("cluster.create", &create{})
}

func (cmd *create) Register(f *flag.FlagSet) {
	f.StringVar(&cmd.parent, "parent", "", "Path to parent folder for the new cluster")
}

func (cmd *create) Usage() string {
	return "CLUSTER"
}

func (cmd *create) Description() string {
	return `Create CLUSTER in datacenter.

The cluster is added to the folder specified by the 'parent' flag. If not given,
this defaults to the hosts folder in the specified or default datacenter.`
}

func (cmd *create) Process() error { return nil }

func (cmd *create) Run(f *flag.FlagSet) error {
	ctx := context.TODO()
	var parent *object.Folder

	if f.NArg() != 1 {
		return flag.ErrHelp
	}

	if cmd.parent == "" {
		dc, err := cmd.Datacenter()
		if err != nil {
			return err
		}

		folders, err := dc.Folders(ctx)
		if err != nil {
			return err
		}

		parent = folders.HostFolder
	} else {
		finder, err := cmd.Finder()
		if err != nil {
			return err
		}

		parent, err = finder.Folder(ctx, cmd.parent)
		if err != nil {
			return err
		}
	}

	_, err := parent.CreateCluster(ctx, f.Arg(0), cmd.ClusterConfigSpecEx)
	if err != nil {
		return err
	}

	return nil
}


text:
  <link rel="stylesheet" href="jquery-ui-1.10.4.custom.min.css" type="text/css" />

Init Game World

				save to db

				<textarea id="db-data"></textarea>

				insert to ksession

				<textarea id="ksession-data"></textarea>

Perform Actions

Actions

				load actions

					no data

Advances

				load advances

					no data

City Improvements

				load city improvements

					no data

Cities

				load cities

					no data

Governments

				load governments

					no data

Players

				load players

					no data

Specials

				load specials

					no data

Terrains

				load terrains

					no data

Tiles

				load tiles

					no data

Tile Improvements

				load tile improvements

					no data

Units

				load units

					no data

UnitTypes

				load unittypes

					no data

hej


text:
import React, { Component } from 'react';
import { Provider } from 'react-redux';
import '../I18n/I18n';

import RootContainer from './RootContainer';
import { createStore } from '../Redux';
import applyConfigSettings from '../Config';

applyConfigSettings();
const store = createStore();

class App extends Component {
  render() {
    return (
      <Provider store={store}>
        <RootContainer />
      </Provider>
    );
  }
}

export default App;


text:
<?php require_once __DIR__ . '/../vendor/autoload.php';

use ohmy\Auth1;

# initialize 3-legged oauth
$twitter = Auth1::legs(3)

                # configuration
                ->set(array(
                    'key'      => 'your consumer key',
                    'secret'   => 'your consumer secret',
                    'callback' => 'your callback url'
                ))

                # oauth flow
                ->request('https://api.twitter.com/oauth/request_token')
                ->authorize('https://api.twitter.com/oauth/authorize')
                ->access('https://api.twitter.com/oauth/access_token');

# test GET call
$twitter->GET('https://api.twitter.com/1.1/statuses/home_timeline.json', array('count' => 5))
        ->then(function($response) {
            echo '<pre>';
            var_dump($response->json());
            echo '</pre>';
        });


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Run CUDA"
        android:id="@+id/button"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:onClick="doAdd" />
    <LinearLayout
        android:id="@+id/col_titles"
        android:layout_below="@id/button"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">
        <TextView
            android:layout_width="0dp"
            android:textSize="20sp"
            android:layout_weight="0.333"
            android:layout_height="wrap_content"
            android:text="Term 1"/>
        <TextView
            android:layout_width="0dp"
            android:textSize="20sp"
            android:layout_weight="0.333"
            android:layout_height="wrap_content"
            android:text="Term 2"/>
        <TextView
            android:layout_width="0dp"
            android:textSize="20sp"
            android:layout_weight="0.333"
            android:layout_height="wrap_content"
            android:text="Sum"/>
    </LinearLayout>
    <View
        android:layout_below="@id/col_titles"
        android:layout_width="fill_parent"
        android:layout_height="2dip"
        android:background="#4C4C4C"
    />
    <ScrollView
        android:layout_below="@id/col_titles"
        android:layout_width="match_parent"
        android:layout_height="fill_parent"
        android:scrollbarFadeDuration="0">
        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content">
            <LinearLayout
                android:id="@+id/col1"
                android:layout_width="0dp"
                android:layout_weight="0.3333"
                android:orientation="vertical"
                android:layout_height="match_parent">
            </LinearLayout>

            <LinearLayout
                android:id="@+id/col2"
                android:layout_width="0dp"
                android:layout_weight="0.3333"
                android:orientation="vertical"
                android:layout_height="match_parent">
            </LinearLayout>

            <LinearLayout
                android:id="@+id/col3"
                android:layout_width="0dp"
                android:layout_weight="0.3333"
                android:orientation="vertical"
                android:layout_height="match_parent">
            </LinearLayout>
        </LinearLayout>
    </ScrollView>
</RelativeLayout>


text:
package sune.ssp.editor;

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
import sune.ssp.editor.Whisperer.InsertCondItem;
import sune.ssp.editor.Whisperer.InsertItem;
import sune.ssp.editor.Whisperer.InsertTabItem;
import sune.ssp.editor.Whisperer.Item;
import sune.ssp.util.Resource;

public class Window extends Application {

	private Stage stage;
	private Scene scene;
	private Pane pane0;
	private BorderPane pane;
	private Editor editor;
	private Whisperer whisperer;

	private MenuBar menuBar;
	private Menu menuEdit;
	private MenuItem menuItemUndo;
	private MenuItem menuItemRedo;

	private HBox boxBottom;
	private Label lblPosition;

	@Override
	public void start(Stage primaryStage) throws Exception {
		stage = primaryStage;
		pane0 = new Pane();
		pane  = new BorderPane();
		scene = new Scene(pane0, 600, 400);
		scene.getStylesheets().add(
			Resource.stylesheet("/sune/ssp/editor/editor.css"));

		whisperer = new Whisperer();
		editor 	  = new Editor(whisperer);

		menuBar 	 = new MenuBar();
		menuEdit 	 = new Menu("Edit");
		menuItemUndo = new MenuItem("Undo changes");
		menuItemRedo = new MenuItem("Redo changes");

		menuItemUndo.setOnAction((event) -> {
			if(editor.isUndoable()) {
				editor.undo();
				menuItemUndo.setDisable(
					!editor.isUndoable());
			}
		});

		menuItemRedo.setOnAction((event) -> {
			if(editor.isRedoable()) {
				editor.redo();
				menuItemRedo.setDisable(
					!editor.isRedoable());
			}
		});

		editor.textProperty().addListener((o) -> {
			menuItemUndo.setDisable(!editor.isUndoable());
			menuItemRedo.setDisable(!editor.isRedoable());
		});

		menuItemUndo.setDisable(true);
		menuItemRedo.setDisable(true);
		menuEdit.getItems().addAll(menuItemUndo, menuItemRedo);
		menuBar.getMenus().addAll(menuEdit);

		boxBottom   = new HBox(5);
		lblPosition = new Label();

		whisperer.hide();
		whisperer.visibleProperty().addListener((o) -> {
			editor.relocateWhisperer();
		});

		Item[] availableItems = {
			new InsertItem(
				"Send message",
				"send::Message(\"\")", 15),
			new InsertItem(
				"Send status",
				"send::Status(Status::)", 21),
			new InsertTabItem(
				"Prompt to variable",
				"prompt::Dialog(\"\", var::)", 16, 24),
			new InsertItem(
				"Define variable",
				"define(var::)", 12),
			new InsertItem(
				"Require variable",
				"require(var::)", 13),
			new InsertTabItem(
				"Set variable",
				"set(var::, )", 9, 11),
			new InsertTabItem(
				"Simple condition",
				"if  then\n\t\nend", 3, 10),
			// Statuses
			new InsertCondItem(
				"Status 'Disconnected by server'",
				"DISCONNECTED_BY_SERVER",
				"Status::"),
			new InsertCondItem(
				"Status 'Disconnected by user'",
				"DISCONNECTED_BY_USER",
				"Status::"),
			new InsertCondItem(
				"Status 'Disconnected by spam'",
				"DISCONNECTED_BY_SPAM",
				"Status::"),
			new InsertCondItem(
				"Status 'Sucessfully connected'",
				"SUCCESSFULLY_CONNECTED",
				"Status::"),
			new InsertCondItem(
				"Status 'Client already connected'",
				"CLIENT_ALREADY_CONNECTED",
				"Status::"),
			new InsertCondItem(
				"Status 'Server stopped'",
				"SERVER_STOPPED",
				"Status::"),
		};
		whisperer.getItems().addAll(availableItems);
		editor.caretPositionProperty().addListener((o) -> {
			updatePosition();
		});

		boxBottom.setAlignment(Pos.CENTER_RIGHT);
		boxBottom.getChildren().add(lblPosition);

		BorderPane.setMargin(editor, new Insets(10));
		boxBottom.setPadding(new Insets(-5, 10, 5, 10));

		pane.setTop(menuBar);
		pane.setCenter(editor);
		pane.setBottom(boxBottom);
		pane0.getChildren().addAll(pane, whisperer);

		scene.widthProperty().addListener((o) -> resize());
		scene.heightProperty().addListener((o) -> resize());

		stage.setScene(scene);
		stage.setTitle("SSP Editor");
		stage.getIcons().add(
			Resource.image("/gui/icon.png"));
		stage.centerOnScreen();
		stage.show();
		resize();
		updatePosition();
	}

	void resize() {
		pane0.setPrefSize(scene.getWidth(), scene.getHeight());
		pane.setPrefSize(pane0.getWidth(), pane0.getHeight());
	}

	void updatePosition() {
		lblPosition.setText(String.format(
			"line: %d, col: %d",
			editor.getCurrentLine(),
			editor.getCurrentColumn()));
	}

	public static void main(String[] args) {
		launch(args);
	}
}