text:
module Azure::Automation::Mgmt::V2015_10_31
  module Models
    #
    # The response model for the list credential operation.
    #
    class CredentialListResult

      include MsRestAzure

      include MsRest::JSONable
      # @return [Array<Credential>] Gets or sets a list of credentials.
      attr_accessor :value

      # @return [String] Gets or sets the next link.
      attr_accessor :next_link

      # return [Proc] with next page method call.
      attr_accessor :next_method

      #
      # Gets the rest of the items for the request, enabling auto-pagination.
      #
      # @return [Array<Credential>] operation results.
      #
      def get_all_items
        items = @value
        page = self
        while page.next_link != nil && !page.next_link.strip.empty? do
          page = page.get_next_page
          items.concat(page.value)
        end
        items
      end

      #
      # Gets the next page of results.
      #
      # @return [CredentialListResult] with next page content.
      #
      def get_next_page
        response = @next_method.call(@next_link).value! unless @next_method.nil?
        unless response.nil?
          @next_link = response.body.next_link
          @value = response.body.value
          self
        end
      end

      #
      # Mapper for CredentialListResult class as Ruby Hash.
      # This will be used for serialization/deserialization.
      #
      def self.mapper()
        {
          client_side_validation: true,
          required: false,
          serialized_name: 'CredentialListResult',
          type: {
            name: 'Composite',
            class_name: 'CredentialListResult',
            model_properties: {
              value: {
                client_side_validation: true,
                required: false,
                serialized_name: 'value',
                type: {
                  name: 'Sequence',
                  element: {
                      client_side_validation: true,
                      required: false,
                      serialized_name: 'CredentialElementType',
                      type: {
                        name: 'Composite',
                        class_name: 'Credential'
                      }
                  }
                }
              },
              next_link: {
                client_side_validation: true,
                required: false,
                serialized_name: 'nextLink',
                type: {
                  name: 'String'
                }
              }
            }
          }
        }
      end
    end
  end
end


text:
from oslo_concurrency import processutils

from neutron import privileged

@privileged.dhcp_release_cmd.entrypoint
def dhcp_release(interface_name, ip_address, mac_address, client_id,
                 namespace=None):
    cmd = []
    if namespace:
        cmd += ['ip', 'netns', 'exec', namespace]
    cmd += ['dhcp_release', interface_name, ip_address, mac_address]
    if client_id:
        cmd.append(client_id)
    log_errors = processutils.LOG_FINAL_ERROR
    return processutils.execute(*cmd, log_errors=log_errors)

@privileged.dhcp_release_cmd.entrypoint
def dhcp_release6(interface_name, ip_address, client_id, server_id, iaid,
                  namespace=None):
    cmd = []
    if namespace:
        cmd += ['ip', 'netns', 'exec', namespace]
    cmd += ['dhcp_release6', '--iface', interface_name, '--ip', ip_address,
            '--client-id', client_id, '--server-id', server_id, '--iaid', iaid]
    log_errors = processutils.LOG_FINAL_ERROR
    return processutils.execute(*cmd, log_errors=log_errors)

@privileged.dhcp_release_cmd.entrypoint
def dhcp_release6_supported():
    cmd = ['dhcp_release6', '--help']
    result = processutils.execute(*cmd, check_exit_code=False,
                                  env_variables={'LC_ALL': 'C'})
    return not bool(result[1])

redpajama_set_name: RedPajamaGithub


text:
require 'spec_helper'

RSpec.shared_context 'IssuesFinder context' do
  set(:user) { create(:user) }
  set(:user2) { create(:user) }
  set(:group) { create(:group) }
  set(:subgroup) { create(:group, parent: group) }
  set(:project1) { create(:project, group: group) }
  set(:project2) { create(:project) }
  set(:project3) { create(:project, group: subgroup) }
  set(:milestone) { create(:milestone, project: project1) }
  set(:label) { create(:label, project: project2) }
  set(:label2) { create(:label, project: project2) }
  set(:issue1) { create(:issue, author: user, assignees: [user], project: project1, milestone: milestone, title: 'gitlab', created_at: 1.week.ago, updated_at: 1.week.ago) }
  set(:issue2) { create(:issue, author: user, assignees: [user], project: project2, description: 'gitlab', created_at: 1.week.from_now, updated_at: 1.week.from_now) }
  set(:issue3) { create(:issue, author: user2, assignees: [user2], project: project2, title: 'tanuki', description: 'tanuki', created_at: 2.weeks.from_now, updated_at: 2.weeks.from_now) }
  set(:issue4) { create(:issue, project: project3) }
  set(:award_emoji1) { create(:award_emoji, name: 'thumbsup', user: user, awardable: issue1) }
  set(:award_emoji2) { create(:award_emoji, name: 'thumbsup', user: user2, awardable: issue2) }
  set(:award_emoji3) { create(:award_emoji, name: 'thumbsdown', user: user, awardable: issue3) }
end

RSpec.shared_context 'IssuesFinder#execute context' do
  let!(:closed_issue) { create(:issue, author: user2, assignees: [user2], project: project2, state: 'closed') }
  let!(:label_link) { create(:label_link, label: label, target: issue2) }
  let!(:label_link2) { create(:label_link, label: label2, target: issue3) }
  let(:search_user) { user }
  let(:params) { {} }
  let(:issues) { described_class.new(search_user, params.reverse_merge(scope: scope, state: 'opened')).execute }

  before(:context) do
    project1.add_maintainer(user)
    project2.add_developer(user)
    project2.add_developer(user2)
    project3.add_developer(user)

    issue1
    issue2
    issue3
    issue4

    award_emoji1
    award_emoji2
    award_emoji3
  end
end


text:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:state_pressed="true"><shape android:shape="rectangle">
            <solid android:color="@color/setting_exit_pressed" />

            <corners android:radius="5dp" />
        </shape></item>
    <item><shape android:shape="rectangle">
            <solid android:color="@color/setting_exit_normal" />

            <corners android:radius="5dp" />
        </shape></item>

</selector>


text:
<?php echo Form::open(array("class"=>"form-horizontal")); ?>

	<fieldset>

			<?php echo Form::label('Name', 'name', array('class'=>'control-label')); ?>

				<?php echo Form::input('name', Input::post('name', isset($comment) ? $comment->name : ''), array('class' => 'col-md-4 form-control', 'placeholder'=>'Name')); ?>

			<?php echo Form::label('Email', 'email', array('class'=>'control-label')); ?>

				<?php echo Form::input('email', Input::post('email', isset($comment) ? $comment->email : ''), array('class' => 'col-md-4 form-control', 'placeholder'=>'Email')); ?>

			<?php echo Form::label('Website', 'website', array('class'=>'control-label')); ?>

				<?php echo Form::input('website', Input::post('website', isset($comment) ? $comment->website : ''), array('class' => 'col-md-4 form-control', 'placeholder'=>'Website')); ?>

			<?php echo Form::label('Message', 'message', array('class'=>'control-label')); ?>

				<?php echo Form::textarea('message', Input::post('message', isset($comment) ? $comment->message : ''), array('class' => 'col-md-8 form-control', 'rows' => 8, 'placeholder'=>'Message')); ?>

			<?php echo Form::label('Post id', 'post_id', array('class'=>'control-label')); ?>

				<?php echo Form::input('post_id', Input::post('post_id', isset($comment) ? $comment->post_id : ''), array('class' => 'col-md-4 form-control', 'placeholder'=>'Post id')); ?>

			<?php echo Form::label('Ngocson', 'ngocson', array('class'=>'control-label')); ?>

				<?php echo Form::textarea('ngocson', Input::post('ngocson', isset($comment) ? $comment->ngocson : ''), array('class' => 'col-md-8 form-control', 'rows' => 8, 'placeholder'=>'Ngocson')); ?>

			<?php echo Form::submit('submit', 'Save', array('class' => 'btn btn-primary')); ?>

	</fieldset>
<?php echo Form::close(); ?>


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>Swiper demo</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1">

  <link rel="stylesheet" href="../dist/css/swiper.min.css">


text:
import {ObservableHandler, WritableObservable} from "./observable";
import AbstractObservable from "./abstract";

export default class ObservableProperty<T> extends AbstractObservable<T> implements WritableObservable<T> {

    private _parent: any;
    private _value: T;

    /* private */ constructor(parent: any, name: string) {
        super(name);

        this._parent = parent;

        this._value = parent[name];

        Object.defineProperty(parent, name, {
            enumerable: true,
            get: () => this._value,
            set: (value) => { this.set(value); }
        });

        parent['$' + name] = this;
    }

    get name() {
        return this._name;
    }

    get parent() {
        return this._parent;
    }

    get(): T {
        return this._value;
    }

    set(value: T, noTrigger = false, caller?: any) {
        var oldValue = this._value;
        this._value = value;
        if (!noTrigger) {
            this._trigger(value, oldValue, caller);
        }
    }

    static on(parent: any, name: string) {
        return new ObservableProperty(parent, name);
    }
}


text:
var gulp = require('gulp');
var gutil = require('gulp-util');

module.exports = {
    /**
     * This method builds our license string for embedding into the compiled file
     */
    license: function () {
        var pkg = require(process.cwd() + '/package.json');
        var licenses = [];
        pkg.licenses.forEach(function (license) {
            licenses.push(license.type);
        });

        return '/*! ' + pkg.name + ' - v' + pkg.version + ' - ' + gutil.date("yyyy-mm-dd") + "\n" +
            (pkg.homepage ? "* " + pkg.homepage + "\n" : "") +
            '* Copyright (c) ' + gutil.date("yyyy") + ' ' + pkg.author.name +
            '; Licensed ' + licenses.join(', ') + ' */\n';
    }
};


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ArcGIS.Desktop.Framework;
using ArcGIS.Desktop.Framework.Contracts;
using System.Windows.Input;
using ArcGIS.Desktop.Core;
using System.Windows;
using Microsoft.Win32;
using System.IO;
using System.Collections.ObjectModel;

namespace MetadataBrowserControl
{
    internal class MetadataBrowserViewModel : DockPane
    {
        private const string _dockPaneID = "MetadataBrowserControl_Dockpane1";

        protected MetadataBrowserViewModel() { }

        ///
        /// Show the DockPane.
        ///
        internal static void Show()
        {
            DockPane pane = FrameworkApplication.DockPaneManager.Find(_dockPaneID);
            if (pane == null)
                return;

            pane.Activate();
        }

        protected override Task InitializeAsync()
        {
            DockpaneVisible = Visibility.Collapsed; //Visibility controlled from the module
            XSLFiles.Clear();
            XSLFiles.Add(new XSLFile(AppDomain.CurrentDomain.BaseDirectory.Replace("bin\\", "Resources\\Metadata\\Stylesheets\\XML.xsl")));
            XSLFiles.Add(new XSLFile("Browse for stylesheet"));
            this.SelectedXSL = XSLFiles[0];
            return base.InitializeAsync();
        }
        #region public properties
        private string _heading = "Select stylesheet to render Item Metadata";
        public string Heading
        {
            get { return _heading; }
            set
            {
                SetProperty(ref _heading, value, () => Heading);
            }
        }
        ///
        /// The string to display in the browser control - represents the transformed XML of the project item's metadata
        ///
        private string _webPage = @"Select a project item to view its Metadata. You cannot view the metadata for some items such as system styles.";
        public string WebPage
        {
            get {

                return _webPage;
            }
            set
            {
                SetProperty(ref _webPage, value, () => WebPage);
            }
        }
        private ItemMetadata _itemInfo = null;
        ///
        /// The selected project item's ItemMetadata
        ///
        public ItemMetadata ItemInformation
        {
            get { return _itemInfo; }
            set
            {
                SetProperty(ref _itemInfo, value, () => ItemInformation);
            }
        }

