text:
module.exports = {
  provider: {
    // your provider name directly or from ENV var
    service: 'SendGrid',
    // auth data always from ENV vars
    auth: {
      user: process.env.SENDGRID_USER,
      pass: process.env.SENDGRID_PASS,
    },
  },
  // defaults to be passed to nodemailer's emails
  defaults: {
    from: 'wican <noreply@wican.org>',
  },
};

redpajama_set_name: RedPajamaGithub


text:
package com.nio.socket;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.logging.Level;
import java.util.logging.Logger;

public class MyClient3 {

	private final static Logger logger = Logger.getLogger(MyClient3.class
			.getName());

	public static void main(String[] args) throws Exception {
		for (int i = 0; i < 100; i++) {
			final int idx = i;
			new Thread(new MyRunnable(idx)).start();
		}
	}

	private static final class MyRunnable implements Runnable {

		private final int idx;

		private MyRunnable(int idx) {
			this.idx = idx;
		}

		public void run() {
			SocketChannel socketChannel = null;
			try {
				socketChannel = SocketChannel.open();
				SocketAddress socketAddress = new InetSocketAddress(
						"localhost", 10000);
				socketChannel.connect(socketAddress);

				MyRequestObject myRequestObject = new MyRequestObject(
						"request_" + idx, "request_" + idx);
				logger.log(Level.INFO, myRequestObject.toString());
				sendData(socketChannel, myRequestObject);
				MyResponseObject myResponseObject = receiveData(socketChannel);
				logger.log(Level.INFO, myResponseObject.toString());
			} catch (Exception ex) {
				logger.log(Level.SEVERE, null, ex);
			} finally {
				try {
					socketChannel.close();
				} catch (Exception ex) {
				}
			}
		}

		private void sendData(SocketChannel socketChannel,
				MyRequestObject myRequestObject) throws IOException {
			byte[] bytes = SerializableUtil.toBytes(myRequestObject);
			ByteBuffer buffer = ByteBuffer.wrap(bytes);
			socketChannel.write(buffer);
			socketChannel.socket().shutdownOutput();
		}

		private MyResponseObject receiveData(SocketChannel socketChannel)
				throws IOException {
			MyResponseObject myResponseObject = null;
			ByteArrayOutputStream baos = new ByteArrayOutputStream();

			try {
				ByteBuffer buffer = ByteBuffer.allocateDirect(1024);
				byte[] bytes;
				int count = 0;
				while ((count = socketChannel.read(buffer)) >= 0) {
					buffer.flip();
					bytes = new byte[count];
					buffer.get(bytes);
					baos.write(bytes);
					buffer.clear();
				}
				bytes = baos.toByteArray();
				Object obj = SerializableUtil.toObject(bytes);
				myResponseObject = (MyResponseObject) obj;
				socketChannel.socket().shutdownInput();
			} finally {
				try {
					baos.close();
				} catch (Exception ex) {
				}
			}
			return myResponseObject;
		}
	}
}


text:
#ifndef __HPackTable_H__
#define __HPackTable_H__

#include <string>
#include <deque>
#include <map>

namespace hpack {

class HPackTable
{
public:
    using KeyValuePair = std::pair<std::string, std::string>;

public:
    HPackTable();
    void setMode(bool isEncoder) { isEncoder_ = isEncoder; }
    void setMaxSize(size_t maxSize);
    void updateLimitSize(size_t limitSize);
    int  getIndex(const std::string &name, const std::string &value, bool &valueIndexed);
    bool getIndexedName(int index, std::string &name);
    bool getIndexedValue(int index, std::string &value);
    bool addHeader(const std::string &name, const std::string &value);

    size_t getMaxSize() { return maxSize_; }
    size_t getLimitSize() { return limitSize_; }
    size_t getTableSize() { return tableSize_; }

private:
    int getDynamicIndex(int idxSeq);
    void updateIndex(const std::string &key, int idxSeq);
    void removeIndex(const std::string &key);
    bool getIndex(const std::string &key, int &indexD, int &indexS);
    void evictTableBySize(size_t size);

private:
    using KeyValueQueue = std::deque<KeyValuePair>;
    using IndexMap = std::map<std::string, std::pair<int, int>>;

    KeyValueQueue dynamicTable_;
    size_t tableSize_ = 0;
    size_t limitSize_ = 4096;
    size_t maxSize_ = 4096;

    bool isEncoder_ = false;
    int indexSequence_ = 0;
    IndexMap indexMap_; // <key(header name[ + value]), <dynamic index sequence, static index>>
};

} // namespace hpack

#endif /* __HPackTable_H__ */


text:
class TuftsEAD < TuftsBase

  # Tufts specific needed metadata streams
  # This is unusual, because it's an external datastream, but it is loaded by fedora
  has_metadata :name => "Archival.xml", :type => TuftsEADMeta

  def self.to_class_uri
    'info:fedora/cm:Text.EAD'
  end
end


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title></title>
    {% load staticfiles %}

    <link href="{% static 'css/bootstrap.min.css' %}" rel="stylesheet">
    <link href="{% static 'css/grayscale.css' %}" rel="stylesheet">

Home

About

Contact

Blog

        {% block body_block %}
        {% endblock %}


text:
namespace ash {

NotificationMenuView::NotificationMenuView(
    Delegate* notification_item_view_delegate,
    views::SlideOutControllerDelegate* slide_out_controller_delegate,
    const std::string& app_id)
    : app_id_(app_id),
      notification_item_view_delegate_(notification_item_view_delegate),
      slide_out_controller_delegate_(slide_out_controller_delegate),
      double_separator_(AddChildView(std::make_unique<views::MenuSeparator>(
          ui::MenuSeparatorType::DOUBLE_SEPARATOR))),
      header_view_(
          AddChildView(std::make_unique<NotificationMenuHeaderView>())) {
  DCHECK(notification_item_view_delegate_);
  DCHECK(slide_out_controller_delegate_);
  DCHECK(!app_id_.empty())
      << "Only context menus for applications can show notifications.";
}

NotificationMenuView::~NotificationMenuView() = default;

gfx::Size NotificationMenuView::CalculatePreferredSize() const {
  return gfx::Size(
      views::MenuConfig::instance().touchable_menu_min_width,
      double_separator_->GetPreferredSize().height() +
          header_view_->GetPreferredSize().height() +
          kNotificationItemViewHeight +
          (overflow_view_ ? overflow_view_->GetPreferredSize().height() : 0));
}

void NotificationMenuView::Layout() {
  int y = 0;
  double_separator_->SetBoundsRect(gfx::Rect(
      gfx::Point(0, y),
      gfx::Size(views::MenuConfig::instance().touchable_menu_min_width,
                double_separator_->GetPreferredSize().height())));
  y += double_separator_->GetPreferredSize().height();

  header_view_->SetBoundsRect(
      gfx::Rect(gfx::Point(0, y), header_view_->GetPreferredSize()));
  y += header_view_->GetPreferredSize().height();

  auto* item = GetDisplayedNotificationItemView();
  if (item) {
    item->SetBoundsRect(gfx::Rect(gfx::Point(0, y), item->GetPreferredSize()));
    y = item->bounds().bottom();
  }

  if (overflow_view_) {
    overflow_view_->SetBoundsRect(
        gfx::Rect(gfx::Point(0, y), overflow_view_->GetPreferredSize()));
  }
}

bool NotificationMenuView::IsEmpty() const {
  return notification_item_views_.empty();
}

void NotificationMenuView::AddNotificationItemView(
    const message_center::Notification& notification) {
  auto* old_displayed_item = GetDisplayedNotificationItemView();

  auto notification_view = std::make_unique<NotificationItemView>(
      notification_item_view_delegate_, slide_out_controller_delegate_,
      notification.title(), notification.message(), notification.icon(),
      notification.id());
  notification_item_views_.push_front(
      AddChildView(std::move(notification_view)));

  header_view_->UpdateCounter(notification_item_views_.size());

  if (!old_displayed_item)
    return;

  // Push |old_displayed_notification_item_view| to |overflow_view_|.
  old_displayed_item->SetVisible(false);

  const bool overflow_view_created = !overflow_view_;
  if (!overflow_view_)
    overflow_view_ = AddChildView(std::make_unique<NotificationOverflowView>());

  overflow_view_->AddIcon(old_displayed_item->proportional_image_view(),
                          old_displayed_item->notification_id());

  if (overflow_view_created) {
    PreferredSizeChanged();
    // OnOverflowAddedOrRemoved must be called after PreferredSizeChange to
    // ensure that enough room is allocated for the overflow view.
    notification_item_view_delegate_->OnOverflowAddedOrRemoved();
  }
  Layout();
}

void NotificationMenuView::UpdateNotificationItemView(
    const message_center::Notification& notification) {
  // Find the view which corresponds to |notification|.
  const auto i = NotificationIterForId(notification.id());
  if (i == notification_item_views_.end())
    return;

  (*i)->UpdateContents(notification.title(), notification.message(),
                       notification.icon());
}

void NotificationMenuView::OnNotificationRemoved(
    const std::string& notification_id) {
  // Find the view which corresponds to |notification_id|.
  const auto i = NotificationIterForId(notification_id);
  if (i == notification_item_views_.end())
    return;
  const bool removed_displayed_notification =
      *i == GetDisplayedNotificationItemView();

  RemoveChildViewT(*i);
  notification_item_views_.erase(i);
  header_view_->UpdateCounter(notification_item_views_.size());

  if (removed_displayed_notification) {
    // Display the next notification.
    auto* item = GetDisplayedNotificationItemView();
    if (item) {
      item->SetVisible(true);
      if (overflow_view_)
        overflow_view_->RemoveIcon(item->notification_id());
    }
  } else if (overflow_view_) {
    overflow_view_->RemoveIcon(notification_id);
  }

  if (overflow_view_ && overflow_view_->is_empty()) {
    // Remove and delete |overflow_view_|.
    RemoveChildViewT(overflow_view_);
    overflow_view_ = nullptr;
    PreferredSizeChanged();
    notification_item_view_delegate_->OnOverflowAddedOrRemoved();
  }
}

ui::Layer* NotificationMenuView::GetSlideOutLayer() {
  auto* item = GetDisplayedNotificationItemView();
  return item ? item->layer() : nullptr;
}

const NotificationItemView*
NotificationMenuView::GetDisplayedNotificationItemView() const {
  return notification_item_views_.empty() ? nullptr
                                          : notification_item_views_.front();
}

const std::string& NotificationMenuView::GetDisplayedNotificationID() const {
  DCHECK(!notification_item_views_.empty());
  return GetDisplayedNotificationItemView()->notification_id();
}

NotificationMenuView::NotificationItemViews::iterator
NotificationMenuView::NotificationIterForId(const std::string& id) {
  return std::find_if(
      notification_item_views_.begin(), notification_item_views_.end(),
      [id](const auto& item) { return item->notification_id() == id; });
}

}  // namespace ash


