text:
<?php
namespace cupon\UsuarioBundle\Listener;

use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
use Symfony\Component\Routing\Router;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;

class LoginListener{
	private $ciudad;
	private $router;

	public function __construct(Router $router)
	{
		$this->router = $router;
	}
	public function onSecurityInteractiveLogin(InteractiveLoginEvent $event)
	{
		$token = $event->getAuthenticationToken();
		$this->ciudad = $token->getUser()->getCiudad()->getSlug();
	}

	public function onKernelResponse(FilterResponseEvent $event)
	{
		if (null != $this->ciudad) {
			$portada = "";
			$event->setResponse(new RedirectResponse($portada));
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
chrome.test.runTests([
  function getSelectedPopup() {
    chrome.windows.create(
        {type: 'popup', url: 'about:blank', focused: true},
        chrome.test.callbackPass(function(win) {
      chrome.tabs.query(
          {active: true, windowId: chrome.windows.WINDOW_ID_CURRENT},
          chrome.test.callbackPass(function(tabs) {
        chrome.test.assertEq(1, tabs.length);
        chrome.test.assertTrue(tabs[0].windowId == win.id);
        chrome.test.assertFalse(tabs[0].id == chrome.tabs.TAB_ID_NONE);
      }));
      chrome.windows.getCurrent(
          chrome.test.callbackPass(function(currentWindowData) {
        chrome.test.assertTrue(currentWindowData.id == win.id);
      }));
    }));
  }
]);


text:
package org.radargun.service;

import java.util.regex.Pattern;

/**
 * @author Radim Vansa <rvansa@redhat.com>
 */
public class InfinispanServerLifecycle extends ProcessLifecycle {
   private boolean serverStarted;
   private boolean serverStopped;
   private InfinispanServerService service;
   private final static Pattern START_OK = Pattern.compile(".*\\[org\\.jboss\\.as\\].*started in.*");
   private final static Pattern START_ERROR = Pattern.compile(".*\\[org\\.jboss\\.as\\].*started \\(with errors\\) in.*");
   private final static Pattern STOPPED = Pattern.compile(".*\\[org\\.jboss\\.as\\].*stopped in.*");

   public InfinispanServerLifecycle(final InfinispanServerService service) {
      super(service);
      this.service = service;
   }

   @Override
   public synchronized void start() {
      service.registerAction(START_OK, new Runnable() {
         @Override
         public void run() {
            setServerStarted();
            service.unregisterAction(START_OK);
            service.unregisterAction(START_ERROR);
         }
      });
      service.registerAction(START_ERROR, new Runnable() {
         @Override
         public void run() {
            log.warn("Server started with errors");
            setServerStarted();
            service.unregisterAction(START_OK);
            service.unregisterAction(START_ERROR);
         }
      });
      service.registerAction(STOPPED, new Runnable() {
         @Override
         public void run() {
            log.error("Server stopped before it started!");
            setServerStarted();
            setServerStopped();
            service.unregisterAction(START_OK);
            service.unregisterAction(START_ERROR);
            service.unregisterAction(STOPPED);
         }
      });

      super.start();
      long startTime = System.currentTimeMillis();
      while (!serverStarted) {
         try {
            long waitTime = startTime + service.startTimeout - System.currentTimeMillis();
            if (waitTime <= 0) {
               throw new IllegalStateException("Server did not start within timeout");
            }
            wait(waitTime);
         } catch (InterruptedException e) {
            throw new IllegalStateException("Interrupted waiting for server to start", e);
         }
      }
   }

   @Override
   public synchronized void stop() {
      super.stop();
      // TODO: wait for the server to stop?
      if (outputReader != null) {
         try {
            outputReader.join(60000);
         } catch (InterruptedException e) {
            log.warn("Interrupted waiting for the reader");
            Thread.currentThread().interrupt();
         }
         outputReader = null;
      }
   }

   private synchronized void setServerStarted() {
      serverStarted = true;
      serverStopped = false;
      notifyAll();
   }

   private synchronized void setServerStopped() {
      // no serverStarted = false!
      serverStopped = true;
      notifyAll();
   }

}


text:
namespace dawn {
namespace iir {
class StencilFunctionInstantiation;
class StencilMetaInformation;
} // namespace iir

namespace codegen {
namespace cxxnaiveico {

/// @brief ASTVisitor to generate C++ naive backend code for the parameters of the stencil function
/// calls
/// @ingroup cxxnaiveico
class ASTStencilFunctionParamVisitor : public ast::ASTVisitorDisabled, public NonCopyable {
protected:
  const iir::StencilMetaInformation& metadata_;
  const std::shared_ptr<iir::StencilFunctionInstantiation>& currentFunction_;
  /// Underlying stream
  std::stringstream ss_;

public:
  using Base = ast::ASTVisitorDisabled;

  ASTStencilFunctionParamVisitor(const std::shared_ptr<iir::StencilFunctionInstantiation>& function,
                                 const iir::StencilMetaInformation& metadata);
  virtual ~ASTStencilFunctionParamVisitor();

  std::string getCodeAndResetStream();

  std::string getName(const std::shared_ptr<ast::Expr>& expr) const;

  /// @name Expression implementation
  /// @{
  virtual void visit(const std::shared_ptr<ast::VarAccessExpr>& expr) override;
  virtual void visit(const std::shared_ptr<ast::StencilFunArgExpr>& expr) override;
  virtual void visit(const std::shared_ptr<ast::LiteralAccessExpr>& expr) override;
  virtual void visit(const std::shared_ptr<ast::FieldAccessExpr>& expr) override;
  virtual void visit(const std::shared_ptr<ast::StencilFunCallExpr>& expr) override;
  /// @}
};

} // namespace cxxnaiveico
} // namespace codegen
} // namespace dawn


text:
(function() {
  'use strict';

  angular
    .module('app.dancelist')
    .config(configFunction);

  configFunction.$inject = ['$routeProvider'];

  function configFunction($routeProvider) {
    $routeProvider.when('/dancelist', {
      templateUrl: 'app/dancelist/dancelist.html',
      controller: 'danceListController',
      controllerAs: 'vm',
      resolve: {user: resolveUser}
    });

    $routeProvider.when('/addDanceInfo', {
      templateUrl: 'app/dancelist/directives/addDance.html',
      controller: 'danceListController',
      controllerAs: 'vm',
      resolve: {user: resolveUser}
    });

    $routeProvider.when('/showResult', {
      templateUrl: 'app/dancelist/directives/showResult.html',
      controller: 'danceListController',
      controllerAs: 'vm',
      resolve: {user: resolveUser}
    });
  }

  resolveUser.$inject = ['authService'];

  function resolveUser(authService) {
    return authService.firebaseAuthObject.$requireAuth();
  }

})();


text:
using namespace std;
using namespace cv;

int main(int argc, char *argv[]) {
  cerr << "EasyOCR version 0.1.1" << endl;

  long listenPort = 0;
  string varDirectory = "";
  if (argc >= 2 && Helper::isNumber(argv[1]) ) {
    listenPort = strtol(argv[1], NULL, 0);
  } else {
    cerr << "Please provide port number in the first argument." << endl;
    return 0;
  }

  if (argc >= 3 && boost::filesystem::is_directory(argv[2]) ) {
    varDirectory = argv[2];
  } else {
    cerr << "Please provide var directory in the second argument." << endl;
    return 0;
  }
  PrivConfig::varBasePath = varDirectory;

  cerr << "Load svm data start.." << endl;
  EasyOcr::LoadSVM();
  cerr << "Load svm data finished." << endl;

  cerr << "Server start at port " << listenPort << "." << endl;
  WebServer server(listenPort);
  OcrController ocrController;
  DeleteFileController deleteFileController;
  server.addController(&ocrController);
  server.addController(&deleteFileController);

  if (!server.start()) {
    cerr << "Server start error." << endl;
    return 1;
  }

  cerr << "Server stopped." << endl;
  return 0;
}


text:
package cn.hi.eim.db;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

/**
 * SQLiteÊý¾Ý¿â¹ÜÀíÀà
 *
 * Ö÷Òª¸ºÔðÊý¾Ý¿â×ÊÔ´µÄ³õ'»¯,¿ªÆô,¹Ø±Õ,ÒÔ¼°»ñµÃDatabaseHelper°ïÖúÀà²Ù×÷
 *
 * @author shimiso
 *
 */
public class DBManager {
	private int version = 3;
	private String databaseName;

	// ±¾µØContext¶ÔÏó
	private Context mContext = null;

	private static DBManager dBManager = null;

	/**
	 * ¹¹Ô캯Êý
	 *
	 * @param mContext
	 */
	private DBManager(Context mContext) {
		super();
		this.mContext = mContext;
	}

	public static DBManager getInstance(Context mContext, String databaseName) {
		if (null == dBManager) {
			dBManager = new DBManager(mContext);
		}
		dBManager.databaseName = databaseName;
		return dBManager;
	}

	/**
	 * ¹Ø±ÕÊý¾Ý¿â ×¢Òâ:µ±ÊÂÎñ³É¹¦»òÕßÒ»´ÎÐÔ²Ù×÷Íê±ÏʱºòÔٹرÕ
	 */
	public void closeDatabase(SQLiteDatabase dataBase, Cursor cursor) {
		if (null != dataBase) {
			dataBase.close();
		}
		if (null != cursor) {
			cursor.close();
		}
	}

	/**
	 * ´ò¿ªÊý¾Ý¿â ×¢:SQLiteDatabase×ÊÔ´Ò»µ©±»¹Ø±Õ,¸Ãµ×²ã»áÖØвúÉúÒ»¸öеÄSQLiteDatabase
	 */
	public SQLiteDatabase openDatabase() {
		return getDatabaseHelper().getWritableDatabase();
	}

	/**
	 * »ñÈ¡DataBaseHelper
	 *
	 * @return
	 */
	public DataBaseHelper getDatabaseHelper() {
		return new DataBaseHelper(mContext, this.databaseName, null,
				this.version);
	}

}


text:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace JerryMouse.Repositories
{
    public class EfRepository<T> : IRepository<T> where T : class
    {
        public EfRepository(DbContext context)
        {
            if (context == null)
            {
                throw new ArgumentException("An instance of DbContext is required to use this repository.", "context");
            }

            this.Context = context;
            this.DbSet = this.Context.Set<T>();
        }

        protected IDbSet<T> DbSet { get; set; }

        protected DbContext Context { get; set; }

        public T Add(T entity)
        {
            DbEntityEntry entry = this.Context.Entry(entity);
            if (entry.State != EntityState.Detached)
            {
                //this.DbSet.Attach(entity);
                entry.State = EntityState.Added;
            }
            else
            {
                this.DbSet.Add(entity);
            }

            return entity;
        }

        public T Update(int id, T entity)
        {
            DbEntityEntry entry = this.Context.Entry(entity);
            if (entry.State == EntityState.Detached)
            {
                this.DbSet.Attach(entity);
            }

            entry.State = EntityState.Modified;
            return entity;
        }

        public virtual void Delete(T entity)
        {
            DbEntityEntry entry = this.Context.Entry(entity);
            if (entry.State != EntityState.Deleted)
            {
                entry.State = EntityState.Deleted;
            }
            else
            {
                this.DbSet.Attach(entity);
                this.DbSet.Remove(entity);
            }
        }

        public void Delete(int id)
        {
            var entity = this.Get(id);

            if (entity != null)
            {
                this.Delete(entity);
            }
        }

        public T Get(int id)
        {
            return this.DbSet.Find(id);
        }

        public IQueryable<T> All()
        {
            return this.DbSet;
        }

        public IQueryable<T> Find(Expression<Func<T, bool>> predicate)
        {
            return this.DbSet.Where(predicate);
        }
    }
}


text:
namespace cobalt {
namespace dom {

class NodeListTest : public ::testing::Test {
 protected:
  NodeListTest()
      : dom_stat_tracker_(new DomStatTracker("NodeListTest")),
        html_element_context_(&environment_settings_, NULL, NULL, NULL, NULL,
                              NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
                              NULL, NULL, NULL, dom_stat_tracker_.get(), "",
                              base::kApplicationStateStarted, NULL, NULL),
        document_(new Document(&html_element_context_)) {}

  ~NodeListTest() override {}

  testing::StubEnvironmentSettings environment_settings_;
  std::unique_ptr<DomStatTracker> dom_stat_tracker_;
  HTMLElementContext html_element_context_;
  scoped_refptr<Document> document_;
};

TEST_F(NodeListTest, NodeListTest) {
  scoped_refptr<NodeList> node_list = new NodeList();
  EXPECT_EQ(0, node_list->length());

  node_list->AppendNode(document_->CreateElement("div"));
  node_list->AppendNode(document_->CreateElement("div"));
  node_list->AppendNode(document_->CreateElement("div"));
  EXPECT_EQ(3, node_list->length());
  EXPECT_TRUE(node_list->Item(0));
  EXPECT_TRUE(node_list->Item(1));
  EXPECT_TRUE(node_list->Item(2));
  EXPECT_FALSE(node_list->Item(3));
}
}  // namespace dom
}  // namespace cobalt


text:
class Main : public CBase_Main {
public:
	Main(CkArgMsg *msg);
	Main(CkMigrateMessage *msg);
};


text:
@class GTDiffLine;
@class GTDiffPatch;

/// A class representing a hunk within a diff patch.
@interface GTDiffHunk : NSObject

/// The header of the hunk.
@property (nonatomic, readonly, copy) NSString *header;

/// The number of lines represented in the hunk.
@property (nonatomic, readonly) NSUInteger lineCount;

/// Designated initialiser.
///
/// The contents of a hunk are lazily loaded, therefore we initialise the object
/// simply with the patch it originates from and which hunk index it represents.
- (instancetype)initWithPatch:(GTDiffPatch *)patch hunkIndex:(NSUInteger)hunkIndex NS_DESIGNATED_INITIALIZER;

/// Perfoms the given block on each line in the hunk.
///
/// Note that this method blocks during the enumeration.
///
/// error - A pointer to an NSError that will be set if one occurs.
/// block - A block to execute on each line. Setting `stop` to `NO` will
///         immediately stop the enumeration and return from the method.
/// Return YES if the enumeration was successful, NO otherwise (and an error will
/// be set in `error`).
- (BOOL)enumerateLinesInHunk:(NSError **)error usingBlock:(void (^)(GTDiffLine *line, BOOL *stop))block;

@end


text:
<?php

namespace RectorPrefix20210615\TYPO3\CMS\Extbase\Mvc;

if (\class_exists('TYPO3\\CMS\\Extbase\\Mvc\\Response')) {
    return;
}
class Response
{
}


text:
<?php

namespace Minhbang\Image;

use Laracasts\Presenter\PresentableTrait;
use Minhbang\Kit\Extensions\Model;
use Minhbang\Kit\Traits\Model\DatetimeQuery;
use Minhbang\Kit\Traits\Model\SearchQuery;
use Minhbang\User\Support\HasOwner;
use Minhbang\Tag\Taggable;

/**
 * Class ImageModel
 *
 * @package Minhbang\Image
 * @property integer $id
 * @property string $title
 * @property string $filename
 * @property integer $width
 * @property integer $height
 * @property string $mime
 * @property integer $size
 * @property integer $used
 * @property integer $user_id
 * @property \Carbon\Carbon $created_at
 * @property \Carbon\Carbon $updated_at
 * @property-read mixed $type
 * @property-read string $src
 * @property-read string $path
 * @property-read string $thumb
 * @property-read string $thumb_path
 * @property-read string $thumb_4x
 * @property-read string $thumb_4x_path
 * @property-read string $small
 * @property-read string $small_path
 * @property-read string $resource_name
 * @property-read \Minhbang\User\User $user
 * @method static \Illuminate\Database\Query\Builder|\Minhbang\Image\Image whereId( $value )
 * @method static \Illuminate\Database\Query\Builder|\Minhbang\Image\Image whereTitle( $value )
 * @method static \Illuminate\Database\Query\Builder|\Minhbang\Image\Image whereFilename( $value )
 * @method static \Illuminate\Database\Query\Builder|\Minhbang\Image\Image whereWidth( $value )
 * @method static \Illuminate\Database\Query\Builder|\Minhbang\Image\Image whereHeight( $value )
 * @method static \Illuminate\Database\Query\Builder|\Minhbang\Image\Image whereMime( $value )
 * @method static \Illuminate\Database\Query\Builder|\Minhbang\Image\Image whereSize( $value )
 * @method static \Illuminate\Database\Query\Builder|\Minhbang\Image\Image whereUsed( $value )
 * @method static \Illuminate\Database\Query\Builder|\Minhbang\Image\Image whereUserId( $value )
 * @method static \Illuminate\Database\Query\Builder|\Minhbang\Image\Image whereCreatedAt( $value )
 * @method static \Illuminate\Database\Query\Builder|\Minhbang\Image\Image whereUpdatedAt( $value )
 * @method static \Illuminate\Database\Query\Builder|\Minhbang\Kit\Extensions\Model except( $id = null )
 * @method static \Illuminate\Database\Query\Builder|\Minhbang\Image\Image related()
 * @method static \Illuminate\Database\Query\Builder|\Minhbang\Image\Image orderByMatchedTag( $tagNames, $direction = 'desc' )
 * @method static \Illuminate\Database\Query\Builder|\Minhbang\Image\Image withAllTags( $tagNames )
 * @method static \Illuminate\Database\Query\Builder|\Minhbang\Image\Image withAnyTag( $tagNames )
 * @method static \Illuminate\Database\Query\Builder|\Minhbang\Image\Image orderCreated( $direction = 'desc' )
 * @method static \Illuminate\Database\Query\Builder|\Minhbang\Image\Image orderUpdated( $direction = 'desc' )
 * @method static \Illuminate\Database\Query\Builder|\Minhbang\Image\Image period( $start = null, $end = null, $field = 'created_at', $end_if_day = false, $is_month = false )
 * @method static \Illuminate\Database\Query\Builder|\Minhbang\Image\Image today( $field = 'created_at' )
 * @method static \Illuminate\Database\Query\Builder|\Minhbang\Image\Image yesterday( $same_time = false, $field = 'created_at' )
 * @method static \Illuminate\Database\Query\Builder|\Minhbang\Image\Image thisWeek( $field = 'created_at' )
 * @method static \Illuminate\Database\Query\Builder|\Minhbang\Image\Image thisMonth( $field = 'created_at' )
 * @method static \Illuminate\Database\Query\Builder|\Minhbang\Image\Image notMine()
 * @method static \Illuminate\Database\Query\Builder|\Minhbang\Image\Image mine()
 * @method static \Illuminate\Database\Query\Builder|\Minhbang\Image\Image withAuthor()
 * @method static \Illuminate\Database\Query\Builder|\Minhbang\Image\Image searchWhere( $column, $operator = '=', $fn = null )
 * @method static \Illuminate\Database\Query\Builder|\Minhbang\Image\Image searchWhereIn( $column, $fn )
 * @method static \Illuminate\Database\Query\Builder|\Minhbang\Image\Image searchWhereBetween( $column, $fn = null )
 * @method static \Illuminate\Database\Query\Builder|\Minhbang\Image\Image searchWhereInDependent( $column, $column_dependent, $fn, $empty = [] )
 */
class Image extends Model {
    use Taggable;
    use PresentableTrait;
    use DatetimeQuery;
    use HasOwner;
    use SearchQuery;

    protected $presenter = Presenter::class;
    protected $table = 'images';
    protected $fillable = [ 'title', 'filename', 'width', 'height', 'mime', 'size', 'used', 'user_id', 'tag_names' ];

    /**
     * getter $model->type
     *
     * @return string
     */
    public function getTypeAttribute() {
        return $this->mime ? config( "image.mime_types.{$this->mime}" ) : null;
    }

    /**
     * getter $model->src
     *
     * @return string
     */
    public function getSrcAttribute() {
        return $this->getPath( 'images', false );
    }

    /**
     * getter $model->path
     *
     * @return string
     */
    public function getPathAttribute() {
        return $this->getPath( 'images', true );
    }

    /**
     * getter $model->thumb
     *
     * @return string
     */
    public function getThumbAttribute() {
        return $this->getPath( 'thumbs', false );
    }

    /**
     * getter $model->thumb_path
     *
     * @return string
     */
    public function getThumbPathAttribute() {
        return $this->getPath( 'thumbs', true );
    }

    /**
     * getter $model->thumb_4x
     *
     * @return string
     */
    public function getThumb4xAttribute() {
        return $this->getPath( 'thumbs-4x', false );
    }

    /**
     * getter $model->thumb_4x_path
     *
     * @return string
     */
    public function getThumb4xPathAttribute() {
        return $this->getPath( 'thumbs-4x', true );
    }

    /**
     * getter $model->small
     *
     * @return string
     */
    public function getSmallAttribute() {
        return $this->getPath( 'smalls', false );
    }

    /**
     * getter $model->small_path
     *
     * @return string
     */
    public function getSmallPathAttribute() {
        return $this->getPath( 'smalls', true );
    }

    /**
     * Lấy một số attributes, trả về dạng array
     * vd: $select = ['id', 'tag' => 'tag_names']
     * trả về ['id' => $image->id, 'tag' => $images->tag_names]
     *
     * @param array $select
     *
     * @return array
     */
    public function arrayAttributes( $select = [] ) {
        $array = [];
        foreach ( $select as $key => $attr ) {
            $array[is_numeric( $key ) ? $attr : $key] = $this->present()->$attr;
        }

        return $array;
    }

    /**
     * @param string $of
     * @param bool $full
     *
     * @return null|string
     */
    protected function getPath( $of, $full ) {
        if ( $user = $this->user ) {
            return $user->upload_path( $of, $full ) . '/' . $this->filename;
        } else {
            return null;
        }
    }

    /**
     * Hook các events của model
     *
     * @return void
     */
    public static function boot() {
        parent::boot();
        // trước khi xóa $image trong DB, xóa 2 hình ảnh của nó
        static::deleting(
            function ( Image $model ) {
                @unlink( $model->getPathAttribute() );
                @unlink( $model->getThumbPathAttribute() );
                @unlink( $model->getThumb4xPathAttribute() );
                @unlink( $model->getSmallPathAttribute() );
            }
        );
    }
}


text:
// Copyright 2000-2022 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.editor;

import com.intellij.openapi.Disposable;
import com.intellij.openapi.editor.event.CaretListener;
import com.intellij.openapi.editor.markup.TextAttributes;
import com.intellij.openapi.util.Disposer;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.List;

/**
 * Provides services for moving the caret and retrieving information about caret position.
 *

 * May support several carets existing simultaneously in a document. {@link #supportsMultipleCarets()} method can be used to find out
 * whether a particular instance of CaretModel does it. If it does, query and update methods for caret position operate on a certain 'primary'
 * caret. There exists a way to perform the same operation(s) on each caret - see
 * {@link #runForEachCaret(CaretAction)} method. Within its context, query and update methods operate on the
 * current caret in that iteration. This behaviour can change in future though, so using caret and selection query and update methods in
 * actions that need to operate on multiple carets is discouraged - methods on {@link Caret} instances obtained
 * via {@link #getAllCarets()} or {@link #runForEachCaret(CaretAction)} should be used instead.
 *

 * How 'primary' caret is determined by the model is not defined (currently it's the most recently added caret, but that can change).
 *

 * At all times, at least one caret will exist in a document.
 *

 * Update methods, {@link #runBatchCaretOperation(Runnable)} and {@link #runForEachCaret(CaretAction)} methods
 * should only be run from EDT. Query methods can be run from any thread; when called not from EDT, those methods are 'not aware' of
 * 'runForEachCaret' scope - they will always return information about primary caret.
 *
 * @see Editor#getCaretModel()
 */
public interface CaretModel {
  /**
   * Moves the caret by the specified number of lines and/or columns.
   *
   * @param columnShift    the number of columns to move the caret by.
   * @param lineShift      the number of lines to move the caret by.
   * @param withSelection  if true, the caret move should extend the selection range in the document.
   * @param blockSelection This parameter is currently ignored.
   * @param scrollToCaret  if true, the document should be scrolled so that the caret is visible after the move.
   */
  default void moveCaretRelatively(int columnShift,
                                   int lineShift,
                                   boolean withSelection,
                                   boolean blockSelection,
                                   boolean scrollToCaret) {
    getCurrentCaret().moveCaretRelatively(columnShift, lineShift, withSelection, scrollToCaret);
  }

  /**
   * Moves the caret to the specified logical position.
   * If the corresponding position is in the folded region currently, the region will be expanded.
   *
   * @param pos the position to move to.
   */
  default void moveToLogicalPosition(@NotNull LogicalPosition pos) {
    getCurrentCaret().moveToLogicalPosition(pos);
  }

  /**
   * Moves the caret to the specified visual position.
   *
   * @param pos the position to move to.
   */
  default void moveToVisualPosition(@NotNull VisualPosition pos) {
    getCurrentCaret().moveToVisualPosition(pos);
  }

  /**
   * Shorthand for calling {@link #moveToOffset(int, boolean)} with {@code 'false'} as a second argument.
   *
   * @param offset the offset to move to
   */
  default void moveToOffset(int offset) {
    moveToOffset(offset, false);
  }

  /**
   * Moves the caret to the specified offset in the document.
   * If the corresponding position is in the folded region currently, the region will be expanded.
   *
   * @param offset               the offset to move to.
   * @param locateBeforeSoftWrap there is a possible case that there is a soft wrap at the given offset, hence, the same offset
   *                             corresponds to two different visual positions - just before soft wrap and just after soft wrap.
   *                             We may want to clearly indicate where to put the caret then. Given parameter allows to do that.
   *                             Note: it's ignored if there is no soft wrap at the given offset
   */
  default void moveToOffset(int offset, boolean locateBeforeSoftWrap) {
    getCurrentCaret().moveToOffset(offset, locateBeforeSoftWrap);
  }

  /**
   * Tells whether the caret model is currently in a consistent state.
   * This might not be the case during document update, but client code can
   * observe such a state only in specific circumstances.
   * So unless you're implementing very low-level editor logic (involving
   * {@code PrioritizedDocumentListener}), you don't need this method - you'll only see it return {@code true}.
   */
  default boolean isUpToDate() {
    return getCurrentCaret().isUpToDate();
  }

  /**
   * Returns the logical position of the caret.
   *
   * @return the caret position.
   */
  @NotNull
  default LogicalPosition getLogicalPosition() {
    return getCurrentCaret().getLogicalPosition();
  }

  /**
   * Returns the visual position of the caret.
   *
   * @return the caret position.
   */
  @NotNull
  default VisualPosition getVisualPosition() {
    return getCurrentCaret().getVisualPosition();
  }

  /**
   * Returns the offset of the caret in the document.
   *
   * @return the caret offset.
   */
  default int getOffset() {
    return getCurrentCaret().getOffset();
  }

  /**
   * Adds a listener for receiving notifications about caret movement and caret addition/removal.
   *
   * @param listener the listener instance.
   */
  void addCaretListener(@NotNull CaretListener listener);

  /**
   * Adds a listener for receiving notifications about caret movement and caret addition/removal.
   * The listener is removed when the given parent disposable is disposed.
   *
   * @param listener the listener instance.
   */
  default void addCaretListener(@NotNull CaretListener listener, @NotNull Disposable parentDisposable) {
    addCaretListener(listener);
    Disposer.register(parentDisposable, () -> removeCaretListener(listener));
  }

  /**
   * Removes a listener for receiving notifications about caret movement and caret addition/removal.
   *
   * @param listener the listener instance.
   */
  void removeCaretListener(@NotNull CaretListener listener);

  /**
   * @return document offset for the start of the logical line where the caret is located
   */
  default int getVisualLineStart() {
    return getCurrentCaret().getVisualLineStart();
  }

  /**
   * @return document offset that points to the first symbol shown at the next visual line after the one with the caret on it
   */
  default int getVisualLineEnd() {
    return getCurrentCaret().getVisualLineEnd();
  }

  /**
   * Returns visual representation of caret (e.g., background color).
   *
   * @return Caret attributes.
   */
  TextAttributes getTextAttributes();

  /**
   * Tells whether multiple coexisting carets are supported by this CaretModel instance.
   * Multiple carets are not supported when the corresponding Editor instance is a facade over a Swing JTextArea component.
   */
  boolean supportsMultipleCarets();

  /**
   * Maximum number of carets that can be created in the editor.
   */
  int getMaxCaretCount();

  /**
   * Returns current caret - the one query and update methods in the model operate at the moment.
   * In the current implementation this is either an iteration-current caret within the context of
   * {@link #runForEachCaret(CaretAction)} method, or the 'primary' caret without that context.
   *

   * Users {@link #runForEachCaret(CaretAction)} method should use caret parameter passed to
   * {@link CaretAction#perform(Caret)} method instead of this method, as the definition of current caret (as
   * well as caret instance operated on by model methods) can potentially change.
   */
  @NotNull
  Caret getCurrentCaret();

  /**
   * Returns the 'primary' caret.
   */
  @NotNull
  Caret getPrimaryCaret();

  /**
   * Returns number of carets currently existing in the document.
   */
  int getCaretCount();

  /**
   * Returns all carets currently existing in the document, ordered by their visual position in editor.
   * Use {@link #getCaretCount()} if you only need to know the number of carets, it's much faster.
   */
  @NotNull
  List<Caret> getAllCarets();

  /**
   * Returns a caret at the given position in the document, or {@code null}, if there's no caret there.
   */
  @Nullable
  Caret getCaretAt(@NotNull VisualPosition pos);

  /**
   * Same as {@link #addCaret(VisualPosition, boolean)} with {@code true} as a {@code makePrimary} boolean parameter value.
   */
  @Nullable
  default Caret addCaret(@NotNull VisualPosition pos) {
    return addCaret(pos, true);
  }

  /**
   * Adds a new caret at the given position, and returns corresponding {@link Caret} instance.
   * Locations outside of possible values for the given document are trimmed automatically.
   * Newly added caret will become a primary caret if and only if {@code makePrimary} value is {@code true}.
   * Does nothing if multiple carets are not supported, a maximum number of carets already exists in editor (see
   * {@link #getMaxCaretCount()}), a caret already exists at specified location or selection of existing caret
   * includes the specified location, {@code null} is returned in this case.
   */
  @Nullable
  Caret addCaret(@NotNull VisualPosition pos, boolean makePrimary);

  /**
   * Adds a new caret at the given position, and returns corresponding {@link Caret} instance.
   * Locations outside of possible values for the given document are trimmed automatically.
   * Newly added caret will become a primary caret if and only if {@code makePrimary} value is {@code true}.
   * Does nothing if multiple carets are not supported, a maximum number of carets already exists in editor (see
   * {@link #getMaxCaretCount()}), a caret already exists at specified location or selection of existing caret
   * includes the specified location, {@code null} is returned in this case.
   */
  @Nullable
  Caret addCaret(@NotNull LogicalPosition pos, boolean makePrimary);

  /**
   * Removes a given caret if it's recognized by the model and is not the only existing caret in the document, returning {@code true}.
   * {@code false} is returned if any of the above condition doesn't hold, and the removal cannot happen.
   */
  boolean removeCaret(@NotNull Caret caret);

  /**
   * Removes all carets except the 'primary' one from the document.
   */
  void removeSecondaryCarets();

  /**
   * Sets the number of carets, their positions and selection ranges according to the provided data.
   * Null values for caret position or selection boundaries will mean that corresponding caret's position and/or selection won't be changed.
   *

   * If the number of passed {@link CaretState} items is larger than {@link #getMaxCaretCount()}, excessive items will be ignored.
   * Editor might display a user-visible notification in such a case.
   *

   * System selection will be updated, if supported by the current editor.
   *
   * @throws IllegalArgumentException if {@code caretStates} list is empty
   * @see #supportsMultipleCarets()
   * @see #getCaretsAndSelections()
   * @see #setCaretsAndSelections(List, boolean)
   */
  void setCaretsAndSelections(@NotNull List<? extends CaretState> caretStates);

  /**
   * Sets the number of carets, their positions and selection ranges according to the provided data.
   * Null values for caret position or selection boundaries will mean that corresponding caret's position and/or selection won't be changed.
   *

   * If the number of passed {@link CaretState} items is larger than {@link #getMaxCaretCount()}, excessive items will be ignored.
   * Editor might display a user-visible notification in such a case.
   *

   * System selection will be updated, if supported by the current editor
   * and corresponding invocation parameter is set to {@code true}.
   *
   * @throws IllegalArgumentException if {@code caretStates} list is empty
   * @see #supportsMultipleCarets()
   * @see #getCaretsAndSelections()
   */
  void setCaretsAndSelections(@NotNull List<? extends CaretState> caretStates, boolean updateSystemSelection);

  /**
   * Returns the current positions of all carets and their selections.
   * The order of entries in the returned list does not necessarily correspond to the order of {@link #getAllCarets()} method results.
   * Passing the result of this method to {@link #setCaretsAndSelections(List)} will restore the state of carets, including the internal
   * caret order, in particular, the caret that was primary when this method was called will be the primary one after corresponding
   * {@link #setCaretsAndSelections(List)} invocation.
   *
   * @see #setCaretsAndSelections(List)
   */
  @NotNull
  List<CaretState> getCaretsAndSelections();

  /**
   * Same as {@link #runForEachCaret(CaretAction, boolean)} with {@code reverseOrder} set to {@code false}
   */
  void runForEachCaret(@NotNull CaretAction action);

  /**
   * Executes the given task for each existing caret.
   * Set of carets to iterate over is determined in the beginning and is not affected by the potential carets addition or removal by the
   * task being executed.
   * At the end, merging of carets and selections is performed, so that no two carets will occur at the same logical position and
   * no two selections will overlap after this method is finished.
   *

   * Carets are iterated in position order (top-to-bottom) if {@code reverseOrder} is {@code false}, and in reverse order
   * if it's {@code true}.
   *

   * It's possible to call this method not from EDT (for read-only operations).
   * Caret merging is not performed in this case, and no notifications to {@link CaretActionListener}-s are sent.
   */
  void runForEachCaret(@NotNull CaretAction action, boolean reverseOrder);

  /**
   * Adds a listener which will be notified before and after all-caret operations are performed by {@link #runForEachCaret(CaretAction)} and
   * {@link #runForEachCaret(CaretAction, boolean)}.
   * Listeners will be notified only if those methods are invoked from EDT (non-EDT invocations are not allowed to change caret state anyway).
   */
  void addCaretActionListener(@NotNull CaretActionListener listener, @NotNull Disposable disposable);

  /**
   * Executes the given task, performing caret merging afterwards. Caret merging will not happen until the operation is finished.
   */
  void runBatchCaretOperation(@NotNull Runnable runnable);
}


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

using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Management.Automation;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.WindowsAzure.Commands.SqlDatabase.Test.UnitTests.MockServer;
using Microsoft.WindowsAzure.Commands.Test.Utilities.Common;

namespace Microsoft.WindowsAzure.Commands.SqlDatabase.Test.UnitTests.Database.Cmdlet
{
    [TestClass]
    public class NewAzureSqlPremiumDatabaseTests : TestBase
    {
        [TestCleanup]
        public void CleanupTest()
        {
            // Remove the test databases
            NewAzureSqlPremiumDatabaseTests.RemoveTestDatabasesWithSqlAuth();

            // Save the mock session results
            MockServerHelper.SaveDefaultSessionCollection();
        }

        /// <summary>
        /// Create $premiumDB on the given context.
        /// </summary>
        /// <param name="powershell">The powershell instance containing the context.</param>
        /// <param name="contextVariable">The variable name that holds the server context.</param>
        [TestMethod]
        public void CreatePremiumDatabasesWithSqlAuth()
        {
            using (System.Management.Automation.PowerShell powershell =
                System.Management.Automation.PowerShell.Create())
            {
                NewAzureSqlDatabaseServerContextTests.CreateServerContextSqlAuth(
                    powershell,
                    "$context");
                HttpSession testSession = MockServerHelper.DefaultSessionCollection.GetSession(
                    "UnitTest.Common.CreatePremiumDatabasesWithSqlAuth");
                DatabaseTestHelper.SetDefaultTestSessionSettings(testSession);
                testSession.RequestValidator =
                    new Action<HttpMessage, HttpMessage.Request>(
                    (expected, actual) =>
                    {
                        Assert.AreEqual(expected.RequestInfo.Method, actual.Method);
                        Assert.AreEqual(expected.RequestInfo.UserAgent, actual.UserAgent);
                    });

                using (AsyncExceptionManager exceptionManager = new AsyncExceptionManager())
                {
                    Collection<PSObject> premiumDB_P1, PremiumDB_P2;
                    using (new MockHttpServer(
                        exceptionManager,
                        MockHttpServer.DefaultServerPrefixUri,
                        testSession))
                    {
                        powershell.InvokeBatchScript(
                            @"$P1 = Get-AzureSqlDatabaseServiceObjective" +
                            @" -Context $context" +
                            @" -ServiceObjectiveName ""P1""");

                        powershell.InvokeBatchScript(
                            @"$P2 = Get-AzureSqlDatabaseServiceObjective " +
                            @"-Context $context" +
                            @" -ServiceObjectiveName ""P2""");

                        premiumDB_P1 = powershell.InvokeBatchScript(
                            @"$premiumDB_P1 = New-AzureSqlDatabase " +
                            @"-Context $context " +
                            @"-DatabaseName NewAzureSqlPremiumDatabaseTests_P1 " +
                            @"-Edition Premium " +
                            @"-ServiceObjective $P1 ");
                        premiumDB_P1 = powershell.InvokeBatchScript("$PremiumDB_P1");

                        powershell.InvokeBatchScript(
                            @"$PremiumDB_P2 = New-AzureSqlDatabase " +
                            @"-Context $context " +
                            @"-DatabaseName NewAzureSqlPremiumDatabaseTests_P2 " +
                            @"-Collation Japanese_CI_AS " +
                            @"-Edition Premium " +
                            @"-ServiceObjective $P2 " +
                            @"-MaxSizeGB 10 " +
                            @"-Force");
                        PremiumDB_P2 = powershell.InvokeBatchScript("$PremiumDB_P2");
                    }

                    Assert.AreEqual(0, powershell.Streams.Error.Count, "Errors during run!");
                    Assert.AreEqual(0, powershell.Streams.Warning.Count, "Warnings during run!");
                    powershell.Streams.ClearStreams();

                    Assert.IsTrue(
                        premiumDB_P1.Single().BaseObject is Services.Server.Database,
                        "Expecting a Database object");
                    Services.Server.Database databaseP1 =
                        (Services.Server.Database)premiumDB_P1.Single().BaseObject;
                    Assert.AreEqual("NewAzureSqlPremiumDatabaseTests_P1", databaseP1.Name, "Expected db name to be NewAzureSqlPremiumDatabaseTests_P1");

                    Assert.IsTrue(
                        PremiumDB_P2.Single().BaseObject is Services.Server.Database,
                        "Expecting a Database object");
                    Services.Server.Database databaseP2 =
                        (Services.Server.Database)PremiumDB_P2.Single().BaseObject;
                    Assert.AreEqual("NewAzureSqlPremiumDatabaseTests_P2", databaseP2.Name, "Expected db name to be NewAzureSqlPremiumDatabaseTests_P2");

                    Assert.AreEqual(
                        "Japanese_CI_AS",
                        databaseP2.CollationName,
                        "Expected collation to be Japanese_CI_AS");
                    Assert.AreEqual("Premium", databaseP2.Edition, "Expected edition to be Premium");
                    Assert.AreEqual(10, databaseP2.MaxSizeGB, "Expected max size to be 10 GB");
                }
            }
        }

        /// <summary>
        /// Helper function to remove the test databases.
        /// </summary>
        public static void RemoveTestDatabasesWithSqlAuth()
        {
            using (System.Management.Automation.PowerShell powershell =
                System.Management.Automation.PowerShell.Create())
            {
                // Create a context
                NewAzureSqlDatabaseServerContextTests.CreateServerContextSqlAuth(
                    powershell,
                    "$context");

                // Remove the 2 test databases
                NewAzureSqlPremiumDatabaseTests.RemoveTestDatabasesWithSqlAuth(
                    powershell,
                    "$context");
            }
        }

        /// <summary>
        /// Removes all existing db which name starting with PremiumTest on the given context.
        /// </summary>
        /// <param name="powershell">The powershell instance containing the context.</param>
        /// <param name="contextVariable">The variable name that holds the server context.</param>
        public static void RemoveTestDatabasesWithSqlAuth(
            System.Management.Automation.PowerShell powershell,
            string contextVariable)
        {
            HttpSession testSession = MockServerHelper.DefaultSessionCollection.GetSession(
                "UnitTest.Common.RemoveTestPremiumDatabasesWithSqlAuth");
            DatabaseTestHelper.SetDefaultTestSessionSettings(testSession);
            testSession.RequestValidator =
                new Action<HttpMessage, HttpMessage.Request>(
                (expected, actual) =>
                {
                    Assert.AreEqual(expected.RequestInfo.Method, actual.Method);
                    Assert.AreEqual(expected.RequestInfo.UserAgent, actual.UserAgent);
                    switch (expected.Index)
                    {
                        // Request 0-11: Remove database requests
                        case 0:
                        case 1:
                        case 2:
                        case 3:
                        case 4:
                        case 5:
                        case 6:
                        case 7:
                        case 8:
                        case 9:
                        case 10:
                        case 11:
                            DatabaseTestHelper.ValidateHeadersForODataRequest(
                                expected.RequestInfo,
                                actual);
                            break;
                        default:
                            Assert.Fail("No more requests expected.");
                            break;
                    }
                });

            using (AsyncExceptionManager exceptionManager = new AsyncExceptionManager())
            {
                using (new MockHttpServer(
                    exceptionManager,
                    MockHttpServer.DefaultServerPrefixUri,
                    testSession))
                {
                    powershell.InvokeBatchScript(
                        @"Get-AzureSqlDatabase $context | " +
                        @"? {$_.Name.contains(""NewAzureSqlPremiumDatabaseTests"")} " +
                        @"| Remove-AzureSqlDatabase -Context $context -Force");
                }

                Assert.AreEqual(0, powershell.Streams.Error.Count, "Errors during run!");
                Assert.AreEqual(0, powershell.Streams.Warning.Count, "Warnings during run!");
                powershell.Streams.ClearStreams();
            }
        }
    }
}


text:
import {getChrColor} from "../bam/bamTrack.js"
import Locus from "../locus.js"
import {CircularView} from "../../node_modules/circular-view/dist/circular-view.js"
import {createSupplementaryAlignments} from "../bam/supplementaryAlignment.js"
import {IGVColor} from "../../node_modules/igv-utils/src/index.js"

/**
 * The minimum length for a VCF structural variant.  VCF records < this length are ignored in the circular view
 * @type {number}
 */
const MINIMUM_SV_LENGTH = 1000000

const circViewIsInstalled = () => CircularView.isInstalled()

const shortChrName = (chrName) => {
    return chrName.startsWith("chr") ? chrName.substring(3) : chrName
}

const makePairedAlignmentChords = (alignments) => {

    const chords = []
    for (let a of alignments) {

        if(a.paired) {
            if(a.firstAlignment && a.secondAlignment) {
                chords.push({
                    uniqueId: a.readName,
                    refName: shortChrName(a.firstAlignment.chr),
                    start: a.firstAlignment.start,
                    end: a.firstAlignment.end,
                    mate: {
                        refName: shortChrName(a.secondAlignment.chr),
                        start: a.secondAlignment.start,
                        end: a.secondAlignment.end,
                    }
                })
            }
        }
        else {
            const mate = a.mate
            if (mate && mate.chr && mate.position) {
                chords.push({
                    uniqueId: a.readName,
                    refName: shortChrName(a.chr),
                    start: a.start,
                    end: a.end,
                    mate: {
                        refName: shortChrName(mate.chr),
                        start: mate.position - 1,
                        end: mate.position,
                    }
                })
            }
        }
    }
    return chords
}

const makeSupplementalAlignmentChords = (alignments) => {

    const makeChords = (a) => {
        const sa = a.tags()['SA']
        const supAl = createSupplementaryAlignments(sa)
        let n = 0
        for (let s of supAl) {
            if (s.start !== a.start) {
                chords.push({
                    uniqueId: `${a.readName}_${n++}`,
                    refName: shortChrName(a.chr),
                    start: a.start,
                    end: a.end,
                    mate: {
                        refName: shortChrName(s.chr),
                        start: s.start,
                        end: s.start + s.lenOnRef
                    }
                })
            }
        }
    }

    const chords = []
    for (let a of alignments) {
        if(a.paired) {
            makeChords(a.firstAlignment)
            if(a.secondAlignment) {
                makeChords(a.secondAlignment)
            }
        } else {
            makeChords(a)
        }
    }
    return chords
}

const makeBedPEChords = (features) => {

    return features.map(v => {

        // If v is a whole-genome feature, get the true underlying variant.
        const f = v._f || v

        return {
            uniqueId: `${f.chr1}:${f.start1}-${f.end1}_${f.chr2}:${f.start2}-${f.end2}`,
            refName: shortChrName(f.chr1),
            start: f.start1,
            end: f.end1,
            mate: {
                refName: shortChrName(f.chr2),
                start: f.start2,
                end: f.end2,
            }
        }
    })
}

const makeVCFChords = (features) => {

    const svFeatures = features.filter(v => {
        const f = v._f || v
        const isLargeEnough = f.info && f.info.CHR2 && f.info.END &&
            (f.info.CHR2 !== f.chr || Math.abs(Number.parseInt(f.info.END) - f.pos) > MINIMUM_SV_LENGTH)
        return isLargeEnough
    })
    return svFeatures.map(v => {

        // If v is a whole-genome feature, get the true underlying variant.
        const f = v._f || v

        const pos2 = Number.parseInt(f.info.END)
        const start2 = pos2 - 100
        const end2 = pos2 + 100

        return {
            uniqueId: `${f.chr}:${f.start}-${f.end}_${f.info.CHR2}:${f.info.END}`,
            refName: shortChrName(f.chr),
            start: f.start,
            end: f.end,
            mate: {
                refName: shortChrName(f.info.CHR2),
                start: start2,
                end: end2
            }
        }
    })
}

function makeCircViewChromosomes(genome) {
    const regions = []
    const colors = []
    for (let chrName of genome.wgChromosomeNames) {
        const chr = genome.getChromosome(chrName)
        colors.push(getChrColor(chr.name))
        regions.push(
            {
                name: chr.name,
                bpLength: chr.bpLength
            }
        )
    }
    return regions
}

function sendChords(chords, track, refFrame, alpha) {

    const chordSetColor = IGVColor.addAlpha("all" === refFrame.chr ? track.color : getChrColor(refFrame.chr), alpha)
    const trackColor = IGVColor.addAlpha(track.color || 'rgb(0,0,255)', alpha)

    // name the chord set to include locus and filtering information
    const encodedName = track.name.replaceAll(' ', '%20')
    const chordSetName = "all" === refFrame.chr ? encodedName :
        `${encodedName}  ${refFrame.chr}:${refFrame.start}-${refFrame.end}`
    track.browser.circularView.addChords(chords, {track: chordSetName, color: chordSetColor, trackColor: trackColor})

    // show circular view if hidden
    if(!track.browser.circularViewVisible) track.browser.circularViewVisible = true

}

function createCircularView(el, browser) {

    const circularView = new CircularView(el, {

        onChordClick: (feature, chordTrack, pluginManager) => {

            const f1 = feature.data
            const f2 = f1.mate
            addFrameForFeature(f1)
            addFrameForFeature(f2)

            function addFrameForFeature(feature) {

                feature.chr = browser.genome.getChromosomeName(feature.refName)
                let frameFound = false
                for (let referenceFrame of browser.referenceFrameList) {
                    const l = Locus.fromLocusString(referenceFrame.getLocusString())
                    if (l.contains(feature)) {
                        frameFound = true
                        break
                    } else if (l.overlaps(feature)) {
                        referenceFrame.extend(feature)
                        frameFound = true
                        break
                    }
                }
                if (!frameFound) {
                    const flanking = 2000
                    const center = (feature.start + feature.end) / 2
                    browser.addMultiLocusPanel(feature.chr, center - flanking, center + flanking)

                }
            }
        }
    })

    return circularView
}

export {
    circViewIsInstalled,
    makeBedPEChords,
    makePairedAlignmentChords,
    makeSupplementalAlignmentChords,
    makeVCFChords,
    createCircularView,
    makeCircViewChromosomes,
    sendChords
}


text:
package com.groupon.uuid;

public class GenerateUUID {
    public static void main(String[] args) {
        System.out.println(new UUID().toString());
    }
}


text:
"""Общий класс демона для Python 3."""

import sys
import os
import time
import atexit
import signal

class Daemon:

    """Общий класс демона.

    Использование: наследоваться от класса и переопределить метод run()"""

    def __init__(self, pidfile):
        self.pidfile = pidfile

    def daemonize(self):
        """Демонизировать класс. Используется магия двойного fork()."""
        try:
            pid = os.fork()
            if pid > 0:
                # выходим из первого родителя
                sys.exit(0)
        except OSError as err:
            sys.stderr.write('fork #1 failed: {0}\n'.format(err))
            sys.exit(1)

        # отсоединяемся от родительского окружения
        os.chdir('/')
        os.setsid()
        os.umask(0)

        # форкаемся второй раз
        try:
            pid = os.fork()
            if pid > 0:

                # выходим из второго родителя
                sys.exit(0)
        except OSError as err:
            sys.stderr.write('fork #2 failed: {0}\n'.format(err))
            sys.exit(1)

        # перенаправляем стандартные файловые дескрипторы
        sys.stdout.flush()
        sys.stderr.flush()

        sin = open(os.devnull, 'r')
        sout = open("/var/log/jsh.stdout.log", "w")
        serr = open("/var/log/jsh.stderr.log", "w")

        os.dup2(sin.fileno(), sys.stdin.fileno())
        os.dup2(sout.fileno(), sys.stdout.fileno())
        os.dup2(serr.fileno(), sys.stderr.fileno())

        # записываем pidfile
        atexit.register(self.delpid)

        pid = str(os.getpid())

        with open("/var/log/jsh.log", mode='w') as log:
            log.write("pid = {}".format(pid))

        with open(self.pidfile, 'w') as pfile:
            pfile.write(pid + '\n')

    def delpid(self):
        os.remove(self.pidfile)

    def start(self, argv):
        """Запустить демон."""

        # Смотрим, существует ли уже pidfile
        try:
            with open(self.pidfile, 'r') as pfile:

                pid = int(pfile.read().strip())
        except IOError:
            pid = None

        if pid:
            message = "pidfile {0} already exist. " + \
                    "Daemon already running?\n"
            sys.stderr.write(message.format(self.pidfile))
            sys.exit(1)

        # Запускаем демон
        self.daemonize()
        self.run(argv)

    def stop(self):
        """Остановить демон."""

        # Получаем pid из pidfile
        try:
            with open(self.pidfile, 'r') as pfile:
                pid = int(pfile.read().strip())
        except IOError:
            pid = None

        if not pid:
            message = "pidfile {0} does not exist. " + \
                    "Daemon not running?\n"
            sys.stderr.write(message.format(self.pidfile))
            return  # not an error in a restart

        # Try killing the daemon process
        try:
            while 1:
                os.kill(pid, signal.SIGINT)
                time.sleep(0.1)
        except OSError as err:
            errors = str(err.args)
            if errors.find("No such process") > 0:
                if os.path.exists(self.pidfile):
                    os.remove(self.pidfile)
            else:
                print(str(err.args))
                sys.exit(1)

    def restart(self, argv):
        """Перезапустить демон."""
        self.stop()
        self.start(argv)

    def run(self, argv):
        """Вы должны переопределить этот класс, когда наследуетесь от Daemon.

        Он будет вызван после того, как класс демонизируется и сделает start()
        или restart()"""


text:
package org.apereo.cas.configuration.model.support.jaas;

import org.apereo.cas.configuration.model.core.authentication.PasswordEncoderProperties;
import org.apereo.cas.configuration.model.core.authentication.PrincipalTransformationProperties;
import org.apereo.cas.configuration.support.RequiredProperty;
import org.springframework.boot.context.properties.NestedConfigurationProperty;

import java.io.Serializable;

/**
 * This is {@link JaasAuthenticationProperties}.
 *
 * @author Misagh Moayyed
 * @since 5.0.0
 */
public class JaasAuthenticationProperties implements Serializable {
    private static final long serialVersionUID = 4643338626978471986L;
    /**
     * JAAS realm to use.
     */
    @RequiredProperty
    private String realm;
    /**
     * Typically, the default realm and the KDC for that realm are indicated in the Kerberos {@code krb5.conf} configuration file.
     * However, if you like, you can instead specify the realm value by setting this following system property value.
     *
If you set the realm property, you SHOULD also configure the {@link #setKerberosKdcSystemProperty(String)}.
     *
Also note that if you set these properties, then no cross-realm authentication is possible unless
     * a {@code krb5.conf} file is also provided from which the additional information required for cross-realm authentication
     * may be obtained.
     *
If you set values for these properties, then they override the default realm and KDC values specified
     * in {@code krb5.conf} (if such a file is found). The {@code krb5.conf} file is still consulted if values for items
     * other than the default realm and KDC are needed. If no {@code krb5.conf} file is found,
     * then the default values used for these items are implementation-specific.
     *
     * @see
     * Oracle documentation
     */
    private String kerberosRealmSystemProperty;
    /**
     * Typically, the default realm and the KDC for that realm are indicated in the Kerberos {@code krb5.conf} configuration file.
     * However, if you like, you can instead specify the realm value by setting this following system property value.
     *
If you set the realm property, you SHOULD also configure the {@link #setKerberosKdcSystemProperty(String)}.
     *
Also note that if you set these properties, then no cross-realm authentication is possible unless
     * a {@code krb5.conf} file is also provided from which the additional information required for cross-realm authentication
     * may be obtained.
     *
If you set values for these properties, then they override the default realm and KDC values specified
     * in {@code krb5.conf} (if such a file is found). The {@code krb5.conf} file is still consulted if values for items
     * other than the default realm and KDC are needed. If no {@code krb5.conf} file is found,
     * then the default values used for these items are implementation-specific.
     *
     * @see
     * Oracle documentation
     */
    private String kerberosKdcSystemProperty;

    /**
     * A number of authentication handlers are allowed to determine whether they can operate on the provided credential
     * and as such lend themselves to be tried and tested during the authentication handler selection phase.
     * The credential criteria may be one of the following options:

     *
1) A regular expression pattern that is tested against the credential identifier.

     *
2) A fully qualified class name of your own design that implements {@code Predicate<Credential>}.

     *
3) Path to an external Groovy script that implements the same interface.

     *

     */
    private String credentialCriteria;

    /**
     * Principal transformation settings.
     */
    @NestedConfigurationProperty
    private PrincipalTransformationProperties principalTransformation = new PrincipalTransformationProperties();

    /**
     * Password encoder settings for JAAS authentication.
     */
    @NestedConfigurationProperty
    private PasswordEncoderProperties passwordEncoder = new PasswordEncoderProperties();

    /**
     * Name of the authentication handler.
     */
    private String name;

    public String getCredentialCriteria() {
        return credentialCriteria;
    }

    public void setCredentialCriteria(final String credentialCriteria) {
        this.credentialCriteria = credentialCriteria;
    }

    public String getName() {
        return name;
    }

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

    public PrincipalTransformationProperties getPrincipalTransformation() {
        return principalTransformation;
    }

    public void setPrincipalTransformation(final PrincipalTransformationProperties principalTransformation) {
        this.principalTransformation = principalTransformation;
    }

    public PasswordEncoderProperties getPasswordEncoder() {
        return passwordEncoder;
    }

    public void setPasswordEncoder(final PasswordEncoderProperties passwordEncoder) {
        this.passwordEncoder = passwordEncoder;
    }

    public String getRealm() {
        return realm;
    }

    public void setRealm(final String realm) {
        this.realm = realm;
    }

    public String getKerberosRealmSystemProperty() {
        return kerberosRealmSystemProperty;
    }

    public void setKerberosRealmSystemProperty(final String kerberosRealmSystemProperty) {
        this.kerberosRealmSystemProperty = kerberosRealmSystemProperty;
    }

    public String getKerberosKdcSystemProperty() {
        return kerberosKdcSystemProperty;
    }

    public void setKerberosKdcSystemProperty(final String kerberosKdcSystemProperty) {
        this.kerberosKdcSystemProperty = kerberosKdcSystemProperty;
    }
}


text:
source ~/utils/utils.sh

echo "install switchaudio-osx"
brew_smart_install "switchaudio-osx"

echo "install sox"
brew_smart_install "sox"

# Big Sur doesn't support soundflower installation without user interaction https://github.com/mattingalls/Soundflower/releases/tag/2.0b2
# Install blackhole-2ch for Big Sur instead
if is_Catalina; then
    echo "install soundflower"
    brew install --cask soundflower

    echo "set Soundflower (2ch) as input/output device"
    SwitchAudioSource -s "Soundflower (2ch)" -t input
    SwitchAudioSource -s "Soundflower (2ch)" -t output
else
    echo "install blackhole-2ch"
    brew_smart_install "blackhole-2ch"

    echo "set BlackHole 2ch as input/output device"
    SwitchAudioSource -s "BlackHole 2ch" -t input
    SwitchAudioSource -s "BlackHole 2ch" -t output
fi

invoke_tests "System" "Audio Device"


text:
package de.jowisoftware.sshclient.terminal.input.controlsequences;

import de.jowisoftware.sshclient.terminal.SSHSession;
import de.jowisoftware.sshclient.terminal.buffer.Buffer;
import de.jowisoftware.sshclient.terminal.buffer.Range;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ANSISequenceCapitalK implements ANSISequence {
    private static final Logger LOGGER = LoggerFactory.getLogger(ANSISequenceCapitalK.class);

    @Override
    public void process(final SSHSession sessionInfo, final String... args) {
        final int mod = args.length == 0 ? 0 : Integer.parseInt(args[0]);

        final Buffer buffer = sessionInfo.getBuffer();
        switch(mod) {
        case 0: buffer.erase(new Range(buffer.getCursorPosition(),
                        buffer.getCursorPosition().withX(buffer.getSize().x))); break;
        case 1: buffer.erase(new Range(buffer.getCursorPosition().withX(1),
                buffer.getCursorPosition())); break;
        case 2: buffer.erase(new Range(buffer.getCursorPosition().withX(1),
                buffer.getCursorPosition().withX(buffer.getSize().x))); break;
        default:
            LOGGER.error("Unknown control sequence: <ESC>{}K", mod);
        }
    }
}


text:
#
# Test the binary composition from CQL files by comparing generated Ruby output
#

ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../../Gemfile', __FILE__)
require 'bundler/setup' # Set up gems listed in the Gemfile.

require 'spec_helper'
require 'activefacts/compositions/binary'
require 'activefacts/compositions/names'
require 'activefacts/generator/ruby'
require 'activefacts/input/cql'

RUBY_CQL_DIR = Pathname.new(__FILE__+'/../../cql').relative_path_from(Pathname(Dir.pwd)).to_s
RUBY_TEST_DIR = Pathname.new(__FILE__+'/..').relative_path_from(Pathname(Dir.pwd)).to_s

RSpec::Matchers.define :be_like do |expected|
  match do |actual|
    actual == expected
  end

  failure_message do
    'Output doesn\'t match expected, see diff'
  end

  diffable
end

describe "Ruby schema from CQL" do
  dir = ENV['CQL_DIR'] || RUBY_CQL_DIR
  actual_dir = (ENV['CQL_DIR'] ? '' : RUBY_TEST_DIR+'/') + 'actual'
  expected_dir = (ENV['CQL_DIR'] ? '' : RUBY_TEST_DIR+'/') + 'expected'
  Dir.mkdir actual_dir unless Dir.exist? actual_dir
  if f = ENV['TEST_FILES']
    files = Dir[dir+"/#{f}*.cql"]
  else
    files = `git ls-files "#{dir}/*.cql"`.split(/\n/)
  end
  files.each do |cql_file|
    basename = cql_file.sub(%r{(.*/)?([^/]*).cql\Z}, '\2')
    expected = expected_dir+'/'+basename+'.rb'
    actual = actual_dir+'/'+basename+'.rb'
    begin
      expected_text = File.read(expected)
    rescue Errno::ENOENT => exception
    end
    next unless expected_text || ENV['TEST_FILES']

    it "produces the expected Ruby for #{cql_file}" do
      vocabulary = ActiveFacts::Input::CQL.readfile(cql_file)
      vocabulary.finalise
      compositor = ActiveFacts::Compositions::Binary.new(vocabulary.constellation, basename)
      compositor.generate

      output = ActiveFacts::Generators::Ruby.new(vocabulary.constellation, compositor.composition).generate

      # Save or delete the actual output file:
      if expected_text != output
        File.write(actual, output)
      else
        File.delete(actual) rescue nil
      end

      if expected_text
        expect(output).to be_like(expected_text), "Output #{actual} doesn't match expected #{expected}"
      else
        pending "Actual output in #{actual} can't be compared with missing expected file #{expected}"
        expect(expected_text).to_not be_nil, "I don't know what to expect"
      end
    end
  end
end


text:
@interface NavBasedTableViewController ()

@end

@implementation NavBasedTableViewController

-(void)viewDidLoad
{
    [super viewDidLoad];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    UIView *v = [[UIView alloc] initWithFrame:self.view.bounds];
    [v setBackgroundColor:[UIColor blueColor]];
    self.tableView.backgroundView = v;
}

@end


text:
Go Programming Challenges

> The best thing about Go is that it comes with its own linter. It literally won't let you write bad code!
>
> -- Random Guy sitting behind me at Defcon

This repository contains a number of challenges. Prove this guy wrong by completing the programming challenge whilst writing the worst code that will still pass `gofmt`, `golint`, and `go vet`. Or, show off how awesome you are by writing completing the challenge and writing the best code you can.

## How It Works

1. Fork the repo
2. List the challenges you're working on in submissions.txt:

    ```shell
    echo "challenge1" >> submissions.txt
    echo "challenge2" >> submissions.txt
    ```
3. Make the test pass `./test`
4. Submit a pull request, indicating whether or not this is an example of good or bad code by prefixing `[BAD]` or `[GOOD]` to the pull request title
5. Vote on other people's pull requests by leaving a comment or something

## Rules

* The tests must pass
* The following files are off-limits:
```
.travis.yml
test.sh
challenge1_test/challenge1_test.go
```

Eveything else is fair game


text:
: ${HADOOP_PREFIX:=/usr/local/hadoop}

$HADOOP_PREFIX/etc/hadoop/hadoop-env.sh

rm /tmp/*.pid

# installing libraries if any - (resource urls added comma separated to the ACP system variable)
cd $HADOOP_PREFIX/share/hadoop/common ; for cp in ${ACP//,/ }; do  echo == $cp; curl -LO $cp ; done; cd -

## replace config
: ${EXTRA_CONF_DIR:=/config/hadoop}

if [ -d "$EXTRA_CONF_DIR" ]; then
	cp $EXTRA_CONF_DIR/* $HADOOP_PREFIX/etc/hadoop/
fi

/usr/sbin/sshd

while true; do sleep 1000; done


text:
pimcore.registerNS("pimcore.object.classes.data.multiselect");
pimcore.object.classes.data.multiselect = Class.create(pimcore.object.classes.data.data, {

    type: "multiselect",
    /**
     * define where this datatype is allowed
     */
    allowIn: {
        object: true,
        objectbrick: true,
        fieldcollection: true,
        localizedfield: true
    },

    initialize: function (treeNode, initData) {
        this.type = "multiselect";

        this.initData(initData);

        // overwrite default settings
        this.availableSettingsFields = ["name","title","tooltip","mandatory","noteditable","invisible",
            "visibleGridView","visibleSearch","style"];

        this.treeNode = treeNode;
    },

    getTypeName: function () {
        return t("multiselect");
    },

    getGroup: function () {
        return "select";
    },

    getIconClass: function () {
        return "pimcore_icon_multiselect";
    },

    getLayout: function ($super) {

        if(typeof this.datax.options != "object") {
            this.datax.options = [];
        }

        this.valueStore = new Ext.data.JsonStore({
            fields: ["key", "value"],
            data: this.datax.options
        });

        this.valueGrid = new Ext.grid.EditorGridPanel({
            tbar: [{
                xtype: "tbtext",
                text: t("selection_options")
            }, "-", {
                xtype: "button",
                iconCls: "pimcore_icon_add",
                handler: function () {
                    var u = new this.valueStore.recordType({
                        key: "",
                        value: ""
                    });
                    this.valueStore.insert(0, u);
                }.bind(this)
            }],
            style: "margin-top: 10px",
            store: this.valueStore,
            selModel:new Ext.grid.RowSelectionModel({singleSelect:true}),
            columnLines: true,
            columns: [
                {header: t("display_name"), sortable: false, dataIndex: 'key', editor: new Ext.form.TextField({}),
                                                    width: 200},
                {header: t("value"), sortable: false, dataIndex: 'value', editor: new Ext.form.TextField({}),
                                                    width: 200},
                {
                    xtype:'actioncolumn',
                    width:30,
                    items:[
                        {
                            tooltip:t('up'),
                            icon:"/pimcore/static/img/icon/arrow_up.png",
                            handler:function (grid, rowIndex) {
                                if (rowIndex > 0) {
                                    var rec = grid.getStore().getAt(rowIndex);
                                    grid.getStore().removeAt(rowIndex);
                                    grid.getStore().insert(rowIndex - 1, [rec]);
                                }
                            }.bind(this)
                        }
                    ]
                },
                {
                    xtype:'actioncolumn',
                    width:30,
                    items:[
                        {
                            tooltip:t('down'),
                            icon:"/pimcore/static/img/icon/arrow_down.png",
                            handler:function (grid, rowIndex) {
                                if (rowIndex < (grid.getStore().getCount() - 1)) {
                                    var rec = grid.getStore().getAt(rowIndex);
                                    grid.getStore().removeAt(rowIndex);
                                    grid.getStore().insert(rowIndex + 1, [rec]);
                                }
                            }.bind(this)
                        }
                    ]
                },
                {
                    xtype: 'actioncolumn',
                    width: 30,
                    items: [
                        {
                            tooltip: t('remove'),
                            icon: "/pimcore/static/img/icon/cross.png",
                            handler: function (grid, rowIndex) {
                                grid.getStore().removeAt(rowIndex);
                            }.bind(this)
                        }
                    ]
                }
            ],
            autoHeight: true
        });

        $super();

        this.specificPanel.removeAll();
        this.specificPanel.add([
            {
                xtype: "spinnerfield",
                fieldLabel: t("width"),
                name: "width",
                value: this.datax.width
            },
            {
                xtype: "spinnerfield",
                fieldLabel: t("height"),
                name: "height",
                value: this.datax.height
            },this.valueGrid
        ]);

        return this.layout;
    },

    applyData: function ($super) {

        $super();

        var options = [];

        this.valueStore.commitChanges();
        this.valueStore.each(function (rec) {
            options.push({
                key: rec.get("key"),
                value: rec.get("value")
            });
        });

        this.datax.options = options;
    }
});


text:
#pragma once
#include <aws/email/SES_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSStreamFwd.h>
#include <aws/core/utils/DateTime.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Xml
{
  class XmlNode;
} // namespace Xml
} // namespace Utils
namespace SES
{
namespace Model
{

