text:
<?php

   // no direct access
   defined('_JEXEC') or die;

   require_once __DIR__ . '/../cached_image_util.php';

   require_once __DIR__ . '/../helper.php' ;

   $fullImage = $this->item->image;

   // add css
    $doc =& JFactory::getDocument();
    $getapps= & JFactory::getApplication();
    $template = $getapps->getTemplate();
    //$doc->addStyleSheet( 'templates/' . $template . '/css/recipe_item.css' );

    $doc->setMetaData("og:image",JURI::root() . substr($fullImage,1));

   $isMobile = 0;

   if ( class_exists('MobileDetector') ) {
      $isMobile = MobileDetector::isMobile();
   }

   ?>
<?php if(JRequest::getInt('print')==1): ?>

<?php echo JText::_('K2_PRINT_THIS_PAGE'); ?>

<?php endif; ?>

<span id="startOfPageId<?php echo JRequest::getInt('id'); ?>">

   <div id="k2Container" class="itemView<?php echo ($this->item->featured) ? ' itemIsFeatured' : ''; ?><?php if($this->item->params->get('pageclass_sfx')) echo ' '.$this->item->params->get('pageclass_sfx'); ?>">

         <?php echo $this->item->event->BeforeDisplay; ?>

         <?php echo $this->item->event->K2BeforeDisplay; ?>

            <?php if($this->item->params->get('itemTitle')): ?>

               <?php if(isset($this->item->editLink)): ?>

               <a class="modal" rel="{handler:'iframe',size:{x:990,y:550}}" href="<?php echo $this->item->editLink; ?>">
               <?php echo JText::_('K2_EDIT_ITEM'); ?>

               <?php endif; ?>
               <?php echo $this->item->title; ?>
               <?php if($this->item->params->get('itemFeaturedNotice') && $this->item->featured): ?>

               <?php echo JText::_('K2_FEATURED'); ?>

               <?php endif; ?>

            <?php endif; ?>

         <?php echo $this->item->event->AfterDisplayTitle; ?>

         <?php //echo $this->item->event->K2AfterDisplayTitle; ?>

            <?php if($this->item->params->get('itemAuthor')): ?>

            <img class="img-circle" src="<?php echo $this->item->author->avatar; ?>" alt="<?php echo K2HelperUtilities::cleanHtml($this->item->author->name); ?>" />
            <?php if(empty($this->item->created_by_alias)): ?>
            <a rel="author" href="<?php echo $this->item->author->link; ?>"><?php echo $this->item->author->name; ?>
            <?php else: ?>
            <?php echo $this->item->author->name; ?>
            <?php endif; ?>
<?php echo $this->item->event->K2AfterDisplayTitle; ?>

            <?php endif; ?>
            <?php if($this->item->params->get('itemDateCreated')): ?>

            <?php
               $published_datetime = new DateTime(JHTML::_('date', $this->item->created , 'Y-m-d H:i:s'));
               ?>
            <span class="itemDateCreated" itemprop="dateCreated" content="<?php echo $published_datetime->format(DateTime::ISO8601) ; ?>">
             On <?php echo JHTML::_('date', $this->item->publish_up , JText::_('K2_DATE_FORMAT_LC2')); ?>

            <?php endif; ?>

         <?php if($this->item->params->get('itemImage') && !empty($this->item->image)): ?>

                  <img class="img-thumbnail" itemprop="image" src="<?php echo $this->item->image; ?>" alt="<?php if(!empty($this->item->image_caption)) echo K2HelperUtilities::cleanHtml($this->item->image_caption); else echo K2HelperUtilities::cleanHtml($this->item->title); ?>"  >

               <?php if($this->item->params->get('itemImageMainCaption') && !empty($this->item->image_caption)): ?>

		<a href="http://shutterstock.7eer.net/c/174119/42916/1305?u=<?php echo $this->item->image_credits;?>" title="<?php echo $this->item->image_caption; ?>">
			<?php echo $this->item->image_caption; ?>
		 Via ShutterStock

               <?php endif; ?>
               <?php if($this->item->params->get('itemImageMainCredits') && !empty($this->item->image_credits)): ?>

               <?php endif; ?>

               <link itemprop="contentUrl" src="<?php echo $this->item->image; ?>" content="<?php echo $this->item->image; ?>" />

         <?php endif; ?>

         <?php if($this->item->params->get('itemTwitterButton',1) || $this->item->params->get('itemFacebookButton',1) || $this->item->params->get('itemGooglePlusOneButton',1)): ?>

                  <?php include __DIR__ . '/../share_buttons.php' ; ?>

         <?php endif; ?>

            <?php echo $this->item->event->BeforeDisplayContent; ?>

            <?php echo $this->item->event->K2BeforeDisplayContent; ?>

                  <?php if(!empty($this->item->fulltext)): ?>
                     <?php if($this->item->params->get('itemIntroText')): ?>

                        <?php echo $this->item->introtext; ?>

                     <?php endif; ?>

                     <?php
                           $doc      = JFactory::getDocument();
                           $renderer = $doc->loadRenderer( 'modules' );
                           $module_count =  $doc->countModules('item_inline_banner' . ( ($isMobile) ? '_mobile_1' : '_1' ) );
                     ?>

                     <?php if (($module_count) && ($isMobile) ): ?>
                        <div class="row item_inline_banner<?php echo  ( ($isMobile) ? '_mobile_1' : '_1' ); ?>">
                           <?php

                              $raw      = array( 'style' => 'xhtml' );
                              echo $renderer->render('item_inline_banner' . ( ($isMobile) ? '_mobile_1' : '_1' ), $raw, null);
                           ?>

                     <?php endif; ?>

                     <?php if($this->item->params->get('itemFullText')): ?>

                        <?php echo $this->item->fulltext; ?>

                     <?php endif; ?>
                  <?php else: ?>

                     <?php echo $this->item->introtext; ?>

                  <?php endif; ?>

                  <?php echo $this->item->event->AfterDisplayContent; ?>

                  <?php echo $this->item->event->K2AfterDisplayContent; ?>

                  <?php echo $this->item->event->AfterDisplay; ?>

                  <?php echo $this->item->event->K2AfterDisplay; ?>

		<?php
			echo AKPressmagK2TemplateHelper::getShareandsubscribe($this->item) ;
		 ?>

                  <?php if($this->item->params->get('itemCategory')): ?>

                     <?php echo JText::_('K2_PUBLISHED_IN'); ?>
                     <a href="<?php echo $this->item->category->link; ?>"><?php echo $this->item->category->name; ?>

                  <?php endif; ?>
                  <?php if($this->item->params->get('itemTags') && count($this->item->tags)): ?>

                        <?php foreach ($this->item->tags as $tag): ?>

<a href="<?php echo $tag->link; ?>"><?php echo $tag->name; ?>

                        <?php endforeach; ?>

                  <?php endif; ?>

	<?php
         	echo AKPressmagK2TemplateHelper::getAuthorBlock($this->item) ;
	 ?>

         <?php
               $doc      = JFactory::getDocument();
               $renderer = $doc->loadRenderer( 'modules' );
               $module_count =  $doc->countModules('item_inline_banner' . ( ($isMobile) ? '_mobile_2' : '_2' ) );
         ?>

         <?php if ($module_count): ?>
            <div class="row item_inline_banner<?php echo  ( ($isMobile) ? '_mobile_2' : '_2' ); ?>">
               <?php

                  $raw      = array( 'style' => 'xhtml' );
                  echo $renderer->render('item_inline_banner' . ( ($isMobile) ? '_mobile_2' : '_2' ), $raw, null);
               ?>

         <?php endif; ?>

               <?php
                  $itemsperslide = 3;
                  if ( $isMobile ) {
                    include "latest_items_from_author_mobile.php" ;
                  } else {
                    include "latest_items_from_author_carousel.php" ;
                  }

               ?>

               <?php
                  $itemsperslide = 3;
                  if ( $isMobile ) {
                    include "related_items_mobile.php" ;
                  } else {
                    include "related_items_carousel.php" ;
                  }
               ?>

            <?php if($this->item->params->get('itemHits') || ($this->item->params->get('itemDateModified') && intval($this->item->modified)!=0)): ?>

               <?php if($this->item->params->get('itemHits')): ?>

                  <?php echo JText::_('K2_READ'); ?> <?php echo $this->item->hits; ?> <?php echo JText::_('K2_TIMES'); ?>

               <?php endif; ?>
               <?php if($this->item->params->get('itemDateModified') && intval($this->item->modified)!=0): ?>

               <?php
                  $modifeddatetime = new DateTime(JHTML::_('date', $this->item->modified , 'Y-m-d H:i:s'));
               ?>
               <span class="itemDateModified" itemprop="dateModified" content="<?php echo $modifeddatetime->format(DateTime::ISO8601) ;?>">
               <?php echo JText::_('K2_LAST_MODIFIED_ON'); ?> <?php echo JHTML::_('date', $this->item->modified, JText::_('K2_DATE_FORMAT_LC2')); ?>

               <?php endif; ?>

            <?php endif; ?>

                  Please enable JavaScript to view the comments powered by Disqus.

<?php
        $doc = JFactory::getDocument();
        $doc->addScriptDeclaration(
'
((window.adpushup = window.adpushup || {}).configure = (window.adpushup.configure || [])).push({"pageGroup": "POST"});
'
);
?>


text:
from collections import namedtuple
import itertools

PageLink = namedtuple('PageLink', 'string, page_number clickable')

class PaginatorBase(object):

    def __init__(self, page=1, show_per_page=20):

        self.skip = (page - 1) * show_per_page
        self.show_per_page = show_per_page
        self.current_page = page
        self.limit = show_per_page

    def _previous_pages_count(self):
        'A generator of previous page integers.'
        skip = self.skip
        if skip == 0:
            return 0
        count, remainder = divmod(skip, self.limit)
        return count

    def _subsequent_pages_count(self):
        count, remainder = divmod(self.count, self.limit)
        if remainder:
            count += 1
        return count

    def previous_pages_numbers(self):
        'A generator of previous page integers.'
        count = self._previous_pages_count() + 1
        for i in reversed(range(1, count)):
            yield i

    def subsequent_pages_numbers(self):
        for page in xrange(self.current_page + 1,
                           self._subsequent_pages_count() + 1):
            yield page

    @property
    def last_page(self):
        last_page, remainder = divmod(self.count, self.limit)
        if remainder:
            last_page += 1
        return last_page

    @property
    def next_page(self):
        return self.current_page + 1

    @property
    def previous_page(self):
        return self.current_page - 1

    @property
    def range_start(self):
        '''"Showing 40-50 of 234 results
                    ^
        '''
        start = (self.current_page - 1) * self.show_per_page
        return start + 1

    @property
    def range_end(self):
        '''"Showing 40 - 50 of 234 results
                         ^
        '''
        count = self.count
        range_end = self.range_start + self.limit - 1
        if count < range_end:
            range_end = count
        return range_end

    @property
    def total_count(self):
        '''"Showing 40 - 50 of 234 results
                               ^
        '''
        return self.count

    @property
    def has_next(self):
        return self.current_page != self.last_page

    @property
    def has_previous(self):
        return self.current_page != 1

    def pagination_data(self, max_number_of_links=7):
        '''Returns a generator of tuples (string, page_number, clickable),
        where `string` is the text of the html link, `page_number` is
        the number of the page the link points to, and `clickable` is
        a boolean indicating whether the link is clickable or not.
        '''
        div, mod = divmod(max_number_of_links, 2)
        if not mod == 1:
            msg = 'Max number of links must be odd, was %r.'
            raise ValueError(msg % max_number_of_links)

        midpoint = (max_number_of_links - 1) / 2
        current_page = self.current_page
        last_page = self.last_page

        show_link_firstpage = midpoint < current_page
        show_link_previouspage = 1 < current_page
        show_link_lastpage = current_page < (self.last_page - midpoint)
        show_link_nextpage = current_page < last_page

        extra_room_previous = midpoint - current_page
        if extra_room_previous < 0:
            extra_room_previous = 0
        if not show_link_firstpage:
            extra_room_previous += 1
        if not show_link_previouspage:
            extra_room_previous += 1

        extra_room_subsequent = current_page - last_page + midpoint
        extra_room_subsequent = max([extra_room_subsequent, 0])
        if not show_link_nextpage:
            extra_room_subsequent += 1
        if not show_link_lastpage:
            extra_room_subsequent += 1

        if self.current_page == 1:
            yield PageLink(string=1, page_number=1, clickable=False)
        else:
            # The  "first page" link.
            if show_link_firstpage:
                #[<<] [<] [7] [8] [9] 10 [11] ...'
                #  ^
                yield PageLink(string=u"\u00AB", page_number=1, clickable=True)

            if show_link_previouspage:
                # The "previous page" link.
                #[<<] [<] [7] [8] [9] 10 [11] ...'
                #      ^
                yield PageLink(string=u"\u2039",
                               page_number=self.previous_page,
                               clickable=True)

        # Up to `midpoint + extra_room_subsequent` previous page numbers.
        previous = itertools.islice(self.previous_pages_numbers(),
                                    midpoint + extra_room_subsequent)
        previous = list(previous)[::-1]

        for page_number in previous:
            yield PageLink(string=page_number,
                           page_number=page_number, clickable=True)

        # The current page, clickable.
        if current_page != 1:
            yield PageLink(string=current_page,
                           page_number=current_page, clickable=False)

        # Up to `midpoint + extra_room_previous` subsequent page numbers.
        subsequent_count = midpoint + extra_room_previous
        _subsequent_pages_count = self._subsequent_pages_count
        if _subsequent_pages_count < subsequent_count:
            subsequent_count = _subsequent_pages_count

        for page_number in itertools.islice(self.subsequent_pages_numbers(),
                                            subsequent_count):
            yield PageLink(string=page_number,
                           page_number=page_number, clickable=True)

        if show_link_nextpage:
            yield PageLink(string=u"\u203A",
                           page_number=current_page + 1,
                           clickable=True)

        if show_link_lastpage:
            yield PageLink(string=u"\u00BB",
                           page_number=last_page,
                           clickable=True)