        ///
        /// Visibility of dockpane
        ///
        private Visibility _dockpaneVisible;
        public Visibility DockpaneVisible
        {
            get { return _dockpaneVisible; }
            set
            {
                SetProperty(ref _dockpaneVisible, value, () => DockpaneVisible);
            }
        }
        private ObservableCollection<XSLFile> _xslFiles = new ObservableCollection<XSLFile>();
        ///
        /// Collection of XSLFiles displayed in combo box
        ///
        public ObservableCollection<XSLFile> XSLFiles
        {
            get { return _xslFiles; }
            set {
                SetProperty(ref _xslFiles, value, () => XSLFiles);
            }
        }
        private XSLFile _selectedXSLFile;
        ///
        /// The selected XSLFile to apply the transform with
        ///
        public XSLFile SelectedXSL
        {
            get { return _selectedXSLFile; }
            set {
                if (!File.Exists(value.FileFullName)) // User picked browse
                {
                    if (_selectedXSLFile == null) //flag to check so we don't get into the setter when XSLFile is added to collection
                        return;
                    XSLFile browsedFile = BrowseFileName();
                    if (browsedFile == null) //user cancelled
                        return;
                    _selectedXSLFile = null; //set to null so setter is not called when user Browses.
                    XSLFiles.Insert(0, browsedFile); //insert new file to start of collection.
                    SetProperty(ref _selectedXSLFile, browsedFile, () => SelectedXSL);
                }
                else
                    SetProperty(ref _selectedXSLFile, value, () => SelectedXSL);
                ApplyTransform();
            }
        }
        #endregion

        ///
        /// Applies the transform to view the metadata in a browser control
        ///

        public void ApplyTransform()
        {
            if (SelectedXSL == null)
                return;
            if (this.ItemInformation == null)
                return;

            if (!string.IsNullOrEmpty(this.ItemInformation.XML))
            {
                WebPage = ItemMetadata.TransformXML(ItemInformation.XML, SelectedXSL.FileFullName);
            }
        }
        //Browse for a new stylesheet
        private XSLFile BrowseFileName()
        {
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            dlg.DefaultExt = ".xslt";
            dlg.Filter = ("Stylesheets (*.xslt;*xsl)|*.xslt;*xsl");
            if (dlg.ShowDialog() == true)
            {
                var browsedXSLFile = new XSLFile(dlg.FileName);
                return browsedXSLFile;
            }
            else //user cancelled
            {
                return null;
            }
        }
    }

    ///
    /// Button implementation to show the DockPane.
    ///
    internal class Dockpane1_ShowButton : Button
    {
        protected override void OnClick()
        {
            MetadataBrowserViewModel.Show();
        }
    }
}


text:
Write tests to prevent regressions and write better code.

## Userspace