  /**
   *
Contains information about the reputation settings for a configuration
   * set.

See Also:
   AWS
   * API Reference

   */
  class AWS_SES_API ReputationOptions
  {
  public:
    ReputationOptions();
    ReputationOptions(const Aws::Utils::Xml::XmlNode& xmlNode);
    ReputationOptions& operator=(const Aws::Utils::Xml::XmlNode& xmlNode);

    void OutputToStream(Aws::OStream& ostream, const char* location, unsigned index, const char* locationValue) const;
    void OutputToStream(Aws::OStream& oStream, const char* location) const;

    /**
     *
Describes whether email sending is enabled or disabled for the configuration
     * set. If the value is true, then Amazon SES will send emails that
     * use the configuration set. If the value is false, Amazon SES will
     * not send emails that use the configuration set. The default value is
     * true. You can change this setting using
     * UpdateConfigurationSetSendingEnabled.

     */
    inline bool GetSendingEnabled() const{ return m_sendingEnabled; }

    /**
     *
Describes whether email sending is enabled or disabled for the configuration
     * set. If the value is true, then Amazon SES will send emails that
     * use the configuration set. If the value is false, Amazon SES will
     * not send emails that use the configuration set. The default value is
     * true. You can change this setting using
     * UpdateConfigurationSetSendingEnabled.

     */
    inline void SetSendingEnabled(bool value) { m_sendingEnabledHasBeenSet = true; m_sendingEnabled = value; }