class CursorPaginator(PaginatorBase):

    def __init__(self, cursor, *args, **kwargs):
        super(CursorPaginator, self).__init__(*args, **kwargs)
        self.cursor = cursor
        self.count = cursor.count()
        self._cached = False

    def __iter__(self):
        'The specific page of records.'
        if self._cached:
            for record in self._cache:
                yield record
            return

        else:
            cache = []
        for record in self.cursor.skip(self.skip).limit(self.limit):
            yield record
            cache.append(record)

        self._cached = True
        self._cache = cache

class BillSearchPaginator(PaginatorBase):

    def __init__(self, result, *args, **kwargs):
        super(BillSearchPaginator, self).__init__(*args, **kwargs)
        self.result = result
        self.count = len(result)
        self._cached = False

    def __iter__(self):
        'The specific page of records.'
        if self._cached:
            for record in self._cache:
                yield record
            return
        else:
            cache = []

        for record in self.result[self.skip:self.skip + self.limit]:
            yield record
            cache.append(record)

        self._cached = True
        self._cache = cache

redpajama_set_name: RedPajamaGithub


text:
namespace tuishogi {
  using namespace osl;

  void
  showState(const NumEffectState& state)
  {
    std::cout << state << std::endl;
  }

  Move
  selectMove(const NumEffectState& state, const MoveVector& moves)
  {
    static boost::mt11213b generator(random());
    return moves[generator() % moves.size()];
  }

  bool
  isMated(const NumEffectState& state)
  {
    return state.inCheck(alt(state.turn()));
  }

  bool
  computerOperate(NumEffectState& state)
  {
    MoveVector moves;
    LegalMoves::generate(state, moves);
    if (moves.empty()) {
      std::cout << "You Win!" << std::endl;
      return true;
    }
    const Move my_move = selectMove(state, moves);
    assert(state.isValidMove(my_move));
    state.makeMove(my_move);

    showState(state);
    csaShow(std::cout, my_move);
    std::cout << "\n";

    if (isMated(state)) {
      std::cout << "You Lose..." << std::endl;
      return true;
    }

    return false;
  }

  bool
  playerOperate(NumEffectState& state, std::string line)
  {
    Move op_move;
    if (line.length() == 4) {
      MoveVector moves;
      LegalMoves::generate(state, moves);
      int i;
      for (i = 0; i < moves.size(); i++) {
        Move m = moves[i];
        Square from = m.from();
        Square to = m.to();
        if (((int)line[0] - (int)'0') == from.x() &&
            ((int)line[1] - (int)'0') == from.y() &&
            ((int)line[2] - (int)'0') == to.x() &&
            ((int)line[3] - (int)'0') == to.y()) {
          op_move = m;
          break;
        }
      }
    } else if (line.length() != 7) {
      std::cout << "error: invalid format." << std::endl;
      return true;
    } else {
      try {
        op_move = record::csa::strToMove(line, state);
      } catch (const std::runtime_error& e) {
        std::cout << e.what() << std::endl;
        return true;
      }
    }

    if (! state.isValidMove(op_move)) {
      return true;
    }

    state.makeMove(op_move);

    showState(state);
    csaShow(std::cout, op_move);
    std::cout << "\n";

    return false;
  }

  std::string
  inputLine(void)
  {
    std::string line;
    if (! std::getline(std::cin, line)) {
      return NULL;
    }
    return line;
  }
}

int
main()
{
  using namespace tuishogi;

  srandom(time(0));

  NumEffectState state((SimpleState(HIRATE)));
  while (true) {
    bool ended = computerOperate(state);
    if (ended) {
      break;
    }

    std::string line = inputLine();
    bool failed = playerOperate(state, line);
    if (failed) {
      break;
    }
  }
}


text:
chrome.extension.sendRequest({method: 'getCSS'}, function(response) {
  console.log(response);
  var css = document.createElement('style'); css.innerText = response;
  var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(css, s);
});


text:
(function(qs, mysql) {
  var connection;

  /////////////////////////////////////////////////////////////////////////////
  // CONFIGURATION
  /////////////////////////////////////////////////////////////////////////////

  var MYSQL_CONFIG = {
    host     : 'localhost',
    user     : 'osjs',
    password : 'osjs',
    database : 'osjs'
  };

  /////////////////////////////////////////////////////////////////////////////
  // USER SESSION ABSTRACTION
  /////////////////////////////////////////////////////////////////////////////

  var APIUser = function() {};
  APIUser.login = function(login, request, response, callback) {
    console.log('APIUser::login()');

    function complete(data) {
      request.cookies.set('username', data.username, {httpOnly:true});
      request.cookies.set('groups', JSON.stringify(data.groups), {httpOnly:true});

      callback(false, {
        userData : {
          id : data.id,
          username : data.username,
          name : data.name,
          groups : data.groups
        },
        userSettings: data.settings
      });
    }

    function invalid() {
      callback('Invalid login credentials');
    }

    if ( !login ) {
      invalid();
      return;
    }

    var q = 'SELECT `id`, `username`, `name`, `groups`, `settings` FROM `users` WHERE `username` = ? AND `password` = ? LIMIT 1;';
    var a = [login.username, login.password];

    connection.query(q, a, function(err, rows, fields) {
      if ( err ) {
        console.error(err);
        callback(err.Error);
        return;
      } else {
        if ( rows[0] ) {
          var row = rows[0];
          var settings = {};
          var groups = [];

          try {
            settings = JSON.parse(row.settings);
          } catch ( e ) {
            console.log('failed to parse settings', e);
          }

          try {
            groups = JSON.parse(row.groups);
          } catch ( e ) {
            console.log('failed to parse groups', e);
          }

          complete({
            id: parseInt(row.id, 10),
            username: row.username,
            name: row.name,
            groups: groups,
            settings: settings
          });
          return;
        }
      }

      invalid();
    });
  };

  APIUser.updateSettings = function(settings, request, response, callback) {
    var uname = request.cookies.get('username');

    var q = 'UPDATE `users` SET `settings` = ? WHERE `username` = ?;';
    var a = [JSON.stringify(settings), uname];

    connection.query(q, a, function(err, rows, fields) {
      if ( err ) {
        console.error(err);
        callback(err.Error);
        return;
      }

      callback(false, true);
    });
  };

  APIUser.logout = function(request, response) {
    console.log('APIUser::logout()');
    request.cookies.set('username', null, {httpOnly:true});
    request.cookies.set('groups', null, {httpOnly:true});
    return true;
  };

  /////////////////////////////////////////////////////////////////////////////
  // API EVENTS
  /////////////////////////////////////////////////////////////////////////////

  exports.onServerStart = function() {
    if ( !connection ) {
      connection = mysql.createConnection(MYSQL_CONFIG);
      connection.connect();
    }
  };

  exports.onServerEnd = function() {
    if ( connection ) {
      connection.end();
    }
  };

  exports.onRequestStart = function(request, response) {
  };

  exports.onRequestEnd = function(request, response) {
  };

  /////////////////////////////////////////////////////////////////////////////
  // API EXPORT
  /////////////////////////////////////////////////////////////////////////////

  exports.register = function(CONFIG, API, HANDLER) {
    console.info('-->', 'Registering handler API methods');

    API.login = function(args, callback, request, response, body) {
      APIUser.login(args, request, response, function(error, result) {
        callback(error, result);
      });
    };

    API.logout = function(args, callback, request, response) {
      var result = APIUser.logout(request, response);
      callback(false, result);
    };

    API.settings = function(args, callback, request, response) {
      APIUser.updateSettings(args.settings, request, response, callback);
    };

  };

})(require('querystring'), require('mysql'));


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>TaskType</title>
<meta name="date" content="2015-12-14">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Enum Constants |

Field |

Method

Detail:

Enum Constants |

Field |

Method

ie.gmit.sw.runner

Enum TaskType

java.lang.Object

java.lang.Enum<TaskType>

ie.gmit.sw.runner.TaskType

All Implemented Interfaces:

java.io.Serializable, java.lang.Comparable<TaskType>

public enum TaskType
extends java.lang.Enum<TaskType>

Enum Constant Summary

Enum Constants

Enum Constant and Description

CRACK

DECRYPT

ENCRYPT

UNDEFINED

Method Summary

All Methods Static Methods Concrete Methods

Modifier and Type
Method and Description

static TaskType
valueOf(java.lang.String name)

Returns the enum constant of this type with the specified name.

static TaskType[]
values()

Returns an array containing the constants of this enum type, in
the order they are declared.

Methods inherited from class java.lang.Enum

compareTo, equals, getDeclaringClass, hashCode, name, ordinal, toString, valueOf

Methods inherited from class java.lang.Object

getClass, notify, notifyAll, wait, wait, wait

Enum Constant Detail

ENCRYPT

public static final TaskType ENCRYPT

DECRYPT

public static final TaskType DECRYPT

CRACK

public static final TaskType CRACK

UNDEFINED

public static final TaskType UNDEFINED

Method Detail

values

public static TaskType[] values()

Returns an array containing the constants of this enum type, in
the order they are declared.  This method may be used to iterate
over the constants as follows:

for (TaskType c : TaskType.values())
    System.out.println(c);

Returns:

an array containing the constants of this enum type, in the order they are declared

valueOf

public static TaskType valueOf(java.lang.String name)

Returns the enum constant of this type with the specified name.
The string must match exactly an identifier used to declare an
enum constant in this type.  (Extraneous whitespace characters are
not permitted.)

Parameters:

name - the name of the enum constant to be returned.

Returns:

the enum constant with the specified name

Throws:

java.lang.IllegalArgumentException - if this enum type has no constant with the specified name

java.lang.NullPointerException - if the argument is null

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Enum Constants |

Field |

Method

Detail:

Enum Constants |

Field |

Method


text:
package biz.neustar.ultra.rest.dto;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.google.common.base.Objects;

import javax.validation.constraints.NotNull;

/**
 * Represents an abstract AllFail (aka Backup) record for a AR Pools(SF,SLB,TM pools).
 */
@SuppressWarnings("PMD.AbstractClassWithoutAbstractMethod")
@JsonInclude(JsonInclude.Include.NON_NULL)
public abstract class AllFailRecord {
    @NotNull(message = "ALLFAIL_RECORD_RDATA_REQUIRED")
    private String rData;
    private String description;

    protected AllFailRecord() {
        // empty constructor
    }

    protected AllFailRecord(String rdata, String description) {
        this.rData = rdata;
        this.description = description;
    }

    public String getRData() {
        return rData;
    }

    public void setRData(String rdata) {
        this.rData = rdata;
    }

    public String getDescription() {
        return description;
    }

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

    @Override
    public String toString() {
        return "FailoverRecord [rData=" + rData + ", description=" + description + "]";
    }