text:
var emitter = require('eventemitter2');
var $ = require('$');
angular.module('views').factory('AuthService', ['$rootScope', '$interval', '$browser', '$q', '$sessionStorage', '$window', function ($rootScope, $interval, $browser, $q, $sessionStorage, $window) {
  var _authenticated = false;
  var _refreshing = false;
  var authEmitter = new emitter();

  var doTokenTimer = null;
  var countDownTimer = null;
  var _idleMax = 120;
  var _idleCounter = 0;
  var _sessionCancelled = false;

  var _getIdleCounter = function(){
    return _idleCounter;
  };

  var startCountdown = function(){
    _idleMax = _idleCounter = 120;

    countDownTimer = $interval(function() {
      _idleCounter--;
      $rootScope.idleCounter = _idleCounter;
      $rootScope.$emit("$idleCounter", $rootScope.idleCounter);
      if (_idleCounter <= 0 && !_sessionCancelled) {
        _sessionCancelled = true;
        $rootScope.$emit("$sessionCancelled", _sessionCancelled);
        $interval.cancel(countDownTimer);
      }
    }, 1000, _idleMax);
  };

  var _doToken = function (result) {
    var now = new Date().getTime();
    var warning_time = 121000;
    var issued = new Date(result.issued).getTime();
    var expires_in = result.expires_in;
    var expires_time = issued + expires_in;
    var expires = new Date(expires_time);
    var popup_in = expires_time - now - warning_time;
    $interval.cancel(doTokenTimer);
    doTokenTimer = $interval(function () {
      $rootScope.$emit("$inactive", expires_time);
      startCountdown();
      var off = $rootScope.$on('$active', function () {
        off();
        console.log('$active', "refreshing");
        _isAuthenticated(true);
      });
    }, popup_in, 1);
  };

  authEmitter.on("token", _doToken);

  var _isAuthenticated = function (refresh, toState, fromState) {
    var deferAuth = $q.defer();
    // look for stored token, return true/false
    // console.log("checking authentication");

    _getAuthToken(refresh).then(function (result) {
      var now = new Date();
      var issued = new Date(result.issued).getTime();
      var expires_in = result.expires_in;
      var expires = new Date(issued + expires_in);

      // expired are we?
      if (expires < now) {
        //clearing storage because you are expired.
        $sessionStorage.$reset();
        deferAuth.resolve(false);
      } else if (result.access_token) {
        if (refresh) {
          _refreshAuthToken(toState, fromState).then(function (result) {
            deferAuth.resolve(true);
          }, function () {
            deferAuth.resolve(false);
          });
        } else {
          deferAuth.resolve(true);
        }
      } else {
        deferAuth.resolve(false);
      }
    }, function (error) {
      deferAuth.resolve(false);
    });

    return deferAuth.promise;
  };

  var _getAuthToken = function (orFail) {
    var deferGetToken = $q.defer();
    var objToken = {};

    if (_refreshing) {
      // listen for "new token"
      authEmitter.once("token", function (objToken) {
        deferGetToken.resolve(objToken);
      });
    } else {
      // TODO: date diff it, refresh it
      var token = require('qs').parse(location.hash.replace(/#.*#/, ""));
      if ($sessionStorage.careToken) {
        deferGetToken.resolve($sessionStorage.careToken);
      } else if (token.access_token) {
        $sessionStorage.careToken = token;
        deferGetToken.resolve($sessionStorage.careToken);

      } else if (orFail) {
        deferGetToken.reject();
      } else {
        authEmitter.once("token", function (objToken) {
          deferGetToken.resolve(objToken);
        });
      }
    }
    return deferGetToken.promise;
  };

  var _getRefresh = function () {
    var deferGetRefresh = $q.defer();

    _getAuthToken().then(function (response) {
      deferGetRefresh.resolve(response.refresh_token);
    });

    return deferGetRefresh.promise;
  };

  var _getAccess = function () {
    var deferGetAccess = $q.defer();

    _getAuthToken().then(function (response) {
      deferGetAccess.resolve(response.access_token);
    });

    return deferGetAccess.promise;
  };

  var _refreshAuthToken = function (toState, fromState) {
    var deferRefresh = $q.defer();
    if(_refreshing) {
      authEmitter.once("token", function(data){
        deferRefresh.resolve($sessionStorage.careToken);
      });
      return deferRefresh.promise;
    }
    if ($sessionStorage.careToken){
      _refreshing = true;
      var data = {
        grant_type: "refresh_token",
        refresh_token: $sessionStorage.careToken.refresh_token,
        client_id: "0"
      };

      // Angular $http FAIL. $ WIN.
      // get a new token or die
      console.log("$$incOutstandingRequestCount");
      $browser.$$incOutstandingRequestCount();

      console.log(JSON.stringify(data));
      var funTimes = 1;
      var fun = function () {
        var def = {
          type: "POST",
          headers: {
            "x-to-state": toState ? JSON.stringify(toState) : "unknown",
            "x-from-state": fromState ? JSON.stringify(fromState) : "unknown"
          },
          contentType: "application/json",
          data: JSON.stringify(data),
          success: function (data) {
            $sessionStorage.careToken = {};
            console.log(JSON.stringify(data));
            $sessionStorage.careToken.access_token = data.access_token;
            $sessionStorage.careToken.refresh_token = data.refresh_token;
            $sessionStorage.careToken.issued = data.issued;
            $sessionStorage.careToken.expires_in = data.expires_in;

            _refreshing = false;
            // emit "new token"
            authEmitter.emit("token", data);
            $rootScope.$emit("$auth.refresh");
            deferRefresh.resolve($sessionStorage.careToken);

            console.log("$$completeOutstandingRequest");
            $browser.$$completeOutstandingRequest(angular.noop);
          }
        };
        if (funTimes > 0) {
          def.timeout = 1000;
        }
        $.ajax('/auth/token', def).fail(function (jqXHR, status, error) {
          // do error type stuff;
          if (error == "timeout") {
            if (0 < funTimes--) {
              return fun();
            }
          }
          _refreshing = false;
          delete $sessionStorage.careToken;
          deferRefresh.reject({});
          console.log("$$completeOutstandingRequest");
          $browser.$$completeOutstandingRequest(angular.noop);
        });
      };
      fun();
    }else{
      deferRefresh.reject({});
    }
    return deferRefresh.promise;
  };

  var _setAuthToken = function (objToken) {
    console.log("inside SetAuth with " + JSON.stringify(objToken));
    var deferSetToken = $q.defer();

    if (objToken.access_token) {
      console.log("$window", $window);
      authEmitter.emit("token", objToken);
      $sessionStorage.careToken = objToken;
      _authenticated = true;
      $rootScope.auth = objToken;
      deferSetToken.resolve(objToken);
    } else {
      try {
        delete $sessionStorage.careToken;
        _authenticated = false;
        $rootScope.auth = objToken;
        deferSetToken.resolve(objToken);
      } catch (err) {
        console.log(err);
      }
    }
    return deferSetToken.promise;
  };

  return {
    authenticated: _authenticated,
    getAuthToken: _getAuthToken,
    isAuthenticated: _isAuthenticated,
    setAuthToken: _setAuthToken,
    getAccess: _getAccess,
    getRefresh: _getRefresh,
    getIdleCounter: _getIdleCounter,
    idleMax: _idleMax,
    idleCounter: _idleCounter,
    sessionCancelled: _sessionCancelled
  };
}]);


text:
package gnu.javax.crypto.keyring;

import java.util.Date;

/**
 * A primitive entry is an entry that contains a single cryptographic entity.
 */
public abstract class PrimitiveEntry
    extends Entry
{
  /** The creation date. */
  protected Date creationDate;

  protected PrimitiveEntry(int type, Date creationDate, Properties properties)
  {
    super(type, properties);
    if (creationDate == null)
      this.creationDate = new Date();
    else
      this.creationDate = (Date) creationDate.clone();
    if (! this.properties.containsKey("alias")
        || this.properties.get("alias").length() == 0)
      throw new IllegalArgumentException("primitive entries MUST have an alias");
    this.properties.put("creation-date",
                        String.valueOf(this.creationDate.getTime()));
  }

  protected PrimitiveEntry(int type)
  {
    super(type);
  }

  /**
   * Returns the alias of this primitive entry.
   *
   * @return The alias.
   */
  public String getAlias()
  {
    return properties.get("alias");
  }

  /**
   * Returns the creation date of this primitive entry.
   *
   * @return The creation date.
   */
  public Date getCreationDate()
  {
    return (Date) creationDate.clone();
  }

  public boolean equals(Object object)
  {
    if (! getClass().equals(object.getClass()))
      return false;
    return getAlias().equals(((PrimitiveEntry) object).getAlias());
  }

  protected final void makeCreationDate() throws MalformedKeyringException
  {
    String s = properties.get("creation-date");
    if (s == null)
      throw new MalformedKeyringException("no creation date");
    try
      {
        creationDate = new Date(Long.parseLong(s));
      }
    catch (NumberFormatException nfe)
      {
        throw new MalformedKeyringException("invalid creation date");
      }
  }
}


text:
{{{
  "title": "Configuring Windows File-level Backup (VSS)",
  "date": "7-23-2014",
  "author": "Jake Malmad",
  "attachments": [],
  "contentIsHTML": true
}}}

Microsoft's Volume Shadow Copy Service (VSS) is a framework which allows for backup operations to be performed without interrupting operations and generally does not cause perceivable performance degradation. While there are limitations and
  best-practices for VSS (i.e. high transaction environments, locked files, or non-VSS aware applications) the VSS service is a simple and effective way to provide an additional layer of granular protection and self-service restore operations. The most
  common use case for VSS is enabling revision history and backup for file servers- this document will demonstrate the configuration of both backup and restores on Windows Server 2008. The same principles apply to all version of Windows Server and Desktop
  operating systems.

While VSS is a powerful tool for retaining file versions, it is not a full-featured backup solution! It is meant to augment your overall backup strategy, but is NOT a technology that should be solely relied upon for enterprise backup and recovery- The CenturyLink Cloud's team of Solution Architects can assist in building an encompassing backup and Disaster Recovery solution to meet your business requirements.

To enable VSS, open Windows Explorer and browse to the volume you wish to protect. Right-click the volume and select "Properties". You will see a tab entitled "Shadow Copies"

By default, VSS is disabled. Click the "Enable" button to begin- an information dialog box will appear, to continue enabling VSS, select the "Yes" option. It is important to heed the warning presented by Microsoft, echoing the use cases outlined in this
  introduction of this article: "The default settings are not appropriate for servers that have high I/O load. For heavily used servers, you should manually configure shadow copies and place the storage area on a volume that will not be shadow copied". Again,
  if you require a backup solution for a high-performance server, The CenturyLink Cloud's Solution Architects can assist you in designing an appropriate backup solution.

Once you have clicked "Yes", you will see a time stamp noting the first successful shadow copy. By clicking the "Settings" button, you can configure both the storage limits as well as the snapshot schedule- the default configuration does not have a storage
  limit and takes snapshots at 7:00A.M and 12:00P.M.

To set a storage limit, select the "Use Limit" radio button and input an integer value for the size limit (in megabytes). You can use the "Details" button if you would like to specify a separate volume for VSS snapshot storage. In this example, we limit
  the consumption to 2GB:

Use the "Schedule" button to adjust the default schedules. In the initial view, you can change the two pre-defined schedules- create additional schedules using the "New" button, or delete existing schedules using the "Delete" button.

If you would like to change the snapshot frequency, click the "Advanced" button, and check the "Repeat Task" check-box. In this example, we will take VSS snapshots every 15 minutes during business hours:

Performing a restore:

To perform a restore of a deleted or modified file, right-click on the parent folder and select "Properties". Navigate to the "Previous Versions" tab:

From this dialog, you can either open the folder to restore individual files or sub-folders, or restore the entire folder. If you wish to restore a single file, select "Open" and then copy and paste the previous version of the desired file to a new location.

If you wish to restore the entire folder- you will be presented with a warning- please proceed with caution as the restore operation will replace the current version of the folder on your machine.


text:
/**
 *  \file
 *
 *  \section Purpose
 *
 *  Interface for configuring and using Timer Counter (TC) peripherals.
 *
 *  \section Usage
 *  -# Optionally, use TC_FindMckDivisor() to let the program find the best
 *     TCCLKS field value automatically.
 *  -# Configure a Timer Counter in the desired mode using TC_Configure().
 *  -# Start or stop the timer clock using TC_Start() and TC_Stop().
 */

#ifndef _TC_
#define _TC_

/*------------------------------------------------------------------------------
 *         Headers
 *------------------------------------------------------------------------------*/

#include "chip.h"

#include <stdint.h>

/*------------------------------------------------------------------------------
 *         Global functions
 *------------------------------------------------------------------------------*/

#ifdef __cplusplus
 extern "C" {
#endif

extern void TC_Configure( Tc *pTc, uint32_t dwChannel, uint32_t dwMode ) ;

extern void TC_Start( Tc *pTc, uint32_t dwChannel ) ;

extern void TC_Stop( Tc *pTc, uint32_t dwChannel ) ;

extern uint32_t TC_FindMckDivisor( uint32_t dwFreq, uint32_t dwMCk, uint32_t *dwDiv, uint32_t *dwTcClks, uint32_t dwBoardMCK ) ;

extern uint32_t TC_ReadCV(Tc *p_tc, uint32_t ul_channel);

extern uint32_t TC_GetStatus(Tc *p_tc, uint32_t ul_channel);

extern void TC_SetRA(Tc *tc, uint32_t chan, uint32_t v) ;

extern void TC_SetRB(Tc *tc, uint32_t chan, uint32_t v) ;

extern void TC_SetRC(Tc *tc, uint32_t chan, uint32_t v) ;

#ifdef __cplusplus
}
#endif

#endif /* #ifndef _TC_ */


text:
{-# LANGUAGE CPP #-}

module SAWScript.AutoMatch.ArgMapping
  ( ArgMapping
  , typeBins
  , nameLocs
  , makeArgMapping
  , removeName
  , lookupName
  , lookupType
  , emptyArgMapping
  , isEmptyArgMapping ) where

import qualified Data.Map as Map
import           Data.Map   (Map)
import qualified Data.Set as Set
import           Data.Set   (Set)

import Data.Maybe
#if !MIN_VERSION_base(4,8,0)
import Control.Applicative
#endif

import SAWScript.AutoMatch.Declaration
import SAWScript.AutoMatch.Util

-- | A bidirectional mapping representing what arguments have what types at what positions in a declaration
--   Abstract, because we preserve the invariant that the maps contained are coherent.
data ArgMapping =
   ArgMapping { typeBins_ :: Map Type (Set (Name, Int))
              , nameLocs_ :: Map Name (Int, Type) }
              deriving (Show)

typeBins :: ArgMapping -> Map Type (Set (Name, Int))
typeBins = typeBins_

nameLocs :: ArgMapping -> Map Name (Int, Type)
nameLocs = nameLocs_

-- | Make an argMapping from a list of Args
makeArgMapping :: [Arg] -> ArgMapping
makeArgMapping =
   ArgMapping <$> foldr (uncurry (\k -> Map.insertWith Set.union k . Set.singleton)) Map.empty
                  . map (\(i, a) -> (argType a, (argName a, i)))
                  . zip [0..]
              <*> foldr (uncurry Map.insert) Map.empty
                  . map (\(i, a) -> (argName a, (i, argType a)))
                  . zip [0..]

-- | Remove a name from an ArgMapping
removeName :: Name -> ArgMapping -> ArgMapping
removeName name mapping =
   fromMaybe mapping $ do
      (nameIndex, nameType) <- Map.lookup name (nameLocs mapping)
      return $ ArgMapping
         (deleteFromSetMap nameType (name, nameIndex) (typeBins mapping))
         (Map.delete name (nameLocs mapping))

-- | Look up a name's type and position in the original declaration
lookupName :: Name -> ArgMapping -> Maybe (Int, Type)
lookupName name (ArgMapping _ nls) = Map.lookup name nls

-- | Look up all the names of a given type and their indices
lookupType :: Type -> ArgMapping -> Maybe (Set (Name, Int))
lookupType typ (ArgMapping tbs _) = Map.lookup typ tbs

-- | The empty ArgMapping
emptyArgMapping :: ArgMapping
emptyArgMapping = makeArgMapping []

-- | Test if an ArgMapping is empty
isEmptyArgMapping :: ArgMapping -> Bool
isEmptyArgMapping (ArgMapping t n) =
  Map.null t && Map.null n


text:
[Mina](https://github.com/mina-deploy/mina) tasks for interacting with [Rollbar](http://rollbar.com).

Adds the following tasks:

    rollbar:notify

## Installation

Add this line to your application's Gemfile:

```ruby
gem 'mina-rollbar', require: false
```

And then execute:

    $ bundle

## Usage

    require 'mina/rollbar'

    ...
    # replace value w/your real access token
    set :rollbar_access_token, 'this-is-not-a-real-token'

    task deploy: :environment do
      deploy do
        ...

        to :launch do
          ...
          invoke :'rollbar:notify'
        end
      end
    end

## Options

| Name                         | Description                                            |
| ---------------------------- | ------------------------------------------------------ |
| `rollbar_access_token`       | Rollbar access token (post_server_item token)          |
| `rollbar_username`           | Rollbar username of deploying user (optional)          |
| `rollbar_local_username`     | Local username of deploying user (optional)            |
| `rollbar_comment`            | Comment for this deployment (optional)                 |
| `rollbar_env`                | Deployment environment string, defaults to `rails_env` |

## Contributing

1. Fork it ( https://github.com/code-lever/mina-rollbar/fork )
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create a new Pull Request


text:
import os
import shutil
import zipfile

from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect, Http404
from django.shortcuts import get_object_or_404, render_to_response
from django.template import RequestContext
from django.views.generic.list_detail import object_list

from guardian.shortcuts import assign

from builds.forms import AliasForm, VersionForm
from builds.filters import VersionFilter
from builds.models import Version
from projects.forms import (ImportProjectForm, build_versions_form,
                            build_upload_html_form, SubprojectForm,
                            UserForm, EmailHookForm, TranslationForm,
                            AdvancedProjectForm)
from projects.models import Project, EmailHook
from projects import constants

@login_required
def project_dashboard(request):
    """
    A dashboard!  If you aint know what that means you aint need to.
    Essentially we show you an overview of your content.
    """
    qs = (Version.objects.active(user=request.user)
          .filter(project__users__in=[request.user]))
    filter = VersionFilter(constants.IMPORTANT_VERSION_FILTERS, queryset=qs)
    return object_list(
        request,
        queryset=request.user.projects.live(),
        page=int(request.GET.get('page', 1)),
        template_object_name='project',
        template_name='projects/project_dashboard.html',
        extra_context={
            'filter': filter,
        }
    )

@login_required
def project_manage(request, project_slug):
    """
    The management view for a project, where you will have links to edit
    the projects' configuration, edit the files associated with that
    project, etc.

    Now redirects to the normal /projects/<slug> view.
    """
    return HttpResponseRedirect(reverse('projects_detail',
                                        args=[project_slug]))

@login_required
def project_edit(request, project_slug):
    """
    Edit an existing project - depending on what type of project is being
    edited (created or imported) a different form will be displayed
    """
    project = get_object_or_404(request.user.projects.live(),
                                slug=project_slug)

    form_class = ImportProjectForm

    form = form_class(instance=project, data=request.POST or None)

    if request.method == 'POST' and form.is_valid():
        form.save()
        project_dashboard = reverse('projects_detail', args=[project.slug])
        return HttpResponseRedirect(project_dashboard)

    return render_to_response(
        'projects/project_edit.html',
        {'form': form, 'project': project},
        context_instance=RequestContext(request)
    )

@login_required
def project_advanced(request, project_slug):
    """
    Edit an existing project - depending on what type of project is being
    edited (created or imported) a different form will be displayed
    """
    project = get_object_or_404(request.user.projects.live(),
                                slug=project_slug)
    form_class = AdvancedProjectForm
    form = form_class(instance=project, data=request.POST or None, initial={'num_minor': 2, 'num_major': 2, 'num_point': 2})

    if request.method == 'POST' and form.is_valid():
        form.save()
        project_dashboard = reverse('projects_detail', args=[project.slug])
        return HttpResponseRedirect(project_dashboard)

    return render_to_response(
        'projects/project_advanced.html',
        {'form': form, 'project': project},
        context_instance=RequestContext(request)
    )

@login_required
def project_versions(request, project_slug):
    """
    Shows the available versions and lets the user choose which ones he would
    like to have built.
    """
    project = get_object_or_404(request.user.projects.live(),
                                slug=project_slug)

    if not project.is_imported:
        raise Http404

    form_class = build_versions_form(project)

    form = form_class(data=request.POST or None)

    if request.method == 'POST' and form.is_valid():
        form.save()
        project_dashboard = reverse('projects_detail', args=[project.slug])
        return HttpResponseRedirect(project_dashboard)

    return render_to_response(
        'projects/project_versions.html',
        {'form': form, 'project': project},
        context_instance=RequestContext(request)
    )

@login_required
def project_version_detail(request, project_slug, version_slug):
    project = get_object_or_404(request.user.projects.live(),
                                slug=project_slug)
    version = get_object_or_404(project.versions.all(), slug=version_slug)

    form = VersionForm(request.POST or None, instance=version)

    if request.method == 'POST' and form.is_valid():
        form.save()
        url = reverse('projects_versions', args=[project.slug])
        return HttpResponseRedirect(url)

    return render_to_response(
        'projects/project_version_detail.html',
        {'form': form, 'project': project, 'version': version},
        context_instance=RequestContext(request)
    )

@login_required
def project_delete(request, project_slug):
    """
    Make a project as deleted on POST, otherwise show a form asking for
    confirmation of delete.
    """
    project = get_object_or_404(request.user.projects.live(),
                                slug=project_slug)

    if request.method == 'POST':
        # Remove the repository checkout
        shutil.rmtree(project.doc_path, ignore_errors=True)
        # Delete the project and everything related to it
        project.delete()
        project_dashboard = reverse('projects_dashboard')
        return HttpResponseRedirect(project_dashboard)

    return render_to_response(
        'projects/project_delete.html',
        {'project': project},
        context_instance=RequestContext(request)
    )

@login_required
def project_import(request):
    """
    Import docs from an repo
    """
    form = ImportProjectForm(request.POST or None)

    if request.method == 'POST' and form.is_valid():
        project = form.save()
        form.instance.users.add(request.user)
        assign('view_project', request.user, project)
        project_manage = reverse('projects_detail', args=[project.slug])
        return HttpResponseRedirect(project_manage + '?docs_not_built=True')

    return render_to_response(
        'projects/project_import.html',
        {'form': form},
        context_instance=RequestContext(request)
    )

@login_required
def edit_alias(request, project_slug, id=None):
    proj = get_object_or_404(Project.objects.all(), slug=project_slug)
    if id:
        alias = proj.aliases.get(pk=id)
        form = AliasForm(instance=alias, data=request.POST or None)
    else:
        form = AliasForm(request.POST or None)

    if request.method == 'POST' and form.is_valid():
        alias = form.save()
        return HttpResponseRedirect(alias.project.get_absolute_url())
    return render_to_response(
        'projects/alias_edit.html',
        {'form': form},
        context_instance=RequestContext(request)
    )

@login_required
def list_alias(request, project_slug):
    proj = get_object_or_404(Project.objects.all(), slug=project_slug)
    return object_list(
        request,
        queryset=proj.aliases.all(),
        template_object_name='alias',
        template_name='projects/alias_list.html',
    )

@login_required
def project_subprojects(request, project_slug):
    project = get_object_or_404(request.user.projects.live(),
                                slug=project_slug)

    form = SubprojectForm(data=request.POST or None, parent=project)

    if request.method == 'POST' and form.is_valid():
        form.save()
        project_dashboard = reverse('projects_subprojects', args=[project.slug])
        return HttpResponseRedirect(project_dashboard)

    subprojects = project.subprojects.all()

    return render_to_response(
        'projects/project_subprojects.html',
        {'form': form, 'project': project, 'subprojects': subprojects},
        context_instance=RequestContext(request)
    )

@login_required
def project_subprojects_delete(request, project_slug, child_slug):
    parent = get_object_or_404(request.user.projects.live(), slug=project_slug)
    child = get_object_or_404(Project.objects.all(), slug=child_slug)

    parent.remove_subproject(child)

    project_dashboard = reverse('projects_detail', args=[parent.slug])
    return HttpResponseRedirect(project_dashboard)

@login_required
def project_users(request, project_slug):
    project = get_object_or_404(request.user.projects.live(),
                                slug=project_slug)

    form = UserForm(data=request.POST or None, project=project)

    if request.method == 'POST' and form.is_valid():
        form.save()
        project_dashboard = reverse('projects_users', args=[project.slug])
        return HttpResponseRedirect(project_dashboard)

    users = project.users.all()

    return render_to_response(
        'projects/project_users.html',
        {'form': form, 'project': project, 'users': users},
        context_instance=RequestContext(request)
    )

@login_required
def project_users_delete(request, project_slug):
    if request.method != 'POST':
        raise Http404
    project = get_object_or_404(request.user.projects.live(),
                                slug=project_slug)
    user = get_object_or_404(User.objects.all(),
                             username=request.POST.get('username'))
    if user == request.user:
        raise Http404
    project.users.remove(user)
    project_dashboard = reverse('projects_users', args=[project.slug])
    return HttpResponseRedirect(project_dashboard)

@login_required
def project_notifications(request, project_slug):
    project = get_object_or_404(request.user.projects.live(),
                                slug=project_slug)
    form = EmailHookForm(data=request.POST or None, project=project)

    if request.method == 'POST' and form.is_valid():
        form.save()
        project_dashboard = reverse('projects_notifications',
                                    args=[project.slug])
        return HttpResponseRedirect(project_dashboard)

    emails = project.emailhook_notifications.all()

    return render_to_response(
        'projects/project_notifications.html',
        {'form': form, 'project': project, 'emails': emails},
        context_instance=RequestContext(request)
    )

@login_required
def project_notifications_delete(request, project_slug):
    if request.method != 'POST':
        raise Http404
    project = get_object_or_404(request.user.projects.live(),
                                slug=project_slug)
    notification = get_object_or_404(EmailHook.objects.all(),
                                     email=request.POST.get('email'))
    notification.delete()
    project_dashboard = reverse('projects_notifications', args=[project.slug])
    return HttpResponseRedirect(project_dashboard)

@login_required
def project_translations(request, project_slug):
    project = get_object_or_404(request.user.projects.live(),
                                slug=project_slug)
    form = TranslationForm(data=request.POST or None, parent=project)

    if request.method == 'POST' and form.is_valid():
        form.save()
        project_dashboard = reverse('projects_translations',
                                    args=[project.slug])
        return HttpResponseRedirect(project_dashboard)

    lang_projects = project.translations.all()

    return render_to_response(
        'projects/project_translations.html',
        {'form': form, 'project': project, 'lang_projects': lang_projects},
        context_instance=RequestContext(request)
    )

@login_required
def project_translations_delete(request, project_slug, child_slug):
    project = get_object_or_404(request.user.projects.live(),
                                slug=project_slug)
    subproj = get_object_or_404(Project.objects.public(), slug=child_slug)
    project.translations.remove(subproj)
    project_dashboard = reverse('projects_translations', args=[project.slug])
    return HttpResponseRedirect(project_dashboard)


text:
package io.github.jokoframework.mboehaolib.util;

import android.content.Context;
import android.graphics.Point;
import android.view.Display;
import android.view.WindowManager;

import java.util.HashMap;
import java.util.Map;

import io.github.jokoframework.mboehaolib.constants.Constants;

/**
 * Created by joaquin on 23/08/17.
 */

public class ImageUtils {

    private static final String DEFAULT_FONT_SIZE = "2";
    private static final String HD_FONT_SIZE = "3";
    private static final String TABLET_FONT_SIZE = "4";
    private static Map<Integer, Integer> warningPoints = new HashMap<>();

    private ImageUtils() {
    }

    public static Point getScreenSizeInPixels(Context context) {
        WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        Display display = windowManager.getDefaultDisplay();
        Point size = new Point();
        display.getSize(size);
        return size;
    }

    public static String getHtmlScaledFontSize(Context context) {
        String fontSize = DEFAULT_FONT_SIZE;
        Point screenSize = getScreenSizeInPixels(context);
        if (screenSize != null) {
            if (Constants.TABLET_VERTICAL_RESOLUTION >= screenSize.y) {
                fontSize = TABLET_FONT_SIZE;
            } else if (Constants.HD_VERTICAL_RESOLUTION >= screenSize.y) {
                fontSize = HD_FONT_SIZE;
            }
        }
        return fontSize;
    }
}


text:
using System.Linq;
using System.Linq.Expressions;
using System.Security.Claims;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Xunit;

namespace Microsoft.AspNetCore.Identity.Test;

/// <summary>
/// Common functionality tests that all verifies user manager functionality regardless of store implementation
/// </summary>
/// <typeparam name="TUser">The type of the user.</typeparam>
/// <typeparam name="TRole">The type of the role.</typeparam>
public abstract class IdentitySpecificationTestBase<TUser, TRole> : IdentitySpecificationTestBase<TUser, TRole, string>
    where TUser : class
    where TRole : class
{ }

/// <summary>
/// Base class for tests that exercise basic identity functionality that all stores should support.
/// </summary>
/// <typeparam name="TUser">The type of the user.</typeparam>
/// <typeparam name="TRole">The type of the role.</typeparam>
/// <typeparam name="TKey">The primary key type.</typeparam>
public abstract class IdentitySpecificationTestBase<TUser, TRole, TKey> : UserManagerSpecificationTestBase<TUser, TKey>
    where TUser : class
    where TRole : class
    where TKey : IEquatable<TKey>
{
    /// <summary>
    /// Configure the service collection used for tests.
    /// </summary>
    /// <param name="services"></param>
    /// <param name="context"></param>
    protected override void SetupIdentityServices(IServiceCollection services, object context)
    {
        services.AddHttpContextAccessor();
        services.AddSingleton<IDataProtectionProvider, EphemeralDataProtectionProvider>();
        services.AddIdentity<TUser, TRole>(options =>
        {
            options.Password.RequireDigit = false;
            options.Password.RequireLowercase = false;
            options.Password.RequireNonAlphanumeric = false;
            options.Password.RequireUppercase = false;
            options.User.AllowedUserNameCharacters = null;
        }).AddDefaultTokenProviders();
        AddUserStore(services, context);
        AddRoleStore(services, context);
        services.AddLogging();
        services.AddSingleton<ILogger<UserManager<TUser>>>(new TestLogger<UserManager<TUser>>());
        services.AddSingleton<ILogger<RoleManager<TRole>>>(new TestLogger<RoleManager<TRole>>());
    }

    /// <summary>
    /// Setup the IdentityBuilder
    /// </summary>
    /// <param name="services"></param>
    /// <param name="context"></param>
    /// <returns></returns>
    protected override IdentityBuilder SetupBuilder(IServiceCollection services, object context)
    {
        var builder = base.SetupBuilder(services, context);
        builder.AddRoles<TRole>();
        AddRoleStore(services, context);
        services.AddSingleton<ILogger<RoleManager<TRole>>>(new TestLogger<RoleManager<TRole>>());
        return builder;
    }

    /// <summary>
    /// Creates the role manager for tests.
    /// </summary>
    /// <param name="context">The context that will be passed into the store, typically a db context.</param>
    /// <param name="services">The service collection to use, optional.</param>
    /// <returns></returns>
    protected virtual RoleManager<TRole> CreateRoleManager(object context = null, IServiceCollection services = null)
    {
        if (services == null)
        {
            services = new ServiceCollection();
        }
        if (context == null)
        {
            context = CreateTestContext();
        }
        SetupIdentityServices(services, context);
        return services.BuildServiceProvider().GetService<RoleManager<TRole>>();
    }

    /// <summary>
    /// Adds an IRoleStore to services for the test.
    /// </summary>
    /// <param name="services">The service collection to add to.</param>
    /// <param name="context">The context for the store to use, optional.</param>
    protected abstract void AddRoleStore(IServiceCollection services, object context = null);

    /// <summary>
    /// Creates a new test role instance.
    /// </summary>
    /// <param name="roleNamePrefix">Optional name prefix, name will be randomized.</param>
    /// <param name="useRoleNamePrefixAsRoleName">If true, the prefix should be used as the rolename without a random pad.</param>
    /// <returns></returns>
    protected abstract TRole CreateTestRole(string roleNamePrefix = "", bool useRoleNamePrefixAsRoleName = false);

    /// <summary>
    /// Query used to do name equality checks.
    /// </summary>
    /// <param name="roleName">The role name to match.</param>
    /// <returns>The query to use.</returns>
    protected abstract Expression<Func<TRole, bool>> RoleNameEqualsPredicate(string roleName);

    /// <summary>
    /// Query used to do user name prefix matching.
    /// </summary>
    /// <param name="roleName">The role name to match.</param>
    /// <returns>The query to use.</returns>
    protected abstract Expression<Func<TRole, bool>> RoleNameStartsWithPredicate(string roleName);

    /// <summary>
    /// Test.
    /// </summary>
    /// <returns>Task</returns>
    [Fact]
    public async Task CanCreateRoleTest()
    {
        var manager = CreateRoleManager();
        var roleName = "create" + Guid.NewGuid().ToString();
        var role = CreateTestRole(roleName, useRoleNamePrefixAsRoleName: true);
        Assert.False(await manager.RoleExistsAsync(roleName));
        IdentityResultAssert.IsSuccess(await manager.CreateAsync(role));
        Assert.True(await manager.RoleExistsAsync(roleName));
    }

    private sealed class AlwaysBadValidator : IUserValidator<TUser>, IRoleValidator<TRole>,
        IPasswordValidator<TUser>
    {
        public static readonly IdentityError ErrorMessage = new IdentityError { Description = "I'm Bad.", Code = "BadValidator" };

        public Task<IdentityResult> ValidateAsync(UserManager<TUser> manager, TUser user, string password)
        {
            return Task.FromResult(IdentityResult.Failed(ErrorMessage));
        }

        public Task<IdentityResult> ValidateAsync(RoleManager<TRole> manager, TRole role)
        {
            return Task.FromResult(IdentityResult.Failed(ErrorMessage));
        }

        public Task<IdentityResult> ValidateAsync(UserManager<TUser> manager, TUser user)
        {
            return Task.FromResult(IdentityResult.Failed(ErrorMessage));
        }
    }

    /// <summary>
    /// Test.
    /// </summary>
    /// <returns>Task</returns>
    [Fact]
    public async Task BadValidatorBlocksCreateRole()
    {
        var manager = CreateRoleManager();
        manager.RoleValidators.Clear();
        manager.RoleValidators.Add(new AlwaysBadValidator());
        var role = CreateTestRole("blocked");
        IdentityResultAssert.IsFailure(await manager.CreateAsync(role),
            AlwaysBadValidator.ErrorMessage);
        IdentityResultAssert.VerifyLogMessage(manager.Logger, $"Role {await manager.GetRoleIdAsync(role) ?? NullValue} validation failed: {AlwaysBadValidator.ErrorMessage.Code}.");
    }

    /// <summary>
    /// Test.
    /// </summary>
    /// <returns>Task</returns>
    [Fact]
    public async Task CanChainRoleValidators()
    {
        var manager = CreateRoleManager();
        manager.RoleValidators.Clear();
        manager.RoleValidators.Add(new AlwaysBadValidator());
        manager.RoleValidators.Add(new AlwaysBadValidator());
        var role = CreateTestRole("blocked");
        var result = await manager.CreateAsync(role);
        IdentityResultAssert.IsFailure(result, AlwaysBadValidator.ErrorMessage);
        IdentityResultAssert.VerifyLogMessage(manager.Logger, $"Role {await manager.GetRoleIdAsync(role) ?? NullValue} validation failed: {AlwaysBadValidator.ErrorMessage.Code};{AlwaysBadValidator.ErrorMessage.Code}.");
        Assert.Equal(2, result.Errors.Count());
    }

    /// <summary>
    /// Test.
    /// </summary>
    /// <returns>Task</returns>
    [Fact]
    public async Task BadValidatorBlocksRoleUpdate()
    {
        var manager = CreateRoleManager();
        var role = CreateTestRole("poorguy");
        IdentityResultAssert.IsSuccess(await manager.CreateAsync(role));
        var error = AlwaysBadValidator.ErrorMessage;
        manager.RoleValidators.Clear();
        manager.RoleValidators.Add(new AlwaysBadValidator());
        IdentityResultAssert.IsFailure(await manager.UpdateAsync(role), error);
        IdentityResultAssert.VerifyLogMessage(manager.Logger, $"Role {await manager.GetRoleIdAsync(role) ?? NullValue} validation failed: {AlwaysBadValidator.ErrorMessage.Code}.");
    }

    /// <summary>
    /// Test.
    /// </summary>
    /// <returns>Task</returns>
    [Fact]
    public async Task CanDeleteRole()
    {
        var manager = CreateRoleManager();
        var roleName = "delete" + Guid.NewGuid().ToString();
        var role = CreateTestRole(roleName, useRoleNamePrefixAsRoleName: true);
        Assert.False(await manager.RoleExistsAsync(roleName));
        IdentityResultAssert.IsSuccess(await manager.CreateAsync(role));
        Assert.True(await manager.RoleExistsAsync(roleName));
        IdentityResultAssert.IsSuccess(await manager.DeleteAsync(role));
        Assert.False(await manager.RoleExistsAsync(roleName));
    }

    /// <summary>
    /// Test.
    /// </summary>
    /// <returns>Task</returns>
    [Fact]
    public async Task CanAddRemoveRoleClaim()
    {
        var manager = CreateRoleManager();
        var role = CreateTestRole("ClaimsAddRemove");
        var roleSafe = CreateTestRole("ClaimsAdd");
        IdentityResultAssert.IsSuccess(await manager.CreateAsync(role));
        IdentityResultAssert.IsSuccess(await manager.CreateAsync(roleSafe));
        Claim[] claims = { new Claim("c", "v"), new Claim("c2", "v2"), new Claim("c2", "v3") };
        foreach (Claim c in claims)
        {
            IdentityResultAssert.IsSuccess(await manager.AddClaimAsync(role, c));
            IdentityResultAssert.IsSuccess(await manager.AddClaimAsync(roleSafe, c));
        }
        var roleClaims = await manager.GetClaimsAsync(role);
        var safeRoleClaims = await manager.GetClaimsAsync(roleSafe);
        Assert.Equal(3, roleClaims.Count);
        Assert.Equal(3, safeRoleClaims.Count);
        IdentityResultAssert.IsSuccess(await manager.RemoveClaimAsync(role, claims[0]));
        roleClaims = await manager.GetClaimsAsync(role);
        safeRoleClaims = await manager.GetClaimsAsync(roleSafe);
        Assert.Equal(2, roleClaims.Count);
        Assert.Equal(3, safeRoleClaims.Count);
        IdentityResultAssert.IsSuccess(await manager.RemoveClaimAsync(role, claims[1]));
        roleClaims = await manager.GetClaimsAsync(role);
        safeRoleClaims = await manager.GetClaimsAsync(roleSafe);
        Assert.Equal(1, roleClaims.Count);
        Assert.Equal(3, safeRoleClaims.Count);
        IdentityResultAssert.IsSuccess(await manager.RemoveClaimAsync(role, claims[2]));
        roleClaims = await manager.GetClaimsAsync(role);
        safeRoleClaims = await manager.GetClaimsAsync(roleSafe);
        Assert.Equal(0, roleClaims.Count);
        Assert.Equal(3, safeRoleClaims.Count);
    }

    /// <summary>
    /// Test.
    /// </summary>
    /// <returns>Task</returns>
    [Fact]
    public async Task CanRoleFindById()
    {
        var manager = CreateRoleManager();
        var role = CreateTestRole("FindByIdAsync");
        Assert.Null(await manager.FindByIdAsync(await manager.GetRoleIdAsync(role)));
        IdentityResultAssert.IsSuccess(await manager.CreateAsync(role));
        Assert.Equal(role, await manager.FindByIdAsync(await manager.GetRoleIdAsync(role)));
    }

    /// <summary>
    /// Test.
    /// </summary>
    /// <returns>Task</returns>
    [Fact]
    public async Task CanRoleFindByName()
    {
        var manager = CreateRoleManager();
        var roleName = "FindByNameAsync" + Guid.NewGuid().ToString();
        var role = CreateTestRole(roleName, useRoleNamePrefixAsRoleName: true);
        Assert.Null(await manager.FindByNameAsync(roleName));
        Assert.False(await manager.RoleExistsAsync(roleName));
        IdentityResultAssert.IsSuccess(await manager.CreateAsync(role));
        Assert.Equal(role, await manager.FindByNameAsync(roleName));
    }

    /// <summary>
    /// Test.
    /// </summary>
    /// <returns>Task</returns>
    [Fact]
    public async Task CanUpdateRoleName()
    {
        var manager = CreateRoleManager();
        var roleName = "update" + Guid.NewGuid().ToString();
        var role = CreateTestRole(roleName, useRoleNamePrefixAsRoleName: true);
        Assert.False(await manager.RoleExistsAsync(roleName));
        IdentityResultAssert.IsSuccess(await manager.CreateAsync(role));
        Assert.True(await manager.RoleExistsAsync(roleName));
        IdentityResultAssert.IsSuccess(await manager.SetRoleNameAsync(role, "Changed"));
        IdentityResultAssert.IsSuccess(await manager.UpdateAsync(role));
        Assert.False(await manager.RoleExistsAsync("update"));
        Assert.Equal(role, await manager.FindByNameAsync("Changed"));
    }

    /// <summary>
    /// Test.
    /// </summary>
    /// <returns>Task</returns>
    [Fact]
    public virtual async Task CanQueryableRoles()
    {
        var manager = CreateRoleManager();
        if (manager.SupportsQueryableRoles)
        {
            var roles = GenerateRoles("CanQueryableRolesTest", 4);
            foreach (var r in roles)
            {
                IdentityResultAssert.IsSuccess(await manager.CreateAsync(r));
            }
            Expression<Func<TRole, bool>> func = RoleNameStartsWithPredicate("CanQueryableRolesTest");
            Assert.Equal(roles.Count, manager.Roles.Count(func));
            func = RoleNameEqualsPredicate("bogus");
            Assert.Empty(manager.Roles.Where(func));

        }
    }

    /// <summary>
    /// Test.
    /// </summary>
    /// <returns>Task</returns>
    [Fact]
    public async Task CreateRoleFailsIfExists()
    {
        var manager = CreateRoleManager();
        var roleName = "dupeRole" + Guid.NewGuid().ToString();
        var role = CreateTestRole(roleName, useRoleNamePrefixAsRoleName: true);
        Assert.False(await manager.RoleExistsAsync(roleName));
        IdentityResultAssert.IsSuccess(await manager.CreateAsync(role));
        Assert.True(await manager.RoleExistsAsync(roleName));
        var role2 = CreateTestRole(roleName, useRoleNamePrefixAsRoleName: true);
        IdentityResultAssert.IsFailure(await manager.CreateAsync(role2));
    }

    /// <summary>
    /// Test.
    /// </summary>
    /// <returns>Task</returns>
    [Fact]
    public async Task CanAddUsersToRole()
    {
        var context = CreateTestContext();
        var manager = CreateManager(context);
        var roleManager = CreateRoleManager(context);
        var roleName = "AddUserTest" + Guid.NewGuid().ToString();
        var role = CreateTestRole(roleName, useRoleNamePrefixAsRoleName: true);
        IdentityResultAssert.IsSuccess(await roleManager.CreateAsync(role));
        TUser[] users =
        {
                CreateTestUser("1"),CreateTestUser("2"),CreateTestUser("3"),CreateTestUser("4"),
            };
        foreach (var u in users)
        {
            IdentityResultAssert.IsSuccess(await manager.CreateAsync(u));
            IdentityResultAssert.IsSuccess(await manager.AddToRoleAsync(u, roleName));
            Assert.True(await manager.IsInRoleAsync(u, roleName));
        }
    }

    /// <summary>
    /// Test.
    /// </summary>
    /// <returns>Task</returns>
    [Fact]
    public async Task CanGetRolesForUser()
    {
        var context = CreateTestContext();
        var userManager = CreateManager(context);
        var roleManager = CreateRoleManager(context);
        var users = GenerateUsers("CanGetRolesForUser", 4);
        var roles = GenerateRoles("CanGetRolesForUserRole", 4);
        foreach (var u in users)
        {
            IdentityResultAssert.IsSuccess(await userManager.CreateAsync(u));
        }
        foreach (var r in roles)
        {
            IdentityResultAssert.IsSuccess(await roleManager.CreateAsync(r));
            foreach (var u in users)
            {
                IdentityResultAssert.IsSuccess(await userManager.AddToRoleAsync(u, await roleManager.GetRoleNameAsync(r)));
                Assert.True(await userManager.IsInRoleAsync(u, await roleManager.GetRoleNameAsync(r)));
            }
        }

        foreach (var u in users)
        {
            var rs = await userManager.GetRolesAsync(u);
            Assert.Equal(roles.Count, rs.Count);
            foreach (var r in roles)
            {
                var expectedRoleName = await roleManager.GetRoleNameAsync(r);
                Assert.Contains(rs, role => role == expectedRoleName);
            }
        }
    }

    /// <summary>
    /// Test.
    /// </summary>
    /// <returns>Task</returns>
    [Fact]
    public async Task RemoveUserFromRoleWithMultipleRoles()
    {
        var context = CreateTestContext();
        var userManager = CreateManager(context);
        var roleManager = CreateRoleManager(context);
        var user = CreateTestUser();
        IdentityResultAssert.IsSuccess(await userManager.CreateAsync(user));
        var roles = GenerateRoles("RemoveUserFromRoleWithMultipleRoles", 4);
        foreach (var r in roles)
        {
            IdentityResultAssert.IsSuccess(await roleManager.CreateAsync(r));
            IdentityResultAssert.IsSuccess(await userManager.AddToRoleAsync(user, await roleManager.GetRoleNameAsync(r)));
            Assert.True(await userManager.IsInRoleAsync(user, await roleManager.GetRoleNameAsync(r)));
        }
        IdentityResultAssert.IsSuccess(await userManager.RemoveFromRoleAsync(user, await roleManager.GetRoleNameAsync(roles[2])));
        Assert.False(await userManager.IsInRoleAsync(user, await roleManager.GetRoleNameAsync(roles[2])));
    }

    /// <summary>
    /// Test.
    /// </summary>
    /// <returns>Task</returns>
    [Fact]
    public async Task CanRemoveUsersFromRole()
    {
        var context = CreateTestContext();
        var userManager = CreateManager(context);
        var roleManager = CreateRoleManager(context);
        var users = GenerateUsers("CanRemoveUsersFromRole", 4);
        foreach (var u in users)
        {
            IdentityResultAssert.IsSuccess(await userManager.CreateAsync(u));
        }
        var r = CreateTestRole("r1");
        var roleName = await roleManager.GetRoleNameAsync(r);
        IdentityResultAssert.IsSuccess(await roleManager.CreateAsync(r));
        foreach (var u in users)
        {
            IdentityResultAssert.IsSuccess(await userManager.AddToRoleAsync(u, roleName));
            Assert.True(await userManager.IsInRoleAsync(u, roleName));
        }
        foreach (var u in users)
        {
            IdentityResultAssert.IsSuccess(await userManager.RemoveFromRoleAsync(u, roleName));
            Assert.False(await userManager.IsInRoleAsync(u, roleName));
        }
    }

    /// <summary>
    /// Test.
    /// </summary>
    /// <returns>Task</returns>
    [Fact]
    public async Task RemoveUserNotInRoleFails()
    {
        var context = CreateTestContext();
        var userMgr = CreateManager(context);
        var roleMgr = CreateRoleManager(context);
        var roleName = "addUserDupeTest" + Guid.NewGuid().ToString();
        var role = CreateTestRole(roleName, useRoleNamePrefixAsRoleName: true);
        var user = CreateTestUser();
        IdentityResultAssert.IsSuccess(await userMgr.CreateAsync(user));
        IdentityResultAssert.IsSuccess(await roleMgr.CreateAsync(role));
        var result = await userMgr.RemoveFromRoleAsync(user, roleName);
        IdentityResultAssert.IsFailure(result, _errorDescriber.UserNotInRole(roleName));
        IdentityResultAssert.VerifyLogMessage(userMgr.Logger, $"User is not in role {roleName}.");
    }

    /// <summary>
    /// Test.
    /// </summary>
    /// <returns>Task</returns>
    [Fact]
    public async Task AddUserToRoleFailsIfAlreadyInRole()
    {
        var context = CreateTestContext();
        var userMgr = CreateManager(context);
        var roleMgr = CreateRoleManager(context);
        var roleName = "addUserDupeTest" + Guid.NewGuid().ToString();
        var role = CreateTestRole(roleName, useRoleNamePrefixAsRoleName: true);
        var user = CreateTestUser();
        IdentityResultAssert.IsSuccess(await userMgr.CreateAsync(user));
        IdentityResultAssert.IsSuccess(await roleMgr.CreateAsync(role));
        IdentityResultAssert.IsSuccess(await userMgr.AddToRoleAsync(user, roleName));
        Assert.True(await userMgr.IsInRoleAsync(user, roleName));
        IdentityResultAssert.IsFailure(await userMgr.AddToRoleAsync(user, roleName), _errorDescriber.UserAlreadyInRole(roleName));
        IdentityResultAssert.VerifyLogMessage(userMgr.Logger, $"User is already in role {roleName}.");
    }

    /// <summary>
    /// Test.
    /// </summary>
    /// <returns>Task</returns>
    [Fact]
    public async Task AddUserToRolesIgnoresDuplicates()
    {
        var context = CreateTestContext();
        var userMgr = CreateManager(context);
        var roleMgr = CreateRoleManager(context);
        var roleName = "addUserDupeTest" + Guid.NewGuid().ToString();
        var role = CreateTestRole(roleName, useRoleNamePrefixAsRoleName: true);
        var user = CreateTestUser();
        IdentityResultAssert.IsSuccess(await userMgr.CreateAsync(user));
        IdentityResultAssert.IsSuccess(await roleMgr.CreateAsync(role));
        Assert.False(await userMgr.IsInRoleAsync(user, roleName));
        IdentityResultAssert.IsSuccess(await userMgr.AddToRolesAsync(user, new[] { roleName, roleName }));
        Assert.True(await userMgr.IsInRoleAsync(user, roleName));
    }

    /// <summary>
    /// Test.
    /// </summary>
    /// <returns>Task</returns>
    [Fact]
    public async Task CanFindRoleByNameWithManager()
    {
        var roleMgr = CreateRoleManager();
        var roleName = "findRoleByNameTest" + Guid.NewGuid().ToString();
        var role = CreateTestRole(roleName, useRoleNamePrefixAsRoleName: true);
        IdentityResultAssert.IsSuccess(await roleMgr.CreateAsync(role));
        Assert.NotNull(await roleMgr.FindByNameAsync(roleName));
    }

    /// <summary>
    /// Test.
    /// </summary>
    /// <returns>Task</returns>
    [Fact]
    public async Task CanFindRoleWithManager()
    {
        var roleMgr = CreateRoleManager();
        var roleName = "findRoleTest" + Guid.NewGuid().ToString();
        var role = CreateTestRole(roleName, useRoleNamePrefixAsRoleName: true);
        IdentityResultAssert.IsSuccess(await roleMgr.CreateAsync(role));
        Assert.Equal(roleName, await roleMgr.GetRoleNameAsync(await roleMgr.FindByNameAsync(roleName)));
    }

    /// <summary>
    /// Test.
    /// </summary>
    /// <returns>Task</returns>
    [Fact]
    public async Task CanGetUsersInRole()
    {
        var context = CreateTestContext();
        var manager = CreateManager(context);
        var roleManager = CreateRoleManager(context);
        var roles = GenerateRoles("UsersInRole", 4);
        var roleNameList = new List<string>();

        foreach (var role in roles)
        {
            IdentityResultAssert.IsSuccess(await roleManager.CreateAsync(role));
            roleNameList.Add(await roleManager.GetRoleNameAsync(role));
        }

        for (int i = 0; i < 6; i++)
        {
            var user = CreateTestUser();
            IdentityResultAssert.IsSuccess(await manager.CreateAsync(user));

            if ((i % 2) == 0)
            {
                IdentityResultAssert.IsSuccess(await manager.AddToRolesAsync(user, roleNameList));
            }
        }

        foreach (var role in roles)
        {
            Assert.Equal(3, (await manager.GetUsersInRoleAsync(await roleManager.GetRoleNameAsync(role))).Count);
        }

        Assert.Equal(0, (await manager.GetUsersInRoleAsync("123456")).Count);
    }

    private List<TRole> GenerateRoles(string namePrefix, int count)
    {
        var roles = new List<TRole>(count);
        for (var i = 0; i < count; i++)
        {
            roles.Add(CreateTestRole(namePrefix + i));
        }
        return roles;
    }
}


text:
<?php

namespace ErpNET\App\Interfaces;

/**
 * Interface SummaryServiceInterface
 * @package namespace ErpNET\App\Interfaces;
 */
interface SummaryServiceInterface
{
    /**
     * @return \Carbon\Carbon
     */
    public function lastEnd();
}


text:
/** \file
 * Groups all the 3D include files for the directory io.
 */

#include "io/base64.h"
#include "io/serializerIO.h"
#include "io/serializerIO_3D.h"
#include "io/vtkDataOutput.h"
#include "io/sparseVtkDataOutput.h"
#include "io/vtkStructuredDataOutput.h"
#include "io/parallelIO.h"
#include "io/colormaps.h"
#include "io/imageWriter.h"
#include "io/endianness.h"
#include "io/plbFiles.h"
#include "io/multiBlockReader3D.h"
#include "io/multiBlockWriter3D.h"
#include "io/utilIO_3D.h"
#include "io/transientStatistics3D.h"


text:
package sociam.pybossa;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.bson.Document;
import org.json.JSONObject;

import facebook4j.Comment;
import facebook4j.Facebook;
import facebook4j.PagableList;
import facebook4j.Post;
import sociam.pybossa.config.Config;
import sociam.pybossa.methods.FacebookMethods;
import sociam.pybossa.methods.MongodbMethods;
import sociam.pybossa.methods.PybossaMethods;
import sociam.pybossa.util.FacebookAccount;

/**
 *
 * @author user Saud Aljaloud
 * @author email sza1g10@ecs.soton.ac.uk
 *
 */
public class FacebookTaskCollector {

	final static Logger logger = Logger.getLogger(FacebookTaskCollector.class);
	final static SimpleDateFormat MongoDBformatter = new SimpleDateFormat(
			"yyyy-MM-dd HH:mm:ss");
	final static SimpleDateFormat PyBossaformatter = new SimpleDateFormat(
			"yyyy-mm-dd'T'hh:mm:ss.SSSSSS");
	final static String SOURCE = "Facebook";

	static Facebook facebook;

	public static void main(String[] args) {

		PropertyConfigurator.configure("log4j.properties");
		facebook = FacebookAccount.setFacebookAccount(1);
		logger.info("TaskCollector will be repeated every "
				+ Config.TaskCollectorTrigger + " ms");
		try {
			while (true) {
				Config.reload();
				run();
				logger.info("Sleeping for " + Config.TaskCollectorTrigger
						+ " ms");
				Thread.sleep(Integer.valueOf(Config.TaskCollectorTrigger));
			}
		} catch (InterruptedException e) {
			logger.error("Error ", e);
		}
	}

	public static void run() {
		try {

			logger.debug("Getting time line from facebook");
			ArrayList<Post> postsfromFacebook = FacebookMethods
					.getLatestPosts(facebook);
			if (postsfromFacebook != null) {
				logger.debug("There are "
						+ postsfromFacebook.size()
						+ " facebook posts with at least one message to be processed");
				for (Post post : postsfromFacebook) {
					String postMessage = post.getMessage();
					Pattern pattern = Pattern.compile("(#t[0-9]+)");
					Matcher matcher = pattern.matcher(postMessage);
					String taskID = "";
					if (matcher.find()) {
						logger.debug("Found a taskID in the orginal post");
						taskID = matcher.group(1).replaceAll("#t", "");
						Integer intTaskID = Integer.valueOf(taskID);
						logger.debug("Retriving Task id from Collection: "
								+ Config.taskCollection);
						Document doc = MongodbMethods
								.getTaskFromMongoDB(intTaskID);
						if (doc != null) {
							int project_id = doc.getInteger("project_id");
							PagableList<Comment> comments = post.getComments();
							for (Comment comment : comments) {
								String taskResponse = comment.getMessage();
								String contributorName = comment.getFrom()
										.getName();
								if (insertTaskRun(taskResponse, intTaskID,
										project_id, contributorName, SOURCE)) {
									logger.debug("Task run was completely processed");
								} else {
									logger.error("Failed to process the task run");
								}
							}
						} else {
							logger.error("Couldn't find task with ID " + taskID);
						}
					} else {
						logger.error("couldn't find an associated task id with the one in the post "
								+ postMessage);
					}
				}
			} else {
				logger.error("facebook is not returning any posts!");
			}
		} catch (Exception e) {
			logger.error("Error ", e);
		}
	}

	public static Boolean insertTaskRun(String text, int task_id,
			int project_id, String contributor_name, String source) {

		Document taskRun = MongodbMethods.getTaskRunsFromMongoDB(task_id,
				contributor_name, text);
		if (taskRun != null) {
			logger.error("You are only allowed one contribution for each task.");
			logger.error("task_id= " + task_id + " screen_name: "
					+ contributor_name);
			return false;
		}

		JSONObject jsonData = PybossaMethods.BuildJsonTaskRunContent(text,
				task_id, project_id);
		if (MongodbMethods.insertTaskRunIntoMongoDB(jsonData, contributor_name,
				source)) {
			logger.debug("Task run was successfully inserted into MongoDB");
			// Project has to be reqested before inserting a task run
			logger.debug("Requesting the project ID from PyBossa before inserting it");
			String postURL = Config.PyBossahost + Config.taskRunDir
					+ Config.api_key;
			JSONObject postResponse = PybossaMethods.insertTaskRunIntoPyBossa(
					postURL, jsonData);
			if (postResponse != null) {
				logger.debug("Task run was successfully inserted into PyBossa");
				return true;
			} else {
				return false;
			}
		} else {
			logger.error("Task run was not inserted into MongoDB!");
			return false;
		}
	}

}


text:
___="source_${BASH_SOURCE//[![:alnum:]]/_}" ; [[ ${!___-} ]] && return 0 || eval "declare -gr $___=@" ;
#!

#
# image/machine settings persistence
#

# ensure variable declaration
ns_context_assert() {
    local name=; for name in $context ; do
        ns_a_has_declare "$name"
    done
}

# persist settings
ns_context_any_save() {
    local "$@" # file context
    # context declared
    ns_context_assert
    # export into file
    declare -p $context | ns_a_save
}

# restore settings in local context
ns_context_any_load() {
    local "$@" # file context
    # context declared
    ns_context_assert
    # import from file
    source "$file" ; declare -p $context
}

# persist image settings
ns_context_image_save() {
    local "$@" # file
    ns_context_any_save context="$image_context"
}

# restore image settings
ns_context_image_load() {
    local "$@" # file
    ns_context_any_load context="$image_context"
}

# persist container settings
ns_context_machine_save() {
    local "$@" # file
    ns_context_any_save context="$machine_context"
}

# restore container settings
ns_context_machine_load() {
    local "$@" # file
    ns_context_any_load context="$machine_context"
}


text:
package org.apache.solr.cloud;

import org.apache.solr.client.solrj.SolrRequest;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.request.QueryRequest;
import org.apache.solr.cloud.overseer.OverseerAction;
import org.apache.solr.common.SolrException;
import org.apache.solr.common.cloud.ClusterState;
import org.apache.solr.common.cloud.Slice;
import org.apache.solr.common.cloud.Slice.State;
import org.apache.solr.common.cloud.ZkNodeProps;
import org.apache.solr.common.cloud.ZkStateReader;
import org.apache.solr.common.params.CollectionParams;
import org.apache.solr.common.params.ModifiableSolrParams;
import org.apache.solr.common.util.Utils;
import org.apache.zookeeper.KeeperException;
import org.junit.Test;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class DeleteShardTest extends AbstractFullDistribZkTestBase {

  public DeleteShardTest() {
    super();
    sliceCount = 2;
  }

  // TODO: Custom hash slice deletion test

  @Test
  @ShardsFixed(num = 2)
  public void test() throws Exception {
    ClusterState clusterState = cloudClient.getZkStateReader().getClusterState();

    Slice slice1 = clusterState.getSlice(AbstractDistribZkTestBase.DEFAULT_COLLECTION, SHARD1);
    Slice slice2 = clusterState.getSlice(AbstractDistribZkTestBase.DEFAULT_COLLECTION, SHARD2);

    assertNotNull("Shard1 not found", slice1);
    assertNotNull("Shard2 not found", slice2);
    assertSame("Shard1 is not active", Slice.State.ACTIVE, slice1.getState());
    assertSame("Shard2 is not active", Slice.State.ACTIVE, slice2.getState());

    try {
      deleteShard(SHARD1);
      fail("Deleting an active shard should not have succeeded");
    } catch (HttpSolrClient.RemoteSolrException e) {
      // expected
    }

    setSliceState(SHARD1, Slice.State.INACTIVE);

    clusterState = cloudClient.getZkStateReader().getClusterState();

    slice1 = clusterState.getSlice(AbstractDistribZkTestBase.DEFAULT_COLLECTION, SHARD1);

    assertSame("Shard1 is not inactive yet.", Slice.State.INACTIVE, slice1.getState());

    deleteShard(SHARD1);

    confirmShardDeletion(SHARD1);

    setSliceState(SHARD2, Slice.State.CONSTRUCTION);
    deleteShard(SHARD2);
    confirmShardDeletion(SHARD2);
  }

  protected void confirmShardDeletion(String shard) throws SolrServerException, KeeperException,
      InterruptedException {
    ZkStateReader zkStateReader = cloudClient.getZkStateReader();
    ClusterState clusterState = zkStateReader.getClusterState();
    int counter = 10;
    while (counter-- > 0) {
      zkStateReader.updateClusterState();
      clusterState = zkStateReader.getClusterState();
      if (clusterState.getSlice("collection1", shard) == null) {
        break;
      }
      Thread.sleep(1000);
    }

    assertNull("Cluster still contains shard1 even after waiting for it to be deleted.",
        clusterState.getSlice(AbstractDistribZkTestBase.DEFAULT_COLLECTION, SHARD1));
  }

  protected void deleteShard(String shard) throws SolrServerException, IOException,
      KeeperException, InterruptedException {

    ModifiableSolrParams params = new ModifiableSolrParams();
    params.set("action", CollectionParams.CollectionAction.DELETESHARD.toString());
    params.set("collection", AbstractFullDistribZkTestBase.DEFAULT_COLLECTION);
    params.set("shard", shard);
    SolrRequest request = new QueryRequest(params);
    request.setPath("/admin/collections");

    String baseUrl = ((HttpSolrClient) shardToJetty.get(SHARD1).get(0).client.solrClient)
        .getBaseURL();
    baseUrl = baseUrl.substring(0, baseUrl.length() - "collection1".length());

    try (HttpSolrClient baseServer = new HttpSolrClient(baseUrl)) {
      baseServer.setConnectionTimeout(15000);
      baseServer.setSoTimeout(60000);
      baseServer.request(request);
    }
  }

  protected void setSliceState(String slice, State state) throws SolrServerException, IOException,
      KeeperException, InterruptedException {
    DistributedQueue inQueue = Overseer.getInQueue(cloudClient.getZkStateReader().getZkClient());
    Map<String, Object> propMap = new HashMap<>();
    propMap.put(Overseer.QUEUE_OPERATION, OverseerAction.UPDATESHARDSTATE.toLower());
    propMap.put(slice, state.toString());
    propMap.put(ZkStateReader.COLLECTION_PROP, "collection1");
    ZkNodeProps m = new ZkNodeProps(propMap);
    ZkStateReader zkStateReader = cloudClient.getZkStateReader();
    inQueue.offer(Utils.toJSON(m));
    boolean transition = false;

    for (int counter = 10; counter > 0; counter--) {
      zkStateReader.updateClusterState();
      ClusterState clusterState = zkStateReader.getClusterState();
      State sliceState = clusterState.getSlice("collection1", slice).getState();
      if (sliceState == state) {
        transition = true;
        break;
      }
      Thread.sleep(1000);
    }

    if (!transition) {
      throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "Could not set shard [" + slice + "] as " + state);
    }
  }

}


text:
#ifndef SVGZoomEvent_h
#define SVGZoomEvent_h
#if ENABLE(SVG)

#include "FloatRect.h"
#include "SVGPoint.h"
#include "UIEvent.h"

namespace WebCore {

class SVGZoomEvent : public UIEvent {
public:
    static PassRefPtr<SVGZoomEvent> create() { return adoptRef(new SVGZoomEvent); }

    // 'SVGZoomEvent' functions
    FloatRect zoomRectScreen() const;

    float previousScale() const;
    void setPreviousScale(float);

    SVGPoint previousTranslate() const;

    float newScale() const;
    void setNewScale(float);

    SVGPoint newTranslate() const;

    virtual const AtomicString& interfaceName() const;

private:
    SVGZoomEvent();

    float m_newScale;
    float m_previousScale;

    FloatRect m_zoomRectScreen;

    SVGPoint m_newTranslate;
    SVGPoint m_previousTranslate;
};

} // namespace WebCore

#endif // ENABLE(SVG)
#endif // SVGZoomEvent_h

// vim:ts=4:noet


text:
package com.permissioneverywhere;

import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;

/**
 * Created by Farruxx on 01.05.2016.
 */
 class Util {
    public static boolean hasPermission(Context context, String[] permissions){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            for (String permission :permissions) {
                boolean result = (context.checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED);
                if(result == false){
                    return false;
                }
            }
        }
            return true;
        }
}


text:
import { guidFor } from 'ember-utils';
import { get, tagForProperty, tagFor, isProxy } from 'ember-metal';
import {
  objectAt,
  isEmberArray
} from 'ember-runtime';
import {
  UpdatableReference,
  UpdatablePrimitiveReference
} from './references';
import { isEachIn } from '../helpers/each-in';
import {
  CONSTANT_TAG,
  UpdatableTag,
  combine
} from '@glimmer/reference';

const ITERATOR_KEY_GUID = 'be277757-bbbe-4620-9fcb-213ef433cca2';

export default function iterableFor(ref, keyPath) {
  if (isEachIn(ref)) {
    return new EachInIterable(ref, keyForEachIn(keyPath));
  } else {
    return new ArrayIterable(ref, keyForArray(keyPath));
  }
}

function keyForEachIn(keyPath) {
  switch (keyPath) {
    case '@index':
    case undefined:
    case null:
      return index;
    case '@identity':
      return identity;
    default:
      return (item) => get(item, keyPath);
  }
}

function keyForArray(keyPath) {
  switch (keyPath) {
    case '@index':
      return index;
    case '@identity':
    case undefined:
    case null:
      return identity;
    default:
      return (item) => get(item, keyPath);
  }
}

function index(item, index) {
  return String(index);
}

function identity(item) {
  switch (typeof item) {
    case 'string':
    case 'number':
      return String(item);
    default:
      return guidFor(item);
  }
}

function ensureUniqueKey(seen, key) {
  let seenCount = seen[key];

  if (seenCount > 0) {
    seen[key]++;
    return `${key}${ITERATOR_KEY_GUID}${seenCount}`;
  } else {
    seen[key] = 1;
  }

  return key;
}

class ArrayIterator {
  constructor(array, keyFor) {
    this.array = array;
    this.length = array.length;
    this.keyFor = keyFor;
    this.position = 0;
    this.seen = Object.create(null);
  }

  isEmpty() {
    return false;
  }

  getMemo(position) {
    return position;
  }

  getValue(position) {
    return this.array[position];
  }

  next() {
    let { length, keyFor, position, seen } = this;

    if (position >= length) { return null; }

    let value = this.getValue(position);
    let memo = this.getMemo(position);
    let key = ensureUniqueKey(seen, keyFor(value, memo));

    this.position++;

    return { key, value, memo };
  }
}

class EmberArrayIterator extends ArrayIterator {
  constructor(array, keyFor) {
    super(array, keyFor);
    this.length = get(array, 'length');
  }

  getValue(position) {
    return objectAt(this.array, position);
  }
}

class ObjectKeysIterator extends ArrayIterator {
  constructor(keys, values, keyFor) {
    super(values, keyFor);
    this.keys = keys;
    this.length = keys.length;
  }

  getMemo(position) {
    return this.keys[position];
  }

  getValue(position) {
    return this.array[position];
  }
}

class EmptyIterator {
  isEmpty() {
    return true;
  }

  next() {
    throw new Error('Cannot call next() on an empty iterator');
  }
}

const EMPTY_ITERATOR = new EmptyIterator();

class EachInIterable {
  constructor(ref, keyFor) {
    this.ref = ref;
    this.keyFor = keyFor;

    let valueTag = this.valueTag = new UpdatableTag(CONSTANT_TAG);

    this.tag = combine([ref.tag, valueTag]);
  }

  iterate() {
    let { ref, keyFor, valueTag } = this;

    let iterable = ref.value();

    valueTag.update(tagFor(iterable));

    if (isProxy(iterable)) {
      iterable = get(iterable, 'content');
    }

    let typeofIterable = typeof iterable;

    if (iterable && (typeofIterable === 'object' || typeofIterable === 'function')) {
      let keys = Object.keys(iterable);
      let values = keys.map(key => iterable[key]);
      return keys.length > 0 ? new ObjectKeysIterator(keys, values, keyFor) : EMPTY_ITERATOR;
    } else {
      return EMPTY_ITERATOR;
    }
  }

  // {{each-in}} yields |key value| instead of |value key|, so the memo and
  // value are flipped

  valueReferenceFor(item) {
    return new UpdatablePrimitiveReference(item.memo);
  }

  updateValueReference(reference, item) {
    reference.update(item.memo);
  }

  memoReferenceFor(item) {
    return new UpdatableReference(item.value);
  }

  updateMemoReference(reference, item) {
    reference.update(item.value);
  }
}

class ArrayIterable {
  constructor(ref, keyFor) {
    this.ref = ref;
    this.keyFor = keyFor;

    let valueTag = this.valueTag = new UpdatableTag(CONSTANT_TAG);

    this.tag = combine([ref.tag, valueTag]);
  }

  iterate() {
    let { ref, keyFor, valueTag } = this;

    let iterable = ref.value();

    valueTag.update(tagForProperty(iterable, '[]'));

    if (!iterable || typeof iterable !== 'object') {
      return EMPTY_ITERATOR;
    }

    if (Array.isArray(iterable)) {
      return iterable.length > 0 ? new ArrayIterator(iterable, keyFor) : EMPTY_ITERATOR;
    } else if (isEmberArray(iterable)) {
      return get(iterable, 'length') > 0 ? new EmberArrayIterator(iterable, keyFor) : EMPTY_ITERATOR;
    } else if (typeof iterable.forEach === 'function') {
      let array = [];
      iterable.forEach(function(item) {
        array.push(item);
      });
      return array.length > 0 ? new ArrayIterator(array, keyFor) : EMPTY_ITERATOR;
    } else {
      return EMPTY_ITERATOR;
    }
  }

  valueReferenceFor(item) {
    return new UpdatableReference(item.value);
  }

  updateValueReference(reference, item) {
    reference.update(item.value);
  }

  memoReferenceFor(item) {
    return new UpdatablePrimitiveReference(item.memo);
  }

  updateMemoReference(reference, item) {
    reference.update(item.memo);
  }
}


text:
namespace boost { namespace parameter {

    // This metafunction can be used to describe the treatment of particular
    // named parameters for the purposes of overload elimination with SFINAE,
    // by placing specializations in the parameters<...> list.
    //
    // If a keyword k is specified with deduced<...>, that keyword
    // will be automatically deduced from the argument list.
    template <typename Tag>
    struct deduced
    {
        typedef Tag key_type;
    };
}}

#include <boost/parameter/config.hpp>

#if defined(BOOST_PARAMETER_CAN_USE_MP11)
#include <boost/mp11/integral.hpp>
#else
#include <boost/mpl/bool.hpp>
#endif

namespace boost { namespace parameter { namespace aux {

    template <typename T>
    struct is_deduced_aux
#if defined(BOOST_PARAMETER_CAN_USE_MP11)
      : ::boost::mp11::mp_false
#else
      : ::boost::mpl::false_
#endif
    {
    };

    template <typename Tag>
    struct is_deduced_aux< ::boost::parameter::deduced<Tag> >
#if defined(BOOST_PARAMETER_CAN_USE_MP11)
      : ::boost::mp11::mp_true
#else
      : ::boost::mpl::true_
#endif
    {
    };

    template <typename T>
    struct is_deduced0
      : ::boost::parameter::aux::is_deduced_aux<typename T::key_type>::type
    {
    };
}}} // namespace boost::parameter::aux

#include <boost/parameter/required.hpp>
#include <boost/parameter/optional.hpp>

#if defined(BOOST_PARAMETER_CAN_USE_MP11)
#include <boost/mp11/utility.hpp>
#else
#include <boost/mpl/if.hpp>
#endif

namespace boost { namespace parameter { namespace aux {

    //
    // tag_type, has_default, and predicate --
    //
    // These metafunctions accept a ParameterSpec and extract the
    // keyword tag, whether or not a default is supplied for the
    // parameter, and the predicate that the corresponding actual
    // argument type is required match.
    //
    // a ParameterSpec is a specialization of either keyword<...>,
    // required<...>, optional<...>
    //

    template <typename T>
#if defined(BOOST_PARAMETER_CAN_USE_MP11)
    using has_default = ::boost::mp11::mp_if<
        ::boost::parameter::aux::is_required<T>
      , ::boost::mp11::mp_false
      , ::boost::mp11::mp_true
    >;
#else
    struct has_default
      : ::boost::mpl::if_<
            ::boost::parameter::aux::is_required<T>
          , ::boost::mpl::false_
          , ::boost::mpl::true_
        >::type
    {
    };
#endif

    template <typename T>
#if defined(BOOST_PARAMETER_CAN_USE_MP11)
    using is_deduced = ::boost::mp11::mp_if<
        ::boost::mp11::mp_if<
            ::boost::parameter::aux::is_optional<T>
          , ::boost::mp11::mp_true
          , ::boost::parameter::aux::is_required<T>
        >
      , ::boost::parameter::aux::is_deduced0<T>
      , ::boost::mp11::mp_false
    >;
#else
    struct is_deduced
      : ::boost::mpl::if_<
            typename ::boost::mpl::if_<
                ::boost::parameter::aux::is_optional<T>
              , ::boost::mpl::true_
              , ::boost::parameter::aux::is_required<T>
            >::type
          , ::boost::parameter::aux::is_deduced0<T>
          , ::boost::mpl::false_
        >::type
    {
    };
#endif  // BOOST_PARAMETER_CAN_USE_MP11
}}} // namespace boost::parameter::aux

#endif  // include guard


text:
/* atm_tcp.h - Driver-specific declarations of the ATMTCP driver (for use by
	       driver-specific utilities) */

/* Written 1997-2000 by Werner Almesberger, EPFL LRC/ICA */

#ifndef LINUX_ATM_TCP_H
#define LINUX_ATM_TCP_H

#include <linux/atmapi.h>
#include <linux/types.h>
#include <linux/atmioc.h>

/*
 * All values in struct atmtcp_hdr are in network byte order
 */

struct atmtcp_hdr {
	uint16_t	vpi;
	uint16_t	vci;
	uint32_t	length;		/* ... of data part */
};

/*
 * All values in struct atmtcp_command are in host byte order
 */

#define ATMTCP_HDR_MAGIC	(~0)	/* this length indicates a command */
#define ATMTCP_CTRL_OPEN	1	/* request/reply */
#define ATMTCP_CTRL_CLOSE	2	/* request/reply */

struct atmtcp_control {
	struct atmtcp_hdr hdr;	/* must be first */
	int type;		/* message type; both directions */
	atm_kptr_t vcc;		/* both directions */
	struct sockaddr_atmpvc addr; /* suggested value from kernel */
	struct atm_qos	qos;	/* both directions */
	int result;		/* to kernel only */
} __ATM_API_ALIGN;

/*
 * Field usage:
 * Messge type	dir.	hdr.v?i	type	addr	qos	vcc	result
 * -----------  ----	------- ----	----	---	---	------
 * OPEN		K->D	Y	Y	Y	Y	Y	0
 * OPEN		D->K	-	Y	Y	Y	Y	Y
 * CLOSE	K->D	-	-	Y	-	Y	0
 * CLOSE	D->K	-	-	-	-	Y	Y
 */

#define SIOCSIFATMTCP	_IO('a',ATMIOC_ITF)	/* set ATMTCP mode */
#define ATMTCP_CREATE	_IO('a',ATMIOC_ITF+14)	/* create persistent ATMTCP
						   interface */
#define ATMTCP_REMOVE	_IO('a',ATMIOC_ITF+15)	/* destroy persistent ATMTCP
						   interface */

#endif


text:
//
//  AmAxisBase.h
//  AmCharts
//
//  Created by Andrew on 4/28/14.
//  Copyright (c) 2014 Chimp Studios. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface AmAxisBase : NSObject

/**
 Specifies whether number of gridCount is specified automatically, acoarding to the axis size.
 */
@property(strong) NSNumber * autoGridCount;

/**
 Axis opacity. Value range is 0 - 1.
 */
@property(strong) NSNumber * axisAlpha;

/**
 Axis color.
 */
@property(strong) NSString * axisColor;

/**
 Thickness of the axis.
 */
@property(strong) NSNumber * axisThickness;

/**
 Read-only. Returns x coordinate of the axis.
 */
@property(strong) NSNumber * axisX;

/**
 Read-only. Returns y coordinate of the axis.
 */
@property(strong) NSNumber * axisY;

/**
 Specifies if axis labels should be bold or not.
 */
@property(strong) NSNumber *boldLabels;

/**
 Color of axis value labels. Will use chart's color if not set.
 */
@property(strong) NSString * color;

/**
 Length of a dash. 0 means line is not dashed.
 */
@property(strong) NSNumber * dashLength;

/**
 Date formats of different periods. Possible period values: fff - milliseconds, ss - seconds, mm - minutes, hh - hours, DD - days, MM - months, WW - weeks, YYYY - years. Check this page for date formatting strings.
 */
@property(strong) NSMutableArray * dateFormats;

/**
 Fill opacity. Every second space between grid lines can be filled with color. Set fillAlpha to a value greater than 0 to see the fills.
 */
@property(strong) NSNumber * fillAlpha;

/**
 Fill color. Every second space between grid lines can be filled with color. Set fillAlpha to a value greater than 0 to see the fills.
 */
@property(strong) NSString * fillColor;

/**
 Size of value labels text. Will use chart's fontSize if not set.
 */
@property(strong) NSNumber * fontSize;

/**
 Opacity of grid lines.
 */
@property(strong) NSNumber * gridAlpha;

/**
 Color of grid lines.
 */
@property(strong) NSString * gridColor;

/**
 Number of grid lines. In case this is value axis, or your categoryAxis parses dates, the number is approximate. The default value is 5. If you set autoGridCount to true, this property is ignored.
 */
@property(strong) NSNumber * gridCount;

/**
 Thickness of grid lines.
 */
@property(strong) NSNumber * gridThickness;

/**
 The array of guides belonging to this axis.
 */
@property(strong) NSMutableArray * guides;

/**
 If autoMargins of a chart is set to true, but you want this axis not to be measured when calculating margin, set ignoreAxisWidth to true.
 */
@property(strong) NSNumber * ignoreAxisWidth;

/**
 Specifies whether values should be placed inside or outside plot area.
 */
@property(strong) NSNumber * inside;

/**
 Frequency at which labels should be placed. Doesn't work for CategoryAxis if parseDates is set to true.
 */
@property(strong) NSNumber * labelFrequency;

/**
 You can use it to adjust position of axes labels. Works both with CategoryAxis and ValueAxis.
 */
@property(strong) NSNumber * labelOffset;

/**
 Rotation angle of a label. Only horizontal axis' values can be rotated. If you set this for vertical axis, the setting will be ignored. Possible values from -90 to 90.
 */
@property(strong) NSNumber * labelRotation;

/**
 Specifies whether axis displays category axis' labels and value axis' values.
 */
@property(strong) NSNumber * labelsEnabled;

/**
 This property is used when calculating grid count (when autoGridCount is true). It specifies minimum cell width required for one span between grid lines.
 */
@property(strong) NSNumber * minHorizontalGap;

/**
 Opacity of minor grid. In order minor to be visible, you should set minorGridEnabled to true.
 */
@property(strong) NSNumber * minorGridAlpha;

/**
 Specifies if minor grid should be displayed.
 */
@property(strong) NSNumber * minorGridEnabled;

/**
 This property is used when calculating grid count (when autoGridCount is true). It specifies minimum cell height required for one span between grid lines.
 */
@property(strong) NSNumber * minVerticalGap;

/**
 The distance of the axis to the plot area, in pixels. Negative values can also be used.
 */
@property(strong) NSNumber * offset;

/**
 Possible values are: "top", "bottom", "left", "right". If axis is vertical, default position is "left". If axis is horizontal, default position is "bottom".
 */
@property(strong) NSString * position;

/**
 Whether to show first axis label or not. This works properly only on ValueAxis. With CategoryAxis it wont work 100%, it depends on the period, zooming, etc. There is no guaranteed way to force category axis to show or hide first label.
 */
@property(strong) NSNumber * showFirstLabel;

/**
 Whether to show last axis label or not. This works properly only on ValueAxis. With CategoryAxis it wont work 100%, it depends on the period, zooming, etc. There is no guaranteed way to force category axis to show or hide last label.
 */
@property(strong) NSNumber * showLastLabel;

/**
 Length of the tick marks.
 */
@property(strong) NSNumber * tickLength;

/**
 Title of the axis.
 */
@property(strong) NSString * title;

/**
 Specifies if title should be bold or not.
 */
@property(strong) NSNumber * titleBold;

/**
 Color of axis title. Will use text color of chart if not set any.
 */
@property(strong) NSString * titleColor;

/**
 Font size of axis title. Will use font size of chart plus two pixels if not set any.
 */
@property(strong) NSNumber * titleFontSize;

- (NSDictionary *)dictionaryRepresentation;
- (NSString *)javascriptRepresentation;

@end


text:
Bunch of lines of code to compare tools or analyzing public data.
The aim is not to judge tools but to find the best tools/parameters to get the best of the data.

### miRNA

* [miRNA genome based annotation](https://github.com/lpantano/mypubs/blob/master/mirna/genome_based_mirna_annotation/stats.md)
* [miRNA annotation](http://rawgit.com/lpantano/mypubs/master/mirna/mirannotation/stats.html)


text:
<?php

final class PhabricatorConfigJSON extends Phobject {
  /**
   * Properly format a JSON value.
   *
   * @param wild Any value, but should be a raw value, not a string of JSON.
   * @return string
   */
  public static function prettyPrintJSON($value) {
    // If the value is an array with keys "0, 1, 2, ..." then we want to
    // show it as a list.
    // If the value is an array with other keys, we want to show it as an
    // object.
    // Otherwise, just use the default encoder.

    $type = null;
    if (is_array($value)) {
      $list_keys = range(0, count($value) - 1);
      $actual_keys = array_keys($value);

      if ($actual_keys === $list_keys) {
        $type = 'list';
      } else {
        $type = 'object';
      }
    }

    switch ($type) {
      case 'list':
        $result = id(new PhutilJSON())->encodeAsList($value);
        break;
      case 'object':
        $result = id(new PhutilJSON())->encodeFormatted($value);
        break;
      default:
        $result = json_encode($value);
        break;
    }

    // For readability, unescape forward slashes. These are normally escaped
    // to prevent the string "</script>" from appearing in a JSON literal,
    // but it's irrelevant here and makes reading paths more difficult than
    // necessary.
    $result = str_replace('\\/', '/', $result);
    return $result;

  }
}