    /**
     *
Describes whether email sending is enabled or disabled for the configuration
     * set. If the value is true, then Amazon SES will send emails that
     * use the configuration set. If the value is false, Amazon SES will
     * not send emails that use the configuration set. The default value is
     * true. You can change this setting using
     * UpdateConfigurationSetSendingEnabled.

     */
    inline ReputationOptions& WithSendingEnabled(bool value) { SetSendingEnabled(value); return *this;}

    /**
     *
Describes whether or not Amazon SES publishes reputation metrics for the
     * configuration set, such as bounce and complaint rates, to Amazon CloudWatch.

     *
If the value is true, reputation metrics are published. If the
     * value is false, reputation metrics are not published. The default
     * value is false.

     */
    inline bool GetReputationMetricsEnabled() const{ return m_reputationMetricsEnabled; }

    /**
     *
Describes whether or not Amazon SES publishes reputation metrics for the
     * configuration set, such as bounce and complaint rates, to Amazon CloudWatch.

     *
If the value is true, reputation metrics are published. If the
     * value is false, reputation metrics are not published. The default
     * value is false.

     */
    inline void SetReputationMetricsEnabled(bool value) { m_reputationMetricsEnabledHasBeenSet = true; m_reputationMetricsEnabled = value; }

    /**
     *
Describes whether or not Amazon SES publishes reputation metrics for the
     * configuration set, such as bounce and complaint rates, to Amazon CloudWatch.

     *
If the value is true, reputation metrics are published. If the
     * value is false, reputation metrics are not published. The default
     * value is false.

     */
    inline ReputationOptions& WithReputationMetricsEnabled(bool value) { SetReputationMetricsEnabled(value); return *this;}