    @Override
    public int hashCode() {
        return Objects.hashCode(getRData(), getDescription());
    }

    @Override
    public boolean equals(final Object obj) {
        if (!(obj instanceof AllFailRecord)) {
            return false;
        }
        final AllFailRecord other = (AllFailRecord) obj;
        return Objects.equal(getRData(), other.getRData()) && Objects.equal(getDescription(), other.getDescription());
    }
}


text:
class UserTags extends Extension {
  constructor() {
    super('UserTags');
  }

  static info() {
    return {
      id: 'UserTags',
      title: 'User Tags',
      description: 'Keep tabs on users with short notes on their posts.',
      extendedDescription: `Manage tags shown next to users' names in posts.`,
      author: 'The BetterGaia Team',
      homepage: 'http://www.bettergaia.com/',
      version: '1.0',
      match: ['/forum/**', '/news/**']
    };
  }

  static defaultPrefs() {
    return {
      'tags': {
          //'12345': ['cat', 'He is a cat.', 'http://google.com', 2014]
      }
    };
  }

  static settings() {
    return [
      {type: 'other', pref: 'tags'}
    ];
  }

  render() {
    // Get userid and add tag links
    $('body.forums .post .user_info_wrapper .user_info .user_name').each(function() {
        if ($(this).siblings('.bgUserTag').length === 0) {
            var userid = '', avibox = $(this).closest('.postcontent').find('.avatar_wrapper .avi_box');
            if (avibox.find('a.avatar').length === 0) userid = avibox.find('#animated_item > object').attr('onmousedown').replace("window.location='", '').split("/")[5];
            else userid = avibox.find('a.avatar').attr('href').split('/')[5];
            $(this).after('

');
        }
    });

    // Add stored tags
    var tags = this.getPref('tags');

    if (!$.isEmptyObject(tags)) {
        $.each(tags, function(key, tag){
            if ($('.bgUserTag a[userid="' + key + '"]')) {
                var url = tag[2];
                if (url.match(/\S/) && url.length > 1) $('.bgUserTag a[userid="' + key + '"]').attr({href: url}).text(tag[1]);
                else $('.bgUserTag a[userid="' + key + '"]').text(tag[1]);
            }
        });
    }

    $('.post .user_info_wrapper .user_info .bgUserTag > span').on('click.UserTags', function(){
        if (!$(this).parent().hasClass('bgut_loaded')) {
            var tagvalue = '', urlvalue = $(this).closest('.postcontent').find('.post-directlink a').attr('href');

            if ($(this).siblings('a').text().length > 0) {
                tagvalue = $(this).siblings('a').text();
                if ($(this).siblings('a').attr('href')) urlvalue = $(this).siblings('a').attr('href');
            }

            $(this).after(`

Tag ${$(this).closest('.user_info').find('.user_name').text()}

              <form>
                Tag
                <input type="text" id="bgut_tagtag" maxlength="50" placeholder="Notes and comments" value="${tagvalue}">
                User ID
                <input type="text" id="bgut_idtag" placeholder="Numerical" value="${$(this).siblings('a').attr('userid')}">
                Link
                <input type="text" id="bgut_linktag" placeholder="URL" value="${urlvalue}">

                  Delete
                  Save

            </form>
`);

            $(this).parent().addClass('bgut_loaded bgut_open');
        }
        else $(this).parent().toggleClass('bgut_open');

        $(this).parent().find('#bgut_tagtag').focus();
    });

    $('.bgUserTag').on('click.UserTags', 'a.bgclose', function() {
        $(this).closest('.bgUserTag').removeClass('bgut_open');
    });

    let that = this;
    $('.bgUserTag').on('click.UserTags', '.bgut_save', function() {
      var letsSave = false,
      username = $(this).closest('.user_info').find('.user_name').text(),
      tag = $(this).parent().siblings('#bgut_tagtag'),
      userid = $(this).parent().siblings('#bgut_idtag'),
      url = $(this).parent().siblings('#bgut_linktag');

      // Tags
      if (!tag.val().match(/\S/) || tag.val().length < 1) tag.prev('label').addClass('bgerror');
      else $(this).siblings('label[for="bgut_tagtag"].bgerror').removeClass('bgerror');

      // User ID
      if (userid.val().length < 1 || !userid.val().match(/\S/) || !$.isNumeric(userid.val())) userid.prev('label').addClass('bgerror');
      else $(this).siblings('label[for="bgut_idtag"].bgerror').removeClass('bgerror');

      // Check
      if ($(this).siblings('.bgerror').length === 0) letsSave = true;

      // Save
      if (letsSave) {
        let tags = that.getPref('tags');
        tags[userid.val()] = [username, tag.val(), url.val(), Date.now()];
        that.setPref('tags', tags);

        $('.bgUserTag a[userid="' + userid.val() + '"]').attr({href: url.val()}).text(tag.val());
        tag.closest('.bgUserTag').removeClass('bgut_loaded bgut_open');
        tag.closest('.bgut_model').remove();
      }
    });

    $('.bgUserTag').on('click.UserTags', '.bgut_delete', function() {
      let userid = $(this).parent().siblings('#bgut_idtag'),
          tags = that.getPref('tags');

      if (tags.hasOwnProperty(userid.val())) {
        delete tags[userid.val()];
        that.setPref('tags', tags);
        $('.bgUserTag a[userid="' + userid.val() + '"]').removeAttr('href').text('');
      }

      $(this).closest('.bgUserTag').removeClass('bgut_loaded bgut_open');
      $(this).closest('.bgut_model').remove();
    });
  }

  preMount() {
    this.addStyleSheet('style');
  }

  mount() {
    if (document.querySelector('#topic_header_container #thread_header')) {
      this.render();

      // For ajax thread calls
      this.observer = new window.MutationObserver(() => {
        this.render();
      });
      this.observer.observe(document.getElementById('content-padding'), {
        attributes: false,
        childList: true,
        characterData: false
      });
    }
  }

  unMount() {
    this.removeCSS();
    $('body.forums .post .user_info_wrapper .user_info .bgUserTag > span, body.forums .post .user_info_wrapper .user_info').off('click.UserTags');
    this.observer.disconnect();
    $('.bgUserTag').remove();
  }
}


text:
ACCEPTED

#### According to
World Register of Marine Species

#### Published in
Skryabin & Al-Yamani. 2006. New species of the genera Tintinnopsis, Metacylis and Eutintinnus (Ciliophora: Spirotrichea: Tintinnida) from waters off Kuwait (Arabian Gulf). Biologiya Morya (Vladivostok) Volume: 32 Issue: 5 Pages: 358-362

#### Original name
null

### Remarks
null


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

<vector
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="144dp"
    android:height="144dp"
    android:alpha="0.30"
    android:viewportHeight="24.0"
    android:viewportWidth="24.0"
    >

