text:
============
django-filer
============

A file management application for django that makes handling of files and images a breeze.

Documentation: http://django-filer.readthedocs.org/en/latest/index.html

Wiki: https://github.com/stefanfoulis/django-filer/wiki

Dependencies
------------

* `Django`_ 1.2 with django-staticfiles or `Django`_ 1.3
* django-mptt >= 0.2.1
* `easy_thumbnails`_ >= 1.0-alpha-17
* `django-polymorphic`_ >= 0.2
* `PIL`_ 1.1.7 (with JPEG and ZLIB support)

Installation
------------

To get started using ``django-filer`` simply install it with
``pip``::

    $ pip install django-filer

Add ``"filer"`` to your project's ``INSTALLED_APPS`` setting and run ``syncdb``
(or ``migrate`` if you're using South).

Configuration
-------------

django-filer supports permissions on files. They can be enabled or disabled.
Files with disabled permissions are your regular world readable files in
``MEDIA_ROOT``. Files with permissions are a other case however. To be able to
check permissions on the file downloads a special view is used and they are
saved in a separate location (in a directory called `smedia` next to
``MEDIA_ROOT`` by default).

``filer.server.urls`` needs to be included in the root ``urls.py``::

    urlpatterns += patterns('',
        url(r'^', include('filer.server.urls')),
    )

By default files with permissions are served directly by django. That is
acceptable in a development environment, but very bad for performance in
production. See the docs on how to serve files more efficiently.

For automatic subject location aware cropping of images replace
``easy_thumbnails.processors.scale_and_crop`` with
``filer.thumbnail_processors.scale_and_crop_with_subject_location`` in the
``THUMBNAIL_PROCESSORS`` setting::

    THUMBNAIL_PROCESSORS = (
        'easy_thumbnails.processors.colorspace',
        'easy_thumbnails.processors.autocrop',
        #'easy_thumbnails.processors.scale_and_crop',
        'filer.thumbnail_processors.scale_and_crop_with_subject_location',
        'easy_thumbnails.processors.filters',
    )

.. _Django: http://djangoproject.com
.. _django-polymorphic: https://github.com/bconstantin/django_polymorphic
.. _easy_thumbnails: https://github.com/SmileyChris/easy-thumbnails
.. _sorl.thumbnail: http://thumbnail.sorl.net/
.. _PIL: http://www.pythonware.com/products/pil/
.. _Pillow: http://pypi.python.org/pypi/Pillow/


text:
package com.joestelmach.natty;

import com.joestelmach.natty.generated.DateLexer;
import com.joestelmach.natty.generated.DateParser;
import com.joestelmach.natty.generated.DateWalker;
import com.joestelmach.natty.generated.TreeRewrite;
import org.antlr.runtime.*;
import org.antlr.runtime.tree.CommonTree;
import org.antlr.runtime.tree.CommonTreeNodeStream;
import org.antlr.runtime.tree.Tree;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.*;

/**
 *
 * @author Joe Stelmach
 */
public class Parser {
  private TimeZone _defaultTimeZone;

  private static final Logger _logger = LoggerFactory.getLogger(Parser.class);

  /**
   * Tokens that should be removed from the end any list of tokens before parsing. These are
   * valid tokens, but could never add any meaningful parsing information when located at the
   * end of a token stream.
   */
  private static final Set<Integer> IGNORED_TRAILING_TOKENS =
      new HashSet<Integer>(Arrays.asList(new Integer[] {
          DateLexer.DOT,
          DateLexer.COLON,
          DateLexer.COMMA,
          DateLexer.DASH,
          DateLexer.SLASH,
          DateLexer.DOT,
          DateLexer.PLUS,
          DateLexer.SINGLE_QUOTE
      }));

  /**
   * Creates a new parser using the given time zone as the default
   * @param defaultTimeZone
   */
  public Parser(TimeZone defaultTimeZone) {
    _defaultTimeZone = defaultTimeZone;
  }

  /**
   * Creates a new parser with no explicit default time zone (default will be US/Eastern)
   */
  public Parser() {
    _defaultTimeZone = TimeZone.getDefault();
  }

  /**
   * Parses the given input value for one or more groups of
   * date alternatives
   *
   * @param value
   * @return
   */
  public List<DateGroup> parse(String value) {

    // lex the input value to obtain our global token stream
    ANTLRInputStream input = null;
    try {
      input = new ANTLRNoCaseInputStream(new ByteArrayInputStream(value.getBytes()));

    } catch (IOException e) {
      _logger.error("could not lex input", e);
    }
    DateLexer lexer = new DateLexer(input);

    // collect all sub-token streams that may include date information
    List<TokenStream> streams = collectTokenStreams(new CommonTokenStream(lexer));

    // and parse each of them
    List<DateGroup> groups = new ArrayList<DateGroup>();
    TokenStream lastStream = null;
    for(TokenStream stream:streams) {
      lastStream = stream;
      List<Token> tokens = ((NattyTokenSource) stream.getTokenSource()).getTokens();
      DateGroup group = singleParse(stream, value);
      while((group == null || group.getDates().size() == 0) && tokens.size() > 0) {
        if(group == null || group.getDates().size() == 0) {

          // we have two options:
          // 1. Continuously remove tokens from the end of the stream and re-parse.  This will
          //    recover from the case of an extraneous token at the end of the token stream.
          //    For example: 'june 20th on'
          List<Token> endRemovedTokens = new ArrayList<Token>(tokens);
          while((group == null || group.getDates().isEmpty()) && !endRemovedTokens.isEmpty()) {
            endRemovedTokens = endRemovedTokens.subList(0, endRemovedTokens.size() - 1);
            TokenStream newStream = new CommonTokenStream(new NattyTokenSource(endRemovedTokens));
            group = singleParse(newStream, value);
            lastStream = newStream;
          }

          // 2. Continuously look for another possible starting point in the token
          //    stream and re-parse.
          while((group == null || group.getDates().isEmpty()) && tokens.size() >= 1) {
            tokens = tokens.subList(1, tokens.size());
            Iterator<Token> iter = tokens.iterator();
            while(iter.hasNext()) {
              Token token = iter.next();
              if(!DateParser.FOLLOW_empty_in_parse186.member(token.getType())) {
                iter.remove();
              }
              else {
                break;
              }
            }
            TokenStream newStream = new CommonTokenStream(new NattyTokenSource(tokens));
            group = singleParse(newStream, value);
            lastStream = newStream;
          }
        }
      }

      // If a group with at least one date was found, we'll most likely want to add it to our list,
      // but not if multiple streams were found and the group contains only numeric time information.
      // For example: A full text string of '1' should parse to 1 o'clock, but 'I need 1 hard drive'
      // should result in no groups found.
      if(group != null && !group.getDates().isEmpty() &&
          (streams.size() == 1 || !group.isDateInferred() || !isAllNumeric(lastStream))) {

        // Additionally, we'll only accept this group if the associated text does not have an
        // alphabetic character to the immediate left or right, which would indicate a portion
        // of a word was tokenized. For example, 'nightingale' will result in a 'NIGHT' token,
        // but there's clearly no datetime information there.
        group.setFullText(value);
        String prefix = group.getPrefix(1);
        String suffix = group.getSuffix(1);
        if((prefix.isEmpty() || !Character.isLetter(prefix.charAt(0))) &&
           (suffix.isEmpty() || !Character.isLetter(suffix.charAt(0)))) {

          groups.add(group);
        }
      }
    }
    return groups;
  }

  /**
   * Determines if a token stream contains only numeric tokens
   * @param stream
   * @return true if all tokens in the given stream can be parsed as an integer
   */
  private boolean isAllNumeric(TokenStream stream) {
    List<Token> tokens = ((NattyTokenSource) stream.getTokenSource()).getTokens();
    for(Token token:tokens) {
      try {
        Integer.parseInt(token.getText());
      } catch(NumberFormatException e) {
        return false;
      }
    }
    return true;
  }

  /**
   * Parses the token stream for a SINGLE date time alternative.  This
   * method assumes that the entire token stream represents date and or
   * time information (no extraneous tokens)
   *
   * @param stream
   * @return
   */
  private DateGroup singleParse(TokenStream stream, String fullText) {
	DateGroup group = null;
	List<Token> tokens = ((NattyTokenSource) stream.getTokenSource()).getTokens();
	if(tokens.isEmpty()) return group;

    StringBuilder tokenString = new StringBuilder();
    for(Token token:tokens) {
      tokenString.append(DateParser.tokenNames[token.getType()]);
      tokenString.append(" ");
    }

    try {
      // parse
      ParseListener listener = new ParseListener();
      DateParser parser = new DateParser(stream, listener);
      DateParser.parse_return parseReturn = parser.parse();

      Tree tree = (Tree) parseReturn.getTree();

      // we only continue if a meaningful syntax tree has been built
      if(tree.getChildCount() > 0) {
        _logger.info("PARSE: " + tokenString.toString());

        // rewrite the tree (temporary fix for http://www.antlr.org/jira/browse/ANTLR-427)
        CommonTreeNodeStream nodes = new CommonTreeNodeStream(tree);
        TreeRewrite s = new TreeRewrite(nodes);
        tree = (CommonTree)s.downup(tree);

        // and walk it
        nodes = new CommonTreeNodeStream(tree);
        nodes.setTokenStream(stream);
        DateWalker walker = new DateWalker(nodes);
        walker.getState().setDefaultTimeZone(_defaultTimeZone);
        walker.parse();
        _logger.info("AST: " + tree.toStringTree());

        // run through the results and append the parse information
        group = walker.getState().getDateGroup();
        ParseLocation location = listener.getDateGroupLocation();
        group.setLine(location.getLine());
        group.setText(location.getText());
        group.setPosition(location.getStart());
        group.setSyntaxTree(tree);
        group.setParseLocations(listener.getLocations());
        group.setFullText(fullText);

        // if the group's matching text has an immediate alphabetic prefix or suffix,
        // we ignore this result
        String prefix = group.getPrefix(1);
        String suffix = group.getSuffix(1);
        if((!prefix.isEmpty() && Character.isLetter(prefix.charAt(0))) ||
            (!suffix.isEmpty() && Character.isLetter(suffix.charAt(0)))) {

          group = null;
        }

      }

    } catch(RecognitionException e) {
      _logger.debug("Could not parse input", e);
    }

    return group;
  }

  /**
   * Scans the given token global token stream for a list of sub-token
   * streams representing those portions of the global stream that
   * may contain date time information
   *
   * @param stream
   * @return
   */
  private List<TokenStream> collectTokenStreams(TokenStream stream) {

    // walk through the token stream and build a collection
    // of sub token streams that represent possible date locations
    List<Token> currentGroup = null;
    List<List<Token>> groups = new ArrayList<List<Token>>();
    Token currentToken;
    int currentTokenType;
    StringBuilder tokenString = new StringBuilder();
    while((currentToken = stream.getTokenSource().nextToken()).getType() != DateLexer.EOF) {
      currentTokenType = currentToken.getType();
      tokenString.append(DateParser.tokenNames[currentTokenType]).append(" ");

      // we're currently NOT collecting for a possible date group
      if(currentGroup == null) {
        // skip over white space and known tokens that cannot be the start of a date
        if(currentTokenType != DateLexer.WHITE_SPACE &&
            DateParser.FOLLOW_empty_in_parse186.member(currentTokenType)) {

          currentGroup = new ArrayList<Token>();
          currentGroup.add(currentToken);
        }
      }

      // we're currently collecting
      else {
        // preserve white space
        if(currentTokenType == DateLexer.WHITE_SPACE) {
          currentGroup.add(currentToken);
        }

        else {
          // if this is an unknown token, we'll close out the current group
          if(currentTokenType == DateLexer.UNKNOWN) {
            addGroup(currentGroup, groups);
            currentGroup = null;
          }
          // otherwise, the token is known and we're currently collecting for
          // a group, so we'll add it to the current group
          else {
            currentGroup.add(currentToken);
          }
        }
      }
    }

    if(currentGroup != null) {
      addGroup(currentGroup, groups);
    }

    _logger.info("STREAM: " + tokenString.toString());
    List<TokenStream> streams = new ArrayList<TokenStream>();
    for(List<Token> group:groups) {
      if(!group.isEmpty()) {
        StringBuilder builder = new StringBuilder();
        builder.append("GROUP: ");
        for (Token token : group) {
          builder.append(DateParser.tokenNames[token.getType()]).append(" ");
        }
        _logger.info(builder.toString());

        streams.add(new CommonTokenStream(new NattyTokenSource(group)));
      }
    }

    return streams;
  }

  /**
   * Cleans up the given group and adds it to the list of groups if still valid
   * @param group
   * @param groups
   */
  private void addGroup(List<Token> group, List<List<Token>> groups) {

    if(group.isEmpty()) return;

    // remove trailing tokens that should be ignored
    while(!group.isEmpty() && IGNORED_TRAILING_TOKENS.contains(
        group.get(group.size() - 1).getType())) {
      group.remove(group.size() - 1);
    }

    // if the group still has some tokens left, we'll add it to our list of groups
    if(!group.isEmpty()) {
      groups.add(group);
    }
  }
}

redpajama_set_name: RedPajamaGithub


text:
package websocket.chat;

import java.io.IOException;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.atomic.AtomicInteger;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

import org.jboss.logging.Logger;

import util.HTMLFilter;

@ServerEndpoint(value = "/websocket/chat")
public class ChatAnnotation {

    private static final Logger log = Logger.getLogger(ChatAnnotation.class);

    private static final String GUEST_PREFIX = "Guest";
    private static final AtomicInteger connectionIds = new AtomicInteger(0);
    private static final Set<ChatAnnotation> connections =
            new CopyOnWriteArraySet<ChatAnnotation>();

    private final String nickname;
    private Session session;

    public ChatAnnotation() {
        nickname = GUEST_PREFIX + connectionIds.getAndIncrement();
    }

    @OnOpen
    public void start(Session session) {
        this.session = session;
        connections.add(this);
        String message = String.format("* %s %s", nickname, "has joined.");
        broadcast(message);
    }

    @OnClose
    public void end() {
        connections.remove(this);
        String message = String.format("* %s %s",
                nickname, "has disconnected.");
        broadcast(message);
    }

    @OnMessage
    public void incoming(String message) {
        // Never trust the client
        String filteredMessage = String.format("%s: %s",
                nickname, HTMLFilter.filter(message.toString()));
        broadcast(filteredMessage);
    }

    @OnError
    public void onError(Throwable t) throws Throwable {
        log.error("Chat Error: " + t.toString(), t);
    }

    private static void broadcast(String msg) {
        for (ChatAnnotation client : connections) {
            try {
                synchronized (client) {
                    client.session.getBasicRemote().sendText(msg);
                }
            } catch (IOException e) {
                log.debug("Chat Error: Failed to send message to client", e);
                connections.remove(client);
                try {
                    client.session.close();
                } catch (IOException e1) {
                    // Ignore
                }
                String message = String.format("* %s %s",
                        client.nickname, "has been disconnected.");
                broadcast(message);
            }
        }
    }
}


text:
var async = require('../lib');
var expect = require('chai').expect;

describe('queue', function(){
    context('q.unsaturated(): ',function() {
        it('should have a default buffer property that equals 25% of the concurrenct rate', function(done){
            var calls = [];
            var q = async.queue(function(task, cb) {
                // nop
                calls.push('process ' + task);
                async.setImmediate(cb);
            }, 10);
            expect(q.buffer).to.equal(2.5);
            done();
        });
        it('should allow a user to change the buffer property', function(done){
            var calls = [];
            var q = async.queue(function(task, cb) {
                // nop
                calls.push('process ' + task);
                async.setImmediate(cb);
            }, 10);
            q.buffer = 4;
            expect(q.buffer).to.not.equal(2.5);
            expect(q.buffer).to.equal(4);
            done();
        });
        it('should call the unsaturated callback if tasks length is less than concurrency minus buffer', function(done){
            var calls = [];
            var q = async.queue(function(task, cb) {
                calls.push('process ' + task);
                async.setImmediate(cb);
            }, 10);
            q.unsaturated = function() {
                calls.push('unsaturated');
            };
            q.empty = function() {
                expect(calls.indexOf('unsaturated')).to.be.above(-1);
                setTimeout(function() {
                    expect(calls).eql([
                        'unsaturated',
                        'unsaturated',
                        'unsaturated',
                        'unsaturated',
                        'unsaturated',
                        'process foo0',
                        'process foo1',
                        'process foo2',
                        'process foo3',
                        'process foo4',
                        'foo0 cb',
                        'foo1 cb',
                        'foo2 cb',
                        'foo3 cb',
                        'foo4 cb'
                    ]);
                    done();
                }, 50);
            };
            q.push('foo0', function () {calls.push('foo0 cb');});
            q.push('foo1', function () {calls.push('foo1 cb');});
            q.push('foo2', function () {calls.push('foo2 cb');});
            q.push('foo3', function () {calls.push('foo3 cb');});
            q.push('foo4', function () {calls.push('foo4 cb');});
        });
    });
});


text:
<?php
declare(strict_types=1);

namespace Spires\Plugins\ChannelOperations\Inbound;

use Spires\Plugins\SystemMessage\Inbound\SystemMessage;

class PartSystemMessage extends SystemMessage
{
    public function targets() : array
    {
        list($targets,) = explode(' ', $this->params(), 2);

        return explode(',', $targets);
    }

    public function text()
    {
        list(,$text) = explode(' ', $this->params(), 2);

        return ltrim($text, ':');
    }
}


text:
@interface MscHTTPSURLConnectionError : NSError

+(id)errorWithCode:(NSInteger)code;

@end


text:
package example.service;

import example.repo.Customer727Repository;

import org.springframework.stereotype.Service;

@Service
public class Customer727Service {
	public Customer727Service(Customer727Repository repo) {}
}


text:
package org.neo4j.driver.net;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;

import org.junit.jupiter.api.Test;

class ServerAddressTest {
    @Test
    void shouldCreateAddress() {
        ServerAddress address = ServerAddress.of("my.database.com", 8897);
        assertEquals("my.database.com", address.host());
        assertEquals(8897, address.port());
    }

    @Test
    void shouldFailToCreateAddressWithInvalidHost() {
        assertThrows(NullPointerException.class, () -> ServerAddress.of(null, 9999));
    }

    @Test
    void shouldFailToCreateAddressWithInvalidPort() {
        assertThrows(IllegalArgumentException.class, () -> ServerAddress.of("hello.graphs.com", -42));
        assertThrows(IllegalArgumentException.class, () -> ServerAddress.of("hello.graphs.com", 66_000));
    }
}


text:
import datetime
import readTable
import math
from xml.dom.minidom import parseString
from django.conf import settings

# Global variables
ISO_8601_DATETIME = '%Y-%m-%d'

#=#=#=#=#=#=#=#=#=#=#=#=##=#=#=#=#=#=#=#=#=#=#=#=##=#=#=#=#=#=#=#=#=#=#=#=#
"""
File: adherenceTests.py

    Written by: William J. Bosl
    Children's Hospital Boston Informatics Program
    300 Longwood Avenue
    Boston, MA 02115

    Description: This class has functions that take a list of prescription fulfillment
    dates and does several check for medication adherence. Current tests include
		- a gap check for medication possession gaps larger than 30 days;
		- Actual Medication Possession Ratio (MPR) < 0.80
		- Predicted 1-year MPR<0.80 when less than 1 year has passed since first fill
	Other tests may be added to this list.
    The primary loop for each med has to step through time, by day, to compute the mpr at each day.
    It also keeps track of how many pills are left, how long since the first fill, and the size
    of the largest gap in adherence. Gaps are determined by noting how many days have passed and
    subtracting the number of pills that have been received. We can only assume that if a patient
    has the pills that he or she is actually taking them.

    While stepping through the days for each pill, other tests can be implemented. At this time,
    a logistic regression test is done for certain drug classes. The list of drugs for which
    predictions of adherence can be made are contained in the file settings.DRUGCLASSFILE. If a
    drug is in the list, and mpr values are available at any of 60, 90, or 120 days, a logistic
    regression model is used to make a prediction. Coefficients for the model are contained in
    the external file: settings.LOGREGFILE.

    A brief template function is included at the end that may be used to add future tests. As
    noted, if the new test adds a new outcome option, assigned to the 'flag' variable, that
    options must also be added to index.html and risk.html so that the proper display is
    available.

    Currently, the 'flag' variable takes one of the following options, whose meaning is self-evident:
	 flag = "Good" (One can simply assume the mpr is above the set threshold, no gaps, no other tests failed.)
	 flag = "Poor_gaps"
	 flag = "Poor_lowMPR"
	 flag = "Good_predictedMPR"
	 flag = "Warning_predictedMPR"
	 flag = "Warning_lowMPR"

    The flag values are supposed to give some idea of the adherence level (good, poor) and the
    reason for the value (large gaps, good or poor logistic prediction, currently low MPR if
    no prediction is available.

    Note that the defined threshold for "good" or "poor" adherence based on mpr is contained in
    the variable settings.GOOD_MPR_THRESHOLD and may be changed if required. Other levels, such
    as "good", "acceptable", "poor", for example, may be implemented, with corresponding flags below
    and display entries in index.html and risk.html.

    The threshold for gaps that are considered "poor" adherence is contained in settings.GAP_THRESHOLD
"""
#=#=#=#=#=#=#=#=#=#=#=#=##=#=#=#=#=#=#=#=#=#=#=#=##=#=#=#=#=#=#=#=#=#=#=#=#
class AdherenceTests():

    #=====================================================
    # Initialization of class variables. The primary
    # task here is to read the drug class data, once.
    #=====================================================
    def __init__(self):
		#---------------------------------------------
		# Class variables
		#---------------------------------------------
        self.GOOD_MPR_THRESHOLD = settings.GOOD_MPR_THRESHOLD
        self.GAP_THRESHOLD = settings.GAP_THRESHOLD

		#---------------------------------------------
        # Get the data table from the given regression file
		#---------------------------------------------
        logistic_data_file = settings.LOGREGFILE
        try:
            reader = readTable.ReadTable(logistic_data_file)
        except:
            print "Can't open file ", logistic_data_file
            return
        self.data = reader.read()

		#---------------------------------------------
		# Open and read the file containing drug class information
		#---------------------------------------------
        try:
            drugclassfilename = settings.DRUGCLASSFILE
            file = open(drugclassfilename, 'r')
            allLines = file.readlines()
            file.close()
        except:
            print "Can't open file ", drugclassfilename
            return

		#---------------------------------------------
		# Iterate through the rows, reading lines containing drugname, class
		#---------------------------------------------
        self.drugclasses = {}
        for i in range(len(allLines)):
            row = allLines[i].split(',')
            self.drugclasses[row[0]] = row[1]

    #============================================================================================
	# This function will administer all the adherence tests. It will do this for each medication
	# that the patient is prescribed, as contained in the list patient_refill_data.
    #============================================================================================
    def allTests(self, patient_refill_data, drug, birthday):

        # Local variables
        model_prediction_days = [60,90,120]
        max_gap = {}
        threshold = self.GAP_THRESHOLD     # default gap threshold
        refill_data = {}

		# Returned variables
        gap_flag = []
        mpr_tseries = {}
        refill_day = {}
        gaps = {}

		#---------------------------------------------
        # Go through the list of refill data for each
		# drug and determine which have gaps
		#---------------------------------------------
        for data in patient_refill_data:
            name = data[1]
            if drug=='all' or drug==name:
                quant = int(data[2])
                when = data[3]
                d = datetime.datetime.strptime(str(when), ISO_8601_DATETIME)
                age_on_first_fill = {}

                # Organize all refill dates by drug name
                max_gap[name] = 0.0
                if not refill_data.has_key(name):
                    refill_data[name] = {}
                    mpr_tseries[name] = []
                    gaps[name] = []
                    refill_day[name] = []
                refill_data[name][d] = quant

		#---------------------------------------------
        # Check for gaps and predict adherence
		#---------------------------------------------
        for name in sorted(refill_data.keys()):
            dates = refill_data[name].keys()
            npills = refill_data[name].values()
            pMPR_yesno = -1 # default value: no prediction made
            drug_class = "other"  # default

			#- - - - - - - - - - - - - - - - - - - - -
            # Sort dates and npills list
			# together / simultaneously
			#- - - - - - - - - - - - - - - - - - - - -
            dates, npills = zip(*sorted(zip(dates, npills)))
            nDates = len(dates)
            date0 = dates[0]
            first = date0       # This will change; it's the fill date or the day on which the
            last = date0        # next batch of pills will start to be used.

			#- - - - - - - - - - - - - - - - - - - - -
            # Determine the total length of time, in days, pills have been taken,
            # including gaps (that is, from first day through the day when the
            # last pill from the last prescription fill was taken.
			#- - - - - - - - - - - - - - - - - - - - -
            nDays = 0
            for i in range(1,nDates):
                s1 = (dates[i] - dates[i-1]).days
                s2 = npills[i-1]
                if s1>s2: nDays = nDays + s1
                else: nDays = nDays + s2
            nDays = nDays + npills[nDates-1]

			#- - - - - - - - - - - - - - - - - - - - -
			# If the drug name is in the list of classes
			# that we used in the log regression model, and
			# if the total pills for all refills is less
			# than 1 year, make an adherence prediction
			# based on the regression model.
			#- - - - - - - - - - - - - - - - - - - - -
            make_prediction = False
            shortname = name.split()[0].lower()
            if shortname in self.drugclasses.keys():
                drug_class = self.drugclasses[shortname]
                if nDays < 360: make_prediction = True

			#- - - - - - - - - - - - - - - - - - - - -
            # Determine the patient's age on the
			# date of first fill for this med
			#- - - - - - - - - - - - - - - - - - - - -
            bd = datetime.datetime.strptime(str(birthday), ISO_8601_DATETIME)
            age_on_first_fill[name] = date0 - bd
            age = age_on_first_fill[name].days/365          # Age in years on first fill date

            mpr = 1.0
            latest_mpr = 1.0
            day = 0     # Initial fill
            pills_available = npills[0]
            total_pills_taken = 0
            days_since_initial_fill = 0
            next_refill_index = 1
            next_refill_day = 0
            if nDates > 1:
				next_refill_day = (dates[1] - date0).days
            mpr_tseries[name].append( [0, mpr] )
            refill_day[name].append([0,1.0])

			#- - - - - - - - - - - - - - - - - - - - -
			# Step through each day, compute MPR and
			# find gaps.
			#- - - - - - - - - - - - - - - - - - - - -
            for day in range(1, nDays+1):

                # Is it time for a refill? Check to see if prescription was filled
                if day == next_refill_day and next_refill_day < nDays:
                    refill_day[name].append([day,mpr])
                    pills_available += npills[next_refill_index]
                    next_refill_index += 1
                    if nDates > next_refill_index:
                        next_refill_day = (dates[next_refill_index] - date0).days

                # Does the patient still have pills left? If so, increment
                if pills_available > 0:
                    pills_available -= 1
                    total_pills_taken += 1

                # Time marches on whether or not patient has pills
                days_since_initial_fill += 1

                # Compute the current mpr
                mpr = 1.0*total_pills_taken / days_since_initial_fill

				# If this is the last refill, check to see if we need
				# to make an adherence prediction
                if (day in model_prediction_days) and make_prediction:
					# Record the mpr at 60, 90 and 120 days, in case we need to make a prediction
                    pMPR_yesno = self.predict(name, age, mpr, day)

                # If the number of available pills is less than zero, we have a gap
                if pills_available == 0 and day < nDays:
                    mpr_tseries[name].append( "null" )
                    gaps[name].append( [day, mpr] )
                else:
                    mpr_tseries[name].append( [day, mpr] )
                    latest_mpr = mpr

            for i in range(1,len(dates)):
                # Get the number of pills at the last refill
                q = npills[i-1]
                last = dates[i]

				# Compute the gap and keep track of the largest gap for this drug
                gap = (dates[i] - dates[i-1]).days - q
                if gap > max_gap[name]:
                    max_gap[name] = gap

			#- - - - - - - - - - - - - - - - - - - - -
			# Start the various tests here
			#- - - - - - - - - - - - - - - - - - - - -
            flag = "Good"  # default value, current MPR is good, no gaps

			#- - - - - - - - - - - - - - - - - - - - -
			# Gap check: If a large gap exists,
			# there's an adherence problem. Period.
			#- - - - - - - - - - - - - - - - - - - - -
            if max_gap[name] > 30: # self.GAP_THRESHOLD:
				flag = "Poor_gaps"

			#- - - - - - - - - - - - - - - - - - - - -
			# If data for 1 year or more (nominally 360 days) is available,
			# adherence can be determined by actual MPR value
			#- - - - - - - - - - - - - - - - - - - - -
            elif nDays >= 360 and latest_mpr < self.GOOD_MPR_THRESHOLD:
				flag = "Poor_lowMPR"

			#- - - - - - - - - - - - - - - - - - - - -
			# LogReg prediction test: used only if
			# less than 1 year and prediction was made.
			#- - - - - - - - - - - - - - - - - - - - -
            elif nDays<360 and pMPR_yesno:
				if pMPR_yesno == "Good":
					flag = "Good_predictedMPR"
				elif pMPR_yesno == "Poor":
					flag = "Warning_predictedMPR"
				elif latest_mpr < self.GOOD_MPR_THRESHOLD:
					flag = "Warning_lowMPR"

			#- - - - - - - - - - - - - - - - - - - - -
			# Return all the variables needed for
			# creating nice plots.
			#- - - - - - - - - - - - - - - - - - - - -
            urlname = name.replace (" ", "%20")
            gap_flag.append([name, urlname, flag, first, last, drug_class, nDays, mpr])

		# Fill in class variables needed by other functions
        return gap_flag , gaps, mpr_tseries, refill_day

    #=============================================================================
    # This function computes the outcome from a logistic regression
    # solution. The coefficients from the regression were computed
    # externally and are read from a file upon initiation. Inputs
    # required for the solution are the patients age on the first
    # fill date and the MPR on day 60, 90 or 120. The return value
    # is tertiary: -1 = cannot predict (model is not valid for these parameters)
    # 0 = no adherence problem, 1 = non-adherence (mpr < 0.8) predicted
    # at 1 year from first fill.
    #=============================================================================
    def predict(self, med_name, age, mpr, iday):

        # Initialize to null. This is the default case if none of the given
        # input parameters match the valid model parameters.
        # Some local variables
        adherence_warning = "None"   # By default, no warning is reported
        sday = str(iday)
        allowable_days = ['60', '90', '120']

		#- - - - - - - - - - - - - - - - - - - - -
        # Is the med_name in the list of model_class names?
		#- - - - - - - - - - - - - - - - - - - - -
        name = med_name.split()[0].lower()

		#- - - - - - - - - - - - - - - - - - - - -
        # Get the drug class from the drug name
		#- - - - - - - - - - - - - - - - - - - - -
        if self.drugclasses.has_key(name):
            drug_class = str(self.drugclasses[name])
        else:
            drug_class = "other"
            return adherence_warning  # no prediction

        if not (sday in allowable_days):
            print "day not allowable for adherence calculation"
            return adherence_warning

		#- - - - - - - - - - - - - - - - - - - - -
        # Set up the regression coefficients. Age must be 60, 90 or 120 days at this time.
        # print "2. med, class: ", name, drug_class
        # print "keys:", self.data.keys()
		#- - - - - - - - - - - - - - - - - - - - -
        coeff = self.data[drug_class][sday]
        a = float(coeff[0])
        b = float(coeff[1])
        c = float(coeff[2])

		#- - - - - - - - - - - - - - - - - - - - -
        # Compute the logit function
		#- - - - - - - - - - - - - - - - - - - - -
        g = a + b*mpr + c*age
        exp_g = math.exp(g)
        p = exp_g/(1.0 + exp_g)

		#- - - - - - - - - - - - - - - - - - - - -
        # Determine the meaning of the outcome and return
		#- - - - - - - - - - - - - - - - - - - - -
        if p > 0.5: adherence_warning = "Poor"
        else: adherence_warning = "Good"
        return adherence_warning

    #=====================================================
    # Template for future tests.
	# If the flag value assigned here does not have a
	# corresponding option in index.html and risk.html,
	# it needs to be added.
    #=====================================================
    def newTest(self):
        flag = "New_Test_MPR"
        return flag


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Usnea creberrima Vain.

### Remarks
null


text:
from mpi4py import MPI
import mpiunittest as unittest
try:
    from sys import getrefcount
except ImportError:
    class getrefcount(object):
        def __init__(self, arg):
            pass
        def __eq__(self, other):
            return True
        def __add__(self, other):
            return self
        def __sub__(self, other):
            return self

def memzero(m):
    n = len(m)
    if n == 0: return
    try:
        zero = b'\0'
        m[0] = zero
    except TypeError:
        zero = 0
        m[0] = zero
    for i in range(n):
        m[i] = zero

class BaseTestWin(object):

    COMM = MPI.COMM_NULL
    INFO = MPI.INFO_NULL
    CREATE_FLAVOR = MPI.UNDEFINED

    def testGetAttr(self):
        base = MPI.Get_address(self.memory)
        size = len(self.memory)
        unit = 1
        self.assertEqual(size, self.WIN.Get_attr(MPI.WIN_SIZE))
        self.assertEqual(unit, self.WIN.Get_attr(MPI.WIN_DISP_UNIT))
        self.assertEqual(base, self.WIN.Get_attr(MPI.WIN_BASE))

    def testMemory(self):
        memory = self.WIN.memory
        pointer = MPI.Get_address(memory)
        length = len(memory)
        base, size, dunit = self.WIN.attrs
        self.assertEqual(size,  length)
        self.assertEqual(dunit, 1)
        self.assertEqual(base,  pointer)

    def testAttributes(self):
        base, size, unit = self.WIN.attrs
        self.assertEqual(size, len(self.memory))
        self.assertEqual(unit, 1)
        self.assertEqual(base, MPI.Get_address(self.memory))

    def testGetGroup(self):
        cgroup = self.COMM.Get_group()
        wgroup = self.WIN.Get_group()
        grpcmp = MPI.Group.Compare(cgroup, wgroup)
        cgroup.Free()
        wgroup.Free()
        self.assertEqual(grpcmp, MPI.IDENT)

    def testGetSetInfo(self):
        #info = MPI.INFO_NULL
        #self.WIN.Set_info(info)
        info = MPI.Info.Create()
        self.WIN.Set_info(info)
        info.Free()
        info = self.WIN.Get_info()
        self.WIN.Set_info(info)
        info.Free()

    def testGetSetErrhandler(self):
        for ERRHANDLER in [MPI.ERRORS_ARE_FATAL, MPI.ERRORS_RETURN,
                           MPI.ERRORS_ARE_FATAL, MPI.ERRORS_RETURN,]:
            errhdl_1 = self.WIN.Get_errhandler()
            self.assertNotEqual(errhdl_1, MPI.ERRHANDLER_NULL)
            self.WIN.Set_errhandler(ERRHANDLER)
            errhdl_2 = self.WIN.Get_errhandler()
            self.assertEqual(errhdl_2, ERRHANDLER)
            errhdl_2.Free()
            self.assertEqual(errhdl_2, MPI.ERRHANDLER_NULL)
            self.WIN.Set_errhandler(errhdl_1)
            errhdl_1.Free()
            self.assertEqual(errhdl_1, MPI.ERRHANDLER_NULL)

    def testGetSetName(self):
        try:
            name = self.WIN.Get_name()
            self.WIN.Set_name('mywin')
            self.assertEqual(self.WIN.Get_name(), 'mywin')
            self.WIN.Set_name(name)
            self.assertEqual(self.WIN.Get_name(), name)
        except NotImplementedError:
            pass

    def testCreateFlavor(self):
        if MPI.WIN_CREATE_FLAVOR == MPI.KEYVAL_INVALID: return
        flavors = (MPI.WIN_FLAVOR_CREATE,
                   MPI.WIN_FLAVOR_ALLOCATE,
                   MPI.WIN_FLAVOR_DYNAMIC,
                   MPI.WIN_FLAVOR_SHARED,)
        flavor = self.WIN.Get_attr(MPI.WIN_CREATE_FLAVOR)
        self.assertTrue (flavor in flavors)
        self.assertEqual(flavor, self.WIN.flavor)
        self.assertEqual(flavor, self.CREATE_FLAVOR)

    def testMemoryModel(self):
        if MPI.WIN_MODEL == MPI.KEYVAL_INVALID: return
        models = (MPI.WIN_SEPARATE, MPI.WIN_UNIFIED)
        model = self.WIN.Get_attr(MPI.WIN_MODEL)
        self.assertTrue (model in models)
        self.assertEqual(model, self.WIN.model)

class BaseTestWinCreate(BaseTestWin):

    CREATE_FLAVOR = MPI.WIN_FLAVOR_CREATE

    def setUp(self):
        self.memory = MPI.Alloc_mem(10)
        memzero(self.memory)
        self.WIN = MPI.Win.Create(self.memory, 1, self.INFO, self.COMM)

    def tearDown(self):
        self.WIN.Free()
        MPI.Free_mem(self.memory)

class BaseTestWinAllocate(BaseTestWin):

    CREATE_FLAVOR = MPI.WIN_FLAVOR_ALLOCATE

    def setUp(self):
        self.WIN = MPI.Win.Allocate(10, 1, self.INFO, self.COMM)
        self.memory = self.WIN.memory
        memzero(self.memory)

    def tearDown(self):
        self.WIN.Free()

class BaseTestWinAllocateShared(BaseTestWin):

    CREATE_FLAVOR = MPI.WIN_FLAVOR_SHARED

    def setUp(self):
        self.WIN = MPI.Win.Allocate_shared(10, 1, self.INFO, self.COMM)
        self.memory = self.WIN.memory
        memzero(self.memory)

    def tearDown(self):
        self.WIN.Free()

    def testSharedQuery(self):
        memory = self.WIN.memory
        address = MPI.Get_address(memory)
        length = len(memory)
        memories = self.COMM.allgather((address, length))
        rank = self.COMM.Get_rank()
        size = self.COMM.Get_size()
        for i in range(size):
            mem, disp = self.WIN.Shared_query(rank)
            base = MPI.Get_address(mem)
            size = len(mem)
            if i == rank:
                self.assertEqual(base, memories[i][0])
            self.assertEqual(size, memories[i][1])
            self.assertEqual(disp, 1)

class BaseTestWinCreateDynamic(BaseTestWin):

    CREATE_FLAVOR = MPI.WIN_FLAVOR_DYNAMIC

    def setUp(self):
        self.WIN = MPI.Win.Create_dynamic(self.INFO, self.COMM)

    def tearDown(self):
        self.WIN.Free()

    def testGetAttr(self):
        base = self.WIN.Get_attr(MPI.WIN_BASE)
        size = self.WIN.Get_attr(MPI.WIN_SIZE)
        disp = self.WIN.Get_attr(MPI.WIN_DISP_UNIT)
        self.assertEqual(base, 0)
        self.assertEqual(size, 0)
        #self.assertEqual(disp, 1)

    def testMemory(self):
        self.assertTrue(self.WIN.memory is None)

    def testAttributes(self):
        pass

    def testAttachDetach(self):
        mem1 = MPI.Alloc_mem(8)
        mem2 = MPI.Alloc_mem(16)
        mem3 = MPI.Alloc_mem(32)
        for mem in (mem1, mem2, mem3):
            self.WIN.Attach(mem)
            self.testMemory()
            self.WIN.Detach(mem)
        for mem in (mem1, mem2, mem3):
            self.WIN.Attach(mem)
        self.testMemory()
        for mem in (mem1, mem2, mem3):
            self.WIN.Detach(mem)
        for mem in (mem1, mem2, mem3):
            self.WIN.Attach(mem)
        self.testMemory()
        for mem in (mem3, mem2, mem1):
            self.WIN.Detach(mem)
        MPI.Free_mem(mem1)
        MPI.Free_mem(mem2)
        MPI.Free_mem(mem3)

class TestWinCreateSelf(BaseTestWinCreate, unittest.TestCase):
    COMM = MPI.COMM_SELF

class TestWinCreateWorld(BaseTestWinCreate, unittest.TestCase):
    COMM = MPI.COMM_WORLD

class TestWinAllocateSelf(BaseTestWinAllocate, unittest.TestCase):
    COMM = MPI.COMM_SELF

class TestWinAllocateWorld(BaseTestWinAllocate, unittest.TestCase):
    COMM = MPI.COMM_WORLD

class TestWinAllocateSharedSelf(BaseTestWinAllocateShared, unittest.TestCase):
    COMM = MPI.COMM_SELF

class TestWinAllocateSharedWorld(BaseTestWinAllocateShared, unittest.TestCase):
    COMM = MPI.COMM_WORLD

class TestWinCreateDynamicSelf(BaseTestWinCreateDynamic, unittest.TestCase):
    COMM = MPI.COMM_SELF

class TestWinCreateDynamicWorld(BaseTestWinCreateDynamic, unittest.TestCase):
    COMM = MPI.COMM_WORLD

try:
    MPI.Win.Create(MPI.BOTTOM, 1, MPI.INFO_NULL, MPI.COMM_SELF).Free()
except NotImplementedError:
    del TestWinCreateSelf, TestWinCreateWorld
try:
    MPI.Win.Allocate(1, 1, MPI.INFO_NULL, MPI.COMM_SELF).Free()
except NotImplementedError:
    del TestWinAllocateSelf, TestWinAllocateWorld
try:
    MPI.Win.Allocate_shared(1, 1, MPI.INFO_NULL, MPI.COMM_SELF).Free()
except NotImplementedError:
    del TestWinAllocateSharedSelf, TestWinAllocateSharedWorld
try:
    MPI.Win.Create_dynamic(MPI.INFO_NULL, MPI.COMM_SELF).Free()
except NotImplementedError:
    del TestWinCreateDynamicSelf, TestWinCreateDynamicWorld

name, version = MPI.get_vendor()
if name == 'Open MPI':
    if version < (1,4,0):
        if MPI.Query_thread() > MPI.THREAD_SINGLE:
            del TestWinCreateWorld
            del TestWinAllocateWorld
if name == 'MPICH2':
    import sys
    if sys.platform.startswith('win'):
        del BaseTestWin.testAttributes

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


text:
This chapter will introduce how to use themes and how to develop them.

If you want to see a list of all themes and their supported features, please visit [theme list](/themes/).

## How to use

### Official theme

Pagic has official themes default/docs/blog, which can be used by configuring `theme` in `pagic.config.ts`. The `default` theme will be used by default:

```ts
export default {
  theme: 'default',
};
```

### Third party theme

When using a third-party theme, the value of `theme` should be a complete URL:

```ts
export default {
  theme: 'https://raw.githubusercontent.com/xcatliu/pagic_theme_custom/master/mod.ts',
};
```

### Theme supported plugins

The theme determines how the page is displayed, and the plugin determines the features supported by the page.

After selecting the theme, we can add plugins to extend the features of the webpage, but only if the theme supports this plugin.

Take the `sidebar` plugin as an example. The `sidebar` plugin will display a configured sidebar on the left side of the page, but not all themes support this plugin. For example, the `default` theme is a very basic theme. It supports the most basic functions, so the `sidebar` plugin is not supported.

Generally, you can view the list of plugins supported by the theme's documentation.

### Theme configuration

Theme-related options can be configured in `pagic.config.ts`, common options include `title`, `description`, `head`, etc. For their meaning and usage, please refer to the [Config](./config.md#page-content) chapter.

#### Website configuration? Theme configuration? Plugin configuration?

You may have discovered that unlike some other static site generators that have different config files (or config items) for websites, themes and plugins, Pagic only has one config file `pagic.config.ts`.

You may have some doubts: Isn't this confusing? Will the configuration between the theme and the plugin conflict?

But in fact, Pagic's design is justified:

##### 1. A configuration item may need to be read by the theme and plugin at the same time

Take `sidebar` as an example, if we configure this `sidebar` in `pagic.config.ts`:

```ts
export default {
  sidebar: {
    '/docs/': [
      'docs/introduction.md',
      'docs/usage.md',
      'docs/config.md',
      'docs/content.md',
      'docs/layout.md',
      'docs/themes.md',
      'docs/plugins.md',
      'docs/blog.md',
      'docs/i18n.md',
      'docs/deployment.md',
      'docs/demos.md',
      'docs/limitations.md',
    ],
  },
};
```

Then:

- The `sidebar` plugin needs to parse it and convert it to `ReactElement`
- `docs` theme needs to support rendering `sidebar`, and provide functions such as folding, SPA jump, etc.

It can be seen that it is inappropriate to attribute the configuration of `sidebar` to the configuration of the theme, and it is also inappropriate to attribute the configuration of the plugin. There needs to be one place to manage this configuration.

##### 2. There may be dependencies between plugins and plugins

Take the `prev_next` plugin as an example, it supports automatic insertion of links to the previous page and the next page at the bottom of the page. But it needs to rely on the configuration of `sidebar` to know what the link to the previous page is.

Therefore, the `prev_next` plugin needs to be able to read the configuration of the `sidebar`, so it is more appropriate to put the configuration in the `pagic.config.ts`.

##### 3. This can reduce the user's understanding cost

Users don't need to think about whether a configuration belongs to a theme or a plugin. It can be configured in `pagic.config.ts`.

##### But how to ensure that the configuration between various third-party themes and plugins will not conflict?

First of all, the configuration items of the plugin are generally the same as the plugin name (for example, the `sidebar` plugin provides the `sidebar` configuration item), which ensures that there is generally no conflict between different plugins.

Second, we organize some common configuration items into documents. Developers of third-party themes and plugins should refer to [this document](./config.md) as much as possible to avoid conflicts.

Finally, this design actually constrains the developers of third-party themes and plugins, so that everyone needs to design configuration items according to the same standard, which means that Pagic's third-party themes and plugins have higher quality and compatibility.

## How to develop a theme

Congratulations, you are about to become a developer of Pagic theme!

As long as you understand the operating mechanism of Pagic theme, you can easily develop a Pagic theme.

### Theme operating mechanism

The operating mechanism of Pagic theme is easy to understand, and can even be explained clearly in one sentence:

> When Pagic builds, it will first "copy" all the files in the theme to the user's project directory, and then run the `pagic build` script.

For example, if a theme contains the following files:

```{2-4}
pagic_theme_custom/
|── assets
|   └── index.css
└── _layout.tsx
```

The directory structure of the user's project is as follows:

```
site/
|── pagic.config.ts
└── README.tsx
```

Then when the user uses this theme, the directory structure of the user's project will "become like this":

```{2-4}
site/
|── assets
|   └── index.css
|── _layout.tsx
|── pagic.config.ts
└── README.tsx
```

At this time, when executing `pagic build`, `assets/index.css` will be copied to `dist/assets/index.css`, and `README.md` will be rendered with `_layout.tsx` as a template, and generate `dist/index.html`:

```{2-5}
site/
|── dist    # Output directory
|   |── assets
|   |   └── index.css
|   └── index.html
|── assets
|   └── index.css
|── _layout.tsx
|── pagic.config.ts
└── README.tsx
```

When Pagic builds, each page file (`md/tsx`) will follow the rules described in the [\_layout.tsx](./layout.md) chapter to find its corresponding template file.

A typical application is to write a sub-template in a theme, and then require the directory structure of the project using this theme to conform to this convention.

For example, the theme can create a `posts/_layout.tsx` file:

```{4,5}
pagic_theme_custom/
|── assets
|   └── index.css
|── posts
|   └── _layout.tsx
└── _layout.tsx
```

In this way, the pages under the user's `posts` directory will be rendered with `posts/_layout.tsx` as a template:

```{2,3}
site/
|── posts
|   └── hello.md # This page will be rendered with posts/_layout.tsx in the theme as a template
|── pagic.config.ts
└── README.tsx
```

It should be noted that the files in the theme will not be "copied" to the user's project directory. We can regard this "copy" as a virtual execution.

In addition, if there is a file path in the user's project that is the same as that in the theme, the file in the user's project shall prevail, that is, the file that allows the user to overwrite the theme.

### Entry file

As mentioned before, when using a third-party theme, the value of `theme` should be an entry file URL:

```ts
export default {
  theme: 'https://raw.githubusercontent.com/xcatliu/pagic_theme_custom/master/mod.ts',
};
```

A typical `mod.ts` entry file is listed below:

```ts
export default {
  files: [
    'assets/index.css',
    'assets/prism_tomorrow.css',
    'assets/reset.css',
    'assets/variables.css',
    '_layout.tsx',
    'favicon.ico',
  ],
};
```

This entry file contains the following information:

#### `files`

`files` lists all the files of the theme, they will be "copied" to the user's project directory.

Why is it designed like this? Why can't it traverse all the files in the theme directory automatically?

Because Pagic needs to support an URL to configure the theme, and only one URL cannot traverse to which files are in the path. Just imagine how you can traverse `https://raw.githubusercontent.com/xcatliu/pagic_theme_custom/master`?

To sum up, although it is a bit troublesome, it is necessary to list all the files of the subject.

When you are developing a theme, you can run `pagic init` and select `theme` to automatically scan the files in the current directory and generate a `mod.ts`.

### `props`

The core file in the theme is `_layout.tsx`, and the most important thing to write `_layout.tsx` is to use its `props`.

The previous chapter has introduced `props`, if you need to know all the `props`, you can directly view [\_layout.tsx props](./layout.md#props).

### Reference official theme

The best reference for developing a theme is the official theme. You can directly [view the source code of the official theme](https://github.com/xcatliu/pagic/tree/master/src/themes).


text:
/**
 * Created by mgijsbertihodenpijl on 14/08/15.
 */
/* globals browser, describe, it, element, by, expect, beforeEach */
import Spectangular from '../node_modules/spectangular/dist/spectangular.js';
import * as SpectangularMdLibrary from '../node_modules/spectangular/dist/libraries/md/md.js';

Spectangular.baseUrl = 'https://material.angularjs.org/latest';
Spectangular.library = SpectangularMdLibrary;

describe('Demo of tabs', function () {

    /**
     * Loads the page https://material.angularjs.org/latest/#/demo/material.components.tabs and waits for the element
     * with css selector .demo-toolbar.
     */
    beforeEach(function () {
        Spectangular.loadPage('/#/demo/material.components.tabs', '.demo-toolbar');
    });

    it('should select tab "Two" in Dynamic Height Demo', function () {
        var rootEl = $('[demo-id=\"tabsdemoDynamicHeight\"]');
        expect(rootEl.isPresent()).toBe(true);
        Spectangular
            .tab({
                rootEl: rootEl,
                text: 'two'})
            .click();
    });

    it('should select tab index 3 (=Two) in Dynamic Height Demo', function () {
        var rootEl = $('[demo-id=\"tabsdemoDynamicHeight\"]');
        expect(rootEl.isPresent()).toBe(true);
        Spectangular
            .tab({
                rootEl: rootEl,
                index: 3})
            .click();
    });
});


text:
import React, { Component } from 'react';
import {
    Text,
    View,
    ListView
} from 'react-native';
import DetailItem from './Detail_Item';

export default class DetailList extends Component {
    constructor(props){
        super(props);
    }

    render(){
        return(
            <View style={{flex: 1}}>
                <ListView
                    key={this.props.mode}
                    dataSource={this.props.subjectDS}
                    renderRow={(rowData)=>(<DetailItem subjectData={rowData}/>)}
                />
            </View>
        )
    }
}


text:
(function() {

  'use strict';

  angular
    .module('folsom')
    .controller('uploadCtrl', controller);

  function controller($scope, apiService, $route) {
    $scope.$route = $route;
    $scope.file = {};

    $scope.processUpload = function() {
      $scope.flash = {
        alert_type: 'info',
        message: 'Uploading your file now...'
      };
      console.log($scope.file);
      apiService.uploadFile($scope.file).then(function(response) {
        $scope.flash = {
          alert_type: 'success',
          message: 'Your file was uploaded successfully!'
        };
      }, function(response) {
        $scope.flash = {
          alert_type: 'danger',
          message: response.data.message
        };
      });
    }
  };

})();


text:
import dataclasses
import datetime

try:
    import zoneinfo
except ImportError:
    from backports import zoneinfo  # type: ignore

import freezegun
import pytest  # type: ignore
from almost_equal import datetime_almost_equal

from astral import LocationInfo
from astral.location import Location

class TestLocation:
    """Tests for the Location class"""

    def test_Name(self):
        """Test the default name and that the name is changeable"""
        c = Location()
        assert c.name == "Greenwich"
        c.name = "Köln"
        assert c.name == "Köln"

    def test_Region(self):
        """Test the default region and that the region is changeable"""
        c = Location()
        assert c.region == "England"
        c.region = "Australia"
        assert c.region == "Australia"

    def test_TimezoneName(self):
        """Test the default timezone and that the timezone is changeable"""
        c = Location()
        assert c.timezone == "Europe/London"
        c.name = "Asia/Riyadh"
        assert c.name == "Asia/Riyadh"

    def test_TimezoneNameBad(self):
        """Test that an exception is raised if an invalid timezone is specified"""
        c = Location()
        with pytest.raises(ValueError):
            c.timezone = "bad/timezone"

    def test_TimezoneLookup(self):
        """Test that tz refers to a timezone object"""
        c = Location()
        assert c.tz == zoneinfo.ZoneInfo("Europe/London")  # type: ignore
        c.timezone = "Europe/Stockholm"
        assert c.tz == zoneinfo.ZoneInfo("Europe/Stockholm")  # type: ignore

    def test_Info(self, london: Location, london_info: LocationInfo):
        assert london_info == london.info

    def test_Sun(self, london: Location):
        """Test Location's version of the sun calculation"""
        ldt = datetime.datetime(2015, 8, 1, 5, 23, 20, tzinfo=london.tzinfo)
        sunrise = london.sun(datetime.date(2015, 8, 1))["sunrise"]
        assert datetime_almost_equal(sunrise, ldt)

    def test_Dawn(self, london: Location):
        """Test Location returns dawn times in the local timezone"""
        ldt = datetime.datetime(2015, 8, 1, 4, 41, 44, tzinfo=london.tzinfo)
        dawn = london.dawn(datetime.date(2015, 8, 1))
        assert datetime_almost_equal(dawn, ldt)
        # assert dawn.tzinfo.zone == london.tzinfo.zone

    def test_DawnUTC(self, london: Location):
        """Test Location returns dawn times in the UTC timezone"""
        udt = datetime.datetime(2015, 8, 1, 3, 41, 44, tzinfo=datetime.timezone.utc)
        dawn = london.dawn(datetime.date(2015, 8, 1), local=False)
        assert datetime_almost_equal(dawn, udt)
        # assert dawn.tzinfo.zone == datetime.timezone.utc.zone

    def test_Sunrise(self, london: Location):
        ldt = datetime.datetime(2015, 8, 1, 5, 23, 20, tzinfo=london.tzinfo)
        sunrise = london.sunrise(datetime.date(2015, 8, 1))
        assert datetime_almost_equal(sunrise, ldt)
        # assert sunrise.tzinfo.zone == london.tzinfo.zone

    def test_SunriseUTC(self, london: Location):
        udt = datetime.datetime(2015, 8, 1, 4, 23, 20, tzinfo=datetime.timezone.utc)
        sunrise = london.sunrise(datetime.date(2015, 8, 1), local=False)
        assert datetime_almost_equal(sunrise, udt)
        # assert sunrise.tzinfo.zone == datetime.timezone.utc.zone

    def test_SolarNoon(self, london: Location):
        ldt = datetime.datetime(2015, 8, 1, 13, 6, 53, tzinfo=london.tzinfo)
        noon = london.noon(datetime.date(2015, 8, 1))
        assert datetime_almost_equal(noon, ldt)
        # assert noon.tzinfo.zone == london.tzinfo.zone

    def test_SolarNoonUTC(self, london: Location):
        udt = datetime.datetime(2015, 8, 1, 12, 6, 53, tzinfo=datetime.timezone.utc)
        noon = london.noon(datetime.date(2015, 8, 1), local=False)
        assert datetime_almost_equal(noon, udt)
        # assert noon.tzinfo.zone == datetime.timezone.utc.zone

    def test_Dusk(self, london: Location):
        ldt = datetime.datetime(2015, 12, 1, 16, 35, 11, tzinfo=london.tzinfo)
        dusk = london.dusk(datetime.date(2015, 12, 1))
        assert datetime_almost_equal(dusk, ldt)
        # assert dusk.tzinfo.zone == london.tzinfo.zone

    def test_DuskUTC(self, london: Location):
        udt = datetime.datetime(2015, 12, 1, 16, 35, 11, tzinfo=datetime.timezone.utc)
        dusk = london.dusk(datetime.date(2015, 12, 1), local=False)
        assert datetime_almost_equal(dusk, udt)
        # assert dusk.tzinfo.zone == datetime.timezone.utc.zone

    def test_Sunset(self, london: Location):
        ldt = datetime.datetime(2015, 12, 1, 15, 55, 29, tzinfo=london.tzinfo)
        sunset = london.sunset(datetime.date(2015, 12, 1))
        assert datetime_almost_equal(sunset, ldt)
        # assert sunset.tzinfo.zone == london.tzinfo.zone

    def test_SunsetUTC(self, london: Location):
        udt = datetime.datetime(2015, 12, 1, 15, 55, 29, tzinfo=datetime.timezone.utc)
        sunset = london.sunset(datetime.date(2015, 12, 1), local=False)
        assert datetime_almost_equal(sunset, udt)
        # assert sunset.tzinfo.zone == datetime.timezone.utc.zone

    def test_SolarElevation(self, riyadh: Location):
        dt = datetime.datetime(2015, 12, 14, 8, 0, 0, tzinfo=riyadh.tzinfo)
        elevation = riyadh.solar_elevation(dt)
        assert abs(elevation - 17) < 0.5

    def test_SolarAzimuth(self, riyadh: Location):
        dt = datetime.datetime(2015, 12, 14, 8, 0, 0, tzinfo=riyadh.tzinfo)
        azimuth = riyadh.solar_azimuth(dt)
        assert abs(azimuth - 126) < 0.5

    def test_TimeAtAltitude(self, new_delhi: Location):
        test_data = {datetime.date(2016, 1, 5): datetime.datetime(2016, 1, 5, 10, 0)}

        for day, cdt in test_data.items():
            cdt = cdt.replace(tzinfo=new_delhi.tzinfo)
            dt = new_delhi.time_at_elevation(28, day)
            assert datetime_almost_equal(dt, cdt, seconds=600)

    def test_SolarDepression(self):
        c = Location(
            LocationInfo("Heidelberg", "Germany", "Europe/Berlin", 49.412, -8.71)
        )
        c.solar_depression = "nautical"
        assert c.solar_depression == 12

        c.solar_depression = 18
        assert c.solar_depression == 18

    def test_BadSolarDepression(self):
        loc = Location()
        with pytest.raises(KeyError):
            loc.solar_depression = "uncivil"

    def test_Moon(self):
        d = datetime.date(2017, 12, 1)
        c = Location()
        assert c.moon_phase(date=d) == pytest.approx(11.62, abs=0.01)  # type: ignore

    @freezegun.freeze_time("2015-12-01")
    def test_MoonNoDate(self):
        c = Location()
        assert c.moon_phase() == pytest.approx(19.47, abs=0.01)  # type: ignore

    def test_TzError(self):
        with pytest.raises(AttributeError):
            c = Location()
            c.tz = 1  # type: ignore

    def test_Equality(self):
        c1 = Location()
        c2 = Location()
        assert c1 == c2

    def test_LocationEquality_NotEqual(self, london_info: LocationInfo):
        location1 = Location(london_info)
        location2 = Location(london_info)
        location2.latitude = 23.0

        assert location2 != location1

    def test_LocationEquality_NotALocation(self, london_info: LocationInfo):
        location = Location(london_info)

        class NotALocation:
            _location_info = london_info

        assert NotALocation() != location

    def test_SetLatitudeFloat(self):
        loc = Location()
        loc.latitude = 34.0
        assert loc.latitude == 34.0

    def test_SetLatitudeString(self):
        loc = Location()
        loc.latitude = "24°28'N"

        assert loc.latitude == pytest.approx(24.46666666666666)  # type: ignore

    def test_SetLongitudeFloat(self):
        loc = Location()
        loc.longitude = 24.0
        assert loc.longitude == 24.0

    def test_SetLongitudeString(self):
        loc = Location()
        loc.longitude = "24°28'S"

        assert loc.longitude == pytest.approx(-24.46666666666666)  # type: ignore

    def test_SetBadLongitudeString(self):
        loc = Location()
        with pytest.raises(ValueError):
            loc.longitude = "wibble"

    def test_BadTzinfo(self):
        loc = Location()
        loc._location_info = dataclasses.replace(  # type: ignore
            loc._location_info, timezone="Bad/Timezone"  # type: ignore
        )

        with pytest.raises(ValueError):
            loc.tzinfo


text:
u"""
:Copyright:

 Copyright 2016 - 2022
 Andr\xe9 Malo or his licensors, as applicable

:License:

 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.

=============================
 Tests for CDB iterator type
=============================

Tests for CDB iterator type.
"""
__author__ = u"Andr\xe9 Malo"

import tempfile as _tempfile
import weakref as _weakref

from pytest import raises

import cdbx as _cdbx

# pylint: disable = consider-using-with, pointless-statement

def test_closed():
    """ bail if closed """
    make = _cdbx.CDB.make(_tempfile.TemporaryFile(), close=True)
    make.add('foo', 'bar')
    cdb = make.commit()

    obj = cdb.items()
    for _ in obj:
        cdb.close()
        break

    with raises(IOError):
        list(obj)

def test_weakref():
    """ weakref handling """
    make = _cdbx.CDB.make(_tempfile.TemporaryFile(), close=True)
    make.add('foo', 'bar')
    cdb = make.commit()

    obj = iter(cdb)
    proxy = _weakref.proxy(obj)
    assert list(proxy) == [b'foo']
    assert list(proxy) == []
    del obj

    with raises(ReferenceError):
        list(proxy)


text:
#ifndef SYNCED_MEMORY_H
#define SYNCED_MEMORY_H

#include <memory>
#include <stdlib.h>

#include <cuda_runtime.h>

#include "base.h"
#include "gtest.h"
//#include "log.h"
#include "util/common.h"

namespace BigBang {

class SyncedMemory {
public:
	explicit SyncedMemory(size_t size) :
		size_(size), cpu_data_(nullptr),
		gpu_data_(nullptr), mem_state_(UNINITIALIZED) {
		CHECK_LT(size, MAX_CAPACITY);
#ifndef CPU_ONLY
		CUDA_CHECK(cudaGetDevice(&device_));
#endif
	}
	~SyncedMemory() {
		if (cpu_data_) free(cpu_data_);
		if (gpu_data_) cudaFree(gpu_data_);
	}

	enum SyncedState { UNINITIALIZED, AT_GPU, AT_CPU, SYNCED };

	const void* cpu_data();
	const void* gpu_data();
	void* mutable_cpu_data();
	void* mutable_gpu_data();
	void Reset();

#ifndef CPU_ONLY
	void async_gpu_data_push(const cudaStream_t& stream);
#endif

private:
	void Check() {
		CheckDevice();
	}

	/*void Init() {
		if (mem_state_ == SyncedState::UNINITIALIZED) {
			cpu_data_ = malloc(size_);
			bigbangcpumemset(cpu_data_, 0, size_);
#ifndef CPU_ONLY
			cudaMalloc(&gpu_data_, size_);
			cudaMemset(gpu_data_, 0, size_);
#endif
			mem_state_ = SyncedState::SYNCED;
		}
	}*/

	void CheckDevice();
	void CpuToGpu();
	void GpuToCpu();

private:
	size_t size_;
	void* cpu_data_;
	void* gpu_data_;
	SyncedState mem_state_;
	int device_;
};

}

#endif


text:
#include "../headers/Line.hpp"

Line::Line():m_baseline(0){

}

void Line::setBaseline(int y)
{
	/*
	* \brief For each CC of Line, the baseline of CC is modified by y if CC baseline is different of m_baseline
	*/
	for(std::vector<ConnectedComponent>::iterator it = m_ListCC.begin(); it != m_ListCC.end(); ++it)
		if(it->getBaseline() == m_baseline)
    	it->setBaseline(y);
  m_baseline = y;
}

int Line::getBaseline() const
{
  return m_baseline;
}

void Line::addCC(const ConnectedComponent &cc)
{
  m_ListCC.push_back(cc);
}

std::vector<ConnectedComponent> Line::getListCC() const
{
  return m_ListCC;
}

ConnectedComponent Line::getConnectedComponentAtIndex(int index) const{
	assert(index>=0 && index<= m_ListCC.size());
	return m_ListCC.at(index);
}

void Line::setBoundingBoxAtIndex(int index, int up, int down, int left, int right){
	m_ListCC[index].setBoundingBox(up, down, left, right);
}

void Line::computeBaseLine(){
	sort(m_ListCC.begin(), m_ListCC.end(), [](const ConnectedComponent c1, const ConnectedComponent c2){
        return cv::boundingRect(c1.getListPoint()).x < cv::boundingRect(c2.getListPoint()).x;
    });

  int median = (int)m_ListCC.size()/2;
  cv::Rect bb = cv::boundingRect(m_ListCC[median].getListPoint());
  setBaseline(bb.y + bb.height);
	for(int unsigned i=0;i<m_ListCC.size();i++)
	{
		m_ListCC[i].setBaseline(bb.y + bb.height);
	}
}

void Line::removeConnectedComponentAt(int index)
{
	m_ListCC.erase(m_ListCC.begin() + index);
}

void Line::setBaselineAtIndex(int index, int value)
{
	assert(index>=0);
	m_ListCC[index].setBaseline(value);
}


text:
  <title>Sign our guestbook!</title>
  <link rel="stylesheet" href="style.css" type="text/css"></link>
  <link rel="stylesheet" href="guestbook.css" type="text/css"></link>

Home

Classes

Interests

Worldview

Guestbook

An old fashioned guestbook

Yes, it is a bit old fashioned, but a guestbook is a nice way to let me know you visited and share a comment with me.

            <form action="http://rememberthepoor.asia/webdesign/echo_post.php" method="POST">

                  <input type="text" name="firstname" placeholder="First Name"/>
                  <input type="text" name="lastname" placeholder="Last Name"/>

                  <input type="text" name="email" placeholder="Email"/>

                  <textarea name="comment" placeholder="Comment to share?"></textarea>

                  <input type="submit" value="Save"/>

            </form>


text:
using Kentico.Kontent.Delivery.Abstractions;

namespace Kentico.Kontent.Delivery.Rx.Tests.Models.ContentTypes
{
    public class Office
    {
        public const string Codename = "office";
        public const string NameCodename = "name";
        public const string StreetCodename = "street";
        public const string CityCodename = "city";
        public const string CountryCodename = "country";
        public const string StateCodename = "state";
        public const string ZipCodeCodename = "zip_code";
        public const string PhoneCodename = "phone";
        public const string EmailCodename = "email";

        public string Name { get; set; }
        public string Street { get; set; }
        public string City { get; set; }
        public string Country { get; set; }
        public string State { get; set; }
        public string ZipCode { get; set; }
        public string Phone { get; set; }
        public string Email { get; set; }
        public IContentItemSystemAttributes System { get; set; }
    }
}


text:
Sets breakpoints in .gdbinit file and starts your favorite debugger.

![Preview](https://i.imgur.com/MtJBFmI.gif)

### Requirement

The ~/.gdbinit file must have `add-auto-load-safe-path /` to allow .gdbinit files in any directory.

    echo "add-auto-load-safe-path /" >> ~/.gdbinit


text:
package org.apache.causeway.applib.services.xml;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

/**
 * This service provides a number of utility services for interacting with
 * w3c DOM (XML) {@link Document}s
 *
 * @since 1.x {@index}
 */
public interface XmlService {

    /**
     * Converts xml string into an {@link Document W3C Document}.
     *
     * @see #asString(Document)
     */
    Document asDocument(String xmlStr);

    /**
     * Serializes a {@link Document W3C Document} back into a string.
     *
     * @see #asDocument(String)
     */
    public String asString(final Document doc);

    /**
     * Convenience method to walk XML document.
     */
    Element getChildElement(
                    final Element el, final String tagname);

    /**
     * Convenience method to obtain value of child text node.
     */
    String getChildTextValue(final Element el);

}


text:
/**
 * Is Layout for persistent in this programm.
 *
 * @author Anton Vasilyuk  (wrajina99@gmail.com)
 * @version $Id$
 * @since 0.1
 */
package ru.job4j.persistent;


text:
/*
 * Displays a thumbnail depicting a file attachment.
 *
 * There are two ways that Review Board currently renders file attachments.
 * One is on page load (as part of the initial page template), and the other
 * is dynamically (when uploading vs Drag and Drop or manual upload).
 *
 * Depending on the method, we either already have elements to work with,
 * or we don't. In the latter case, it's currently up to the caller to
 * tell us, using the renderThumbnail option.
 *
 * File attachments that aren't already on the page that are currently loading
 * will be displayed as a blank file attachment (no identifying information)
 * with a spinner. When loaded, it will appear as a standard file attachment.
 *
 * The following signals are provided, on top of the standard Backbone.View
 * signals:
 *
 *     * beginEdit
 *       - Editing of the file attachment (caption) has begun.
 *
 *     * endEdit
 *       - Editing of the file attachment (caption) has finished.
 *
 *     * commentSaved
 *       - A draft comment on the file has been saved.
 *         (Only for file attachments without a Review UI.)
 */
RB.FileAttachmentThumbnail = Backbone.View.extend({
    className: 'file-container',

    events: {
        'click .file-delete': '_onDeleteClicked',
        'click .file-add-comment a': '_onAddCommentClicked',
        'click .file-update a': '_onUpdateClicked'
    },

    template: _.template([
        '
',
        '
',
        '

',
        '
',
        '

',
        '
',
        // spaceless
        '
',
        '<a href="<%- downloadURL %>" class="<%- captionClass %>">',
        '<%- caption %>',
        '',
        '
',
        // end spaceless
        '
',
        '
'
    ].join('')),

    actionsTemplate: _.template([
        '<% if (loaded) { %>',
        '<%  if (reviewURL) { %>',
        '
<a class="file-review" href="<%- reviewURL %>">',
        ' <%- reviewText %>',
        '
',
        '<%  } else { %>',
        '
',
        ' <%- commentText %>',
        '
',
        '<%  } %>',
        '
<a class="file-download" href="<%- downloadURL %>">',
        ' <%- downloadText %>',
        '
',
        '<%  if (canEdit) { %>',
        '<%   if (attachmentHistoryID) { %>',
        '
',
        '<a href="#" data-attachment-history-id="<%- attachmentHistoryID %>">',
        ' <%- updateText %>',
        '
',
        '<%   } %>',
        '
',
        ' <%- deleteText %>',
        '
',
        '<%  } %>',
        '<% } %>'
    ].join('')),

    thumbnailContainerTemplate: _.template([
        '<% if (!loaded) { %>',
        '',
        '<% } else { %>',
        '<%     if (reviewURL) { %>',
        '<a href="<%- reviewURL %>" class="file-thumbnail-overlay">',
        '<%     } %>',
        '<%=  thumbnailHTML %>',
        '<% } %>'
    ].join('')),

    initialize: function(options) {
        this.options = options;

        this._draftComment = null;
        this._comments = [];
        this._commentsProcessed = false;
        this._scrollingThumbnail = false;
    },

    /*
     * Renders the file attachment, and hooks up all events.
     *
     * If the renderThumbnail option was provided when constructing the view,
     * this will render the thumbnail from scratch, and then dynamically
     * update it as it loads. It will start off displaying with a spinner,
     * if not yet loaded.
     *
     * In either case, this will set up the caption editor and other signals
     * to control the lifetime of the thumbnail.
     */
    render: function() {
        var self = this;

        /*
         * Until FileAttachmentThumbnail is the only thing rendering thumbnails,
         * we'll be in a situation where we may either be working with an
         * existing DOM element (for existing file attachments), or a new one
         * (for newly uploaded file attachments). In the latter case, we'll want
         * to render our own thumbnail.
         */
        if (this.options.renderThumbnail) {
            this._renderContents();
        }

        this._$captionContainer = this.$('.file-caption');
        this._$caption = this._$captionContainer.find('a.edit');

        this.listenTo(this.model, 'destroy', function() {
            this.$el.fadeOut(function() {
                self.remove();
            });
        });

        this.listenTo(this.model, 'change:caption', this._onCaptionChanged);
        this._onCaptionChanged();

        this.$el.hover(_.bind(this._onHoverIn, this),
                       _.bind(this._onHoverOut, this));

        if (this.options.renderThumbnail) {
            this._$actionsContainer = this.$('.file-actions-container');
            this._$actions = this._$actionsContainer.children('.file-actions');
            this._$captionContainer = this.$('.file-caption-container');
            this._$thumbnailContainer = this.$('.file-thumbnail-container');
            this._$file = this.$('.file');

            this._$actions.find('.file-download')
                .bindProperty('href', this.model, 'downloadURL', {
                    elementToModel: false
                });

            this._$caption.bindProperty('href', this.model, 'downloadURL', {
                elementToModel: false
            });

            this.listenTo(this.model, 'change:loaded', this._onLoadedChanged);
            this._onLoadedChanged();

            this.listenTo(this.model, 'change:thumbnailHTML',
                          this._renderThumbnail);
            this._renderThumbnail();
        }

        if (this.options.canEdit !== false) {
            this._$caption
                .inlineEditor({
                    editIconClass: 'rb-icon rb-icon-edit',
                    showButtons: true
                })
                .on({
                    beginEditPreShow: function() {
                        self.$el.addClass('editing');
                        self._stopAnimating();
                    },
                    beginEdit: function() {
                        var $this = $(this);

                        if ($this.hasClass('empty-caption')) {
                            $this.inlineEditor('field').val('');
                        }

                        self.trigger('beginEdit');
                    },
                    cancel: function() {
                        self.$el.removeClass('editing');
                        self.trigger('endEdit');
                    },
                    complete: function(e, value) {
                        self.$el.removeClass('editing');

                        /*
                         * We want to set the caption after ready() finishes,
                         * it case it loads state and overwrites.
                         */
                        self.model.ready({
                            ready: function() {
                                self.model.set('caption', value);
                                self.trigger('endEdit');
                                self.model.save({
                                    attrs: ['caption']
                                });
                            }
                        });
                    }
                });
        }

        return this;
    },

    fadeIn: function() {
        this.$el
            .css('opacity', 0)
            .fadeTo(1000, 1);
    },

    /*
     * Shows the comment dialog for the file attachment.
     *
     * This is only ever used if the file attachment does not have a
     * Review UI for it. A single comment dialog will appear, allowing
     * comments on the file as a whole.
     */
    showCommentDlg: function() {
        console.assert(!this.model.get('reviewURL'),
                       'showCommentDlg can only be called if the file ' +
                       'attachment does not have a review UI');
        this._processComments();
        this._createDraftComment();

        RB.CommentDialogView.create({
            comment: this._draftComment,
            publishedComments: this._comments,
            publishedCommentsType: 'file_attachment_comments',
            position: {
                beside: {
                    el: this.$el,
                    side: 'br',
                    fitOnScreen: true
                }
            }
        });
    },

    /*
     * Processes all comments provided when constructing the view.
     *
     * The comments will be made usable by the comment dialog.
     *
     * This is only used if the file attachment does not have a Review UI.
     */
    _processComments: function() {
        var comments = this.options.comments || [],
            len = comments.length,
            comment,
            i;

        if (this._commentsProcessed) {
            return;
        }

        for (i = 0; i < len; i++) {
            comment = comments[i];

            if (comment.localdraft) {
                this._createDraftComment(comment.comment_id, comment.text);
            } else {
                this._comments.push(comment);
            }
        }

        this._commentsProcessed = true;
    },

    /*
     * Creates a new draft comment with the given ID and text.
     *
     * Only one draft comment can be created at a time.
     *
     * This is only used if the file attachment does not have a Review UI.
     */
    _createDraftComment: function(commentID, text) {
        var review;

        if (this._draftComment !== null) {
            return;
        }

        review = this.options.reviewRequest.createReview();
        this._draftComment = review.createFileAttachmentComment(commentID,
                                                                this.model.id);

        if (text) {
            this._draftComment.set('text', text);
        }

        this._draftComment.on('saved', function() {
            this.trigger('commentSaved', this._draftComment);
        }, this);
    },

    /*
     * Renders the contents of this view's element.
     *
     * This is only done when requested by the caller.
     */
    _renderContents: function() {
        var caption = this.model.get('caption'),
            captionText = caption ? caption : gettext('No caption'),
            captionClass = caption ? 'edit' : 'edit empty-caption';

        this.$el
            .html(this.template(_.defaults({
                caption: captionText,
                captionClass: captionClass
            }, this.model.attributes)))
            .addClass(this.className);
    },

    /*
     * Renders the thumbnail for the file attachment.
     */
    _renderThumbnail: function() {
        this._$thumbnailContainer.html(
            this.thumbnailContainerTemplate(this.model.attributes));

        _.each(this._$thumbnailContainer.find('img'), function(el) {
            if (el.hasAttribute('data-at2x')) {
                this._retinaImage = new RetinaImage(el);
                el.removeAttribute('data-at2x');
            }
        }, this);

        // Disable tabbing to any  elements inside the thumbnail.
        this._$thumbnailContainer.find('a').each(function() {
            this.tabIndex = -1;
        });
    },

    /*
     * Handler for when the model's 'loaded' property changes.
     *
     * Depending on if the file attachment is now loaded, either a
     * blank spinner thumbnail will be shown, or a full thumbnail.
     */
    _onLoadedChanged: function() {
        this._$actions.html(this.actionsTemplate(_.defaults({
            canEdit: this.options.canEdit,
            deleteText: gettext('Delete'),
            downloadText: gettext('Download'),
            reviewText: gettext('Review'),
            commentText: gettext('Comment'),
            updateText: gettext('Update')
        }, this.model.attributes)));
    },

    /*
     * Handler for when the model's caption changes.
     *
     * If a caption is set, the thumbnail will display it. Otherwise,
     * it will display "No caption".
     */
    _onCaptionChanged: function() {
        var caption = this.model.get('caption');

        if (caption) {
            this._$caption
                .text(caption)
                .removeClass('empty-caption');
        } else {
            this._$caption
                .text(gettext('No caption'))
                .addClass('empty-caption');
        }
    },

    /*
     * Handler for the New Comment button.
     *
     * Shows the comment dialog.
     */
    _onAddCommentClicked: function(e) {
        e.preventDefault();
        e.stopPropagation();

        this.showCommentDlg();
    },

    /*
     * Handler for the Update button.
     *
     * Shows the upload form.
     */
    _onUpdateClicked: function(e) {
        var updateDlg;

        e.preventDefault();
        e.stopPropagation();

        updateDlg = new RB.UploadAttachmentView({
            attachmentHistoryID: $(e.target).data('attachment-history-id'),
            presetCaption: this.model.get('caption'),
            reviewRequest: this.options.reviewRequest
        });
        updateDlg.render();
    },

    /*
     * Handler for the Delete button.
     *
     * Deletes the file attachment from the review request draft.
     */
    _onDeleteClicked: function(e) {
        e.preventDefault();
        e.stopPropagation();

        this.model.destroy();
    },

    /*
     * Handler for when the mouse hovers over the thumbnail.
     *
     * Determines if we should scroll the thumbnail or not.
     */
    _onHoverIn: function() {
        var self = this,
            $thumbnail = this.$('.file-thumbnail').children(),
            actionsWidth = this._$actionsContainer.outerWidth(),
            actionsRight = this._$file.offset().left +
                           this._$file.outerWidth() +
                           actionsWidth,
            elHeight,
            thumbnailHeight,
            distance,
            duration;

        this.trigger('hoverIn');

        /*
         * Position the actions menu to the left or right of the attachment
         * thumbnail.
         */
        if (actionsRight > $(window).width()) {
            this._$actionsContainer
                .css('left', -actionsWidth)
                .addClass('left');
        } else {
            this._$actionsContainer
                .css('left', '100%')
                .addClass('right');
        }

        if (!this.$el.hasClass('editing') && $thumbnail.length === 1) {
            elHeight = this.$el.height();
            thumbnailHeight = $thumbnail.height() || 0;

            if (thumbnailHeight > elHeight) {
                distance = elHeight - thumbnailHeight;
                duration = (Math.abs(distance) / 200) * 1000; // 200 pixels/s

                this._scrollingThumbnail = true;
                $thumbnail
                    .delay(1000)
                    .animate(
                        { 'margin-top': distance + 'px' },
                        {
                            duration: duration,
                            easing: 'linear'
                        })
                    .delay(500)
                    .animate(
                        { 'margin-top': 0 },
                        {
                            duration: duration,
                            easing: 'linear',
                            complete: function() {
                                self._scrollingThumbnail = false;
                            }
                        });
            }
        }
    },

    /*
     * Handler for when the mouse stops hovering over the thumbnail.
     *
     * Removes the classes for the actions container, and stops animating
     * the thumbnail contents.
     */
    _onHoverOut: function() {
        this.trigger('hoverOut');

        this._$actionsContainer
            .removeClass('left')
            .removeClass('right');

        this._stopAnimating();
    },

    /*
     * Stop animating this thumbnail.
     *
     * This is when moving the mouse outside of the thumbnail, or when the
     * caption editor is opened.
     */
    _stopAnimating: function() {
        if (this._scrollingThumbnail) {
            this._scrollingThumbnail = false;
            this.$('.file-thumbnail').children()
                .stop(true)
                .animate(
                    { 'margin-top': 0 },
                    { duration: 100 });
        }
    }
});


text:
namespace UnitTest
{
    using System.IO;
    using NUnit.Framework;
    using Bond;
    using Bond.Protocols;
    using Bond.IO.Unsafe;

    [TestFixture]
    public class StreamTests
    {
        [Test]
        public void StreamPositionLengthTest()
        {
            const int _50MB = 50*1024*1024;

            var from1 = Random.Init<Containers>();
            var from2 = Random.Init<Containers>();
            var stream = new MemoryStream();

            var output = new OutputStream(stream, 11);
            var writer = new CompactBinaryWriter<OutputStream>(output);

            Assert.IsTrue(output.Position == 0);

            Serialize.To(writer, from1);

            var pos = output.Position;

            output.Flush();

            Assert.IsTrue(output.Position == pos);
            Assert.IsTrue(output.Position == stream.Length);

            output.Position = _50MB;

            Serialize.To(writer, from2);
            output.Flush();

            pos = output.Position;

            stream.Position = 0;

            var input = new InputStream(stream);
            var reader = new CompactBinaryReader<InputStream>(input);

            Assert.IsTrue(input.Position == stream.Position);
            Assert.IsTrue(input.Length == stream.Length);

            var to1 = Deserialize<Containers>.From(reader);
            Assert.IsTrue(from1.IsEqual<Containers>(to1));

            Assert.IsTrue(input.Length == stream.Length);

            input.Position = _50MB;

            var to2 = Deserialize<Containers>.From(reader);
            Assert.IsTrue(from2.IsEqual<Containers>(to2));

            Assert.IsTrue(input.Position == pos);
        }

        [Test]
        public void StreamBufferReuseTest()
        {
            var buffer = new byte[5 * 1024];

            for (var i = 0; i < buffer.Length; ++i)
                buffer[i] = (byte)(i % 256);

            for (var k = 3; k < 20; ++k)
            {
                var stream = new MemoryStream(buffer, 0, buffer.Length, false, true);
                var input = new InputStream(stream, 9);

                while (input.Position + k + sizeof(long) < input.Length)
                {
                    var x = input.Position;
                    var bytes = input.ReadBytes(k);
                    input.ReadUInt64();
                    for (var j = 0; j < bytes.Count; ++j)
                        Assert.AreEqual(bytes.Array[bytes.Offset + j], (x + j) % 256);
                }
            }
        }

        delegate void IntTest<T>(T value);

        [Test]
        public void Varint()
        {
            IntTest<ushort> test16 = (value) =>
            {
                var output = new OutputBuffer();
                output.WriteVarUInt16(value);
                var input = new InputBuffer(output.Data);
                Assert.AreEqual(value, input.ReadVarUInt16());
            };

            IntTest<uint> test32 = (value) =>
            {
                var output = new OutputBuffer();
                output.WriteVarUInt32(value);
                var input = new InputBuffer(output.Data);
                Assert.AreEqual(value, input.ReadVarUInt32());
            };

            IntTest<ulong> test64 = (value) =>
            {
                var output = new OutputBuffer();
                output.WriteVarUInt64(value);
                var input = new InputBuffer(output.Data);
                Assert.AreEqual(value, input.ReadVarUInt64());
            };

            test16(ushort.MinValue);
            test16(ushort.MaxValue);
            test32(uint.MinValue);
            test32(uint.MaxValue);
            test64(ulong.MinValue);
            test64(ulong.MaxValue);
        }
    }
}


text:
@org.osgi.annotation.versioning.Version("1.0.0")
package org.jcommand.queue.api;


text:
"""Plots the number of records in each acsql database table.

Authors
-------

    Matthew Bourque

Use
---

    This script is intended to be executed via the command line as
    such:
    ::

        python database_by_table.py

Dependencies
------------

    - ``acsql``
    - ``matplotlib``
    - ``numpy``
"""

import glob
import os

import matplotlib.pyplot as plt
import numpy as np

from acsql.database import database_interface
from acsql.database.database_interface import session
from acsql.utils.utils import HRC_FILE_EXTS
from acsql.utils.utils import SBC_FILE_EXTS
from acsql.utils.utils import SETTINGS
from acsql.utils.utils import WFC_FILE_EXTS

if __name__ == '__main__':

    # Build list of all tables
    hrc_tables, sbc_tables, wfc_tables = [], [], []
    for filetype in HRC_FILE_EXTS:
        for extension in HRC_FILE_EXTS[filetype]:
            hrc_tables.append('HRC_{}_{}'.format(filetype, extension))
    for filetype in SBC_FILE_EXTS:
        for extension in SBC_FILE_EXTS[filetype]:
            sbc_tables.append('SBC_{}_{}'.format(filetype, extension))
    for filetype in WFC_FILE_EXTS:
        for extension in WFC_FILE_EXTS[filetype]:
            wfc_tables.append('WFC_{}_{}'.format(filetype, extension))

    # Get the class objects for each table
    hrc_class_objs = [getattr(database_interface, table) for table in hrc_tables]
    sbc_class_objs = [getattr(database_interface, table) for table in sbc_tables]
    wfc_class_objs = [getattr(database_interface, table) for table in wfc_tables]

    # Determine number of records in each table
    hrc_num_records = []
    for table in hrc_class_objs:
        print('Querying {}'.format(table))
        hrc_num_records.append(session.query(table).count())

    sbc_num_records = []
    for table in sbc_class_objs:
        print('Querying {}'.format(table))
        sbc_num_records.append(session.query(table).count())

    wfc_num_records = []
    for table in wfc_class_objs:
        print('Querying {}'.format(table))
        wfc_num_records.append(session.query(table).count())

    # Get number of records for master and datasets tables
    master_num_records = session.query((getattr(database_interface, 'Master'))).count()
    datasets_num_records = session.query((getattr(database_interface, 'Datasets'))).count()

    # Aggregate results into two lists
    table_names = wfc_tables
    table_names.extend(hrc_tables)
    table_names.extend(sbc_tables)
    table_names.extend(['Datasets', 'Master'])

    num_records = wfc_num_records
    num_records.extend(hrc_num_records)
    num_records.extend(sbc_num_records)
    num_records.extend([datasets_num_records, master_num_records])

    # Build list of colors
    colors = ['blue' for item in wfc_tables]
    colors.extend(['green' for item in hrc_tables])
    colors.extend(['red' for item in sbc_tables])
    colors.extend(['orange', 'orange'])

    # Reverse the list so that plot is more aesthetically pleasing
    table_names = table_names[::-1]
    num_records = num_records[::-1]
    colors = colors[::-1]

    # Make the plot
    plt.style.use('bmh')
    plt.rcParams['font.size'] = 10
    fig = plt.figure(figsize=(8,20))
    ax = fig.add_subplot(111)
    ax.barh(np.arange(len(table_names)), num_records, align='center', color=colors)
    ax.set_xlabel('# of records')
    ax.set_ylim((-1, len(table_names)))
    ax.set_yticks(np.arange(len(table_names)))
    ax.set_yticklabels(table_names)
    ax.tick_params(axis=u'both', which=u'both', length=0)
    ax.yaxis.grid(False)
    ax.xaxis.grid(True)
    plt.tight_layout()
    plt.savefig('figures/database_records.png')

    print(sum(num_records))


text:
package com.intellij.xdebugger.impl.actions;

import com.intellij.openapi.project.Project;
import consulo.util.dataholder.UserDataHolder;
import com.intellij.xdebugger.attach.XAttachHost;
import com.intellij.xdebugger.attach.XAttachPresentationGroup;
import consulo.ui.image.Image;
import javax.annotation.Nonnull;

/**
 * from kotlin
 */
public class LocalAttachHostPresentationGroup implements XAttachPresentationGroup<XAttachHost> {
  public static final LocalAttachHostPresentationGroup INSTANCE = new LocalAttachHostPresentationGroup();

  // Should be at the bottom of the list
  @Override
  public int getOrder() {
    return Integer.MAX_VALUE;
  }

  @Nonnull
  @Override
  public String getGroupName() {
    return "";
  }

  @Nonnull
  @Override
  public Image getProcessIcon(@Nonnull Project project, @Nonnull XAttachHost info, @Nonnull UserDataHolder dataHolder) {
    throw new UnsupportedOperationException();
  }

  @Nonnull
  @Override
  public String getProcessDisplayText(@Nonnull Project project, @Nonnull XAttachHost info, @Nonnull UserDataHolder dataHolder) {
    throw new UnsupportedOperationException();
  }

  @Nonnull
  @Override
  public Image getItemIcon(@Nonnull Project project, @Nonnull XAttachHost info, @Nonnull UserDataHolder dataHolder) {
    return Image.empty(16);
  }

  @Nonnull
  @Override
  public String getItemDisplayText(@Nonnull Project project, @Nonnull XAttachHost info, @Nonnull UserDataHolder dataHolder) {
    return "Local Host";
  }

  @Override
  public int compare(XAttachHost o1, XAttachHost o2) {
    return Integer.compare(o1.hashCode(), o2.hashCode());
  }
}