    /**
     *
The date and time at which the reputation metrics for the configuration set
     * were last reset. Resetting these metrics is known as a fresh start.

     *
When you disable email sending for a configuration set using
     * UpdateConfigurationSetSendingEnabled and later re-enable it, the
     * reputation metrics for the configuration set (but not for the entire Amazon SES
     * account) are reset.

If email sending for the configuration set has never
     * been disabled and later re-enabled, the value of this attribute is
     * null.

     */
    inline const Aws::Utils::DateTime& GetLastFreshStart() const{ return m_lastFreshStart; }

    /**
     *
The date and time at which the reputation metrics for the configuration set
     * were last reset. Resetting these metrics is known as a fresh start.

     *
When you disable email sending for a configuration set using
     * UpdateConfigurationSetSendingEnabled and later re-enable it, the
     * reputation metrics for the configuration set (but not for the entire Amazon SES
     * account) are reset.

If email sending for the configuration set has never
     * been disabled and later re-enabled, the value of this attribute is
     * null.

     */
    inline void SetLastFreshStart(const Aws::Utils::DateTime& value) { m_lastFreshStartHasBeenSet = true; m_lastFreshStart = value; }

    /**
     *
The date and time at which the reputation metrics for the configuration set
     * were last reset. Resetting these metrics is known as a fresh start.

     *
When you disable email sending for a configuration set using
     * UpdateConfigurationSetSendingEnabled and later re-enable it, the
     * reputation metrics for the configuration set (but not for the entire Amazon SES
     * account) are reset.

If email sending for the configuration set has never
     * been disabled and later re-enabled, the value of this attribute is
     * null.

     */
    inline void SetLastFreshStart(Aws::Utils::DateTime&& value) { m_lastFreshStartHasBeenSet = true; m_lastFreshStart = std::move(value); }