    <path
        android:fillColor="#FFFFFFFF"
        android:pathData="M18,4l2,4h-3l-2,-4h-2l2,4h-3l-2,-4H8l2,4H7L5,4H4c-1.1,0 -1.99,0.9 -1.99,2L2,18c0,1.1 0.9,2 2,2h16c1.1,0 2,-0.9 2,-2V4h-4z"
        />
</vector>


text:
categories:
    - Release
tags:
    - gh-pages

title: 1.73.0
---

{{page.title}} is live and ready for [download](https://github.com/MaibornWolff/codecharta/releases/tag/{{page.title}}). This version brings the following:

### Added 🚀

-   Improve descriptions ([#1879](https://github.com/MaibornWolff/codecharta/issues/1879))

    ![option dialog](https://user-images.githubusercontent.com/57844849/115393175-b2897b00-a1e1-11eb-8601-d2128f3469a3.png)

### Fixed 🐞

-   Excluding in delta mode is broken ([#1578](https://github.com/MaibornWolff/codecharta/issues/1578))
    (Inclusion and exclusion of files using wildcard searches in the flatten and exclude operations)
-   Fix labels and lines missing a connection in some cases([#1716](https://github.com/MaibornWolff/codecharta/issues/1716))
-   Ribbons resizing when expanding ([#1952](https://github.com/MaibornWolff/codecharta/issues/1952))

### Chore 👨💻 👩💻

-   Fix breaking changes with newest three-js version([#1877](https://github.com/MaibornWolff/codecharta/issues/1877))


text:
package org.tpwk.analyser;

import org.tpwk.analysis.AnalysisResult;

/**
 * The {@code Analyser} interface is implemented by a class performing input sting analysis and providing analysis results
 *
 * @author T-PWK
 */
public interface Analyser extends Analysable
{
    AnalysisResult getAnalysis();
}


text:
#include "utils/Environment.h"

#ifdef WIN32
#include <Windows.h>
#else
#include <unistd.h>
#include <cstdlib>
#include <cerrno>
#endif
#include <mutex>
#include <vector>
#include <iostream>

#include "utils/gsl.h"

namespace org {
namespace apache {
namespace nifi {
namespace minifi {
namespace utils {

bool Environment::runningAsService_(false);

void Environment::accessEnvironment(const std::function<void(void)>& func) {
  static std::recursive_mutex environmentMutex;
  std::lock_guard<std::recursive_mutex> lock(environmentMutex);
  func();
}

std::pair<bool, std::string> Environment::getEnvironmentVariable(const char* name) {
  bool exists = false;
  std::string value;

  Environment::accessEnvironment([&exists, &value, name](){
#ifdef WIN32
    std::vector<char> buffer(32767U);  // https://docs.microsoft.com/en-gb/windows/win32/api/processenv/nf-processenv-getenvironmentvariablea
    // GetEnvironmentVariableA does not set last error to 0 on success, so an error from a pervious API call would influence the GetLastError() later,
    // so we set the last error to 0 before calling
    SetLastError(ERROR_SUCCESS);
    uint32_t ret = GetEnvironmentVariableA(name, buffer.data(), gsl::narrow<DWORD>(buffer.size()));
    if (ret > 0U) {
      exists = true;
      value = std::string(buffer.data(), ret);
    } else if (GetLastError() == ERROR_SUCCESS) {
      // Exists, but empty
      exists = true;
    }
#else
    char* ret = getenv(name);
    if (ret != nullptr) {
      exists = true;
      value = ret;
    }
#endif
  });

  return std::make_pair(exists, std::move(value));
}

bool Environment::setEnvironmentVariable(const char* name, const char* value, bool overwrite /*= true*/) {
  bool success = false;

  Environment::accessEnvironment([&success, name, value, overwrite](){
#ifdef WIN32
    if (!overwrite && Environment::getEnvironmentVariable(name).first) {
      success = true;
    } else {
      success = SetEnvironmentVariableA(name, value);
    }
#else
    int ret = setenv(name, value, static_cast<int>(overwrite));
    success = ret == 0;
#endif
  });

  return success;
}

bool Environment::unsetEnvironmentVariable(const char* name) {
  bool success = false;

  Environment::accessEnvironment([&success, name](){
#ifdef WIN32
    success = SetEnvironmentVariableA(name, nullptr);
#else
    int ret = unsetenv(name);
    success = ret == 0;
#endif
  });

  return success;
}

std::string Environment::getCurrentWorkingDirectory() {
  std::string cwd;

  Environment::accessEnvironment([&cwd](){
#ifdef WIN32
    uint32_t len = 0U;
    std::vector<char> buffer;
    // https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-getcurrentdirectory
    // "If the buffer that is pointed to by lpBuffer is not large enough,
    // the return value specifies the required size of the buffer,
    // in characters, including the null-terminating character."
    while (true) {
      len = GetCurrentDirectoryA(gsl::narrow<DWORD>(buffer.size()), buffer.data());
      if (len < buffer.size()) {
        break;
      }
      buffer.resize(len);
    }
    if (len > 0U) {
      cwd = std::string(buffer.data(), len);
    }
#else
    std::vector<char> buffer(1024U);
    char* path = nullptr;
    while (true) {
      path = getcwd(buffer.data(), buffer.size());
      if (path != nullptr) {
        cwd = path;
        break;
      } else if (errno == ERANGE) {
        buffer.resize(buffer.size() * 2);
      } else {
        break;
      }
    }
#endif
  });

  return cwd;
}

bool Environment::setCurrentWorkingDirectory(const char* directory) {
  bool success = false;

  Environment::accessEnvironment([&success, directory](){
#ifdef WIN32
    success = SetCurrentDirectoryA(directory);
#else
    int ret = chdir(directory);
    success = ret == 0;
#endif
  });

  return success;
}

void Environment::setRunningAsService(bool runningAsService) {
  Environment::accessEnvironment([runningAsService](){
    runningAsService_ = runningAsService;
  });
}

bool Environment::isRunningAsService() {
  bool runningAsService = false;

  Environment::accessEnvironment([&runningAsService](){
    runningAsService = runningAsService_;
  });

  return runningAsService;
}

}  // namespace utils
}  // namespace minifi
}  // namespace nifi
}  // namespace apache
}  // namespace org


text:
import webapp2
from google.appengine.ext import ndb

class Model1(ndb.Model):
    hoge = ndb.StringProperty()
    fuga = ndb.StringProperty()
    piyo = ndb.StringProperty()

class Model2(ndb.Model):
    hoge = ndb.StringProperty()
    fuga = ndb.StringProperty()
    piyo = ndb.StringProperty()

class MainPage(webapp2.RequestHandler):
    def get(self):
        self.response.headers['Content-Type'] = 'text/plain'
        self.response.write('Hello, World!')

class MakeData(webapp2.RequestHandler):
    def get(self):
        hoge = ''
        fuga = ''
        piyo = ''
        for i in range(10):
            hoge += 'あいうえおかきくけこさしすせそ'
            fuga += 'あいうえおかきくけこさしすせそ'
            piyo += 'あいうえおかきくけこさしすせそ'

        for i in range(30):
            models = []
            for j in range(10):
                models.append(Model1(hoge=hoge, fuga=fuga, piyo=piyo))
            ndb.put_multi(models)

        for i in range(30):
            models = []
            for j in range(10):
                models.append(Model2(hoge=hoge, fuga=fuga, piyo=piyo))
            ndb.put_multi(models)

        self.response.headers['Content-Type'] = 'text/plain'
        self.response.write('ok')

class BackupMock(webapp2.RequestHandler):
    def get(self):
        self.response.set_status(200)

app = webapp2.WSGIApplication(
    [
        ('/', MainPage),
        ('/makedata', MakeData),
        ('/_ah/datastore_admin/backup.create', BackupMock),
    ]
    , debug=True)


text:
require "uri"
require "multi_json"
require "faraday"

require "fakturoid/config"
require "fakturoid/connection"
require "fakturoid/request"
require "fakturoid/response"
require "fakturoid/api"
require "fakturoid/client"
require "fakturoid/version"
require "fakturoid/railtie" if defined?(::Rails)

module Fakturoid
  class ApiError < StandardError
    attr_accessor :response_code, :response_body

    def initialize(message = nil, response_code = nil, response_body = nil)
      super(message)
      self.response_code = response_code
      self.response_body = response_body
    end
  end

  class ContentTypeError        < ApiError; end
  class UserAgentError          < ApiError; end
  class AuthenticationError     < ApiError; end
  class BlockedAccountError     < ApiError; end
  class RateLimitError          < ApiError; end
  class ReadOnlySiteError       < ApiError; end
  class PaginationError         < ApiError; end

  class RecordNotFoundError     < ApiError; end
  class InvalidRecordError      < ApiError; end
  class DestroySubjectError     < ApiError; end
  class SubjectLimitError       < ApiError; end
  class GeneratorLimitError     < ApiError; end
  class UnsupportedFeatureError < ApiError; end

  class ClientError < ApiError; end
  class ServerError < ApiError; end

  def self.configure(&block)
    Fakturoid::Api.configure(&block)
  end
end


text:
<?php

// Очищаем все данные сессии
session_destroy();


text:
package com.tlacaelelsoftware.tochtlimail.common;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

import static org.junit.Assert.fail;

/**
 * Unit test for simple App.
 */
public class MailMessageValidationTest {
    ValidatorHelper<MailMessage> validatorHelper = new ValidatorHelper<MailMessage>();

    @Rule
    public ExpectedException thrown = ExpectedException.none();

    @Test
    public void validateWellFormedMessage() {
        MailMessage message = new MailMessage("mail@test.com", "first@mail.com,second@mail.com", "Some subject", "some text");

        try {
            validatorHelper.validate(message);
        } catch (Exception e) {
            fail("validate method should not throw any exception");
        }
    }

    @Test
    public void validateBlankFromAddressMessage() {
        MailMessage message = new MailMessage("", "first@mail.com,second@mail.com", "Some subject", "some text");

        thrown.expect(IllegalArgumentException.class);
        thrown.expectMessage("may not be empty");
        validatorHelper.validate(message);
    }

    @Test
    public void validateBlankRecipients() {
        MailMessage message = new MailMessage("mail@test.com", "", "Some subject", "some text");

        thrown.expect(IllegalArgumentException.class);
        thrown.expectMessage("may not be empty");
        validatorHelper.validate(message);
    }

    @Test
    public void validateBlankSubject() {
        MailMessage message = new MailMessage("mail@test.com", "first@gmail.com,second@gmail.com", "", "some text");

        thrown.expect(IllegalArgumentException.class);
        thrown.expectMessage("may not be empty");
        validatorHelper.validate(message);
    }

    @Test
    public void validateBlankText() {
        MailMessage message = new MailMessage("mail@test.com", "first@gmail.com,second@gmail.com", "Some subject", "");

        thrown.expect(IllegalArgumentException.class);
        thrown.expectMessage("may not be empty");
        validatorHelper.validate(message);
    }

    @Test
    public void fromAddressShouldBeAValidEmail(){
        MailMessage message = new MailMessage("notAMail.com", "first@gmail.com,second@gmail.com", "Some subject", "Some Text");

        thrown.expect(IllegalArgumentException.class);
        thrown.expectMessage("not a well-formed email address");
        validatorHelper.validate(message);
    }
}


text:
using extensions::Extension;

ExtensionAppModelBuilder::ExtensionAppModelBuilder(
    AppListControllerDelegate* controller)
    : AppListModelBuilder(controller, ExtensionAppItem::kItemType) {
}

ExtensionAppModelBuilder::~ExtensionAppModelBuilder() {
  OnShutdown();
  OnShutdown(extension_registry_);
}

void ExtensionAppModelBuilder::InitializePrefChangeRegistrars() {
  profile_pref_change_registrar_.Init(profile()->GetPrefs());
  profile_pref_change_registrar_.Add(
      prefs::kHideWebStoreIcon,
      base::Bind(&ExtensionAppModelBuilder::OnProfilePreferenceChanged,
                 base::Unretained(this)));

  if (!extensions::util::IsNewBookmarkAppsEnabled())
    return;

  // TODO(calamity): analyze the performance impact of doing this every
  // extension pref change.
  extensions::ExtensionsBrowserClient* client =
      extensions::ExtensionsBrowserClient::Get();
  extension_pref_change_registrar_.Init(
      client->GetPrefServiceForContext(profile()));
  extension_pref_change_registrar_.Add(
    extensions::pref_names::kExtensions,
    base::Bind(&ExtensionAppModelBuilder::OnExtensionPreferenceChanged,
               base::Unretained(this)));
}

void ExtensionAppModelBuilder::OnProfilePreferenceChanged() {
  extensions::ExtensionSet extensions;
  controller()->GetApps(profile(), &extensions);

  for (extensions::ExtensionSet::const_iterator app = extensions.begin();
       app != extensions.end(); ++app) {
    bool should_display =
        extensions::ui_util::ShouldDisplayInAppLauncher(app->get(), profile());
    bool does_display = GetExtensionAppItem((*app)->id()) != nullptr;

    if (should_display == does_display)
      continue;

    if (should_display) {
      InsertApp(CreateAppItem((*app)->id(),
                              "",
                              gfx::ImageSkia(),
                              (*app)->is_platform_app()));
    } else {
      RemoveApp((*app)->id());
    }
  }
}

void ExtensionAppModelBuilder::OnExtensionPreferenceChanged() {
  model()->NotifyExtensionPreferenceChanged();
}

void ExtensionAppModelBuilder::OnBeginExtensionInstall(
    const ExtensionInstallParams& params) {
  if (!params.is_app)
    return;

  DVLOG(2) << service() << ": OnBeginExtensionInstall: "
           << params.extension_id.substr(0, 8);
  ExtensionAppItem* existing_item = GetExtensionAppItem(params.extension_id);
  if (existing_item) {
    existing_item->SetIsInstalling(true);
    return;
  }

  // Icons from the webstore can be unusual sizes. Once installed,
  // ExtensionAppItem uses extension_misc::EXTENSION_ICON_MEDIUM (48) to load
  // it, so be consistent with that.
  gfx::Size icon_size(extension_misc::EXTENSION_ICON_MEDIUM,
                      extension_misc::EXTENSION_ICON_MEDIUM);
  gfx::ImageSkia resized(gfx::ImageSkiaOperations::CreateResizedImage(
      params.installing_icon, skia::ImageOperations::RESIZE_BEST, icon_size));

  InsertApp(CreateAppItem(params.extension_id,
                          params.extension_name,
                          resized,
                          params.is_platform_app));
}

void ExtensionAppModelBuilder::OnDownloadProgress(
    const std::string& extension_id,
    int percent_downloaded) {
  ExtensionAppItem* item = GetExtensionAppItem(extension_id);
  if (!item)
    return;
  item->SetPercentDownloaded(percent_downloaded);
}

void ExtensionAppModelBuilder::OnInstallFailure(
    const std::string& extension_id) {
  model()->DeleteItem(extension_id);
}

void ExtensionAppModelBuilder::OnExtensionLoaded(
    content::BrowserContext* browser_context,
    const extensions::Extension* extension) {
  if (!extensions::ui_util::ShouldDisplayInAppLauncher(extension, profile()))
    return;

  DVLOG(2) << service() << ": OnExtensionLoaded: "
           << extension->id().substr(0, 8);
  ExtensionAppItem* existing_item = GetExtensionAppItem(extension->id());
  if (existing_item) {
    existing_item->Reload();
    if (service())
      service()->UpdateItem(existing_item);
    return;
  }

  InsertApp(CreateAppItem(extension->id(),
                          "",
                          gfx::ImageSkia(),
                          extension->is_platform_app()));
}

void ExtensionAppModelBuilder::OnExtensionUnloaded(
    content::BrowserContext* browser_context,
    const extensions::Extension* extension,
    extensions::UnloadedExtensionInfo::Reason reason) {
  ExtensionAppItem* item = GetExtensionAppItem(extension->id());
  if (!item)
    return;
  item->UpdateIcon();
}

void ExtensionAppModelBuilder::OnExtensionUninstalled(
    content::BrowserContext* browser_context,
    const extensions::Extension* extension,
    extensions::UninstallReason reason) {
  if (service()) {
    DVLOG(2) << service() << ": OnExtensionUninstalled: "
             << extension->id().substr(0, 8);
    service()->RemoveUninstalledItem(extension->id());
    return;
  }
  model()->DeleteUninstalledItem(extension->id());
}

void ExtensionAppModelBuilder::OnDisabledExtensionUpdated(
    const Extension* extension) {
  if (!extensions::ui_util::ShouldDisplayInAppLauncher(extension, profile()))
    return;

  ExtensionAppItem* existing_item = GetExtensionAppItem(extension->id());
  if (existing_item)
    existing_item->Reload();
}

void ExtensionAppModelBuilder::OnShutdown() {
  if (tracker_) {
    tracker_->RemoveObserver(this);
    tracker_ = nullptr;
  }
}

void ExtensionAppModelBuilder::OnShutdown(
    extensions::ExtensionRegistry* registry) {
  if (!extension_registry_)
    return;

  DCHECK_EQ(extension_registry_, registry);
  extension_registry_->RemoveObserver(this);
  extension_registry_ = nullptr;
}

scoped_ptr<ExtensionAppItem> ExtensionAppModelBuilder::CreateAppItem(
    const std::string& extension_id,
    const std::string& extension_name,
    const gfx::ImageSkia& installing_icon,
    bool is_platform_app) {
  return make_scoped_ptr(new ExtensionAppItem(profile(),
                                              GetSyncItem(extension_id),
                                              extension_id,
                                              extension_name,
                                              installing_icon,
                                              is_platform_app));
}

void ExtensionAppModelBuilder::BuildModel() {
  DCHECK(!tracker_);

  InitializePrefChangeRegistrars();

  tracker_ = controller()->GetInstallTrackerFor(profile());
  extension_registry_ = extensions::ExtensionRegistry::Get(profile());

  PopulateApps();

  // Start observing after model is built.
  if (tracker_)
    tracker_->AddObserver(this);

  if (extension_registry_)
    extension_registry_->AddObserver(this);
}

void ExtensionAppModelBuilder::PopulateApps() {
  extensions::ExtensionSet extensions;
  controller()->GetApps(profile(), &extensions);

  for (extensions::ExtensionSet::const_iterator app = extensions.begin();
       app != extensions.end(); ++app) {
    if (!extensions::ui_util::ShouldDisplayInAppLauncher(app->get(), profile()))
      continue;
    InsertApp(CreateAppItem((*app)->id(),
                            "",
                            gfx::ImageSkia(),
                            (*app)->is_platform_app()));
  }
}

ExtensionAppItem* ExtensionAppModelBuilder::GetExtensionAppItem(
    const std::string& extension_id) {
  return static_cast<ExtensionAppItem*>(GetAppItem(extension_id));
}

void ExtensionAppModelBuilder::OnListItemMoved(size_t from_index,
                                               size_t to_index,
                                               app_list::AppListItem* item) {
  DCHECK(!service());

  // This will get called from AppListItemList::ListItemMoved after
  // set_position is called for the item.
  if (item->GetItemType() != ExtensionAppItem::kItemType)
    return;

  app_list::AppListItemList* item_list = model()->top_level_item_list();
  ExtensionAppItem* prev = nullptr;
  for (size_t idx = to_index; idx > 0; --idx) {
    app_list::AppListItem* item = item_list->item_at(idx - 1);
    if (item->GetItemType() == ExtensionAppItem::kItemType) {
      prev = static_cast<ExtensionAppItem*>(item);
      break;
    }
  }
  ExtensionAppItem* next = nullptr;
  for (size_t idx = to_index; idx < item_list->item_count() - 1; ++idx) {
    app_list::AppListItem* item = item_list->item_at(idx + 1);
    if (item->GetItemType() == ExtensionAppItem::kItemType) {
      next = static_cast<ExtensionAppItem*>(item);
      break;
    }
  }
  // item->Move will call set_position, overriding the item's position.
  if (prev || next)
    static_cast<ExtensionAppItem*>(item)->Move(prev, next);
}


text:
/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/

"use strict";

const Cache = require("../Cache");

/** @typedef {import("webpack-sources").Source} Source */
/** @typedef {import("../Cache").Etag} Etag */
/** @typedef {import("../Compiler")} Compiler */
/** @typedef {import("../Module")} Module */

class MemoryWithGcCachePlugin {
	constructor({ maxGenerations }) {
		this._maxGenerations = maxGenerations;
	}
	/**
	 * Apply the plugin
	 * @param {Compiler} compiler the compiler instance
	 * @returns {void}
	 */
	apply(compiler) {
		const maxGenerations = this._maxGenerations;
		/** @type {Map<string, { etag: Etag | null, data: any }>} */
		const cache = new Map();
		/** @type {Map<string, { entry: { etag: Etag | null, data: any }, until: number }>} */
		const oldCache = new Map();
		let generation = 0;
		let cachePosition = 0;
		const logger = compiler.getInfrastructureLogger("MemoryWithGcCachePlugin");
		compiler.hooks.afterDone.tap("MemoryWithGcCachePlugin", () => {
			generation++;
			let clearedEntries = 0;
			let lastClearedIdentifier;
			for (const [identifier, entry] of oldCache) {
				if (entry.until > generation) break;

				oldCache.delete(identifier);
				if (cache.get(identifier) === undefined) {
					cache.delete(identifier);
					clearedEntries++;
					lastClearedIdentifier = identifier;
				}
			}
			if (clearedEntries > 0 || oldCache.size > 0) {
				logger.log(
					`${cache.size - oldCache.size} active entries, ${
						oldCache.size
					} recently unused cached entries${
						clearedEntries > 0
							? `, ${clearedEntries} old unused cache entries removed e. g. ${lastClearedIdentifier}`
							: ""
					}`
				);
			}
			let i = (cache.size / maxGenerations) | 0;
			let j = cachePosition >= cache.size ? 0 : cachePosition;
			cachePosition = j + i;
			for (const [identifier, entry] of cache) {
				if (j !== 0) {
					j--;
					continue;
				}
				if (entry !== undefined) {
					// We don't delete the cache entry, but set it to undefined instead
					// This reserves the location in the data table and avoids rehashing
					// when constantly adding and removing entries.
					// It will be deleted when removed from oldCache.
					cache.set(identifier, undefined);
					oldCache.delete(identifier);
					oldCache.set(identifier, {
						entry,
						until: generation + maxGenerations
					});
					if (i-- === 0) break;
				}
			}
		});
		compiler.cache.hooks.store.tap(
			{ name: "MemoryWithGcCachePlugin", stage: Cache.STAGE_MEMORY },
			(identifier, etag, data) => {
				cache.set(identifier, { etag, data });
			}
		);
		compiler.cache.hooks.get.tap(
			{ name: "MemoryWithGcCachePlugin", stage: Cache.STAGE_MEMORY },
			(identifier, etag, gotHandlers) => {
				const cacheEntry = cache.get(identifier);
				if (cacheEntry === null) {
					return null;
				} else if (cacheEntry !== undefined) {
					return cacheEntry.etag === etag ? cacheEntry.data : null;
				}
				const oldCacheEntry = oldCache.get(identifier);
				if (oldCacheEntry !== undefined) {
					const cacheEntry = oldCacheEntry.entry;
					if (cacheEntry === null) {
						oldCache.delete(identifier);
						cache.set(identifier, cacheEntry);
						return null;
					} else {
						if (cacheEntry.etag !== etag) return null;
						oldCache.delete(identifier);
						cache.set(identifier, cacheEntry);
						return cacheEntry.data;
					}
				}
				gotHandlers.push((result, callback) => {
					if (result === undefined) {
						cache.set(identifier, null);
					} else {
						cache.set(identifier, { etag, data: result });
					}
					return callback();
				});
			}
		);
		compiler.cache.hooks.shutdown.tap(
			{ name: "MemoryWithGcCachePlugin", stage: Cache.STAGE_MEMORY },
			() => {
				cache.clear();
				oldCache.clear();
			}
		);
	}
}
module.exports = MemoryWithGcCachePlugin;


text:
#ifndef _DW1000_H_INCLUDED
#define _DW1000_H_INCLUDED

// Time resolution in micro-seconds of time based registers/values.
// Each bit in a timestamp counts for a period of approx. 15.65ps
#define TIME_RES 0.000015650040064103
#define TIME_RES_INV 63897.6

// time stamp byte length
#define LEN_STAMP 5

// enum to determine RX or TX mode of device
#define IDLE_MODE 0x00
#define RX_MODE 0x01
#define TX_MODE 0x02

// used for SPI ready w/o actual writes
#define JUNK 0x00

// no sub-address for register write
#define NO_SUB 0x00

// device id register
#define DEV_ID 0x00
#define LEN_DEV_ID 4

// extended unique identifier register
#define EUI 0x01
#define LEN_EUI 8

// PAN identifier, short address register
#define PANADR 0x03
#define LEN_PANADR 4

// device configuration register
#define SYS_CFG 0x04
#define LEN_SYS_CFG 4
#define FFEN_BIT 0
#define FFBC_BIT 1
#define FFAB_BIT 2
#define FFAD_BIT 3
#define FFAA_BIT 4
#define FFAM_BIT 5
#define FFAR_BIT 6
#define DIS_DRXB_BIT 12
#define DIS_STXP_BIT 18
#define HIRQ_POL_BIT 9
#define RXAUTR_BIT 29
#define PHR_MODE_SUB 16
#define LEN_PHR_MODE_SUB 2
#define RXM110K_BIT 22

// device control register
#define SYS_CTRL 0x0D
#define LEN_SYS_CTRL 4
#define SFCST_BIT 0
#define TXSTRT_BIT 1
#define TXDLYS_BIT 2
#define TRXOFF_BIT 6
#define WAIT4RESP_BIT 7
#define RXENAB_BIT 8
#define RXDLYS_BIT 9

// system event status register
#define SYS_STATUS 0x0F
#define LEN_SYS_STATUS 5
#define CPLOCK_BIT 1
#define AAT_BIT 3
#define TXFRB_BIT 4
#define TXPRS_BIT 5
#define TXPHS_BIT 6
#define TXFRS_BIT 7
#define LDEDONE_BIT 10
#define RXPHE_BIT 12
#define RXDFR_BIT 13
#define RXFCG_BIT 14
#define RXFCE_BIT 15
#define RXRFSL_BIT 16
#define RXRFTO_BIT 17
#define LDEERR_BIT 18
#define RFPLL_LL_BIT 24
#define CLKPLL_LL_BIT 25

// system event mask register
// NOTE: uses the bit definitions of SYS_STATUS (below 32)
#define SYS_MASK 0x0E
#define LEN_SYS_MASK 4

// system time counter
#define SYS_TIME 0x06
#define LEN_SYS_TIME LEN_STAMP

// RX timestamp register
#define RX_TIME 0x15
#define LEN_RX_TIME 14
#define RX_STAMP_SUB 0x00
#define FP_AMPL1_SUB 0x07
#define LEN_RX_STAMP LEN_STAMP
#define LEN_FP_AMPL1 2

// RX frame quality
#define RX_FQUAL 0x12
#define LEN_RX_FQUAL 8
#define STD_NOISE_SUB 0x00
#define FP_AMPL2_SUB 0x02
#define FP_AMPL3_SUB 0x04
#define CIR_PWR_SUB 0x06
#define LEN_STD_NOISE 2
#define LEN_FP_AMPL2 2
#define LEN_FP_AMPL3 2
#define LEN_CIR_PWR 2

// TX timestamp register
#define TX_TIME 0x17
#define LEN_TX_TIME 10
#define TX_STAMP_SUB 0
#define LEN_TX_STAMP LEN_STAMP

// timing register (for delayed RX/TX)
#define DX_TIME 0x0A
#define LEN_DX_TIME LEN_STAMP

// transmit data buffer
#define TX_BUFFER 0x09
#define LEN_TX_BUFFER 1024
#define LEN_UWB_FRAMES 127
#define LEN_EXT_UWB_FRAMES 1023

// RX frame info
#define RX_FINFO 0x10
#define LEN_RX_FINFO 4

// receive data buffer
#define RX_BUFFER 0x11
#define LEN_RX_BUFFER 1024

// transmit control
#define TX_FCTRL 0x08
#define LEN_TX_FCTRL 5

// channel control
#define CHAN_CTRL 0x1F
#define LEN_CHAN_CTRL 4
#define DWSFD_BIT 17
#define TNSSFD_BIT 20
#define RNSSFD_BIT 21

// user-defined SFD
#define USR_SFD 0x21
#define LEN_USR_SFD 41
#define SFD_LENGTH_SUB 0x00
#define LEN_SFD_LENGTH 1

// OTP control (for LDE micro code loading only)
#define OTP_IF 0x2D
#define OTP_ADDR_SUB 0x04
#define OTP_CTRL_SUB 0x06
#define OTP_RDAT_SUB 0x0A
#define LEN_OTP_ADDR 2
#define LEN_OTP_CTRL 2
#define LEN_OTP_RDAT 4

// AGC_TUNE1/2 (for re-tuning only)
#define AGC_TUNE 0x23
#define AGC_TUNE1_SUB 0x04
#define AGC_TUNE2_SUB 0x0C
#define AGC_TUNE3_SUB 0x12
#define LEN_AGC_TUNE1 2
#define LEN_AGC_TUNE2 4
#define LEN_AGC_TUNE3 2

// DRX_TUNE2 (for re-tuning only)
#define DRX_TUNE 0x27
#define DRX_TUNE0b_SUB 0x02
#define DRX_TUNE1a_SUB 0x04
#define DRX_TUNE1b_SUB 0x06
#define DRX_TUNE2_SUB 0x08
#define DRX_TUNE4H_SUB 0x26
#define LEN_DRX_TUNE0b 2
#define LEN_DRX_TUNE1a 2
#define LEN_DRX_TUNE1b 2
#define LEN_DRX_TUNE2 4
#define LEN_DRX_TUNE4H 2

// LDE_CFG1 (for re-tuning only)
#define LDE_IF 0x2E
#define LDE_CFG1_SUB 0x0806
#define LDE_RXANTD_SUB 0x1804
#define LDE_CFG2_SUB 0x1806
#define LDE_REPC_SUB 0x2804
#define LEN_LDE_CFG1 1
#define LEN_LDE_CFG2 2
#define LEN_LDE_REPC 2
#define LEN_LDE_RXANTD 2

// TX_POWER (for re-tuning only)
#define TX_POWER 0x1E
#define LEN_TX_POWER 4

// RF_CONF (for re-tuning only)
#define RF_CONF 0x28
#define RF_RXCTRLH_SUB 0x0B
#define RF_TXCTRL_SUB 0x0C
#define LEN_RF_RXCTRLH 1
#define LEN_RF_TXCTRL 4

// TX_CAL (for re-tuning only)
#define TX_CAL 0x2A
#define TC_PGDELAY_SUB 0x0B
#define LEN_TC_PGDELAY 1

// FS_CTRL (for re-tuning only)
#define FS_CTRL 0x2B
#define FS_PLLCFG_SUB 0x07
#define FS_PLLTUNE_SUB 0x0B
#define FS_XTALT_SUB 0x0E
#define LEN_FS_PLLCFG 4
#define LEN_FS_PLLTUNE 1
#define LEN_FS_XTALT 1

// PMSC
#define PMSC 0x36
#define PMSC_CTRL0_SUB 0x00
#define LEN_PMSC_CTRL0 4

// TX_ANTD Antenna delays
#define TX_ANTD 0x18
#define LEN_TX_ANTD 2

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <Arduino.h>
#include "DW1000Time.h"
#include <SPI.h>

class DW1000Class {
public:
	/* TODO impl: later
	 * - TXBOFFS in TX_FCTRL for offset buffer transmit
 	 * - TR in TX_FCTRL for flagging for ranging messages
	 * - CANSFCS in SYS_CTRL to cancel frame check suppression
	 * - HSRBP in SYS_CTRL to determine in double buffered mode from which buffer to read
	 */

	/* ##### Init ################################################################ */
	/**
	Initiates and starts a sessions with one or more DW1000.

	@param[in] irq The interrupt line/pin that connects the Arduino.
	@param[in] rst The reset line/pin for hard resets of ICs that connect to the Arduino.
	*/
	static void begin(int irq, int rst);

	/**
	Initiates and starts a sessions with one or more DW1000. Soft resets (i.e. command
	triggered) are used and it is assumed that no reset line is wired.

	@param[in] irq The interrupt line/pin that connects the Arduino.
	*/
	static void begin(int irq);

	/**
	Selects a specific DW1000 chip for communication. In case of a single DW1000 chip in use
	this call only needs to be done once at start up, but is still mandatory. Other than a call
	to `reselect()` this function performs an initial setup of the now-selected chip.

	@param[in] ss The chip select line/pin that connects the to-be-selected chip with the
	Arduino.
	*/
	static void select(int ss);

	/**
	(Re-)selects a specific DW1000 chip for communication. In case of a single DW1000 chip in use
	this call is not needed; only a call to `select()` has to be performed once at start up. Other
	than a call to `select()` this function does not perform an initial setup of the (again-)selected
	chips and assumes it to have a valid configuration loaded.

	@param[in] ss The chip select line/pin that connects the to-be-selected chip with the
	Arduino.
	*/
	static void reselect(int ss);

	/**
	Tells the driver library that no communication to a DW1000 will be required anymore.
	This basically just frees SPI and the previously used pins.
	*/
	static void end();

	/**
	Resets all connected or the currently selected DW1000 chip. A hard reset of all chips
	is preferred, although a soft reset of the currently selected one is executed if no
	reset pin has been specified (when using `begin(int)`, instead of `begin(int, int)`).
	*/
	static void reset();

	/**
	Resets the currently selected DW1000 chip programmatically (via corresponding commands).
	*/
	static void softReset();

	/* ##### Print device id, address, etc. ###################################### */
	/**
	Generates a String representation of the device identifier of the chip. That usually
	are the letters "DECA" plus the	version and revision numbers of the chip.

	@param[out] msgBuffer The String buffer to be filled with printable device information.
		Provide 128 bytes, this should be sufficient.
	*/
	static void getPrintableDeviceIdentifier(char msgBuffer[]);

	/**
	Generates a String representation of the extended unique identifier (EUI) of the chip.

	@param[out] msgBuffer The String buffer to be filled with printable device information.
		Provide 128 bytes, this should be sufficient.
	*/
	static void getPrintableExtendedUniqueIdentifier(char msgBuffer[]);

	/**
	Generates a String representation of the short address and network identifier currently
	defined for the respective chip.

	@param[out] msgBuffer The String buffer to be filled with printable device information.
		Provide 128 bytes, this should be sufficient.
	*/
	static void getPrintableNetworkIdAndShortAddress(char msgBuffer[]);

	/**
	Generates a String representation of the main operational settings of the chip. This
	includes data rate, pulse repetition frequency, preamble and channel settings.

	@param[out] msgBuffer The String buffer to be filled with printable device information.
		Provide 128 bytes, this should be sufficient.
	*/
	static void getPrintableDeviceMode(char msgBuffer[]);

	/* ##### Device address management, filters ################################## */
	/**
	(Re-)set the network identifier which the selected chip should be associated with. This
	setting is important for certain MAC address filtering rules.

	@param[in] val An arbitrary numeric network identifier.
	*/

	static void setNetworkId(unsigned int val);

	/**
	(Re-)set the device address (i.e. short address) for the currently selected chip. This
	setting is important for certain MAC address filtering rules.

	@param[in] val An arbitrary numeric device address.
	*/
	static void setDeviceAddress(unsigned int val);
	// TODO MAC and filters

	static void setEUI(char eui[]);
	static void setEUI(byte eui[]);

	/* ##### General device configuration ######################################## */
	/**
	Specifies whether the DW1000 chip should, again, turn on its receiver in case that the
	last reception failed.

	This setting is enabled as part of `setDefaults()` if the device is
	in idle mode.

	@param[in] val `true` to enable, `false` to disable receiver auto-reenable.
	*/
	static void setReceiverAutoReenable(boolean val);

	/**
	Specifies the interrupt polarity of the DW1000 chip.

	As part of `setDefaults()` if the device is in idle mode, interrupt polarity is set to
	active high.

	@param[in] val `true` for active high interrupts, `false` for active low interrupts.
	*/
	static void setInterruptPolarity(boolean val);

	/**
	Specifies whether to suppress any frame check measures while sending or receiving messages.
	If suppressed, no 2-byte checksum is appended to the message before sending and this
	checksum is also not expected at receiver side. Note that when suppressing frame checks,
	the error event handler	(attached via `attachReceiveErrorHandler()`) will not be triggered
	if received data is corrupted.

	Frame checks are enabled as part of `setDefaults()` if the device is in idle mode.

	@param[in] val `true` to suppress frame check on sender and receiver side, `false` otherwise.
	*/
	static void suppressFrameCheck(boolean val);

	/**
	Specifies the data transmission rate of the DW1000 chip. One of the values
	- `TRX_RATE_110KBPS` (i.e. 110 kb/s)
	- `TRX_RATE_850KBPS` (i.e. 850 kb/s)
	- `TRX_RATE_6800KBPS` (i.e. 6.8 Mb/s)
	has to be provided.

	See `setDefaults()` and `enableMode()` for additional information on data rate settings.

	@param[in] rate The data transmission rate, encoded by the above defined constants.
	*/
	static void setDataRate(byte rate);

	/**
	Specifies the pulse repetition frequency (PRF) of data transmissions with the DW1000. Either
	- `TX_PULSE_FREQ_16MHZ` (i.e. 16 MHz)
	- `TX_PULSE_FREQ_64MHZ` (i.e. 64 MHz)
	has to be chosen.

	Note that the 16 MHz setting is more power efficient, while the 64 MHz setting requires more
	power, but also delivers slightly better transmission performance (i.e. on communication range and
	timestamp accuracy) (see DWM1000 User Manual, section 9.3).

	See `setDefaults()` and `enableMode()` for additional information on PRF settings.

	@param[in] freq The PRF, encoded by the above defined constants.
	*/
	static void setPulseFrequency(byte freq);
	static byte getPulseFrequency();
	static void setPreambleLength(byte prealen);
	static void setChannel(byte channel);
	static void setPreambleCode(byte preacode);
	static void useSmartPower(boolean smartPower);

	/* transmit and receive configuration. */
	static DW1000Time   setDelay(const DW1000Time& delay);
	static void         receivePermanently(boolean val);
	static void         setData(byte data[], unsigned int n);
	static void         setData(const String& data);
	static void         getData(byte data[], unsigned int n);
	static void         getData(String& data);
	static unsigned int getDataLength();
	static void         getTransmitTimestamp(DW1000Time& time);
	static void         getReceiveTimestamp(DW1000Time& time);
	static void         getSystemTimestamp(DW1000Time& time);
	static void         getTransmitTimestamp(byte data[]);
	static void         getReceiveTimestamp(byte data[]);
	static void         getSystemTimestamp(byte data[]);

	/* receive quality information. */
	static float getReceivePower();
	static float getFirstPathPower();
	static float getReceiveQuality();

	/* interrupt management. */
	static void interruptOnSent(boolean val);
	static void interruptOnReceived(boolean val);
	static void interruptOnReceiveFailed(boolean val);
	static void interruptOnReceiveTimeout(boolean val);
	static void interruptOnReceiveTimestampAvailable(boolean val);
	static void interruptOnAutomaticAcknowledgeTrigger(boolean val);

	/* callback handler management. */
	static void attachErrorHandler(void (* handleError)(void)) {
		_handleError = handleError;
	}

	static void attachSentHandler(void (* handleSent)(void)) {
		_handleSent = handleSent;
	}

	static void attachReceivedHandler(void (* handleReceived)(void)) {
		_handleReceived = handleReceived;
	}

	static void attachReceiveFailedHandler(void (* handleReceiveFailed)(void)) {
		_handleReceiveFailed = handleReceiveFailed;
	}

	static void attachReceiveTimeoutHandler(void (* handleReceiveTimeout)(void)) {
		_handleReceiveTimeout = handleReceiveTimeout;
	}

	static void attachReceiveTimestampAvailableHandler(void (* handleReceiveTimestampAvailable)(void)) {
		_handleReceiveTimestampAvailable = handleReceiveTimestampAvailable;
	}

	/* device state management. */
	// idle state
	static void idle();

	// general configuration state
	static void newConfiguration();
	static void commitConfiguration();

	// reception state
	static void newReceive();
	static void startReceive();

	// transmission state
	static void newTransmit();
	static void startTransmit();

	/* ##### Operation mode selection ############################################ */
	/**
	Specifies the mode of operation for the DW1000. Modes of operation are pre-defined
	combinations of data rate, pulse repetition frequency, preamble and channel settings
	that properly go together. If you simply want the chips to work, choosing a mode is
	preferred over manual configuration.

	The following modes are pre-configured and one of them needs to be chosen:
	- `MODE_LONGDATA_RANGE_LOWPOWER` (basically this is 110 kb/s data rate, 16 MHz PRF and long preambles)
	- `MODE_SHORTDATA_FAST_LOWPOWER` (basically this is 6.8 Mb/s data rate, 16 MHz PRF and short preambles)
	- `MODE_LONGDATA_FAST_LOWPOWER` (basically this is 6.8 Mb/s data rate, 16 MHz PRF and long preambles)
	- `MODE_SHORTDATA_FAST_ACCURACY` (basically this is 6.8 Mb/s data rate, 64 MHz PRF and short preambles)
	- `MODE_LONGDATA_FAST_ACCURACY` (basically this is 6.8 Mb/s data rate, 64 MHz PRF and long preambles)
	- `MODE_LONGDATA_RANGE_ACCURACY` (basically this is 110 kb/s data rate, 64 MHz PRF and long preambles)

	Note that LOWPOWER and ACCURACY refers to the better power efficiency and improved transmission performance
	of 16 MHZ and 64 MHZ PRF respectively (see `setPulseFrequency()`).

	The default setting that is selected by `setDefaults()` is MODE_LONGDATA_RANGE_LOWPOWER.

	@param[in] mode The mode of operation, encoded by the above defined constants.
	*/
	static void enableMode(const byte mode[]);

	// use RX/TX specific and general default settings
	static void setDefaults();

	/* debug pretty print registers. */
	static void getPrettyBytes(byte cmd, word offset, char msgBuffer[], unsigned int n);
	static void getPrettyBytes(byte data[], char msgBuffer[], unsigned int n);

	//convert from char to 4 bits (hexadecimal)
	static int  nibbleFromChar(char c);
	static void convertToByte(char string[], byte* eui_byte);

	// transmission/reception bit rate
	static const byte TRX_RATE_110KBPS  = 0x00;
	static const byte TRX_RATE_850KBPS  = 0x01;
	static const byte TRX_RATE_6800KBPS = 0x02;

	// transmission pulse frequency
	// 0x00 is 4MHZ, but receiver in DW1000 does not support it (!??)
	static const byte TX_PULSE_FREQ_16MHZ = 0x01;
	static const byte TX_PULSE_FREQ_64MHZ = 0x02;

	// preamble length (PE + TXPSR bits)
	static const byte TX_PREAMBLE_LEN_64   = 0x01;
	static const byte TX_PREAMBLE_LEN_128  = 0x05;
	static const byte TX_PREAMBLE_LEN_256  = 0x09;
	static const byte TX_PREAMBLE_LEN_512  = 0x0D;
	static const byte TX_PREAMBLE_LEN_1024 = 0x02;
	static const byte TX_PREAMBLE_LEN_1536 = 0x06;
	static const byte TX_PREAMBLE_LEN_2048 = 0x0A;
	static const byte TX_PREAMBLE_LEN_4096 = 0x03;

	// PAC size. */
	static const byte PAC_SIZE_8  = 8;
	static const byte PAC_SIZE_16 = 16;
	static const byte PAC_SIZE_32 = 32;
	static const byte PAC_SIZE_64 = 64;

	/* channel of operation. */
	static const byte CHANNEL_1 = 1;
	static const byte CHANNEL_2 = 2;
	static const byte CHANNEL_3 = 3;
	static const byte CHANNEL_4 = 4;
	static const byte CHANNEL_5 = 5;
	static const byte CHANNEL_7 = 7;

	/* preamble codes. */
	static const byte PREAMBLE_CODE_16MHZ_1  = 1;
	static const byte PREAMBLE_CODE_16MHZ_2  = 2;
	static const byte PREAMBLE_CODE_16MHZ_3  = 3;
	static const byte PREAMBLE_CODE_16MHZ_4  = 4;
	static const byte PREAMBLE_CODE_16MHZ_5  = 5;
	static const byte PREAMBLE_CODE_16MHZ_6  = 6;
	static const byte PREAMBLE_CODE_16MHZ_7  = 7;
	static const byte PREAMBLE_CODE_16MHZ_8  = 8;
	static const byte PREAMBLE_CODE_64MHZ_9  = 9;
	static const byte PREAMBLE_CODE_64MHZ_10 = 10;
	static const byte PREAMBLE_CODE_64MHZ_11 = 11;
	static const byte PREAMBLE_CODE_64MHZ_12 = 12;
	static const byte PREAMBLE_CODE_64MHZ_17 = 17;
	static const byte PREAMBLE_CODE_64MHZ_18 = 18;
	static const byte PREAMBLE_CODE_64MHZ_19 = 19;
	static const byte PREAMBLE_CODE_64MHZ_20 = 20;

	/* frame length settings. */
	static const byte FRAME_LENGTH_NORMAL   = 0x00;
	static const byte FRAME_LENGTH_EXTENDED = 0x03;

	/* pre-defined modes of operation (3 bytes for data rate, pulse frequency and
	preamble length). */
	static const byte MODE_LONGDATA_RANGE_LOWPOWER[];
	static const byte MODE_SHORTDATA_FAST_LOWPOWER[];
	static const byte MODE_LONGDATA_FAST_LOWPOWER[];
	static const byte MODE_SHORTDATA_FAST_ACCURACY[];
	static const byte MODE_LONGDATA_FAST_ACCURACY[];
	static const byte MODE_LONGDATA_RANGE_ACCURACY[];

private:
	/* chip select, reset and interrupt pins. */
	static unsigned int _ss;
	static unsigned int _rst;
	static unsigned int _irq;

	/* callbacks. */
	static void (* _handleError)(void);
	static void (* _handleSent)(void);
	static void (* _handleReceived)(void);
	static void (* _handleReceiveFailed)(void);
	static void (* _handleReceiveTimeout)(void);
	static void (* _handleReceiveTimestampAvailable)(void);

	/* register caches. */
	static byte _syscfg[LEN_SYS_CFG];
	static byte _sysctrl[LEN_SYS_CTRL];
	static byte _sysstatus[LEN_SYS_STATUS];
	static byte _txfctrl[LEN_TX_FCTRL];
	static byte _sysmask[LEN_SYS_MASK];
	static byte _chanctrl[LEN_CHAN_CTRL];

	/* PAN and short address. */
	static byte _networkAndAddress[LEN_PANADR];

	/* internal helper that guide tuning the chip. */
	static boolean    _smartPower;
	static byte       _extendedFrameLength;
	static byte       _preambleCode;
	static byte       _channel;
	static byte       _preambleLength;
	static byte       _pulseFrequency;
	static byte       _dataRate;
	static byte       _pacSize;
	static DW1000Time _antennaDelay;

	/* internal helper to remember how to properly act. */
	static boolean _permanentReceive;
	static boolean _frameCheck;

	// whether RX or TX is active
	static int _deviceMode;

	/* Arduino interrupt handler */
	static void handleInterrupt();

public: // TODO move and resort functions - filter functions should be accessible from external
	/* Allow MAC frame filtering . */
	// TODO auto-acknowledge
	static void setFrameFilter(boolean val);
	static void setFrameFilterBehaveCoordinator(boolean val);
	static void setFrameFilterAllowBeacon(boolean val);
	//data type is used in the FC_1 0x41
	static void setFrameFilterAllowData(boolean val);
	static void setFrameFilterAllowAcknowledgement(boolean val);
	static void setFrameFilterAllowMAC(boolean val);
	//Reserved is used for the Blink message
	static void setFrameFilterAllowReserved(boolean val);

private:
	// note: not sure if going to be implemented for now
	static void setDoubleBuffering(boolean val);
	// TODO is implemented, but needs testing
	static void useExtendedFrameLength(boolean val);
	// TODO is implemented, but needs testing
	static void waitForResponse(boolean val);

	/* tuning according to mode. */
	static void tune();

	/* device status flags */
	static boolean isReceiveTimestampAvailable();
	static boolean isTransmitDone();
	static boolean isReceiveDone();
	static boolean isReceiveFailed();
	static boolean isReceiveTimeout();
	static boolean isClockProblem();

	/* interrupt state handling */
	static void clearInterrupts();
	static void clearAllStatus();
	static void clearReceiveStatus();
	static void clearReceiveTimestampAvailableStatus();
	static void clearTransmitStatus();

	/* internal helper to read/write system registers. */
	static void readSystemEventStatusRegister();
	static void readSystemConfigurationRegister();
	static void writeSystemConfigurationRegister();
	static void readNetworkIdAndDeviceAddress();
	static void writeNetworkIdAndDeviceAddress();
	static void readSystemEventMaskRegister();
	static void writeSystemEventMaskRegister();
	static void readChannelControlRegister();
	static void writeChannelControlRegister();
	static void readTransmitFrameControlRegister();
	static void writeTransmitFrameControlRegister();

	/* clock management. */
	static void enableClock(byte clock);

	/* LDE micro-code management. */
	static void manageLDE();

	/* timestamp correction. */
	static void correctTimestamp(DW1000Time& timestamp);

	/* reading and writing bytes from and to DW1000 module. */
	static void readBytes(byte cmd, word offset, byte data[], unsigned int n);
	static void readBytesOTP(word address, byte data[]);
	static void writeBytes(byte cmd, word offset, byte data[], unsigned int n);

	/* writing numeric values to bytes. */
	static void writeValueToBytes(byte data[], long val, unsigned int n);

	/* internal helper for bit operations on multi-bytes. */
	static boolean getBit(byte data[], unsigned int n, unsigned int bit);
	static void    setBit(byte data[], unsigned int n, unsigned int bit, boolean val);

	/* Register is 6 bit, 7 = write, 6 = sub-adressing, 5-0 = register value
	 * Total header with sub-adressing can be 15 bit. */
	static const byte WRITE      = 0x80; // regular write
	static const byte WRITE_SUB  = 0xC0; // write with sub address
	static const byte READ       = 0x00; // regular read
	static const byte READ_SUB   = 0x40; // read with sub address
	static const byte RW_SUB_EXT = 0x80; // R/W with sub address extension

	/* clocks available. */
	static const byte AUTO_CLOCK = 0x00;
	static const byte XTI_CLOCK  = 0x01;
	static const byte PLL_CLOCK  = 0x02;

	/* SPI configs. */
	static const SPISettings _fastSPI;
	static const SPISettings _slowSPI;
	static const SPISettings* _currentSPI;

	/* range bias tables (500/900 MHz band, 16/64 MHz PRF), -61 to -95 dBm. */
	static const byte BIAS_500_16_ZERO = 10;
	static const byte BIAS_500_16[];
	static const byte BIAS_500_64_ZERO = 8;
	static const byte BIAS_500_64[];
	static const byte BIAS_900_16_ZERO = 7;
	static const byte BIAS_900_16[];
	static const byte BIAS_900_64_ZERO = 7;
	static const byte BIAS_900_64[];
};

extern DW1000Class DW1000;

#endif


text:
<component name="CopyrightManager">
  <settings default="">
    <module2copyright />
    <LanguageOptions name="JAVA">
      <option name="fileLocation" value="3" />
    </LanguageOptions>
  </settings>
</component>


text:
void AnnounceInActiveBrowser(const std::u16string& message) {
  Browser* const browser = BrowserList::GetInstance()->GetLastActive();
  if (!browser || !browser->is_type_normal() || !browser->window()->IsActive())
    return;

  BrowserView::GetBrowserViewForBrowser(browser)
      ->GetViewAccessibility()
      .AnnounceText(message);
}


text:
Clone a repo

upate and initialised the submodule

    git submodule update --init

Due to how submodule works, command actually tells Git that you want your submodules to each check out the commit already specified in the index of the superproject. So to update the index

    git submodule foreach git pull origin master

If like me, you use a different branch than master, then use this to checkout anouth branch for the submodule.

    git submodule foreach 'git checkout develop && git pull --ff-only origin develop'


text:
"""Interfaces related to streams of values or objects."""

import abc

class Consumer(object):
  """Interface for consumers of finite streams of values or objects."""
  __metaclass__ = abc.ABCMeta

  @abc.abstractmethod
  def consume(self, value):
    """Accepts a value.

    Args:
      value: Any value accepted by this Consumer.
    """
    raise NotImplementedError()

  @abc.abstractmethod
  def terminate(self):
    """Indicates to this Consumer that no more values will be supplied."""
    raise NotImplementedError()

  @abc.abstractmethod
  def consume_and_terminate(self, value):
    """Supplies a value and signals that no more values will be supplied.

    Args:
      value: Any value accepted by this Consumer.
    """
    raise NotImplementedError()


text:
package br.com.erudio.repository.interfaces;

import java.util.List;

import br.com.erudio.dto.PagedSearchDTO;
import br.com.erudio.model.Person;
import br.com.erudio.repository.generic.IGenericRepository;
import br.com.erudio.vo.PersonVO;;

public interface IPersonRepository extends IGenericRepository<Person>{

	List<Person> findAll();
	Person findByName(String name);
	Person findById(Integer id);
	void deleteById(Integer id);
	PagedSearchDTO<PersonVO> pagedSearch(PagedSearchDTO<PersonVO> person);
}


text:
from wtforms import StringField, SubmitField
from wtforms.validators import Required, URL
from flask.ext.wtf import Form
#from wtforms.fields import TextAreaField

class URLForm(Form):
	name = StringField('Enter URL to shorten:', validators=[Required(), URL(message='Invalid URL. Try adding \'http://\'')])
	submit = SubmitField('Submit')


text:
class Reveal < Cask
  url 'http://download.revealapp.com/Reveal.app.zip'
  homepage 'http://revealapp.com/'
  version 'latest'
  sha256 :no_check
  link 'Reveal.app'
end


text:
<?php

?>
<?php

/**
 * TasksGroups
 *
 * This class has been auto-generated by the Doctrine ORM Framework
 *
 * @package    sf_sandbox
 * @subpackage model
 * @author     Your name here
 * @version    SVN: $Id: Builder.php 7490 2010-03-29 19:53:27Z jwage $
 */
class TasksGroups extends BaseTasksGroups
{

}


text:
var fs = require('./OutputWriter');
var file = require('path').join(__dirname, 'Suite4.out');

var test = {

  'test second': function (test) {
    fs.appendFileSync(file, 'test second\n');
  }

}

exports.test = test;


text:
#include "esp_tls_crypto.h"
#include "esp_log.h"
#include "esp_err.h"
static const char *TAG = "esp_crypto";
#ifdef CONFIG_ESP_TLS_USING_MBEDTLS
#include "mbedtls/sha1.h"
#include "mbedtls/base64.h"
#define _esp_crypto_sha1 esp_crypto_sha1_mbedtls
#define _esp_crypto_base64_encode esp_crypto_bas64_encode_mbedtls
#elif  CONFIG_ESP_TLS_USING_WOLFSSL
#include "wolfssl/ssl.h" /* SHA functions are listed in wolfssl/ssl.h */
#include "wolfssl/wolfcrypt/coding.h"
#define _esp_crypto_sha1 esp_crypto_sha1_wolfSSL
#define _esp_crypto_base64_encode esp_crypto_base64_encode_woflSSL
#endif

#ifdef CONFIG_ESP_TLS_USING_MBEDTLS
static int esp_crypto_sha1_mbedtls( const unsigned char *input,
                                    size_t ilen,
                                    unsigned char output[20])
{
    int ret = mbedtls_sha1(input, ilen, output);
    if (ret != 0) {
        ESP_LOGE(TAG, "Error in calculating sha1 sum , Returned 0x%02X", ret);
    }
    return ret;
}

static int esp_crypto_bas64_encode_mbedtls( unsigned char *dst, size_t dlen,
        size_t *olen, const unsigned char *src,
        size_t slen)
{
    return mbedtls_base64_encode(dst, dlen, olen, src, slen);
}

#elif CONFIG_ESP_TLS_USING_WOLFSSL
static int esp_crypto_sha1_wolfSSL( const unsigned char *input,
                                    size_t ilen,
                                    unsigned char output[20])
{
    unsigned char *ret = wolfSSL_SHA1(input, ilen, output);
    if (ret == NULL) {
        ESP_LOGE(TAG, "Error in calculating sha1 sum");
        return -1;
    }
    return 0;
}

static int esp_crypto_base64_encode_woflSSL(unsigned char *dst, size_t dlen, size_t *olen,
        const unsigned char *src, size_t slen)
{
    *olen = dlen;
    return Base64_Encode_NoNl((const byte *) src, (word32) slen, (byte *) dst, (word32 *) olen);
}

#else
#error "No TLS/SSL Stack selected"
#endif

int esp_crypto_sha1( const unsigned char *input,
                     size_t ilen,
                     unsigned char output[20])
{
    return _esp_crypto_sha1(input, ilen, output);
}

int esp_crypto_base64_encode(unsigned char *dst, size_t dlen, size_t *olen,
                             const unsigned char *src, size_t slen )
{
    return _esp_crypto_base64_encode(dst, dlen, olen, src, slen);
}


text:
@implementation FYStorage
single_implementation(FYStorage)
+ (void)initialize
{
    [self creatCacheSubFolder:@"imagesCaches"];
    [self creatCacheSubFolder:@"dataCaches"];
}

+ (NSString *)cacheDirectory
{
    return FYCache;
}
+ (NSString *)documentDirectory
{
    return FYDocument;
}
+ (NSString *)libraryDirectory
{
    return FYLibrary;
}
+ (NSString *)homeDirectory
{
    return FYHome;
}
+ (NSString *)temporaryDirectory
{
    return FYTemporary;
}

+ (NSString *)imageCachesFolder
{
    return [FYCache stringByAppendingPathComponent:@"imageCaches"];
}
+ (NSString *)dataCachesFolder
{
    return [FYCache stringByAppendingPathComponent:@"dataCaches"];
}

+ (NSString *)creatCacheSubFolder:(NSString *)folder
{
    return [self creatFolder:folder path:FYCache];
}

+ (NSString *)creatDocumentSubFolder:(NSString *)folder
{
    return [self creatFolder:folder path:FYDocument];
}
+ (NSString *)creatFolder:(NSString *)folder path:(NSString *)path
{
    //1. 初始化NSFileManager
    NSFileManager *fileManager = [[NSFileManager alloc] init];

    //2. 拼接新目录字符串path/folder
    NSString *newFolder = nil;
    if ([fileManager fileExistsAtPath:path]) {
        newFolder = [path stringByAppendingPathComponent:folder];
    }else {
        NSLog(@"路径path不存在,转存到Caches目录");
        newFolder = [FYCache  stringByAppendingPathComponent:path];
    }
    return newFolder;
}

//字典可加入 rememberPassword:(BOOL)rememberPassword autoLogin:(BOOL)autoLogin两个字段
+ (void)saveLoginListWithUsername:(NSString *)username password:(NSString *)password
{
    NSMutableArray *mutArr = [[NSUserDefaults standardUserDefaults] objectForKey:kLoginInfo];
    if (mutArr == nil) {
        mutArr = [NSMutableArray arrayWithObject:@{@"username" : username, @"password" : password}];
    }else {
        for (NSDictionary *dic in mutArr) {
            //已存在,则更新密码
            if ([[dic objectForKey:@"username"] isEqualToString:username]) {
                [dic setValue:password forKey:@"usernaem"];
                [[NSUserDefaults standardUserDefaults] setObject:mutArr forKey:kLoginInfo];
                [[NSUserDefaults standardUserDefaults] synchronize];
                return;
            }
        }
        [mutArr insertObject:@{username : password} atIndex:0];
        [[NSUserDefaults standardUserDefaults] setObject:mutArr forKey:kLoginInfo];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
}

+ (NSArray *)readLoginList
{
    return [[NSUserDefaults standardUserDefaults] objectForKey:kLoginInfo];
}

+ (BOOL)isNewVersion
{
    NSString *key = (NSString *)kCFBundleVersionKey;
    NSString *version = [NSBundle mainBundle].infoDictionary[key];
    NSString *savedVersion = [[NSUserDefaults standardUserDefaults] objectForKey:key];
    if ([version isEqualToString:savedVersion]) {
        return NO;
    } else {
        [[NSUserDefaults standardUserDefaults] setObject:version forKey:key];
        [[NSUserDefaults standardUserDefaults] synchronize];
        return YES;
    }
}

@end


text:
package com.yahoo.sketches.tuple;

/**
 * Iterator over a generic tuple sketch
 * @param <S> Type of Summary
 */
public class SketchIterator<S extends Summary> {

  private long[] keys_;
  private S[] summaries_;
  private int i_;

  SketchIterator(final long[] keys, final S[] summaries) {
    keys_ = keys;
    summaries_ =  summaries;
    i_ = -1;
  }

  /**
   * Advancing the iterator and checking existence of the next entry
   * is combined here for efficiency. This results in an undefined
   * state of the iterator before the first call of this method.
   * @return true if the next element exists
   */
  public boolean next() {
    if (keys_ == null) { return false; }
    i_++;
    while (i_ < keys_.length) {
      if (keys_[i_] != 0) { return true; }
      i_++;
    }
    return false;
  }

  /**
   * Gets a key from the current entry in the sketch, which is a hash
   * of the original key passed to update(). The original keys are not
   * retained. Don't call this before calling next() for the first time
   * or after getting false from next().
   * @return hash key from the current entry
   */
  public long getKey() {
    return keys_[i_];
  }

  /**
   * Gets a Summary object from the current entry in the sketch.
   * Don't call this before calling next() for the first time
   * or after getting false from next().
   * @return Summary object for the current entry (this is not a copy!)
   */
  public S getSummary() {
    return summaries_[i_];
  }

}


text:
#import "NSObject-Protocol.h"

@protocol UIKeyboardCandidateBarDelegate <NSObject>

@optional
- (void)candidateBarDidScroll:(id)arg1;
@end


text:
local runner = require('user_modules/script_runner')
local common = require('test_scripts/TheSameApp/commonTheSameApp')

--[[ Test Configuration ]]
runner.testSettings.isSelfIncluded = false

--[[ Local Data ]]
local devices = {
  [1] = { host = "1.0.0.1",         port = config.mobilePort },
  [2] = { host = "192.168.100.199", port = config.mobilePort }
}

local appParams = {
	[1] = { appName = "Test Application", appID = "0001",  fullAppID = "0000001" },
	[2] = { appName = "Test Application", appID = "00022", fullAppID = "00000022" }
}

local TestGroup_1 = { rpcs = { AddCommand = { hmi_levels = { "BACKGROUND", "FULL", "LIMITED", "NONE" } } } }
local TestGroup_2 = { rpcs = { AddSubMenu = { hmi_levels = { "BACKGROUND", "FULL", "LIMITED", "NONE" } } } }

local addCommandParams    = { cmdID  = 222, menuParams = { menuName = "Play" } }
local addSubMenuParams    = { menuID = 777, menuName = "Create" }
local reqAddSubmenuParams = { menuID = 888, menuParams = { menuName = "Build" } }

--[[ Local Functions ]]
local function modificationOfPreloadedPT(pPolicyTable)
  common.createNewGroup(appParams[1].fullAppID, "TestGroup_1", TestGroup_1, pPolicyTable)
  common.createNewGroup(appParams[2].fullAppID, "TestGroup_2", TestGroup_2, pPolicyTable)
end

--[[ Scenario ]]
runner.Title("Preconditions")
runner.Step("Clean environment", common.preconditions)
runner.Step("Prepare preloaded PT", common.modifyPreloadedPt, {modificationOfPreloadedPT})
runner.Step("Start SDL and HMI", common.start)
runner.Step("Connect two mobile devices to SDL", common.connectMobDevices, {devices})
runner.Step("Register App1 from device 1", common.registerAppEx, {1, appParams[1], 1})
runner.Step("Register App2 from device 2", common.registerAppEx, {2, appParams[2], 2})

runner.Title("Test")
runner.Step("App1 sends 'AddCommand' RPC from Mobile 1, SUCCESS",    common.sendRPCPositive,
              { 1, "UI.", "AddCommand", addCommandParams })
runner.Step("App2 sends 'AddCommand' RPC from Mobile 2, DISALLOWED", common.sendRPCNegative,
              { 2, "AddCommand", addCommandParams })
runner.Step("App1 sends 'AddSubMenu' RPC from Mobile 1, DISALLOWED", common.sendRPCNegative,
              { 1, "AddSubMenu", addSubMenuParams })
runner.Step("App2 sends 'AddSubMenu' RPC from Mobile 2, SUCCESS",    common.sendRPCPositive,
              { 2, "UI.", "AddSubMenu", addSubMenuParams, reqAddSubmenuParams })

runner.Title("Postconditions")
runner.Step("Remove mobile devices", common.clearMobDevices, {devices})
runner.Step("Stop SDL", common.postconditions)


text:
"""
Tests for the resurrected Py2-like cmp function
"""

from __future__ import absolute_import, unicode_literals, print_function

import os.path
import sys
import traceback
from contextlib import contextmanager

from future.tests.base import unittest
from future.utils import PY3, PY26

if PY3:
    from past.builtins import cmp

_dir = os.path.dirname(os.path.abspath(__file__))
sys.path.append(_dir)
import test_values

@contextmanager
def empty_context_manager(*args, **kwargs):
    yield dict(args=args, kwargs=kwargs)

class TestCmp(unittest.TestCase):
    def test_cmp(self):
        for x, y, cmp_python2_value in test_values.cmp_python2_value:
            if PY26:
                # set cmp works a bit differently in 2.6, we try to emulate 2.7 behavior, so skip set cmp tests
                if isinstance(x, set) or isinstance(y, set):
                    continue
            # to get this to run on python <3.4 which lacks subTest
            with getattr(self, 'subTest', empty_context_manager)(x=x, y=y):
                try:
                    past_cmp_value = cmp(x, y)
                except Exception:
                    past_cmp_value = traceback.format_exc().strip().split('\n')[-1]

                self.assertEqual(cmp_python2_value, past_cmp_value,
                                 "expected result matching python2 __builtins__.cmp({x!r},{y!r}) "
                                 "== {cmp_python2_value} "
                                 "got past.builtins.cmp({x!r},{y!r}) "
                                 "== {past_cmp_value} "
                                 "".format(x=x, y=y, past_cmp_value=past_cmp_value,
                                           cmp_python2_value=cmp_python2_value))

if __name__ == '__main__':
    unittest.main()