It's generally recommended to test your application without tying the tests too closely to MUI.
This is how MUI components are tested internally.
A library that has a first-class API for this approach is [`@testing-library/react`](https://testing-library.com/docs/react-testing-library/intro/).

For example, when rendering a `TextField` your test should not need to query for the specific MUI instance of the `TextField` but rather for the `input`, or `[role="textbox"]`.

By not relying on the React component tree you make your test more robust against internal changes in MUI or, if you need snapshot testing, adding additional wrapper components such as context providers.
We don't recommend snapshot testing though.
["Effective snapshot testing" by Kent C. Dodds](https://kentcdodds.com/blog/effective-snapshot-testing) goes into more details why snapshot testing might be misleading for React component tests.

## Internal

MUI has **a wide range** of tests so we can
iterate with confidence on the components, for instance, the visual regression tests provided by [Argos-CI](https://www.argos-ci.com/mui/material-ui/builds) have proven to be really helpful.
To learn more about the internal tests, you can have a look at the [README](https://github.com/mui/material-ui/blob/HEAD/test/README.md).


text:
A linear algebra package for small matrices and vectors.

## Motivation

There are a lot of matrix libraries that deal with large n-dimensional matrices. Although they may work for small matrices as well, there are some optimizations that can be made if you know ahead of time what dimensions you're working with.

This library was primarily motivated by a 2D algebraic geometry library, curve2d, which uses projective geometry to calculate intersections with conics. The work is primarily 2x2 and 3x3 matrices. However, this library can be used in other applications, such as computer vision.

# Tests

The tests are runnable documentation.

Tests can be run in the terminal:

- Enter `npm test`.

The npm browser script builds the project and wraps it so that the tests can run. For the changes in the project to be reflected in the tests, the browser script must be re-run.

## Author

(c) Tim Bright, 2017.

This library has been influenced by the various authors of the THREE.js math functions. Attributions of their individual contributions are given in the various source files.

## License

MIT License

Copyright (c) 2017 Tim Bright

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.


text:
package org.kie.workbench.common.screens.datamodeller.client.widgets.packageselector;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.enterprise.context.Dependent;
import javax.inject.Inject;

import com.google.gwt.user.client.ui.IsWidget;
import com.google.gwt.user.client.ui.Widget;
import org.kie.workbench.common.screens.datamodeller.client.DataModelerContext;
import org.kie.workbench.common.screens.datamodeller.client.util.DataModelerUtils;
import org.kie.workbench.common.screens.datamodeller.client.util.UIUtil;
import org.uberfire.commons.data.Pair;
import org.uberfire.mvp.Command;

@Dependent
public class PackageSelector
        implements
        PackageSelectorView.Presenter,
        IsWidget {

    private DataModelerContext context;

    private List<String> packageList = new ArrayList<String>(  );

    private PackageSelectorView view;

    private List<PackageSelectorView.PackageSelectorHandler> handlers = new ArrayList<PackageSelectorView.PackageSelectorHandler>(  );

    @Inject
    public PackageSelector( PackageSelectorView view ) {
        this.view = view;
        view.init( this );
    }

    @Override
    public Widget asWidget() {
        return view.asWidget();
    }

    @Override
    public void onPackageChange() {
        handlePackageChange( view.getPackage() );
    }

    @Override
    public void onNewPackage() {
        view.showNewPackagePopup( new Command() {
            @Override
            public void execute() {
                doPackageAdded( view.getNewPackage() );
            }
        } );
    }

    private void doPackageAdded( String newPackage ) {
        final String newPackageName = DataModelerUtils.trim( newPackage );
        if ( newPackageName != null && !"".equals( newPackageName ) ) {
            boolean exists = packageList.contains( newPackageName );
            if ( exists ) {
                view.setPackage( newPackageName );
            } else {
                view.addToPackageList( newPackageName, true );
            }
            if ( context != null ) {
                context.appendPackage( newPackageName.trim() );
            }
        }
        handlePackageAdded( newPackageName );
    }

    private void handlePackageAdded( final String packageName ) {
        for ( PackageSelectorView.PackageSelectorHandler handler : handlers ) {
            handler.onPackageAdded( packageName );
        }
    }
    private void handlePackageChange( String packageName ) {
        for ( PackageSelectorView.PackageSelectorHandler handler : handlers ) {
            handler.onPackageChange( packageName );
        }
    }

    public void enableCreatePackage( boolean enable ) {
        view.enableCreatePackage( enable );
    }

    public void setEnabled( boolean enabled ) {
        view.setEnabled( enabled );
    }

    public boolean isValueSelected() {
        String currentPackage = DataModelerUtils.trim( view.getPackage() );
        return currentPackage != null && !"".equals( currentPackage ) && !UIUtil.NOT_SELECTED.equals( currentPackage );
    }

    public String getPackage() {
        return view.getPackage();
    }

    public String getNewPackage() {
        return view.getNewPackage();
    }

    public DataModelerContext getContext() {
        return context;
    }

    public void setContext( DataModelerContext context ) {
        this.context = context;
        initList( null, true );
    }

    public void setCurrentPackage( String currentPackage ) {
        boolean enableEmptyPackageOption = false;

        if ( currentPackage == null || "".equals( currentPackage ) ) {
            enableEmptyPackageOption = true;
            currentPackage = UIUtil.NOT_SELECTED;
        }
        initList( currentPackage, enableEmptyPackageOption );
    }

    public void clear() {
        view.initPackageList( new ArrayList<Pair<String, String>>(), null, true );
    }

    public void addPackageSelectorHandler( PackageSelectorView.PackageSelectorHandler handler ) {
        if ( !handlers.contains( handler ) ) {
            handlers.add( handler );
        }
    }

    private void initList( String currentPackage, boolean enableEmptyPackageOption ) {
        packageList.clear();

        if ( context != null && context.getCurrentProjectPackages() != null ) {
            for ( String packageName : context.getCurrentProjectPackages() ) {
                packageList.add( packageName );
            }
        }

        if ( currentPackage != null && !packageList.contains( currentPackage ) ) {
            packageList.add( currentPackage );
        }

        Collections.sort( packageList );

        List<Pair<String, String>> packageOptions = new ArrayList<Pair<String, String>>( packageList.size() );
        for ( String packageName : packageList ) {
            packageOptions.add( new Pair<String, String>( packageName, packageName ) );
        }

        view.initPackageList( packageOptions, currentPackage, enableEmptyPackageOption );
    }
}


text:
require.config({
    baseUrl: 'src/main/public/static/js',
    paths: {
        'jasmine-jquery': '../bower_components/jasmine-jquery/lib/jasmine-jquery',
        'js-testing': '../bower_components/hp-autonomy-js-testing-utils/src/js',
        'mock': '../../../../test/js/mock'
    },
    shim: {
        'jasmine-jquery': ['jquery']
    },
    map: {
        '*': {
            'find/app/configuration': 'mock/configuration',
            'find/app/router': 'mock/router',
            'find/app/vent': 'mock/vent',
            'find/app/util/database-name-resolver': 'mock/database-name-resolver',
            'find/lib/backbone/backbone-extensions': 'backbone',
            'find/app/util/confirm-view': 'mock/util/confirm-view',
            'find/app/model/comparisons/comparison-model': 'mock/model/comparisons/comparison-model',
            'find/app/page/search/document/location-tab': 'mock/page/search/document/location-tab',
            'find/app/util/topic-map-view': 'mock/util/topic-map-view'
        },
        'find/app/page/search/service-view': {
            'find/app/model/indexes-collection': 'mock/model/indexes-collection'
        },
        'find/app/page/search/related-concepts/related-concepts-view': {
            'find/app/model/documents-collection': 'mock/model/documents-collection'
        }
    }
});


text:
// Copyright 2012 Cloudera Inc.
//
// 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.

package com.cloudera.recordservice.avro.mapreduce;

import java.io.IOException;

import org.apache.avro.Schema;
import org.apache.avro.mapred.AvroKey;
import org.apache.avro.mapreduce.AvroJob;
import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.classification.InterfaceStability;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.mapreduce.InputSplit;
import org.apache.hadoop.mapreduce.RecordReader;
import org.apache.hadoop.mapreduce.TaskAttemptContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.cloudera.recordservice.avro.GenericRecords;
import com.cloudera.recordservice.avro.RecordIterator;
import com.cloudera.recordservice.avro.RecordUtil;
import com.cloudera.recordservice.avro.SchemaUtils;
import com.cloudera.recordservice.avro.SpecificRecords;
import com.cloudera.recordservice.core.RecordServiceException;
import com.cloudera.recordservice.mapreduce.RecordServiceInputFormatBase;

/**
 * Input format which provides identical functionality to
 * org.apache.mapreduce.AvroKeyInputFormat
 */
@InterfaceAudience.Public
@InterfaceStability.Evolving
public class AvroKeyInputFormat<T> extends
    RecordServiceInputFormatBase<AvroKey<T>, NullWritable> {

  private static final Logger LOG = LoggerFactory.getLogger(AvroKeyInputFormat.class);

  @Override
  public RecordReader<AvroKey<T>, NullWritable> createRecordReader(
      InputSplit split, TaskAttemptContext context)
      throws IOException, InterruptedException {
    Schema readerSchema = AvroJob.getInputKeySchema(context.getConfiguration());
    if (null == readerSchema) {
      LOG.warn("Reader schema was not set. Use AvroJob.setInputKeySchema() if desired.");
      LOG.info("Using a reader schema equal to the writer schema.");
      LOG.info("Using GenericRecords instead of SpecificRecords.");
    }
    return new AvroKeyRecordReader<T>(readerSchema);
  }

  private static class AvroKeyRecordReader<T>
      extends RecordReaderBase<AvroKey<T>, NullWritable> {
    // The schema of the returned records.
    private final Schema avroSchema_;

    // A reusable object to hold the current record.
    private final AvroKey<T> mCurrentRecord;

    // Records to return.
    private RecordIterator<T> records_;

    /**
     * Constructor.
     */
    public AvroKeyRecordReader(Schema schema) {
      avroSchema_ = schema;
      mCurrentRecord = new AvroKey<T>(null);
    }

    /** {@inheritDoc} */
    @Override
    public boolean nextKeyValue() throws IOException, InterruptedException {
      try {
        if (!records_.hasNext()) return false;
        mCurrentRecord.datum(records_.next());
        return true;
      } catch (RecordServiceException e) {
        throw new IOException("Could not fetch record.", e);
      }
    }

    /** {@inheritDoc} */
    @Override
    public AvroKey<T> getCurrentKey() throws IOException, InterruptedException {
      return mCurrentRecord;
    }

    /** {@inheritDoc} */
    @Override
    public NullWritable getCurrentValue() throws IOException, InterruptedException {
      return NullWritable.get();
    }

    @SuppressWarnings({ "rawtypes", "unchecked" })
    @Override
    public void initialize(InputSplit inputSplit, TaskAttemptContext context)
        throws IOException {
      super.initialize(inputSplit, context);
      if (SchemaUtils.isSpecificRecordSchema(avroSchema_)) {
        records_ = new SpecificRecords(avroSchema_, reader_.records(),
            RecordUtil.ResolveBy.NAME);
      } else {
        records_ = (RecordIterator<T>)new GenericRecords(reader_.records());
      }
    }
  }
}


text:
import {TemplatePortal} from '../core/portal/portal';
import {
  ViewContainerRef, Input, TemplateRef, ViewChild, OnInit, ContentChild,
  Component
} from '@angular/core';
import {coerceBooleanProperty} from '../core/coercion/boolean-property';

import {MdTabLabel} from './tab-label';

@Component({
  moduleId: module.id,
  selector: 'md-tab, mat-tab',
  templateUrl: 'tab.html',
})
export class MdTab implements OnInit {
  /** Content for the tab label given by <ng-template md-tab-label>. */
  @ContentChild(MdTabLabel) templateLabel: MdTabLabel;

  /** Template inside the MdTab view that contains an <ng-content>. */
  @ViewChild(TemplateRef) _content: TemplateRef<any>;

  /** The plain text label for the tab, used when there is no template label. */
  @Input('label') textLabel: string = '';

  /** The portal that will be the hosted content of the tab */
  private _contentPortal: TemplatePortal = null;
  get content(): TemplatePortal { return this._contentPortal; }

  /**
   * The relatively indexed position where 0 represents the center, negative is left, and positive
   * represents the right.
   */
  position: number = null;

  /**
   * The initial relatively index origin of the tab if it was created and selected after there
   * was already a selected tab. Provides context of what position the tab should originate from.
   */
  origin: number = null;

  private _disabled = false;

  /** Whether the tab is disabled */
  @Input()
  set disabled(value: boolean) { this._disabled = coerceBooleanProperty(value); }
  get disabled(): boolean { return this._disabled; }

  constructor(private _viewContainerRef: ViewContainerRef) { }

  ngOnInit() {
    this._contentPortal = new TemplatePortal(this._content, this._viewContainerRef);
  }
}


text:
package org.dynmap.web;

import org.dynmap.ConfigurationNode;

import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class CustomHeaderFilter implements Filter {
    private final ConfigurationNode custhttp;
    public CustomHeaderFilter(ConfigurationNode configuration) {
        this.custhttp = configuration;
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse resp = (HttpServletResponse) response;

        if (custhttp != null) {
            for (String k : custhttp.keySet()) {
                String v = custhttp.getString(k);
                if (v != null) {
                    resp.setHeader(k, v);
                }
            }
        }

        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
    }
}


text:
{% extends "layout.html" %}

{% block body %}

Launchpad Bugs Summary Reports

          This service allows to get information about current status of projects:
            main information, bugs' statistic.

          Just select interest project.

                      Project
                      Total Critical Unresolved Bugs
                      Total Unresolved Bugs
                      Total Number of Bugs

            {% for p in prs %}

{{p}}

                {{ statistic[p]["critical"] }}
                {{ statistic[p]["unresolved"] }}
                {{ statistic[p]["total"] }}

            {% endfor %}

{% endblock %}


text:
function [mot_new, translations] = skelfitOptT2( motC3D, fromFrame, toFrame, noDisplay )

if nargin < 2
    fromFrame = 1;
end
if nargin < 3
    toFrame = motC3D.nframes;
end
if nargin < 4
    noDisplay = false;
end

boneLengths = calculateBoneLengths(motC3D);
skelTree = buildSkelTree(motC3D.nameMap);

mot_new = motC3D;
mot_new.jointTrajectories = [];
mot_new.nframes = toFrame - fromFrame + 1;
nJoints = length(motC3D.jointTrajectories);

idxLtoes = strmatch('ltoes', motC3D.nameMap(:,1));
idxLankle = strmatch('lankle', motC3D.nameMap(:,1));

if ~noDisplay
    disp('frame ');
end

warning off;
for i=fromFrame:toFrame

    if ~noDisplay
        if i==1
            disp( [char(8) num2str(i)] );
        else
            disp([repmat(char(8),1,length(num2str(i-1))+1) num2str(i)]);
        end
    end

    [skelFrame, translations(:,i)] = skelfitFrame(motC3D, boneLengths, skelTree, i, idxLtoes, idxLankle);

    for j=1:nJoints
        mot_new.jointTrajectories{j,1}(:,i-fromFrame+1) = skelFrame{j};
    end

end
warning on;


text:
python code.py
start chrome localhost:8080


text:
layout: post
unique_id: big_demo
title: Big Demo
categories: []
locations:
---

YESTERDAY:
* big demo!
  * 9 hours including dinner
* amazing learnings
* farewell to an employee for now
* massive accident on 101, slowdown
* ended up late to dinner I was hosting
* caught up with an old Medallia gang!
* diablo 3

TODAY:
* interview!
* delicious salmon by Jackie for dinner
* leftover baos
* ordered xmas gifts for parents
* also, a visit from Becca
  * drop off at Caltrain

LEARNINGS:
* bun bao is pretty good


text:
namespace huys
{

namespace layout
{

typedef huys::ADT::UVector<UControl *> UControlVec;

class ULIB_API ULayout
{
public:
    ULayout();

    virtual ~ULayout()= 0; /// Implement must be supplied, or link error.

    BOOL addControl(UControl *pCtrl);
    BOOL addControls(UControl **p, int n);
    virtual BOOL go() = 0;

    void setRect(const LPRECT lpRect)
    {
        m_rect = lpRect;
    }

    void setRect(int x, int y, int w, int h)
    {
        m_rect.set(x, y, w, h);
    }
protected:
    huys::URectL m_rect;
    UControlVec m_ctrls;
};

class ULIB_API UHBoxLayout : public ULayout
{
public:
    UHBoxLayout();
    virtual ~UHBoxLayout();
    virtual BOOL go();
private:
};

class ULIB_API UVBoxLayout : public ULayout
{
public:
    UVBoxLayout();
    virtual ~UVBoxLayout();
    virtual BOOL go();
private:
};

class ULIB_API UGridLayout : public ULayout
{
public:
    UGridLayout(int nx = 2, int ny = 2);
    virtual ~UGridLayout();
    virtual BOOL go();
private:
    int nXNum;
    int nYNum;
};

}; // namespace layout

}; // namespace huys

#endif // U_LAYOUT_H


text:
include("clang/gdal_cdefs.jl")
include("clang/gdal_cfuns.jl")

include("gdal/type.jl")
include("gdal/utilities.jl")
include("gdal/drivers.jl")
include("gdal/fileio.jl") # depends: drivers.jl
include("gdal/dataset.jl")
include("gdal/rasterband.jl") # depends: gdal_type.jl
include("gdal/gcp.jl")
include("gdal/color.jl")
include("gdal/statistics.jl")


text:
<?php
return array (
  'Admin Account' => 'Cuenta de administrador',
  'You\'re almost done. In the last step you have to fill out the form to create an admin account. With this account you can manage the whole network.' => '¡Ya casi has acabado! En el último paso necesitarás rellenar un formulario para crear una cuenta de administrador. Con esta cuenta podrás administrar la red entera.',
);


text:
package org.apache.nifi.confluent.schemaregistry;

import org.apache.nifi.annotation.documentation.CapabilityDescription;
import org.apache.nifi.annotation.documentation.Tags;
import org.apache.nifi.annotation.lifecycle.OnEnabled;
import org.apache.nifi.components.PropertyDescriptor;
import org.apache.nifi.components.ValidationContext;
import org.apache.nifi.components.ValidationResult;
import org.apache.nifi.confluent.schemaregistry.client.CachingSchemaRegistryClient;
import org.apache.nifi.confluent.schemaregistry.client.RestSchemaRegistryClient;
import org.apache.nifi.confluent.schemaregistry.client.SchemaRegistryClient;
import org.apache.nifi.context.PropertyContext;
import org.apache.nifi.controller.AbstractControllerService;
import org.apache.nifi.controller.ConfigurationContext;
import org.apache.nifi.processor.util.StandardValidators;
import org.apache.nifi.schema.access.SchemaField;
import org.apache.nifi.schema.access.SchemaNotFoundException;
import org.apache.nifi.schemaregistry.services.SchemaRegistry;
import org.apache.nifi.serialization.record.RecordSchema;
import org.apache.nifi.serialization.record.SchemaIdentifier;
import org.apache.nifi.ssl.SSLContextService;
import org.apache.nifi.ssl.SSLContextService.ClientAuth;

import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumSet;
import java.util.List;
import java.util.Optional;
import java.util.OptionalLong;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Tags({"schema", "registry", "confluent", "avro", "kafka"})
@CapabilityDescription("Provides a Schema Registry that interacts with the Confluent Schema Registry so that those Schemas that are stored in the Confluent Schema "
    + "Registry can be used in NiFi. The Confluent Schema Registry has a notion of a \"subject\" for schemas, which is their terminology for a schema name. When a Schema "
    + "is looked up by name by this registry, it will find a Schema in the Confluent Schema Registry with that subject.")
public class ConfluentSchemaRegistry extends AbstractControllerService implements SchemaRegistry {

    private static final Set<SchemaField> schemaFields = EnumSet.of(SchemaField.SCHEMA_NAME, SchemaField.SCHEMA_TEXT,
        SchemaField.SCHEMA_TEXT_FORMAT, SchemaField.SCHEMA_IDENTIFIER, SchemaField.SCHEMA_VERSION);

    static final PropertyDescriptor SCHEMA_REGISTRY_URLS = new PropertyDescriptor.Builder()
        .name("url")
        .displayName("Schema Registry URLs")
        .description("A comma-separated list of URLs of the Schema Registry to interact with")
        .expressionLanguageSupported(true)
        .defaultValue("http://localhost:8081")
        .required(true)
        .addValidator(new MultipleURLValidator())
        .build();

    static final PropertyDescriptor SSL_CONTEXT = new PropertyDescriptor.Builder()
        .name("ssl-context")
        .displayName("SSL Context Service")
        .description("Specifies the SSL Context Service to use for interacting with the Confluent Schema Registry")
        .identifiesControllerService(SSLContextService.class)
        .required(false)
        .build();

    static final PropertyDescriptor CACHE_SIZE = new PropertyDescriptor.Builder()
        .name("cache-size")
        .displayName("Cache Size")
        .description("Specifies how many Schemas should be cached from the Schema Registry")
        .addValidator(StandardValidators.NON_NEGATIVE_INTEGER_VALIDATOR)
        .defaultValue("1000")
        .required(true)
        .build();

    static final PropertyDescriptor CACHE_EXPIRATION = new PropertyDescriptor.Builder()
        .name("cache-expiration")
        .displayName("Cache Expiration")
        .description("Specifies how long a Schema that is cached should remain in the cache. Once this time period elapses, a "
            + "cached version of a schema will no longer be used, and the service will have to communicate with the "
            + "Schema Registry again in order to obtain the schema.")
        .addValidator(StandardValidators.TIME_PERIOD_VALIDATOR)
        .defaultValue("1 hour")
        .required(true)
        .build();

    static final PropertyDescriptor TIMEOUT = new PropertyDescriptor.Builder()
        .name("timeout")
        .displayName("Communications Timeout")
        .description("Specifies how long to wait to receive data from the Schema Registry before considering the communications a failure")
        .addValidator(StandardValidators.TIME_PERIOD_VALIDATOR)
        .expressionLanguageSupported(false)
        .defaultValue("30 secs")
        .required(true)
        .build();

    private volatile SchemaRegistryClient client;

    @Override
    protected List<PropertyDescriptor> getSupportedPropertyDescriptors() {
        final List<PropertyDescriptor> properties = new ArrayList<>();
        properties.add(SCHEMA_REGISTRY_URLS);
        properties.add(SSL_CONTEXT);
        properties.add(TIMEOUT);
        properties.add(CACHE_SIZE);
        properties.add(CACHE_EXPIRATION);
        return properties;
    }

    @OnEnabled
    public void onEnabled(final ConfigurationContext context) {
        final List<String> baseUrls = getBaseURLs(context);
        final int timeoutMillis = context.getProperty(TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue();

        final SSLContext sslContext;
        final SSLContextService sslContextService = context.getProperty(SSL_CONTEXT).asControllerService(SSLContextService.class);
        if (sslContextService == null) {
            sslContext = null;
        } else {
            sslContext = sslContextService.createSSLContext(ClientAuth.REQUIRED);
        }

        final SchemaRegistryClient restClient = new RestSchemaRegistryClient(baseUrls, timeoutMillis, sslContext, getLogger());

        final int cacheSize = context.getProperty(CACHE_SIZE).asInteger();
        final long cacheExpiration = context.getProperty(CACHE_EXPIRATION).asTimePeriod(TimeUnit.NANOSECONDS).longValue();

        client = new CachingSchemaRegistryClient(restClient, cacheSize, cacheExpiration);
    }

    @Override
    protected Collection<ValidationResult> customValidate(final ValidationContext validationContext) {
        final boolean sslContextSet = validationContext.getProperty(SSL_CONTEXT).isSet();
        if (sslContextSet) {
            final List<String> baseUrls = getBaseURLs(validationContext);
            final List<String> insecure = baseUrls.stream()
                .filter(url -> !url.startsWith("https"))
                .collect(Collectors.toList());

            if (!insecure.isEmpty()) {
                return Collections.singleton(new ValidationResult.Builder()
                    .subject(SCHEMA_REGISTRY_URLS.getDisplayName())
                    .input(insecure.get(0))
                    .valid(false)
                    .explanation("When SSL Context is configured, all Schema Registry URL's must use HTTPS, not HTTP")
                    .build());
            }
        }

        return Collections.emptyList();
    }

    private List<String> getBaseURLs(final PropertyContext context) {
        final String urls = context.getProperty(SCHEMA_REGISTRY_URLS).evaluateAttributeExpressions().getValue();
        final List<String> baseUrls = Stream.of(urls.split(","))
            .map(url -> url.trim())
            .collect(Collectors.toList());

        return baseUrls;
    }

    private RecordSchema retrieveSchemaByName(final SchemaIdentifier schemaIdentifier) throws IOException, SchemaNotFoundException {
        final Optional<String> schemaName = schemaIdentifier.getName();
        if (!schemaName.isPresent()) {
            throw new org.apache.nifi.schema.access.SchemaNotFoundException("Cannot retrieve schema because Schema Name is not present");
        }

        final RecordSchema schema = client.getSchema(schemaName.get());
        return schema;
    }

    private RecordSchema retrieveSchemaById(final SchemaIdentifier schemaIdentifier) throws IOException, SchemaNotFoundException {
        final OptionalLong schemaId = schemaIdentifier.getIdentifier();
        if (!schemaId.isPresent()) {
            throw new org.apache.nifi.schema.access.SchemaNotFoundException("Cannot retrieve schema because Schema Id is not present");
        }

        final RecordSchema schema = client.getSchema((int) schemaId.getAsLong());
        return schema;
    }

    @Override
    public RecordSchema retrieveSchema(final SchemaIdentifier schemaIdentifier) throws IOException, SchemaNotFoundException {
        if (schemaIdentifier.getName().isPresent()) {
            return retrieveSchemaByName(schemaIdentifier);
        } else {
            return retrieveSchemaById(schemaIdentifier);
        }
    }

    @Override
    public Set<SchemaField> getSuppliedSchemaFields() {
        return schemaFields;
    }
}


text:
.. This file is part of the OpenDSA eTextbook project. See
.. http://algoviz.org/OpenDSA for more details.
.. Copyright (c) 2012-2013 by the OpenDSA Project Contributors, and
.. distributed under an MIT open source license.

.. avmetadata::
   :author: Cliff Shaffer
   :prerequisites:
   :topic: Memory Management

Sequential Fit Peformance
=========================

Which sequential fit strategy is best depends on the expected types of
memory requests.
If the requests are of widely ranging size, best fit might work well.
If the requests tend to be of similar size, with rare large and small
requests, first or worst fit might work well.
Unfortunately, there are always request patterns that one of the
three sequential fit methods will service, but which the other two
will not be able to service.
For example, if the series of requests 600, 650, 900, 500, 100 is
made to a freelist containing blocks 500, 700, 650, 900
(in that order),
the requests can all be serviced by first fit, but not by best fit.
Alternatively, the series of requests 600, 500, 700, 900 can be
serviced by best fit but not by first fit on this same freelist.

.. avembed:: AV/Development/firstFit.html ss


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  Copyright 2022 The Android Open Source Project

  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.
   -->

<resources xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
    <!-- no translation found for emoji_category_recent (7142376595414250279) -->
    <skip />
    <string name="emoji_category_emotions" msgid="1570830970240985537">"SMILEY DAN EMOSI"</string>
    <string name="emoji_category_people" msgid="7968173366822927025">"ORANG"</string>
    <string name="emoji_category_animals_nature" msgid="4640771324837307541">"HAIWAN DAN ALAM SEMULA JADI"</string>
    <string name="emoji_category_food_drink" msgid="1189971856721244395">"MAKANAN DAN MINUMAN"</string>
    <string name="emoji_category_travel_places" msgid="8105712773237012672">"PERJALANAN DAN TEMPAT"</string>
    <string name="emoji_category_activity" msgid="4381135114947330911">"AKTIVITI DAN ACARA"</string>
    <string name="emoji_category_objects" msgid="6106115586332708067">"OBJEK"</string>
    <string name="emoji_category_symbols" msgid="5626171724310261787">"SIMBOL"</string>
    <string name="emoji_category_flags" msgid="6185639503532784871">"BENDERA"</string>
    <string name="emoji_empty_non_recent_category" msgid="288822832574892625">"Tiada emoji tersedia"</string>
    <string name="emoji_empty_recent_category" msgid="7863877827879290200">"Anda belum menggunakan mana-mana emoji lagi"</string>
</resources>


text:
package eu.ydp.empiria.player.client.module.dictionary.external.model;

public class Entry {

    private final String entry;
    private final String entryDescription;
    private final String type;
    private final String entryExample;
    private final String entrySound;
    private final String entryExampleSound;
    private final String label;

    Entry(String entry, String entryDescription, String type, String entryExample, String entrySound, String entryExampleSound, String label) {
        this.entry = entry;
        this.entryDescription = entryDescription;
        this.type = type;
        this.entryExample = entryExample;
        this.entrySound = entrySound;
        this.entryExampleSound = entryExampleSound;
        this.label = label;
    }

    public String getEntry() {
        return entry;
    }

    public String getEntryDescription() {
        return entryDescription;
    }

    public String getType() {
        return type;
    }

    public String getEntryExample() {
        return entryExample;
    }

    public String getEntrySound() {
        return entrySound;
    }

    public String getEntryExampleSound() {
        return entryExampleSound;
    }

    public String getLabel() {
        return label;
    }
}


text:
"""Tests for wiki2gfm."""
import codecs
import StringIO
import unittest

from impl import converter
from impl import formatting_handler
from impl import pragma_handler

class BaseTest(unittest.TestCase):
  """Base test for wiki2gfm tests."""

  def setUp(self):
    """Create a base test."""
    self.warnings = []
    self.output = StringIO.StringIO()

    self.pragma_handler = pragma_handler.PragmaHandler(self._TrackWarning)
    self.formatting_handler = formatting_handler.FormattingHandler(
        self._TrackWarning,
        project="test",
        issue_map={123: "https://github.com/abcxyz/test/issues/789"},
        symmetric_headers=False)
    self.converter = converter.Converter(
        self.pragma_handler,
        self.formatting_handler,
        self._TrackWarning,
        project="test",
        wikipages=["TestPage"])

  def assertOutput(self, expected_output):
    """Assert that specific output was written.

    Args:
        expected_output: The expected value of the output.
    """
    self.assertEquals(expected_output, self.output.getvalue())

  def assertNoOutput(self, expected_output):
    self.assertNotEqual(expected_output, self.output.getvalue())

  def assertWarning(self, warning_contents, occurrences=1):
    """Assert that a warning was issued containing the given contents.

    This searches all tracked warnings for the contents.

    Args:
        warning_contents: Text that the warning was expected to contain.
        occurrences: The number of occurrences of the warning contents.
    """
    occurrences_found = 0
    for warning in self.warnings:
      if warning_contents in warning[1]:
        occurrences_found += 1

    if occurrences_found != occurrences:
      self.fail("Failed to find '{0}' in {1} warnings (found it in {2})."
                .format(warning_contents, occurrences, occurrences_found))

  def assertNoWarnings(self):
    """Assert that no warnings were issued."""
    self.assertListEqual([], self.warnings)

  def _TrackWarning(self, input_line, message):
    """Track a warning by storing it in memory.

    Args:
      input_line: Line the warning was issued on.
      message: The warning message.
    """
    self.warnings.append((input_line, message))

class TestPragmaHandler(BaseTest):
  """Tests the pragma handler."""

  def testSummaryPragmaGivesWarning(self):
    self.pragma_handler.HandlePragma(1, self.output, "summary", "abc")

    self.assertWarning("summary")

  def testSidebarPragmaGivesWarning(self):
    self.pragma_handler.HandlePragma(1, self.output, "sidebar", "abc")

    self.assertWarning("sidebar")

  def testUnknownPragmaGivesWarning(self):
    self.pragma_handler.HandlePragma(1, self.output, "fail!", "abc")

    self.assertWarning("fail!")

class TestFormattingHandler(BaseTest):
  """Tests the formatting handler."""

  def testHandleHeaderOpen(self):
    self.formatting_handler.HandleHeaderOpen(1, self.output, 3)

    self.assertOutput("### ")
    self.assertNoWarnings()

  def testHandleHeaderOpenInHtml(self):
    self.formatting_handler._in_html = 1
    self.formatting_handler.HandleHeaderOpen(1, self.output, 3)

    self.assertOutput("
")
    self.assertNoWarnings()

  def testHandleHeaderClose(self):
    self.formatting_handler.HandleHeaderClose(1, self.output, 3)

    self.assertOutput("")  # No header closing markup by default.
    self.assertNoWarnings()

  def testHandleHeaderCloseInHtml(self):
    self.formatting_handler._in_html = 1
    self.formatting_handler.HandleHeaderClose(1, self.output, 3)

    self.assertOutput("
")
    self.assertNoWarnings()

  def testHandleHeaderCloseSymmetric(self):
    self.formatting_handler._symmetric_headers = True
    self.formatting_handler.HandleHeaderClose(1, self.output, 3)

    self.assertOutput(" ###")
    self.assertNoWarnings()

  def testHandleHeaderCloseSymmetricInHtml(self):
    self.formatting_handler._in_html = 1
    self.formatting_handler._symmetric_headers = True
    self.formatting_handler.HandleHeaderClose(1, self.output, 3)

    self.assertOutput("
")
    self.assertNoWarnings()

  def testHandleHRule(self):
    self.formatting_handler.HandleHRule(1, self.output)

    self.assertOutput("\n---\n")
    self.assertNoWarnings()

  def testHandleHRuleInHtml(self):
    self.formatting_handler._in_html = 1
    self.formatting_handler.HandleHRule(1, self.output)

    self.assertOutput("
")
    self.assertNoWarnings()

  def testHandleCodeBlockOpen(self):
    self.formatting_handler.HandleCodeBlockOpen(1, self.output, None)

    self.assertOutput("```\n")
    self.assertNoWarnings()

  def testHandleCodeBlockOpenInHtml(self):
    self.formatting_handler._in_html = 1
    self.formatting_handler.HandleCodeBlockOpen(1, self.output, None)

    self.assertOutput("<pre><code>")
    self.assertWarning("Code markup was used")

  def testHandleCodeBlockOpenWithLanguage(self):
    self.formatting_handler.HandleCodeBlockOpen(1, self.output, "idris")

    self.assertOutput("```idris\n")
    self.assertNoWarnings()

  def testHandleCodeBlockOpenWithLanguageInHtml(self):
    self.formatting_handler._in_html = 1
    self.formatting_handler.HandleCodeBlockOpen(1, self.output, "idris")

    self.assertOutput("
")
    self.assertWarning("Code markup was used")

  def testHandleCodeBlockClose(self):
    self.formatting_handler.HandleCodeBlockClose(1, self.output)

    self.assertOutput("```")
    self.assertNoWarnings()

  def testHandleCodeBlockCloseInHtml(self):
    self.formatting_handler._in_html = 1
    self.formatting_handler.HandleCodeBlockClose(1, self.output)

    self.assertOutput("
")
    self.assertNoWarnings()

  def testHandleNumericList(self):
    self.formatting_handler.HandleNumericListOpen(1, self.output, 1)
    self.formatting_handler.HandleText(1, self.output, "a\n")
    self.formatting_handler.HandleNumericListOpen(2, self.output, 1)
    self.formatting_handler.HandleText(2, self.output, "b\n")
    self.formatting_handler.HandleNumericListOpen(3, self.output, 2)
    self.formatting_handler.HandleText(3, self.output, "c\n")
    self.formatting_handler.HandleListClose(4, self.output)  # Closing 2.
    self.formatting_handler.HandleNumericListOpen(4, self.output, 1)
    self.formatting_handler.HandleText(4, self.output, "d\n")
    self.formatting_handler.HandleListClose(5, self.output)  # Closing 1.

    self.assertOutput("  1. a\n  1. b\n    1. c\n  1. d\n")
    self.assertNoWarnings()

  def testHandleNumericListInHtml(self):
    self.formatting_handler._in_html = 1
    self.formatting_handler.HandleNumericListOpen(1, self.output, 1)
    self.formatting_handler.HandleText(1, self.output, "a\n")
    self.formatting_handler.HandleNumericListOpen(2, self.output, 1)
    self.formatting_handler.HandleText(2, self.output, "b\n")
    self.formatting_handler.HandleNumericListOpen(3, self.output, 2)
    self.formatting_handler.HandleText(3, self.output, "c\n")
    self.formatting_handler.HandleListClose(4, self.output)  # Closing 2.
    self.formatting_handler.HandleNumericListOpen(4, self.output, 1)
    self.formatting_handler.HandleText(4, self.output, "d\n")
    self.formatting_handler.HandleListClose(5, self.output)  # Closing 1.

    self.assertOutput("

a\n

b\n

c\n

"
                      "
d\n

")
    self.assertWarning("Numeric list markup was used", occurrences=2)

  def testHandleBulletList(self):
    self.formatting_handler.HandleBulletListOpen(1, self.output, 1)
    self.formatting_handler.HandleText(1, self.output, "a\n")
    self.formatting_handler.HandleBulletListOpen(2, self.output, 1)
    self.formatting_handler.HandleText(2, self.output, "b\n")
    self.formatting_handler.HandleBulletListOpen(3, self.output, 2)
    self.formatting_handler.HandleText(3, self.output, "c\n")
    self.formatting_handler.HandleListClose(4, self.output)  # Closing 2.
    self.formatting_handler.HandleBulletListOpen(4, self.output, 1)
    self.formatting_handler.HandleText(4, self.output, "d\n")
    self.formatting_handler.HandleListClose(5, self.output)  # Closing 1.

    self.assertOutput("  * a\n  * b\n    * c\n  * d\n")
    self.assertNoWarnings()

  def testHandleBulletListInHtml(self):
    self.formatting_handler._in_html = 1
    self.formatting_handler.HandleBulletListOpen(1, self.output, 1)
    self.formatting_handler.HandleText(1, self.output, "a\n")
    self.formatting_handler.HandleBulletListOpen(2, self.output, 1)
    self.formatting_handler.HandleText(2, self.output, "b\n")
    self.formatting_handler.HandleBulletListOpen(3, self.output, 2)
    self.formatting_handler.HandleText(3, self.output, "c\n")
    self.formatting_handler.HandleListClose(4, self.output)  # Closing 2.
    self.formatting_handler.HandleBulletListOpen(4, self.output, 1)
    self.formatting_handler.HandleText(4, self.output, "d\n")
    self.formatting_handler.HandleListClose(5, self.output)  # Closing 1.

    self.assertOutput("

a\n

b\n

c\n

"
                      "
d\n

")
    self.assertWarning("Bulleted list markup was used", occurrences=2)

  def testHandleBlockQuote(self):
    self.formatting_handler.HandleBlockQuoteOpen(1, self.output, 1)
    self.formatting_handler.HandleText(1, self.output, "a\n")
    self.formatting_handler.HandleBlockQuoteOpen(2, self.output, 1)
    self.formatting_handler.HandleText(2, self.output, "b\n")
    self.formatting_handler.HandleBlockQuoteOpen(3, self.output, 2)
    self.formatting_handler.HandleText(3, self.output, "c\n")
    self.formatting_handler.HandleListClose(4, self.output)  # Closing 2.
    self.formatting_handler.HandleBlockQuoteOpen(4, self.output, 1)
    self.formatting_handler.HandleText(4, self.output, "d\n")
    self.formatting_handler.HandleListClose(5, self.output)  # Closing 1.

    self.assertOutput("> a\n> b\n> > c\n\n> d\n")
    self.assertNoWarnings()

  def testHandleBlockQuoteInHtml(self):
    self.formatting_handler._in_html = 1
    self.formatting_handler.HandleBlockQuoteOpen(1, self.output, 1)
    self.formatting_handler.HandleText(1, self.output, "a\n")
    self.formatting_handler.HandleBlockQuoteOpen(2, self.output, 1)
    self.formatting_handler.HandleText(2, self.output, "b\n")
    self.formatting_handler.HandleBlockQuoteOpen(3, self.output, 2)
    self.formatting_handler.HandleText(3, self.output, "c\n")
    self.formatting_handler.HandleListClose(4, self.output)  # Closing 2.
    self.formatting_handler.HandleBlockQuoteOpen(4, self.output, 1)
    self.formatting_handler.HandleText(4, self.output, "d\n")
    self.formatting_handler.HandleListClose(5, self.output)  # Closing 1.

    self.assertOutput("
a\nb
\n
c\n
"
                      "d\n
")
    self.assertWarning("Blockquote markup was used", occurrences=2)

  def testHandleParagraphBreak(self):
    self.formatting_handler.HandleText(1, self.output, "a\n")
    self.formatting_handler.HandleParagraphBreak(2, self.output)
    self.formatting_handler.HandleText(3, self.output, "b\n")

    self.assertOutput("a\n\nb\n")
    self.assertNoWarnings()

  def testHandleParagraphBreakInHtml(self):
    self.formatting_handler._in_html = 1
    self.formatting_handler.HandleText(1, self.output, "a\n")
    self.formatting_handler.HandleParagraphBreak(2, self.output)
    self.formatting_handler.HandleText(3, self.output, "b\n")

    self.assertOutput("a\n
\nb
\n")
    self.assertNoWarnings()

  def testHandleBold(self):
    self.formatting_handler.HandleBoldOpen(1, self.output)
    self.formatting_handler.HandleText(2, self.output, "xyz")
    self.formatting_handler.HandleBoldClose(3, self.output)

    self.assertOutput("**xyz**")
    self.assertNoWarnings()

  def testHandleBoldInHtml(self):
    self.formatting_handler._in_html = 1
    self.formatting_handler.HandleBoldOpen(1, self.output)
    self.formatting_handler.HandleText(2, self.output, "xyz")
    self.formatting_handler.HandleBoldClose(3, self.output)

    self.assertOutput("xyz")
    self.assertWarning("Bold markup was used")

  def testHandleItalic(self):
    self.formatting_handler.HandleItalicOpen(1, self.output)
    self.formatting_handler.HandleText(2, self.output, "xyz")
    self.formatting_handler.HandleItalicClose(3, self.output)

    self.assertOutput("_xyz_")
    self.assertNoWarnings()

  def testHandleItalicInHtml(self):
    self.formatting_handler._in_html = 1
    self.formatting_handler.HandleItalicOpen(1, self.output)
    self.formatting_handler.HandleText(2, self.output, "xyz")
    self.formatting_handler.HandleItalicClose(3, self.output)

    self.assertOutput("xyz")
    self.assertWarning("Italic markup was used")

  def testHandleStrikethrough(self):
    self.formatting_handler.HandleStrikethroughOpen(1, self.output)
    self.formatting_handler.HandleText(2, self.output, "xyz")
    self.formatting_handler.HandleStrikethroughClose(3, self.output)

    self.assertOutput("~~xyz~~")
    self.assertNoWarnings()

  def testHandleStrikethroughInHtml(self):
    self.formatting_handler._in_html = 1
    self.formatting_handler.HandleStrikethroughOpen(1, self.output)
    self.formatting_handler.HandleText(2, self.output, "xyz")
    self.formatting_handler.HandleStrikethroughClose(3, self.output)

    self.assertOutput("xyz")
    self.assertWarning("Strikethrough markup was used")

  def testHandleSuperscript(self):
    self.formatting_handler.HandleSuperscript(1, self.output, "xyz")

    self.assertOutput("xyz")
    self.assertNoWarnings()

  def testHandleSuperscriptInHtml(self):
    self.formatting_handler._in_html = 1
    self.formatting_handler.HandleSuperscript(1, self.output, "xyz")

    self.assertOutput("xyz")
    self.assertNoWarnings()

  def testHandleSubscript(self):
    self.formatting_handler.HandleSubscript(1, self.output, "xyz")

    self.assertOutput("xyz")
    self.assertNoWarnings()

  def testHandleSubscriptInHtml(self):
    self.formatting_handler._in_html = 1
    self.formatting_handler.HandleSubscript(1, self.output, "xyz")

    self.assertOutput("xyz")
    self.assertNoWarnings()

  def testHandleInlineCode(self):
    self.formatting_handler.HandleInlineCode(1, self.output, "xyz")

    self.assertOutput("`xyz`")
    self.assertNoWarnings()

  def testHandleInlineCodeInHtml(self):
    self.formatting_handler._in_html = 1
    self.formatting_handler.HandleInlineCode(1, self.output, "xyz")

    self.assertOutput("xyz")
    self.assertNoWarnings()

  # Table handling is tested in the Converter tests,
  # as the interactions are multiple and handled there.

  def testHandleLink(self):
    self.formatting_handler.HandleLink(
        1, self.output, "http://example.com", None)

    self.assertOutput("http://example.com")
    self.assertNoWarnings()

  def testHandleLinkInHtml(self):
    self.formatting_handler._in_html = 1
    self.formatting_handler.HandleLink(
        1, self.output, "http://example.com", None)

    self.assertOutput("http://example.com")
    self.assertWarning("Link markup was used")

  def testHandleLinkWithDescription(self):
    self.formatting_handler.HandleLink(
        1, self.output, "http://example.com", "Description")

    self.assertOutput("[Description](http://example.com)")
    self.assertNoWarnings()

  def testHandleLinkWithDescriptionInHtml(self):
    self.formatting_handler._in_html = 1
    self.formatting_handler.HandleLink(
        1, self.output, "http://example.com", "Description")

    self.assertOutput("Description")
    self.assertWarning("Link markup was used")

  def testHandleLinkWithImageDescription(self):
    self.formatting_handler.HandleLink(
        1, self.output, "http://example.com", "http://example.com/a.png")

    self.assertOutput("[![](http://example.com/a.png)](http://example.com)")
    self.assertNoWarnings()

  def testHandleLinkWithImageDescriptionInHtml(self):
    self.formatting_handler._in_html = 1
    self.formatting_handler.HandleLink(
        1, self.output, "http://example.com", "http://example.com/a.png")

    self.assertOutput(""
                      "")
    self.assertWarning("Link markup was used")

  def testHandleImageLink(self):
    self.formatting_handler.HandleLink(
        1, self.output, "http://example.com/a.png", None)

    self.assertOutput("![http://example.com/a.png](http://example.com/a.png)")
    self.assertNoWarnings()

  def testHandleImageLinkInHtml(self):
    self.formatting_handler._in_html = 1
    self.formatting_handler.HandleLink(
        1, self.output, "http://example.com/a.png", None)

    self.assertOutput("")
    self.assertWarning("Link markup was used")

  def testHandleImageLinkWithDescription(self):
    self.formatting_handler.HandleLink(
        1, self.output, "http://example.com/a.png", "Description")

    self.assertOutput("[Description](http://example.com/a.png)")
    self.assertNoWarnings()

  def testHandleImageLinkWithDescriptionInHtml(self):
    self.formatting_handler._in_html = 1
    self.formatting_handler.HandleLink(
        1, self.output, "http://example.com/a.png", "Description")

    self.assertOutput("Description")
    self.assertWarning("Link markup was used")

  def testHandleImageLinkWithImageDescription(self):
    self.formatting_handler.HandleLink(
        1, self.output, "http://example.com/a.png", "http://example.com/b.png")

    self.assertOutput("![![](http://example.com/b.png)]"
                      "(http://example.com/a.png)")
    self.assertNoWarnings()

  def testHandleImageLinkWithImageDescriptionInHtml(self):
    self.formatting_handler._in_html = 1
    self.formatting_handler.HandleLink(
        1, self.output, "http://example.com/a.png", "http://example.com/b.png")

    self.assertOutput(""
                      "")
    self.assertWarning("Link markup was used")

  def testHandleWiki(self):
    self.formatting_handler.HandleWiki(1, self.output, "TestPage", "Test Page")

    self.assertOutput("[Test Page](TestPage.md)")
    self.assertNoWarnings()

  def testHandleWikiInHtml(self):
    self.formatting_handler._in_html = 1
    self.formatting_handler.HandleWiki(1, self.output, "TestPage", "Test Page")

    self.assertOutput("Test Page")
    self.assertWarning("Link markup was used")

  def testHandleIssue(self):
    self.formatting_handler.HandleIssue(1, self.output, "issue ", 123)

    self.assertOutput("[issue 789](https://github.com/abcxyz/test/issues/789)")
    self.assertWarning("Issue 123 was auto-linked")
    self.assertWarning("In the output, it has been linked to the "
                       "migrated issue on GitHub: 789.")

  def testHandleIssueInHtml(self):
    self.formatting_handler._in_html = 1
    self.formatting_handler.HandleIssue(1, self.output, "issue ", 123)

    self.assertOutput(""
                      "issue 789")
    self.assertWarning("Link markup was used")
    self.assertWarning("Issue 123 was auto-linked")
    self.assertWarning("In the output, it has been linked to the "
                       "migrated issue on GitHub: 789.")

  def testHandleIssueNotInMap(self):
    self.formatting_handler.HandleIssue(1, self.output, "issue ", 456)

    self.assertOutput("[issue 456](https://code.google.com/p/"
                      "test/issues/detail?id=456)")
    self.assertWarning("Issue 456 was auto-linked")
    self.assertWarning("However, it was not found in the issue migration map")
    self.assertWarning("As a placeholder, the text has been modified to "
                       "link to the original Google Code issue page")

  def testHandleIssueNotInMapInHtml(self):
    self.formatting_handler._in_html = 1
    self.formatting_handler.HandleIssue(1, self.output, "issue ", 456)

    self.assertOutput("issue 456")
    self.assertWarning("Link markup was used")
    self.assertWarning("Issue 456 was auto-linked")
    self.assertWarning("However, it was not found in the issue migration map")
    self.assertWarning("As a placeholder, the text has been modified to "
                       "link to the original Google Code issue page")

  def testHandleIssueNoMap(self):
    self.formatting_handler._issue_map = None
    self.formatting_handler.HandleIssue(1, self.output, "issue ", 456)

    self.assertOutput("[issue 456](https://code.google.com/p/"
                      "test/issues/detail?id=456)")
    self.assertWarning("Issue 456 was auto-linked")
    self.assertWarning("However, no issue migration map was specified")
    self.assertWarning("As a placeholder, the text has been modified to "
                       "link to the original Google Code issue page")

  def testHandleIssueNoMapInHtml(self):
    self.formatting_handler._in_html = 1
    self.formatting_handler._issue_map = None
    self.formatting_handler.HandleIssue(1, self.output, "issue ", 456)

    self.assertOutput("issue 456")
    self.assertWarning("Link markup was used")
    self.assertWarning("Issue 456 was auto-linked")
    self.assertWarning("However, no issue migration map was specified")
    self.assertWarning("As a placeholder, the text has been modified to "
                       "link to the original Google Code issue page")

  def testHandleIssueNotInMapNoProject(self):
    self.formatting_handler._project = None
    self.formatting_handler.HandleIssue(1, self.output, "issue ", 456)

    self.assertOutput("issue 456 (on Google Code)")
    self.assertWarning("Issue 456 was auto-linked")
    self.assertWarning("However, it was not found in the issue migration map")
    self.assertWarning("Additionally, because no project name was specified "
                       "the issue could not be linked to the original Google "
                       "Code issue page.")
    self.assertWarning("The auto-link has been removed")

  def testHandleIssueNotInMapNoProjectInHtml(self):
    self.formatting_handler._in_html = 1
    self.formatting_handler._project = None
    self.formatting_handler.HandleIssue(1, self.output, "issue ", 456)

    self.assertOutput("issue 456 (on Google Code)")
    self.assertWarning("Issue 456 was auto-linked")
    self.assertWarning("However, it was not found in the issue migration map")
    self.assertWarning("Additionally, because no project name was specified "
                       "the issue could not be linked to the original Google "
                       "Code issue page.")
    self.assertWarning("The auto-link has been removed")

  def testHandleIssueNoMapNoProject(self):
    self.formatting_handler._issue_map = None
    self.formatting_handler._project = None
    self.formatting_handler.HandleIssue(1, self.output, "issue ", 456)

    self.assertOutput("issue 456 (on Google Code)")
    self.assertWarning("Issue 456 was auto-linked")
    self.assertWarning("However, no issue migration map was specified")
    self.assertWarning("Additionally, because no project name was specified "
                       "the issue could not be linked to the original Google "
                       "Code issue page.")
    self.assertWarning("The auto-link has been removed")

  def testHandleIssueNoMapNoProjectInHtml(self):
    self.formatting_handler._in_html = 1
    self.formatting_handler._issue_map = None
    self.formatting_handler._project = None
    self.formatting_handler.HandleIssue(1, self.output, "issue ", 456)

    self.assertOutput("issue 456 (on Google Code)")
    self.assertWarning("Issue 456 was auto-linked")
    self.assertWarning("However, no issue migration map was specified")
    self.assertWarning("Additionally, because no project name was specified "
                       "the issue could not be linked to the original Google "
                       "Code issue page.")
    self.assertWarning("The auto-link has been removed")

  def testHandleRevision(self):
    self.formatting_handler.HandleRevision(1, self.output, "revision ", 7)

    self.assertOutput("[revision 7](https://code.google.com/p/"
                      "test/source/detail?r=7)")
    self.assertWarning("Revision 7 was auto-linked")
    self.assertWarning("As a placeholder, the text has been modified to "
                       "link to the original Google Code source page")

  def testHandleRevisionInHtml(self):
    self.formatting_handler._in_html = 1
    self.formatting_handler.HandleRevision(1, self.output, "revision ", 7)

    self.assertOutput("revision 7")
    self.assertWarning("Link markup was used")
    self.assertWarning("Revision 7 was auto-linked")
    self.assertWarning("As a placeholder, the text has been modified to "
                       "link to the original Google Code source page")

  def testHandleRevisionNoProject(self):
    self.formatting_handler._project = None
    self.formatting_handler.HandleRevision(1, self.output, "revision ", 7)

    self.assertOutput("revision 7 (on Google Code)")
    self.assertWarning("Revision 7 was auto-linked")
    self.assertWarning("Additionally, because no project name was specified "
                       "the revision could not be linked to the original "
                       "Google Code source page.")
    self.assertWarning("The auto-link has been removed")

  def testHandleRevisionNoProjectInHtml(self):
    self.formatting_handler._in_html = 1
    self.formatting_handler._project = None
    self.formatting_handler.HandleRevision(1, self.output, "revision ", 7)

    self.assertOutput("revision 7 (on Google Code)")
    self.assertWarning("Revision 7 was auto-linked")
    self.assertWarning("Additionally, because no project name was specified "
                       "the revision could not be linked to the original "
                       "Google Code source page.")
    self.assertWarning("The auto-link has been removed")

  def testHandleInHtml(self):
    self.formatting_handler.HandleHtmlOpen(
        1, self.output, "tag", {"a": "1", "b": "2"}, False)
    self.formatting_handler.HandleText(2, self.output, "xyz")
    self.formatting_handler.HandleHtmlClose(3, self.output, "tag")

    self.assertOutput("<tag a='1' b='2'>xyz</tag>")
    self.assertNoWarnings()

  def testHandleHtmlInHtml(self):
    self.formatting_handler._in_html = 1
    self.formatting_handler.HandleHtmlOpen(
        1, self.output, "tag", {"a": "1", "b": "2"}, False)
    self.formatting_handler.HandleText(2, self.output, "xyz")
    self.formatting_handler.HandleHtmlClose(3, self.output, "tag")

    self.assertOutput("<tag a='1' b='2'>xyz</tag>")
    self.assertNoWarnings()

  def testHandleInHtmlSelfClose(self):
    self.formatting_handler.HandleHtmlOpen(
        1, self.output, "tag", {"a": "1", "b": "2"}, True)

    self.assertOutput("<tag a='1' b='2' />")
    self.assertNoWarnings()

  def testHandleHtmlSelfCloseInHtml(self):
    self.formatting_handler._in_html = 1
    self.formatting_handler.HandleHtmlOpen(
        1, self.output, "tag", {"a": "1", "b": "2"}, True)

    self.assertOutput("<tag a='1' b='2' />")
    self.assertNoWarnings()

  def testHandleGPlus(self):
    self.formatting_handler.HandleGPlusOpen(1, self.output, None)
    self.formatting_handler.HandleGPlusClose(1, self.output)

    self.assertNoOutput("(TODO: Link to Google+ page.)")
    self.assertWarning("A Google+ +1 button was embedded on this page")

  def testHandleGPlusInHtml(self):
    self.formatting_handler._in_html = 1
    self.formatting_handler.HandleGPlusOpen(1, self.output, None)
    self.formatting_handler.HandleGPlusClose(1, self.output)

    self.assertNoOutput("(TODO: Link to Google+ page.)")
    self.assertWarning("A Google+ +1 button was embedded on this page")

  def testHandleComment(self):
    self.formatting_handler.HandleCommentOpen(1, self.output)
    self.formatting_handler.HandleText(2, self.output, "xyz")
    self.formatting_handler.HandleCommentClose(3, self.output)

    self.assertOutput("")
    self.assertWarning("A comment was used in the wiki file")

  def testHandleCommentInHtml(self):
    self.formatting_handler._in_html = 1
    self.formatting_handler.HandleCommentOpen(1, self.output)
    self.formatting_handler.HandleText(2, self.output, "xyz")
    self.formatting_handler.HandleCommentClose(3, self.output)

    self.assertOutput("")
    self.assertWarning("A comment was used in the wiki file")

  def testHandleVideo(self):
    self.formatting_handler.HandleVideoOpen(
        1, self.output, "FiARsQSlzDc", 320, 240)
    self.formatting_handler.HandleVideoClose(1, self.output)

    self.assertOutput(""
                      "")
    self.assertWarning("GFM does not support embedding the YouTube player")

  def testHandleVideoInHtml(self):
    self.formatting_handler._in_html = 1
    self.formatting_handler.HandleVideoOpen(
        1, self.output, "FiARsQSlzDc", 320, 240)
    self.formatting_handler.HandleVideoClose(1, self.output)

    self.assertOutput(""
                      "")
    self.assertWarning("GFM does not support embedding the YouTube player")

  def testHandleText(self):
    self.formatting_handler.HandleText(1, self.output, "xyz")

    self.assertOutput("xyz")
    self.assertNoWarnings()

  def testHandleTextInHtml(self):
    self.formatting_handler._in_html = 1
    self.formatting_handler.HandleText(1, self.output, "xyz")

    self.assertOutput("xyz")
    self.assertNoWarnings()

  def testHandleEscapedText(self):
    self.formatting_handler.HandleEscapedText(1, self.output, "**_xyz_** ")

    self.assertOutput("\\*\\*\\_xyz\\_\\*\\* <a>")
    self.assertNoWarnings()

  def testHandleEscapedTextInHtml(self):
    self.formatting_handler._in_html = 1
    self.formatting_handler.HandleEscapedText(1, self.output, "**_xyz_** ")

    self.assertOutput("**_xyz_** ")
    self.assertNoWarnings()

class TestConverter(BaseTest):
  """Tests the converter."""

  def testExamplePage(self):
    with codecs.open("example.wiki", "rU", "utf-8") as example_input:
      with codecs.open("example.md", "rU", "utf-8") as example_output:
        self.converter.Convert(example_input, self.output)

        self.assertOutput(example_output.read())

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


text:
from django import template
from django.db.models import Sum

from ..models import Visitor

register = template.Library()

class VisitorsOnSite(template.Node):
    """
    Injects the number of active users on your site as an integer into the context
    """

    def __init__(self, varname, type=None):
        """
        :param varname:
        :param type: same_page/ pv / uv
        """
        self.varname = varname
        self.type = type

    def render(self, context):
        if self.type == 'same_page':
            try:
                request = context['request']
                count = Visitor.objects.active().filter(
                    url=request.path).count()
            except KeyError:
                raise template.TemplateSyntaxError(
                    "Please add 'django.core.context_processors.request' to your TEMPLATE_CONTEXT_PROCESSORS if you want to see how many users are on the same page.")
        elif self.type == 'pv':
            pv_dict = Visitor.objects.aggregate(pv=Sum('page_views'))
            count = pv_dict.get('pv', 0)
        elif self.type == 'uv':
            count = Visitor.objects.all().count()
        else:
            count = Visitor.objects.active().count()

        context[self.varname] = count
        return ''

def visitors_on_site(parser, token):
    """
    Determines the number of active users on your site and puts it into the context
    """
    try:
        tag, a, varname = token.split_contents()
    except ValueError:
        raise template.TemplateSyntaxError(
            'visitors_on_site usage: {% visitors_on_site as visitors %}')

    return VisitorsOnSite(varname)

register.tag(visitors_on_site)

def visitors_on_page(parser, token):
    """
    Determines the number of active users on the same page and puts it into the context
    """
    try:
        tag, a, varname = token.split_contents()
    except ValueError:
        raise template.TemplateSyntaxError(
            'visitors_on_page usage: {% visitors_on_page as visitors %}')

    return VisitorsOnSite(varname, type='same_page')

register.tag(visitors_on_page)

def pv_on_site(parser, token):
    """
    pv into the context
    """
    try:
        tag, a, varname = token.split_contents()
    except ValueError:
        raise template.TemplateSyntaxError(
            'pv_on_site usage: {% pv_on_site as pv %}')

    return VisitorsOnSite(varname, type='pv')

register.tag(pv_on_site)

def uv_on_site(parser, token):
    """
    uv into the context
    """
    try:
        tag, a, varname = token.split_contents()
    except ValueError:
        raise template.TemplateSyntaxError(
            'uv_on_site usage: {% uv_on_site as uv %}')

    return VisitorsOnSite(varname, type='uv')

register.tag(uv_on_site)


text:
//------------------------------------------------------------------------------
// <auto-generated>
//     Dieser Code wurde von einem Tool generiert.
//     Laufzeitversion:4.0.30319.42000
//
//     Änderungen an dieser Datei können falsches Verhalten verursachen und gehen verloren, wenn
//     der Code erneut generiert wird.
// </auto-generated>
//------------------------------------------------------------------------------

namespace SwissAcademic.Addons.ImportJournalsAddon.Properties {
    using System;

    /// <summary>
    ///   Eine stark typisierte Ressourcenklasse zum Suchen von lokalisierten Zeichenfolgen usw.
    /// </summary>
    // Diese Klasse wurde von der StronglyTypedResourceBuilder automatisch generiert
    // -Klasse über ein Tool wie ResGen oder Visual Studio automatisch generiert.
    // Um einen Member hinzuzufügen oder zu entfernen, bearbeiten Sie die .ResX-Datei und führen dann ResGen
    // mit der /str-Option erneut aus, oder Sie erstellen Ihr VS-Projekt neu.
    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")]
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
    internal class Resources {

        private static global::System.Resources.ResourceManager resourceMan;

        private static global::System.Globalization.CultureInfo resourceCulture;

        [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
        internal Resources() {
        }

        /// <summary>
        ///   Gibt die zwischengespeicherte ResourceManager-Instanz zurück, die von dieser Klasse verwendet wird.
        /// </summary>
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        internal static global::System.Resources.ResourceManager ResourceManager {
            get {
                if (object.ReferenceEquals(resourceMan, null)) {
                    global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("SwissAcademic.Addons.ImportJournalsAddon.Properties.Resources", typeof(Resources).Assembly);
                    resourceMan = temp;
                }
                return resourceMan;
            }
        }

        /// <summary>
        ///   Überschreibt die CurrentUICulture-Eigenschaft des aktuellen Threads für alle
        ///   Ressourcenzuordnungen, die diese stark typisierte Ressourcenklasse verwenden.
        /// </summary>
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        internal static global::System.Globalization.CultureInfo Culture {
            get {
                return resourceCulture;
            }
            set {
                resourceCulture = value;
            }
        }

        /// <summary>
        ///   Sucht eine lokalisierte Ressource vom Typ System.Drawing.Bitmap.
        /// </summary>
        internal static System.Drawing.Bitmap addon {
            get {
                object obj = ResourceManager.GetObject("addon", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }

        /// <summary>
        ///   Sucht eine lokalisierte Zeichenfolge, die This file contains invalid characters and cannot be imported. ähnelt.
        /// </summary>
        internal static string FileMacroNotSupportedCharactersMessage {
            get {
                return ResourceManager.GetString("FileMacroNotSupportedCharactersMessage", resourceCulture);
            }
        }

        /// <summary>
        ///   Sucht eine lokalisierte Zeichenfolge, die Text files (*.txt)|*.txt|All files (*.*)|*.* ähnelt.
        /// </summary>
        internal static string FileMacroOpenFileDialogFilters {
            get {
                return ResourceManager.GetString("FileMacroOpenFileDialogFilters", resourceCulture);
            }
        }

        /// <summary>
        ///   Sucht eine lokalisierte Zeichenfolge, die Select the journal file for import (.txt format) ähnelt.
        /// </summary>
        internal static string FileMacroOpenFileDialogSubject {
            get {
                return ResourceManager.GetString("FileMacroOpenFileDialogSubject", resourceCulture);
            }
        }

        /// <summary>
        ///   Sucht eine lokalisierte Zeichenfolge, die {0} journals were imported.
        ///(duplicates were not imported.) ähnelt.
        /// </summary>
        internal static string FileMacroResultMessage {
            get {
                return ResourceManager.GetString("FileMacroResultMessage", resourceCulture);
            }
        }

        /// <summary>
        ///   Sucht eine lokalisierte Zeichenfolge, die Import file… ähnelt.
        /// </summary>
        internal static string ImportJournalsByFileCommandText {
            get {
                return ResourceManager.GetString("ImportJournalsByFileCommandText", resourceCulture);
            }
        }

        /// <summary>
        ///   Sucht eine lokalisierte Zeichenfolge, die From PubMed… ähnelt.
        /// </summary>
        internal static string ImportJournalsByPubMedCommandText {
            get {
                return ResourceManager.GetString("ImportJournalsByPubMedCommandText", resourceCulture);
            }
        }

        /// <summary>
        ///   Sucht eine lokalisierte Zeichenfolge, die From the University of British Columbia… ähnelt.
        /// </summary>
        internal static string ImportJournalsByWoodwardLibraryCommandText {
            get {
                return ResourceManager.GetString("ImportJournalsByWoodwardLibraryCommandText", resourceCulture);
            }
        }

        /// <summary>
        ///   Sucht eine lokalisierte Zeichenfolge, die Import List of Journals ähnelt.
        /// </summary>
        internal static string ImportJournalsMenu {
            get {
                return ResourceManager.GetString("ImportJournalsMenu", resourceCulture);
            }
        }

        /// <summary>
        ///   Sucht eine lokalisierte Zeichenfolge, die An error occurred while importing the list of journals:
        ///
        ///{0} ähnelt.
        /// </summary>
        internal static string MacroImportingErrorMessage {
            get {
                return ResourceManager.GetString("MacroImportingErrorMessage", resourceCulture);
            }
        }

        /// <summary>
        ///   Sucht eine lokalisierte Zeichenfolge, die Could not read file from {0}: {1}" ähnelt.
        /// </summary>
        internal static string PubMedMacroReadErrorMessage {
            get {
                return ResourceManager.GetString("PubMedMacroReadErrorMessage", resourceCulture);
            }
        }

        /// <summary>
        ///   Sucht eine lokalisierte Zeichenfolge, die {0} journal(s) were imported (not counting duplicates) ähnelt.
        /// </summary>
        internal static string PubMedMacroResultMessage {
            get {
                return ResourceManager.GetString("PubMedMacroResultMessage", resourceCulture);
            }
        }

        /// <summary>
        ///   Sucht eine lokalisierte Zeichenfolge, die {0} journal(s) were imported (not counting duplicates)
        ///{1} reference(s) were changed. ähnelt.
        /// </summary>
        internal static string WoodwardMacroResultMessage {
            get {
                return ResourceManager.GetString("WoodwardMacroResultMessage", resourceCulture);
            }
        }

        /// <summary>
        ///   Sucht eine lokalisierte Zeichenfolge, die Would you like to update journal information for references in current selection (Journal information will be updated for all references if no selection is active)? ähnelt.
        /// </summary>
        internal static string WoodwardMacroUpdateMessage {
            get {
                return ResourceManager.GetString("WoodwardMacroUpdateMessage", resourceCulture);
            }
        }
    }
}


text:
This project uses CMake.
General build steps look like:
```sh
mkdir -p build
cd build
cmake ..
make -j8
```

Wasm3 is continuously tested with Clang, GCC, MSVC compilers, and on multiple platforms.
It can be easily integrated into any build system, as shown in `platforms`.

## Build on Linux, OS X

### Clang

```sh
mkdir build
cd build
cmake -GNinja -DCLANG_SUFFIX="-12" ..
ninja
```

### GCC

```sh
mkdir build
cd build
cmake -GNinja ..
ninja
```

## Build on Windows

Prerequisites:
- [Build Tools for Visual Studio 2019](https://visualstudio.microsoft.com/downloads/#build-tools-for-visual-studio-2019)
- [CMake](https://cmake.org/download/)
- [Ninja](https://github.com/ninja-build/ninja/releases)
- [Clang 9](https://releases.llvm.org/download.html#9.0.0)

Recommended tools:
- [Cmder](https://cmder.net/)
- [Python3](https://www.python.org/downloads/)
- [ptime](http://www.pc-tools.net/win32/ptime/)

```sh
# Prepare environment (if needed):
"C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Auxiliary\Build\vcvars64.bat"
set PATH=C:\Python36-32\;C:\Python36-32\Scripts\;%PATH%
```

### Build with MSBuild

```sh
# Create a build directory as usual, then build a specific configuration
mkdir build
cd build

# Configure Clang, x64
cmake -G"Visual Studio 16 2019" -A x64 -T ClangCL ..

# Configure Clang, x86
cmake -G"Visual Studio 16 2019" -A Win32 -T ClangCL ..

# Configure MSVC, x64
cmake -G"Visual Studio 16 2019" -A x64 ..

# Configure MSVC, x86
cmake -G"Visual Studio 16 2019" -A Win32 ..

# Build
cmake --build . --config Release
cp ./Release/wasm3.exe ./
```

### Build with Ninja

```sh
set PATH=C:\Program Files\CMake\bin;%PATH%
set PATH=C:\Program Files\LLVM\bin;%PATH%

# Clang
cmake -GNinja -DCLANG_CL=1 ..
ninja

# MSVC
cmake -GNinja ..
ninja
```

## Build using compiler directly

This can be useful for cross-compilation, quick builds or when a build system (CMake, Ninja, etc.) is not available.

### gcc/clang
```sh
gcc -O3 -g0 -s -Isource -Dd_m3HasWASI source/*.c platforms/app/main.c -lm -o wasm3
```

### msvc/clang-cl
```sh
cl source/*.c platforms/app/main.c /Isource /MD /Ox /Oy /Gw /GS- /W0 /Dd_m3HasWASI /Fewasm3.exe /link advapi32.lib
```

### mingw-w64
```sh
x86_64-w64-mingw32-gcc -O3 -g0 -s -Isource -Dd_m3HasWASI source/*.c platforms/app/main.c -lm -lpthread -static -o wasm3.exe
```

## Build for microcontrollers

In `./platforms/` folder you can find projects for different targets. Some of them are using Platformio, so you can follow the regular pio build process. Others have custom instructions in respective `README.md` files.

## Build with WasiEnv

```sh
wasimake cmake -GNinja ..
ninja
```

If you want to enable experimental WASM features during the build:

```sh
export CFLAGS="-Xclang -target-feature -Xclang +tail-call"
wasimake cmake -GNinja ..
ninja
```

Here's how some options can be used with different tools:

```log
Clang target-feature option          WABT option                        Chromium --js-flags option
----------------------------------------------------------------------------------------------------------------
+multivalue                          --enable-multi-value               --experimental-wasm-mv
+tail-call                           --enable-tail-call                 --experimental-wasm-return-call
+bulk-memory                         --enable-bulk-memory               --experimental-wasm-bulk-memory
+nontrapping-fptoint                 --enable-saturating-float-to-int   --experimental-wasm-sat-f2i-conversions
+sign-ext                            --enable-sign-extension            --experimental-wasm-se
+simd128, +unimplemented-simd128     --enable-simd                      --experimental-wasm-simd
```

```sh
# List clang options:
llc -march=wasm32 -mattr=help

# List Chromium options:
chromium-browser --single-process --js-flags="--help" 2>&1 | grep wasm
```

## Build with Zig

Grab the latest nightly Zig toolchain from [ziglang.org/download], and then simply run:

[ziglang.org/download]: https://ziglang.org/download/

```sh
zig build
```

This will install `wasm3` compiled for your target architecture in `zig-out/bin/wasm3`.

In order to build `wasm3` in a mode different than Debug, e.g., in ReleaseFast, pass in
an appropriate flag like so:

```sh
zig build -Drelease-fast
```

If you want to cross-compile to some specific target, pass in the target with a flag like so:

```sh
zig build -Dtarget=wasm32-wasi
```

Or if targeting Apple Silicon (this works from *any* host with Zig):

```sh
zig build -Dtarget=aarch64-macos
```


text:
import React, { Component } from 'react';
import { Row, Col } from '@freecodecamp/react-bootstrap';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import PropTypes from 'prop-types';
import uniq from 'lodash/uniq';
import { createSelector } from 'reselect';

import SuperBlock from './components/SuperBlock';
import Spacer from '../helpers/Spacer';

import './map.css';
import { ChallengeNode } from '../../redux/propTypes';
import { toggleSuperBlock, toggleBlock, resetExpansion } from './redux';
import { currentChallengeIdSelector } from '../../redux';
import { dasherize } from '../../../../utils/slugs';

const propTypes = {
  currentChallengeId: PropTypes.string,
  hash: PropTypes.string,
  introNodes: PropTypes.arrayOf(
    PropTypes.shape({
      fields: PropTypes.shape({ slug: PropTypes.string.isRequired }),
      frontmatter: PropTypes.shape({
        title: PropTypes.string.isRequired,
        block: PropTypes.string.isRequired
      })
    })
  ),
  isSignedIn: PropTypes.bool,
  nodes: PropTypes.arrayOf(ChallengeNode),
  resetExpansion: PropTypes.func,
  toggleBlock: PropTypes.func.isRequired,
  toggleSuperBlock: PropTypes.func.isRequired
};

const mapStateToProps = state => {
  return createSelector(
    currentChallengeIdSelector,
    currentChallengeId => ({
      currentChallengeId
    })
  )(state);
};

function mapDispatchToProps(dispatch) {
  return bindActionCreators(
    {
      resetExpansion,
      toggleSuperBlock,
      toggleBlock
    },
    dispatch
  );
}

export class Map extends Component {
  constructor(props) {
    super(props);
    this.initializeExpandedState();
  }

  // As this happens in the constructor, it's necessary to manipulate state
  // directly.
  initializeExpandedState() {
    const {
      currentChallengeId,
      hash,
      nodes,
      resetExpansion,
      toggleBlock,
      toggleSuperBlock,
      isSignedIn
    } = this.props;
    resetExpansion();

    let node;

    // find the challenge that has the same superblock with hash
    if (hash) {
      node = nodes.find(node => dasherize(node.superBlock) === hash);
    }

    // without hash only expand when signed in
    if (isSignedIn) {
      // if there is no hash or the hash did not match any challenge superblock
      // and there was a currentChallengeId
      if (!node && currentChallengeId) {
        node = nodes.find(node => node.id === currentChallengeId);
      }
      if (!node) node = nodes[0];
    }

    if (!node) return;

    toggleBlock(node.block);
    toggleSuperBlock(node.superBlock);
  }

  renderSuperBlocks(superBlocks) {
    const { nodes, introNodes } = this.props;
    return superBlocks.map(superBlock => (
      <SuperBlock
        introNodes={introNodes}
        key={superBlock}
        nodes={nodes}
        superBlock={superBlock}
      />
    ));
  }

  render() {
    const { nodes } = this.props;
    // if a given superBlock's nodes have been filtered (via isHidden, say) that
    // superBlock will not appear in superBlocks and will not be rendered.
    const superBlocks = uniq(nodes.map(({ superBlock }) => superBlock));
    return (
      <Row>
        <Col sm={10} smOffset={1} xs={12}>

              {this.renderSuperBlocks(superBlocks)}
              <Spacer />

        </Col>
      </Row>
    );
  }
}

Map.displayName = 'Map';
Map.propTypes = propTypes;

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(Map);