    /**
     *
The date and time at which the reputation metrics for the configuration set
     * were last reset. Resetting these metrics is known as a fresh start.

     *
When you disable email sending for a configuration set using
     * UpdateConfigurationSetSendingEnabled and later re-enable it, the
     * reputation metrics for the configuration set (but not for the entire Amazon SES
     * account) are reset.

If email sending for the configuration set has never
     * been disabled and later re-enabled, the value of this attribute is
     * null.

     */
    inline ReputationOptions& WithLastFreshStart(const Aws::Utils::DateTime& value) { SetLastFreshStart(value); return *this;}

    /**
     *
The date and time at which the reputation metrics for the configuration set
     * were last reset. Resetting these metrics is known as a fresh start.

     *
When you disable email sending for a configuration set using
     * UpdateConfigurationSetSendingEnabled and later re-enable it, the
     * reputation metrics for the configuration set (but not for the entire Amazon SES
     * account) are reset.

If email sending for the configuration set has never
     * been disabled and later re-enabled, the value of this attribute is
     * null.

     */
    inline ReputationOptions& WithLastFreshStart(Aws::Utils::DateTime&& value) { SetLastFreshStart(std::move(value)); return *this;}

  private:

    bool m_sendingEnabled;
    bool m_sendingEnabledHasBeenSet;

    bool m_reputationMetricsEnabled;
    bool m_reputationMetricsEnabledHasBeenSet;

    Aws::Utils::DateTime m_lastFreshStart;
    bool m_lastFreshStartHasBeenSet;
  };

} // namespace Model
} // namespace SES
} // namespace Aws


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

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<title>ublas: boost::numeric::ublas::map_std< I, T, ALLOC > Class Template Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<link href="doxygen.css" rel="stylesheet" type="text/css"/>

Main Page

Related Pages

Classes

Files

Class List

Class Hierarchy

Class Members

boost::numeric::ublas::map_std

boost::numeric::ublas::map_std< I, T, ALLOC > Class Template Reference

List of all members.

Public Member Functions

template<class Archive >

void 	serialize (Archive &ar, const unsigned int)

template<class I, class T, class ALLOC>

 class boost::numeric::ublas::map_std< I, T, ALLOC >

<address style="text-align: right;">Generated on Sun Jul 4 20:31:07 2010 for ublas by

 1.6.1 </address>


text:
import os
from typing import Any, BinaryIO, Callable, Dict, List, Optional, Tuple

# Limit parsing file to 1MB to maintain parity with the UI
MAX_BYTES_LOADED = 1 * 1024 * 1024

def file_generator(path: str):
  with open(path, 'rb') as f:
    yield from read_generator(f)

def read_generator(trace: BinaryIO):
  while True:
    chunk = trace.read(MAX_BYTES_LOADED)
    if not chunk:
      break
    yield chunk

def merge_dicts(a: Dict[str, str], b: Dict[str, str]):
  return {**a, **b}

def parse_trace_uri(uri: str) -> Tuple[Optional[str], str]:
  # This is definitely a path and not a URI
  if uri.startswith('/') or uri.startswith('.'):
    return None, uri

  # If there's no colon, it cannot be a URI
  idx = uri.find(':')
  if idx == -1:
    return None, uri

  # If there is only a single character before the colon
  # this is likely a Windows path; throw an error on other platforms
  # to prevent single character names causing issues on Windows.
  if idx == 1:
    if os.name != 'nt':
      raise Exception('Single character resolvers are not allowed')
    return None, uri

  return (uri[:idx], uri[idx + 1:])

def to_list(cs: Any) -> Optional[List[Any]]:
  """Converts input into list if it is not already a list.

  For resolvers that can accept list types it may happen the user inputs just
  a single value, to make the code generic enough we would want to convert those
  input into list of single element. It does not do anything for None or List
  types.
  """
  if cs is None or isinstance(cs, list):
    return cs
  return [cs]

def _cs_list(cs: List[Any], fn: Callable[[Any], str], empty_default: str,
             condition_sep: str) -> str:
  """Converts list of constraints into list of clauses.

  Applies function `fn` over each element in list `cs` and joins the list of
  transformed strings with join string `condition_sep`. `empty_default` string
  is returned incase cs is a list of length 0. 'TRUE' is returned when cs is
  None

  e.g.
  Input:
    cs: ['Android', 'Linux']
    fn: "platform = '{}'".format
    empty_default: FALSE
    condition_sep: 'OR'
  OUTPUT:
    "(platform = 'Android' OR platform = 'Linux')"
  """
  if cs is None:
    return 'TRUE'
  if not cs:
    return empty_default
  return f'({condition_sep.join([fn(c) for c in cs])})'

def and_list(cs: List[Any], fn: Callable[[Any], str],
             empty_default: str) -> str:
  """Converts list of constraints into list of AND clauses.

  Function `fn` is applied over each element of list `cs` and joins the list of
  transformed strings with ' AND ' string. `empty_default` string
  is returned incase cs is a list of length 0. 'TRUE' is returned when cs is
  None.

  e.g.
  Input:
    cs: ['Android', 'Linux']
    fn: "platform != '{}'".format
    empty_default: FALSE
  OUTPUT:
    "(platform != 'Android' AND platform != 'Linux')"
  """
  return _cs_list(cs, fn, empty_default, ' AND ')

def or_list(cs: List[Any], fn: Callable[[Any], str], empty_default: str) -> str:
  """Converts list of constraints into list of OR clauses.

  Similar to and_list method, just the join string is ' OR ' instead of ' AND '.

  e.g.
  Input:
    cs: ['Android', 'Linux']
    fn: "platform = '{}'".format
    empty_default: FALSE
  OUTPUT:
    "(platform = 'Android' OR platform = 'Linux')"
  """
  return _cs_list(cs, fn, empty_default, ' OR ')


text:
require File.dirname(__FILE__) + '/spec_helper'
require 'nanite/packets'
require 'json'

describe "Packet: FileStart" do
  it "should dump/load as JSON objects" do
    packet = Nanite::FileStart.new('foo.txt', 'somewhere/foo.txt', '0xdeadbeef')
    packet2 = JSON.parse(packet.to_json)
    packet.filename.should == packet2.filename
    packet.dest.should == packet2.dest
    packet.token.should == packet2.token
  end

  it "should dump/load as Marshalled ruby objects" do
    packet = Nanite::FileStart.new('foo.txt', 'somewhere/foo.txt', '0xdeadbeef')
    packet2 = Marshal.load(Marshal.dump(packet))
    packet.filename.should == packet2.filename
    packet.dest.should == packet2.dest
    packet.token.should == packet2.token
  end
end

describe "Packet: FileEnd" do
  it "should dump/load as JSON objects" do
    packet = Nanite::FileEnd.new('0xdeadbeef', 'metadata')
    packet2 = JSON.parse(packet.to_json)
    packet.meta.should == packet2.meta
    packet.token.should == packet2.token
  end

  it "should dump/load as Marshalled ruby objects" do
    packet = Nanite::FileEnd.new('0xdeadbeef', 'metadata')
    packet2 = Marshal.load(Marshal.dump(packet))
    packet.meta.should == packet2.meta
    packet.token.should == packet2.token
  end
end

describe "Packet: FileChunk" do
  it "should dump/load as JSON objects" do
    packet = Nanite::FileChunk.new('chunk','0xdeadbeef')
    packet2 = JSON.parse(packet.to_json)
    packet.chunk.should == packet2.chunk
    packet.token.should == packet2.token
  end

  it "should dump/load as Marshalled ruby objects" do
    packet = Nanite::FileChunk.new('chunk','0xdeadbeef')
    packet2 = Marshal.load(Marshal.dump(packet))
    packet.chunk.should == packet2.chunk
    packet.token.should == packet2.token
  end
end

describe "Packet: Request" do
  it "should dump/load as JSON objects" do
    packet = Nanite::Request.new('/some/foo', 'payload', 'from', '0xdeadbeef', 'reply_to')
    packet2 = JSON.parse(packet.to_json)
    packet.type.should == packet2.type
    packet.payload.should == packet2.payload
    packet.from.should == packet2.from
    packet.token.should == packet2.token
    packet.reply_to.should == packet2.reply_to
  end

  it "should dump/load as Marshalled ruby objects" do
    packet = Nanite::Request.new('/some/foo', 'payload', 'from', '0xdeadbeef', 'reply_to')
    packet2 = Marshal.load(Marshal.dump(packet))
    packet.type.should == packet2.type
    packet.payload.should == packet2.payload
    packet.from.should == packet2.from
    packet.token.should == packet2.token
    packet.reply_to.should == packet2.reply_to
  end
end

describe "Packet: Result" do
  it "should dump/load as JSON objects" do
    packet = Nanite::Result.new('0xdeadbeef', 'to', 'results', 'from')
    packet2 = JSON.parse(packet.to_json)
    packet.token.should == packet2.token
    packet.to.should == packet2.to
    packet.results.should == packet2.results
    packet.from.should == packet2.from
  end

  it "should dump/load as Marshalled ruby objects" do
    packet = Nanite::Result.new('0xdeadbeef', 'to', 'results', 'from')
    packet2 = Marshal.load(Marshal.dump(packet))
    packet.token.should == packet2.token
    packet.to.should == packet2.to
    packet.results.should == packet2.results
    packet.from.should == packet2.from
  end
end

describe "Packet: Register" do
  it "should dump/load as JSON objects" do
    packet = Nanite::Register.new('0xdeadbeef', ['/foo/bar', '/nik/qux'], 0.8)
    packet2 = JSON.parse(packet.to_json)
    packet.identity.should == packet2.identity
    packet.services.should == packet2.services
    packet.status.should == packet2.status
  end

  it "should dump/load as Marshalled ruby objects" do
    packet = Nanite::Register.new('0xdeadbeef', ['/foo/bar', '/nik/qux'], 0.8)
    packet2 = Marshal.load(Marshal.dump(packet))
    packet.identity.should == packet2.identity
    packet.services.should == packet2.services
    packet.status.should == packet2.status
  end
end

describe "Packet: Ping" do
  it "should dump/load as JSON objects" do
    packet = Nanite::Ping.new('0xdeadbeef', 0.8, 'from')
    packet2 = JSON.parse(packet.to_json)
    packet.identity.should == packet2.identity
    packet.status.should == packet2.status
    packet.from.should == packet2.from
  end

  it "should dump/load as Marshalled ruby objects" do
    packet = Nanite::Ping.new('0xdeadbeef', 0.8, 'from')
    packet2 = Marshal.load(Marshal.dump(packet))
    packet.identity.should == packet2.identity
    packet.status.should == packet2.status
    packet.from.should == packet2.from
  end
end


text:
require 'spec_helper'

describe WhosDatedWho do
  let(:client) { WhosDatedWho::Client.new }

  context 'smoke test' do
    it 'fetches and parses the correct results' do
      result = client.fetch('Candice Swanepoel')
      expect(result.status).to eq(:engaged)
      expect(result.biography.first_name).to eq('Candice')
      expect(result.biography.last_name).to eq('Swanepoel')
      expect(result.biography.age).to eq(27)

      result = client.fetch('Jennifer Lawrence')
      expect(result.status).to eq(:dating)
      expect(result.biography.first_name).to eq('Jennifer')
      expect(result.biography.last_name).to eq('Lawrence')
      expect(result.biography.age).to eq(25)
    end
  end
end


text:
import React from 'react'
import PropTypes from 'prop-types'
import { Link } from 'gatsby'

export default class Header extends React.Component {
  state = { menuOpen: false }
  toggleMenu = () => {
    this.setState(({ menuOpen }) => ({ menuOpen: !menuOpen }))
  }
  render () {
    const { stats } = this.props
    return (

          <LogoIcon />

elm-live

          <Link />

        {stats.fold(renderMissingStats, renderStats)}

    )
  }
}

Header.propTypes = {
  repoUrl: PropTypes.object.isRequired,
  stats: PropTypes.object.isRequired
}