text:
package aoc21;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Scanner;
import java.util.Set;

public class Day15 {
    static Map<Point, Integer> board;
    static Point goalPoint;

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        List<String> lines = new ArrayList<>();
        while (in.hasNextLine()) {
            lines.add(in.nextLine());
        }
        board = new HashMap<>();
        int rows = lines.size();
        int cols = lines.get(rows - 1).length();
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                int value = Integer.parseInt(lines.get(i).charAt(j) + "");
                for (int ii = 0; ii < 5; ii++) {
                    for (int jj = 0; jj < 5; jj++) {
                        int thisValue = (ii + jj + value);
                        while (thisValue > 9) {
                            thisValue -= 9;
                        }
                        Point point = new Point((ii * rows) + i, (jj * cols) + j);
                        if (board.containsKey(point)) {
                            throw new RuntimeException(point.toString());
                        }
                        board.put(point, thisValue);
                    }
                }
            }
        }
        for (int i = 0; i < (5 * rows); i++) {
            for (int j = 0; j < (5 * cols); j++) {
                if (!board.containsKey(new Point(i, j))) {
                    throw new RuntimeException(new Point(i, j).toString());
                }
            }
        }
        goalPoint = new Point((rows * 5) - 1, (cols * 5) - 1);
        Map<Point, Integer> dist = new HashMap<>();
        PriorityQueue<Point> points = new PriorityQueue<>(Comparator.comparingInt(dist::get));
        Point source = new Point(0, 0);
        for (Point p : board.keySet()) {
            if (!p.equals(source)) {
                dist.put(p, Integer.MAX_VALUE);
                points.add(p);
            }
        }
        dist.put(source, 0);
        points.add(source);

        while (!points.isEmpty()) {
            Point p = points.remove();
            if (p.equals(goalPoint)) {
                break;
            }
            for (Point neighbor : p.getPointNeighbors()) {
                if (points.contains(neighbor)) {
                    int alt = dist.get(p) + board.get(neighbor);
                    if (!dist.containsKey(neighbor)) {
                        throw new RuntimeException(neighbor.toString());
                    }
                    if (alt < dist.get(neighbor)) {
                        dist.put(neighbor, alt);
                        points.remove(neighbor);
                        points.add(neighbor);
                    }
                }
            }
            if ((points.size() % 1000) == 0) {
                System.out.printf("%s: %s\n", points.size(), dist.get(p));
                //printProgress(points, rows, cols);
            }
        }

        System.out.println(dist.get(goalPoint));

    }

    private static void printProgress(Set<Point> points, int rows, int cols) {
        for (int r = 0; r < rows; r++) {
            for (int c = 0; c < cols; c++) {
                Point p = new Point(r, c);
                System.out.print(points.contains(p) ? "X" : ".");
            }
            System.out.println();
        }
    }

    private static Point getMinPoint(Map<Point, Integer> dist, Set<Point> points) {
        return points.stream().min(Comparator.comparingInt(dist::get)).get();
    }

    private static int calcCost(Point point, Map<Point, Integer> costs, Set<Point> seen) {
        if (costs.containsKey(point)) {
            return costs.get(point);
        }
        if (point.equals(goalPoint)) {
            return 0;
        }
        int cost = Integer.MAX_VALUE;
        HashSet<Point> newSeen = new HashSet<>(seen);
        newSeen.add(point);
        cost = Math.min(cost, getCost(costs, new Point(point.r, point.c + 1), newSeen));
        cost = Math.min(cost, getCost(costs, new Point(point.r, point.c - 1), newSeen));
        cost = Math.min(cost, getCost(costs, new Point(point.r + 1, point.c), newSeen));
        cost = Math.min(cost, getCost(costs, new Point(point.r - 1, point.c), newSeen));
        return cost;
    }

    private static int getCost(Map<Point, Integer> costs, Point right, Set<Point> seen) {
        if (board.containsKey(right) && !seen.contains(right)) {
            return board.get(right) + calcCost(right, costs, seen);
        }
        return Integer.MAX_VALUE;
    }

}


text:
package nz.rafikn.movierates;

import nz.rafikn.movierates.model.Movie;
import nz.rafikn.movierates.model.RawSearch;
import nz.rafikn.movierates.model.SearchResponse;
import nz.rafikn.movierates.model.SearchResult;
import nz.rafikn.movierates.services.VimeoAPIService;
import org.junit.Test;

import java.util.*;

import static org.junit.Assert.assertEquals;

/**
 * Created by rafik on 26/06/16.
 */
public class AggregateTest {

    @Test
    public void testAggregate() {
        // 150 = 10 per result, 5 results per page, 3 pages per response.
        assertEquals(VimeoAPIService.aggregate(mockSearch()), 150);
    }

    private RawSearch mockSearch() {

        RawSearch raw = new RawSearch();

        raw.setMovie(mockMovie());

        for (int page = 1; page < 4; page++) {
            SearchResponse response = new SearchResponse();
            response.setTotal(15);
            response.setPage(1);
            response.setPerPage(5);
            response.setData(mockSearchData());

            raw.getPages().add(response);
        }

        return raw;
    }

    private Movie mockMovie() {
        Movie movie = new Movie();
        movie.setId(1);
        movie.setTitle("Test Movie");
        movie.setSearchTerm("Search Term");
        return movie;
    }

    private Collection<SearchResult> mockSearchData() {
        List<SearchResult> results = new ArrayList<>();

        Map<String, Object> stats = new HashMap<>();

        for (int i =0; i<5; i++) {
            SearchResult result = new SearchResult();
            result.setName("Test Movie");
            result.setUri("/video/test");

            stats.put("plays", 10);
            result.setStats(stats);
            results.add(result);
        }
        return results;
    }

}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:layout_height="match_parent">

    <android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/toolbar"
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:minHeight="?attr/actionBarSize"
        android:background="?attr/colorPrimary" />

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_above="@+id/theater_view"
            android:background="#444">

            <View
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:alpha="0.4"
                android:background="@drawable/gradient_black_100"
                android:rotation="180" />

            <android.support.v4.view.ViewPager
                android:id="@+id/poster_pager"
                android:layout_width="match_parent"
                android:layout_height="match_parent" />
        </RelativeLayout>

        <View
            android:layout_width="match_parent"
            android:layout_height="6dip"
            android:layout_above="@+id/theater_view"
            android:background="@drawable/movie_tile_shadow"
            android:rotation="180" />

        <RelativeLayout
            android:id="@+id/theater_view"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true">

            <include layout="@layout/cell_theater" />

        </RelativeLayout>

        <ImageView
            android:id="@+id/placeholder_image_loader"
            android:layout_width="30dip"
            android:layout_height="30dip"
            android:layout_alignParentRight="true"
            android:layout_margin="10dp"
            android:alpha="0.4"
            android:src="@drawable/ic_drawer_films" />

    </RelativeLayout>
</LinearLayout>


text:
namespace SelfLoad.DataAccess.ERCLevel
{
    public partial class D07_Country_ReChildDto
    {
    }
}


text:
@interface NSArray (Shuffle)
- (NSMutableArray *)shuffle;
@end


text:
package org.mandfer.sunfunpi4j;

import com.pi4j.io.gpio.GpioController;
import com.pi4j.io.gpio.GpioFactory;
import com.pi4j.io.gpio.PinMode;

/**
 *
 * In this example we use type 'short'. In JAVA the type 'byte' is signed and
 * the values go from -128 to 127. There is no unsigned 'byte' type in JAVA. The
 * next numeric type is 'short', which is a 16-bit integer.
 * Documentation about the Hall effect and the ADC0832CCN
 *
 * Hall effect sensing and application by Honeywell
 * http://sensing.honeywell.com/index.php?ci_id=47847
 *
 * Hall effect sensor 44E datasheet
 * http://www.allegromicro.com/~/media/Files/Datasheets/A3141-2-3-4-Datasheet.ashx
 *
 * ADC0832 datasheet
 * http://pdf1.alldatasheet.com/datasheet-pdf/view/158145/NSC/ADC0832CCN.html
 *
 * @author marcandreuf
 */
public class Ex02_03_LinearHall extends ADC_Base {
    private short intensity;

    /**
     * @param gpio controller
     */
    public Ex02_03_LinearHall(GpioController gpio) {
        super(gpio);
    }

    public static void main(String[] args) throws InterruptedException {
        Ex02_03_LinearHall sketch = new Ex02_03_LinearHall(GpioFactory.getInstance());
        sketch.run(args);
    }

    @Override
    protected void setup(String[] args) {
        super.setup(args);
        logger.debug("Linear Hall sensor ready!");
    }

    @Override
    protected void loop(String[] args) {
        short analogVal;
        do {
            analogVal = get_ADC_Result();
            intensity = (short) (210 - analogVal);
            logger.debug("Current intensity of magnetic field: " + Integer.valueOf(intensity));
            delayMilliseconds(500);
        } while (isNotInterrupted);
    }

    public short getIntensity() {
        return intensity;
    }
}


text:
import pytest

@pytest.fixture
def base_reference_epigenome(testapp, lab, award):
    item = {
        'award': award['uuid'],
        'lab': lab['uuid'],
        'status': 'ready for review'
    }
    return testapp.post_json('/reference-epigenomes', item, status=201).json['@graph'][0]

@pytest.fixture
def base_experiment(testapp, lab, award):
    item = {
        'award': award['uuid'],
        'lab': lab['uuid'],
        'assay_term_name': 'RNA-seq',
        'biosample_type': 'cell-free sample',
        'biosample_term_id': 'NTR:0000471',
        'biosample_term_name': 'none',
        'status': 'ready for review'
    }
    return testapp.post_json('/experiment', item, status=201).json['@graph'][0]

@pytest.fixture
def hg19_file(testapp, base_reference_epigenome, award, lab):
    item = {
        'dataset': base_reference_epigenome['@id'],
        'lab': lab['@id'],
        'award': award['@id'],
        'file_format': 'bigBed',
        'file_format_type': 'narrowPeak',
        'file_size': 345,
        'assembly': 'hg19',
        'md5sum': 'e002cd204df36d93dd070ef0712b8eed',
        'output_type': 'replicated peaks',
        'status': 'in progress',  # avoid s3 upload codepath
    }
    return testapp.post_json('/file', item, status=201).json['@graph'][0]

@pytest.fixture
def GRCh38_file(testapp, base_experiment, award, lab):
    item = {
        'dataset': base_experiment['@id'],
        'lab': lab['@id'],
        'award': award['@id'],
        'file_format': 'bigBed',
        'file_format_type': 'narrowPeak',
        'file_size': 345,
        'assembly': 'GRCh38',
        'md5sum': 'e002cd204df36d93dd070ef0712b8ee7',
        'output_type': 'replicated peaks',
        'status': 'in progress',  # avoid s3 upload codepath
    }
    return testapp.post_json('/file', item, status=201).json['@graph'][0]

def test_assembly_from_related_datasets(testapp, base_reference_epigenome, base_experiment, hg19_file, GRCh38_file):
    # If only original file is present in series, assembly should be ['hg19']
    res = testapp.get(base_reference_epigenome['@id'] + '@@index-data')
    assert res.json['object']['assembly'] == ['hg19']
    # Adding a related_dataset with a file in GRCh38 should now give it both ['hg19', 'GRCh38']
    testapp.patch_json(base_reference_epigenome['@id'], {'related_datasets': [base_experiment['@id']]})
    res = testapp.get(base_reference_epigenome['@id'] + '@@index-data')
    assert res.json['object']['assembly'].sort() == ['hg19', 'GRCh38'].sort()
    # Setting the experiment in related_dataset to delete it should exclude its assembly from the calculation
    testapp.patch_json(base_experiment['@id'], {'status': 'deleted'})
    res = testapp.get(base_reference_epigenome['@id'] + '@@index-data')
    assert res.json['object']['assembly'] == ['hg19']


text:
"""
Physical network with type=native does not have isolation technique,
so there can be only one logical network in each physical network.
"""
from vlcp.server.module import Module, publicapi
from vlcp.event.runnable import RoutineContainer
from vlcp.config.config import defaultconfig
from vlcp.utils.networkplugin import createphysicalnetwork,\
    updatephysicalnetwork, default_physicalnetwork_keys, deletephysicalnetwork,\
    deletephysicalport, default_physicalport_keys, createlogicalnetwork,\
    default_logicalnetwork_keys, default_processor, updatelogicalnetwork,\
    deletelogicalnetwork, createphysicalport, updatephysicalport

@defaultconfig
class NetworkNativeDriver(Module):
    """
    Network driver for native networks. Native network is a physical network
    provides only one logical network capacity. Packets from the logical network
    is directly forwarded to the physical network.
    """
    def __init__(self,server):
        super(NetworkNativeDriver,self).__init__(server)
        self.app_routine = RoutineContainer(self.scheduler)
        self.app_routine.main = self._main
        self.routines.append(self.app_routine)
        self.createAPI(
                       publicapi(self.createphysicalnetwork,
                                    criteria=lambda type: type == 'native'),
                       publicapi(self.updatephysicalnetwork,
                                    criteria=lambda type: type == 'native'),
                       publicapi(self.deletephysicalnetwork,
                                    criteria=lambda type: type == 'native'),
                       publicapi(self.createphysicalport,
                                    criteria=lambda type: type == 'native'),
                       publicapi(self.updatephysicalport,
                                    criteria=lambda type: type == 'native'),
                       publicapi(self.deletephysicalport,
                                    criteria=lambda type: type == 'native'),
                       publicapi(self.createlogicalnetwork,
                                    criteria=lambda type: type == 'native'),
                       publicapi(self.updatelogicalnetwork,
                                    criteria=lambda type: type == 'native'),
                       publicapi(self.deletelogicalnetwork,
                                    criteria=lambda type: type == "native"),
                       #used in IOprocessing module
                       publicapi(self.createioflowparts,
                                    criteria=lambda connection,logicalnetwork,
                                    physicalport,logicalnetworkid,physicalportid:
                                    logicalnetwork.physicalnetwork.type == "native")

                       )

    async def _main(self):
        self._logger.info("network_native_driver running ---")

    def createphysicalnetwork(self, type):
        # create an new physical network
        return createphysicalnetwork(type), default_physicalnetwork_keys

    def updatephysicalnetwork(self, type):
        # update a physical network
        return updatephysicalnetwork(), None

    def deletephysicalnetwork(self, type):
        return deletephysicalnetwork(), default_physicalnetwork_keys

    def createphysicalport(self, type):
        return createphysicalport(), default_physicalport_keys

    def updatephysicalport(self, type):
        return updatephysicalport(), None

    def deletephysicalport(self, type):
        return deletephysicalport(), default_physicalport_keys

    def createlogicalnetwork(self, type):
        def logicalnetwork_processor(logicalnetwork, logicalnetworkmap, physicalnetwork,
                                     physicalnetworkmap, walk, write, *, parameters):
            if physicalnetworkmap.logicnetworks.dataset():
                raise ValueError("physical network with type=native can only have one logical network")
            return default_processor(logicalnetwork, parameters=parameters, excluding=('id', 'physicalnetwork'))
        return createlogicalnetwork(create_processor=logicalnetwork_processor), default_logicalnetwork_keys

    def updatelogicalnetwork(self, type):
        return updatelogicalnetwork(), None

    def deletelogicalnetwork(self, type):
        return deletelogicalnetwork(), default_logicalnetwork_keys

    def createioflowparts(self,connection,logicalnetwork,physicalport,logicalnetworkid,physicalportid):

        #
        #  1. used in IOProcessing , when physicalport add to logicalnetwork
        #     return : input flow match vxlan vni, input flow vlan parts actions
        #              output flow vxlan parts actions, output group bucket
        #

        input_match_oxm = []
        input_action = []
        output_action = [
                    connection.openflowdef.ofp_action_output(
                           port = physicalportid
                        )
                ]

        output_group_bucket_action = [
                    connection.openflowdef.ofp_action_output(
                            port = physicalportid
                        )
                ]
        output_action2 = [
                    connection.openflowdef.ofp_action_output(
                           port = connection.openflowdef.OFPP_IN_PORT
                        )
                ]
        return input_match_oxm,input_action,output_action,output_group_bucket_action,output_action2


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="45dp"
    android:orientation="horizontal"
    android:background="@drawable/background_tabs_diagonal_inverted">

    <TextView
        android:id="@+id/title"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingBottom="2dp"
        android:paddingLeft="14dp"
        android:paddingRight="14dp"
        android:paddingTop="14dp"
        android:textSize="14sp"
        android:text="1 min ago at 10:34 AM"
        android:gravity="center_vertical"
        android:textColor="#FFDDDDDD"
        android:textStyle="bold"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginBottom="12dp" />

</RelativeLayout>


text:
layout: compress
---
<!DOCTYPE html>

	<title>{{ site.title }}</title>
	<link rel=stylesheet href="https://fonts.googleapis.com/css?family=Droid+Sans%7CSource+Code+Pro">

	<link rel=stylesheet href="/css/highlight.css"/>
	<meta name=viewport content="width=device-width, initial-scale=1">
	{% feed_meta %}

{{ site.title }}

{{ content }}

	This site can be edited on Github


text:
<?php
namespace Magento\Sales\Api\Data;

/**
 * Persistor class for @see \Magento\Sales\Api\Data\OrderStatusHistoryInterface
 */
class OrderStatusHistoryInterfacePersistor
{
    /**
     * Entity factory
     *
     * @var \Magento\Sales\Api\Data\OrderStatusHistoryInterfaceFactory
     */
    protected $orderStatusHistoryInterfaceFactory = null;

    /**
     * Resource model
     *
     * @var \Magento\Sales\Model\Spi\OrderStatusHistoryResourceInterface
     */
    protected $orderStatusHistoryInterfaceResource = null;

    /**
     * Application Resource
     *
     * @var \Magento\Framework\App\ResourceConnection
     */
    protected $resource = null;

    /**
     * Database Adapter
     *
     * @var \Magento\Framework\DB\Adapter\AdapterInterface
     */
    protected $connection = null;

    /**
     * @var array
     */
    protected $entitiesPool = array(

    );

    /**
     * @var array
     */
    protected $stack = array(

    );

    /**
     * Persistor constructor
     *
     * @param \Magento\Sales\Model\Spi\OrderStatusHistoryResourceInterface
     * $orderStatusHistoryInterfaceResource
     * @param \Magento\Sales\Api\Data\OrderStatusHistoryInterfaceFactory
     * $orderStatusHistoryInterfaceFactory
     * @param \Magento\Framework\App\ResourceConnection $resource
     */
    public function __construct(\Magento\Sales\Model\Spi\OrderStatusHistoryResourceInterface $orderStatusHistoryInterfaceResource, \Magento\Sales\Api\Data\OrderStatusHistoryInterfaceFactory $orderStatusHistoryInterfaceFactory, \Magento\Framework\App\ResourceConnection $resource)
    {
        $this->orderStatusHistoryInterfaceResource = $orderStatusHistoryInterfaceResource;
        $this->orderStatusHistoryInterfaceFactory = $orderStatusHistoryInterfaceFactory;
        $this->resource = $resource;
    }

    /**
     * Returns Adapter interface
     *
     * @return array \Magento\Framework\DB\Adapter\AdapterInterface
     */
    public function getConnection()
    {
        if (!$this->connection) {
            $this->connection = $this->resource->getConnection(\Magento\Framework\App\ResourceConnection::DEFAULT_CONNECTION);
        }
        return $this->connection;
    }

    /**
     * Load entity by key
     *
     * @param int $key
     * @return \Magento\Sales\Api\Data\OrderStatusHistoryInterfacePersistor $entity
     */
    public function loadEntity($key)
    {
        $entity = $this->orderStatusHistoryInterfaceFactory->create()->load($key);
        return $entity;
    }

    /**
     * Register entity to delete
     *
     * @param \Magento\Sales\Api\Data\OrderStatusHistoryInterface $entity
     */
    public function registerDeleted(\Magento\Sales\Api\Data\OrderStatusHistoryInterface $entity)
    {
        $hash = spl_object_hash($entity);array_push($this->stack, $hash);$this->entitiesPool[$hash] = [    'entity' => $entity,    'action' => 'removed'];
    }

    /**
     * Register entity to create
     *
     * @param \Magento\Sales\Api\Data\OrderStatusHistoryInterface $entity
     */
    public function registerNew(\Magento\Sales\Api\Data\OrderStatusHistoryInterface $entity)
    {
        $hash = spl_object_hash($entity);
        $data = [
        'entity' => $entity,
        'action' => 'created'
        ];
        array_push($this->stack, $hash);
        $this->entitiesPool[$hash] = $data;
    }

    /**
     * Register entity to create
     *
     * @param array $data
     * @param \Magento\Sales\Api\Data\OrderStatusHistoryInterface $entity
     */
    public function registerFromArray(array $data)
    {
        $entity = $this->orderStatusHistoryInterfaceFactory->create(['data' => $data]);
        $this->registerNew($entity);
        return $entity;
    }

    /**
     * Perform persist operation
     *
     * @param int $items
     * @return array
     */
    public function doPersist($items = 0)
    {
        $ids = [];
        $this->getConnection()->beginTransaction();
        try {
            do {
                $hash = array_pop($this->stack);
                if (isset($this->entitiesPool[$hash])) {
                    $data = $this->entitiesPool[$hash];
                    if ($data['action'] == 'created') {
                        $this->orderStatusHistoryInterfaceResource->save($data['entity']);
                        $ids[] = $data['entity']->getId();
                    } else {
                        $ids[] = $data['entity']->getId();
                        $this->orderStatusHistoryInterfaceResource->delete($data['removed']);
                    }
                }
                unset($this->entitiesPool[$hash]);
                $items--;
            } while (!empty($this->entitiesPool) || $items === 0);
            $this->getConnection()->commit();
            return $ids;
        } catch (\Exception $e) {
            $this->getConnection()->rollback();
            throw $e;
        }
    }

    /**
     * Persist entity
     *
     * @param \Magento\Sales\Api\Data\OrderStatusHistoryInterface $entity
     */
    public function doPersistEntity(\Magento\Sales\Api\Data\OrderStatusHistoryInterface $entity)
    {
        $hash = spl_object_hash($entity);
        if (isset($this->entitiesPool[$hash])) {
        $tempStack = $this->stack;
        array_flip($tempStack);
        unset($tempStack[$hash]);
        $this->stack = array_flip($tempStack);
        unset($this->entitiesPool[$hash]);
        }
        $this->registerNew($entity);
        return $this->doPersist(1);
    }
}


text:
<!DOCTYPE html>

	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>Nova Escola</title>
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">
	<link href='https://fonts.googleapis.com/css?family=Audiowide' rel='stylesheet' type='text/css'>

	    	<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar-content">

	      </button>

Home(current)

Quem Somos

Saber Mais

Colaborar

Blog

Programa de Bolsas de Estudo

1a Oficina Urbana

1o Solos For Change Teresina

Como Colaborar

Blog Nova Escola

@projetonovaescola on facebook

@projetonovaescola on gmail

					powered by:
					<spam class="nova-geracao">nova geracao</spam>


text:
namespace chromecast {
namespace media {

enum class AudioContentType;
class AudioDecoderWrapper;
class VideoDecoderWrapper;
class MediaPipelineBackend;
class MediaPipelineBackendManager;
class DecoderCreatorCmaBackend;

class MediaPipelineBackendWrapper : public CmaBackend {
 public:
  MediaPipelineBackendWrapper(const media::MediaPipelineDeviceParams& params,
                              MediaPipelineBackendManager* backend_manager,
                              MediaResourceTracker* media_resource_tracker);

  MediaPipelineBackendWrapper(const MediaPipelineBackendWrapper&) = delete;
  MediaPipelineBackendWrapper& operator=(const MediaPipelineBackendWrapper&) =
      delete;

  ~MediaPipelineBackendWrapper() override;

  // After revocation, this class releases the media resource on the device,
  // so the next MediaPipelineBackend can be created for the next application.
  // See b/69180616.
  void Revoke();

  // CmaBackend implementation:
  AudioDecoder* CreateAudioDecoder() override;
  VideoDecoder* CreateVideoDecoder() override;
  bool Initialize() override;
  bool Start(int64_t start_pts) override;
  void Stop() override;
  bool Pause() override;
  bool Resume() override;
  int64_t GetCurrentPts() override;
  bool SetPlaybackRate(float rate) override;
  void LogicalPause() override;
  void LogicalResume() override;

 private:
  std::unique_ptr<AudioDecoderWrapper> audio_decoder_;
  std::unique_ptr<VideoDecoderWrapper> video_decoder_;

  bool revoked_;
  std::unique_ptr<DecoderCreatorCmaBackend> backend_;
  MediaPipelineBackendManager* const backend_manager_;
  const AudioContentType content_type_;
};

}  // namespace media
}  // namespace chromecast

#endif  // CHROMECAST_MEDIA_COMMON_MEDIA_PIPELINE_BACKEND_WRAPPER_H_


text:
//
//  KHMViewController.m
//  KHMColorWheelDemo
//
//  Created by XiaoHM on 15/8/8.
//  Copyright (c) 2015年 KevinHM. All rights reserved.
//

#import "KHMViewController.h"

#import "KHMColorWheelView.h"
#import <Masonry/Masonry.h>

static NSInteger const KHMColorWheelViewSize = 230; //因为我使用的图片为这个尺寸 @2x\@3x

@interface KHMViewController ()
@property (nonatomic, weak) IBOutlet KHMColorWheelView *colorWheelView;
@property (nonatomic, strong) UIImageView *imageView;
@property (nonatomic, strong) NSTimer *eventTimer;

@end

@implementation KHMViewController

#pragma mark - View Life Cycle

- (void)awakeFromNib {
    [super awakeFromNib];
    [[KHMColorWheelView appearance] setColorMinimumAlpha:.1f];
    [[KHMColorWheelView appearance] setDragImageViewSize:23.f];
}

- (void)viewDidLoad {
    [super viewDidLoad];

    [self defaultConfiguration]; /*! 默认设置*/
    [self configuredViewHierarchy]; /*! 构建视图层级*/
    [self layoutComponents]; /*! 视图AL布局*/
}

#pragma mark - private method

- (void)defaultConfiguration {

    self.view.backgroundColor = [UIColor colorWithRed:0.5 green:0.5 blue:0.5 alpha:0.5];
    self.colorWheelView.layer.cornerRadius = (KHMColorWheelViewSize) / 2.0;
    self.colorWheelView.layer.masksToBounds = YES;

    self.imageView.backgroundColor = [UIColor whiteColor];

    __weak typeof(self) weakSelf = self;
    self.colorWheelView.colorDidChangedBlock = ^(UIColor *color) {
        weakSelf.imageView.image = [UIImage imageWithColor:color];
        NSLog(@"Obtain Color : %@",color);
    };

    self.colorWheelView.colorEventBlock = ^(UIColor *color) {
        NSLog(@"Color About Event");
    };

    self.colorWheelView.pressEndEvent = ^{
        NSLog(@"pressEndEvent");
    };

    self.colorWheelView.pressBeginEvent = ^ {
        NSLog(@"pressBeginEvent");
    };
}

- (void)configuredViewHierarchy {
//    manual code
//    [self.view addSubview:self.colorWheelView];
    [self.view addSubview:self.imageView];
}

- (void)layoutComponents {
// manual code
//    [self.colorWheelView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.size.mas_equalTo(CGSizeMake(KHMColorWheelViewSize, KHMColorWheelViewSize));
//        make.centerY.equalTo(self.view.mas_centerY);
//        make.centerX.equalTo(self.view.mas_centerX);
//    }];

    [self.imageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(80, 40));
        make.bottom.equalTo(self.colorWheelView.mas_top).offset(-20);
        make.centerX.equalTo(self.view.mas_centerX);
    }];
}

#pragma mark - Getter/Setter
// manual code
//- (KHMColorWheelView *)colorWheelView {
//    if (!_colorWheelView) {
//        _colorWheelView = [[KHMColorWheelView alloc] init];
//    }
//
//    return _colorWheelView;
//}

- (UIImageView *)imageView {
    if (!_imageView) {
        _imageView = [[UIImageView alloc] init];
    }

    return _imageView;
}

@end


text:
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

from tensorflow.python.ops import control_flow_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import state_ops
from tensorflow.python.framework import ops
from tensorflow.python.training import optimizer
import hyperchamber as hc
import numpy as np
import inspect
from operator import itemgetter
from hypergan.train_hooks.base_train_hook import BaseTrainHook

EPS=1e-8

class ProgressCompressTrainHook(BaseTrainHook):
  """https://arxiv.org/pdf/1805.06370v2.pdf"""
  def __init__(self, gan=None, config=None, trainer=None, name="ProgressCompressTrainHook"):
    super().__init__(config=config, gan=gan, trainer=trainer, name=name)
    d_loss = []

    self.x = tf.Variable(tf.zeros_like(gan.inputs.x))
    self.g = tf.Variable(tf.zeros_like(gan.generator.sample))

    stacked = tf.concat([self.x, self.g], axis=0)
    self.kb = gan.create_component(config["knowledge_base"], name="knowledge_base", input=stacked)
    self.assign_x = tf.assign(self.x, gan.inputs.x)
    self.assign_g = tf.assign(self.g, gan.generator.sample)
    self.re_init_d = [d.initializer for d in gan.discriminator.variables()]
    gan.hack = self.g

    self.assign_knowledge_base = []
    for c in gan.components:
        if hasattr(c, 'knowledge_base'):
            for name, net in c.knowledge_base:
                assign = self.kb.named_layers[name]
                if self.ops.shape(assign)[0] > self.ops.shape(net)[0]:
                    assign = tf.slice(assign,[0 for i in self.ops.shape(net)] , [self.ops.shape(net)[0]]+self.ops.shape(assign)[1:])
                self.assign_knowledge_base.append(tf.assign(net, assign))

    def kl_divergence(_p, _q):
        return tf.reduce_sum(_p * tf.log(_p/(_q+EPS)+EPS))

    if self.config.method == 'gan':
        bs = gan.batch_size()
        real = tf.reshape(gan.loss.sample[:2], [bs, 2])
        fake = tf.reshape(self.kb.sample, [bs, 2])
        gl = tf.concat([real, fake], axis=0)
        self.kb_d = gan.create_component(self.config.knowledge_discriminator, name="kb_d", input=gl)
        self.kb_loss = self.gan.create_loss(self.kb_d)
        self.loss = self.kb_loss.sample[0] + self.kb_loss.sample[1]
        variables = self.kb_d.variables()
        variables += self.kb.variables()
    else:
        self.kb_loss = self.gan.create_component(gan.config.loss, discriminator=self.kb, split=2)

        self.loss = kl_divergence(gan.loss.sample[0], self.kb_loss.sample[0])
        if self.config.kl_on_d_fake:
            self.loss = kl_divergence(gan.loss.d_real, self.kb_loss.d_real)
        if self.config.kl_on_g:
            self.loss += kl_divergence(gan.loss.sample[1], self.kb_loss.sample[1])
        variables = self.kb.variables()
    config["optimizer"]["loss"] = self.loss
    self.optimizer = self.gan.create_optimizer(config["optimizer"])
    grads = tf.gradients(self.loss, variables)
    apply_vec = list(zip(grads, variables)).copy()
    self.optimize_t = self.optimizer.apply_gradients(apply_vec, global_step=gan.global_step)

    self.gan.add_metric('kbl', self.kb_loss.sample[0])
    self.gan.add_metric('kblg', self.kb_loss.sample[1])
    self.gan.add_metric('compress', self.loss)

  def losses(self):
      return [None, None]

  def after_step(self, step, feed_dict):
    if step % (self.config.step_count or 1) != 0:
      return
    # compress
    for i in range(self.config.night_steps or 1):
        self.gan.session.run(self.optimize_t)
    if self.config.reinitialize_every:
        if step % (self.config.reinitialize_every)==0 and step > 0:
            print("Reinitializing active D")
            self.gan.session.run(self.re_init_d)

  def before_step(self, step, feed_dict):
    self.gan.session.run([self.assign_x, self.assign_g]+ self.assign_knowledge_base)


text:
%%%%%%%%%%%%%%%%%
% This is an example CV created using altacv.cls (v1.1.2, 1 February 2017) written by
% LianTze Lim (liantze@gmail.com), based on the
% Cv created by BusinessInsider at http://www.businessinsider.my/a-sample-resume-for-marissa-mayer-2016-7/?r=US&IR=T
%
%% It may be distributed and/or modified under the
%% conditions of the LaTeX Project Public License, either version 1.3
%% of this license or (at your option) any later version.
%% The latest version of this license is in
%%    http://www.latex-project.org/lppl.txt
%% and version 1.3 or later is part of all distributions of LaTeX
%% version 2003/12/01 or later.
%%%%%%%%%%%%%%%%

%% If you want to use \orcid or the
%% academicons icons, add "academicons"
%% to the \documentclass options.
%% Then compile with XeLaTeX or LuaLaTeX.
% \documentclass[10pt,a4paper,academicons]{altacv}
\documentclass[10pt,a4paper]{altacv}

%% AltaCV uses the fontawesome and academicon fonts
%% and packages.
%% See texdoc.net/pkg/fontawecome and http://texdoc.net/pkg/academicons for full list of symbols.
%% When using the "academicons" option,
%% Compile with LuaLaTeX for best results. If you
%% want to use XeLaTeX, you may need to install
%% Academicons.ttf in your operating system's font %% folder.

% Change the page layout if you need to
\geometry{left=1cm,right=9cm,marginparwidth=6.8cm,marginparsep=1.2cm,top=1cm,bottom=1cm}

% Change the font if you want to.

% If using pdflatex:
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage[default]{lato}

% If using xelatex or lualatex:
% \setmainfont{Lato}

% Change the colours if you want to
\definecolor{VividPurple}{HTML}{3E0097}
\definecolor{SlateGrey}{HTML}{2E2E2E}
\definecolor{LightGrey}{HTML}{666666}
\colorlet{heading}{VividPurple}
\colorlet{accent}{VividPurple}
\colorlet{emphasis}{SlateGrey}
\colorlet{body}{LightGrey}

% Change the bullets for itemize and rating marker
% for \cvskill if you want to
\renewcommand{\itemmarker}{{\small\textbullet}}
\renewcommand{\ratingmarker}{\faCircle}

%% sample.bib contains your publications
\addbibresource{sample.bib}

\begin{document}
\name{Ebeid ElSayed}
\tagline{Experienced Software Engineer \& Grade Student}
% Cropped to square from %
\photo{2.5cm}{ebeid_linkedin}
\personalinfo{%
  % Not all of these are required!
  % You can add your own with \printinfo{symbol}{detail}
  \email{Ebeid@gatech.edu}
%   \phone{000-00-0000}
  \mailaddress{5520 Springhouse Dr., Apt. 32}
  \location{Pleasanton, CA}
  \twitter{@ebeidelsayed}
  \linkedin{linkedin.com/in/ebeidelsayed/}
  \github{github.com/Ebeid}
  \homepage{ebeid.github.io}
  }

%% Make the header extend all the way to the right, if you want. Extend the right margin by 8cm (=6.8cm marginparwidth + 1.2cm marginparsep)
\begin{adjustwidth}{}{-8cm}
\makecvheader
\end{adjustwidth}

%% Provide the file name containing the sidebar contents as an optional parameter to \cvsection.
%% You can always just use \marginpar{...} if you do
%% not need to align the top of the contents to any
%% \cvsection title in the "main" bar.
\cvsection[page1sidebar]{Experience}

\cvevent{Software Engineer}{Ellie Mae, Inc}{Oct 2015 -- Ongoing}{Pleasanton, CA}
Built and maintained the APIs needed for Encompass TPO Connect, Encompass Consumer Connect, and core Ellie Mae's Encompass Lending Platform. Contributed to CI/CD infrastructure and platform APM.

\divider\smallskip

\cvevent{Lead Engineer}{Hoot Education, Inc}{April 2015 -- Dec 2015}{Dallas, TX}
Designed, built, and deployed Hoot Education Platform to Microsoft Azure. Hired and managed the technical team. Led the product development from inception to revenue.

\divider\smallskip

\cvevent{Software Engineer}{Interface People, LP}{Oct 2013 -- Sept 2015}{Dallas, TX}
Designed and built features in two flagship products: Quest Designer Suite (Windows Application) and Quest Web (web rendering engine).

\divider\smallskip

\cvevent{Software Engineer}{Bryan Research \& Engineering}{Dec 2011 -- Sep 2013}{Bryan, TX}

\cvevent{Software Engineer - Independent Consultant}{Teneo Software Solutions}{May 2012 -- Oct 2012}{College Station, TX}

\cvevent{Software Applications Developer}{Texas A\&M University}{July 2011 -- Nov 2011}{College Station, TX}

\cvevent{Developer Support Engineer}{Microsoft}{Nov 2008 - Dec 2010}{Cairo, Egypt}

\cvevent{Software Engineer}{ITWorx}{Jan 2008 - Oct 2008}{Cairo, Egypt}

\cvevent{Software Engineer}{quTIP}{Oct 2007 - Dec 2007}{Cairo, Egypt}

\cvevent{First Lieutenant}{Egyptian Army}{June 2005 - Sept 2007}{Cairo, Egypt}

\cvevent{Software Engineer}{EuroSoft}{May 2005 - June 2005}{Cairo, Egypt}

\end{document}


text:
<!doctype html>

    <title>Code coverage report for ./src/client/app/layout\</title>
    <meta charset="utf-8">
    <link rel="stylesheet" href="../../../../prettify.css">
    <link rel="stylesheet" href="../../../../base.css">

Code coverage report for ./src/client/app/layout\

        Statements: 44.44% (8 / 18)
        Branches: 100% (0 / 0)
        Functions: 28.57% (2 / 7)
        Lines: 44.44% (8 / 18)
        Ignored: none

All files » ./src/client/app/layout/

   File

   Statements

   Branches

   Functions

   Lines

	layout.module.js

	100%
	(2 / 2)
	100%
	(0 / 0)
	100%
	(1 / 1)
	100%
	(2 / 2)

	shell.js

	37.5%
	(6 / 16)
	100%
	(0 / 0)
	16.67%
	(1 / 6)
	37.5%
	(6 / 16)

Generated by istanbul at Mon Nov 23 2015 14:24:27 GMT+0000 (GMT Standard Time)


text:
@class UIButton, UISegmentedControl;
@protocol UIWebFormAccessoryDelegate;

__attribute__((visibility("hidden")))
@interface UIWebFormAccessory : UIImageView {
@private
	UIButton* _done;
	UISegmentedControl* _tab;
	UIButton* _autofill;
	id<UIWebFormAccessoryDelegate> delegate;
}
@property(retain, nonatomic) UIButton* _done;
@property(retain, nonatomic) UISegmentedControl* _tab;
@property(retain, nonatomic) UIButton* _autofill;
@property(assign, nonatomic) id<UIWebFormAccessoryDelegate> delegate;
// inherited: -(id)init;
// inherited: -(void)dealloc;
-(void)done:(id)done;
-(void)tab:(id)tab;
-(void)autoFill:(id)fill;
-(void)enableAutoFill:(BOOL)fill;
-(void)enableNext:(BOOL)next enablePrevious:(BOOL)previous;
-(void)layoutSubviews;
@end

#endif


text:
module FortesForum
  class Forum < ActiveRecord::Base
    include FortesForum::Default::Forum

  end
end


text:
<?xml version="1.0"?>
<!--
  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. See accompanying LICENSE file.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
                      http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <parent>
    <artifactId>hadoop-yarn</artifactId>
    <groupId>org.apache.hadoop</groupId>
    <version>2.2.0</version>
  </parent>
  <modelVersion>4.0.0</modelVersion>
  <groupId>org.apache.hadoop</groupId>
  <artifactId>hadoop-yarn-applications</artifactId>
  <version>2.2.0</version>
  <name>hadoop-yarn-applications</name>
  <packaging>pom</packaging>

  <properties>
    <hadoop.common.build.dir>${basedir}/../../../../hadoop-common-project/hadoop-common/target</hadoop.common.build.dir>
  </properties>

  <modules>
    <module>hadoop-yarn-applications-distributedshell</module>
    <module>hadoop-yarn-applications-unmanaged-am-launcher</module>
  </modules>

 <profiles>
  <profile>
    <id>clover</id>
    <activation>
      <activeByDefault>false</activeByDefault>
      <property>
        <name>clover</name>
      </property>
    </activation>
    <dependencies>
      <dependency>
        <groupId>com.cenqua.clover</groupId>
        <artifactId>clover</artifactId>
      </dependency>
    </dependencies>
  </profile>
</profiles>
</project>


text:
<button type="button" class="btn btn-default" id="toggle_news" data-text-swap="Show less news" style="margin-bottom:20px;">Show more news</button>

<script type="text/javascript">
    $(document).ready(function(){
        $('div[class*="news-wrapper-hidden"]').hide();
    })
    $("#toggle_news").click(function(){
        $('div[class*="news-wrapper-hidden"]').toggle();
    })
</script>
<script type="text/javascript">
$("button").on("click", function() {
  var el = $(this);
  if (el.text() == el.data("text-swap")) {
    el.text(el.data("text-original"));
  } else {
    el.data("text-original", el.text());
    el.text(el.data("text-swap"));
  }
});
</script>


text:
namespace rpc {

class Message;
class Container;
class Parameter;
class Invocation;

// All the possible message types
enum MessageType
{
    INVOCATION,
    RETURN,
    REQUEST_NEW,
    REQUEST_LOOKUP,
    REQUEST_LEASE,
    EXCEPTION,
    BARRIER_UP,
    BARRIER_HIT,
    BARRIER_DOWN,
    INVALID
};

// Helper class. Extracts parameters from a demarshalled invocation.
class ParameterPuller
{
public:
    void pullValue( co::IType* descriptor, const co::Any& ret );
    void pullReference( ReferenceType& refType );

    friend class Demarshaller;
private:
    ParameterPuller();

    void setParams( const ::google::protobuf::RepeatedPtrField< ::rpc::Parameter >* params );

    co::int32 _currentParam;
    const ::google::protobuf::RepeatedPtrField< ::rpc::Parameter >* _params;
};

class Demarshaller
{

public:

    Demarshaller();
    ~Demarshaller();

    //
    // Demarshalling methods. Usage: Set the marshalled data first, then get the parameter results.
    //

    // Set the data that will be demarshalled and then have its parameters retrieved.
    MessageType demarshal( inString data );

    void getNew( outString requesterEndpoint, outString instanceType );
    void getLookup( outString requesterEndpoint, outString lookupKey, outString instanceType );
    void getLease( outString requesterEndpoint, co::int32& leaseInstanceID );

    // If message type is Invocation, then this method gets the parameters
    ParameterPuller& getInvocation( outString requesterEndpoint, InvocationDetails& details );

	ParameterPuller& getOutput();
    co::int32 getIntReturn();

    ExceptionType getException( outString exTypeName, outString what );

    // Synchronization Barrier
    void getBarrierCreator( outString creatorEndpoint );

private:
    void checkIfCallMsg();

private:
    Message* _message;
    MessageType _msgType;
    Parameter* _parameter;
    co::int32 _currentParam;

    ParameterPuller _puller;

};

} // namespace rpc
#endif


text:
from __future__ import absolute_import
from .common import read_map, loadtxt
import numpy as np
from healpy import nside2npix
import os

data_dir = os.path.join(os.path.dirname(__file__), 'template')
template = lambda x: os.path.join(data_dir, x)

def models(key, nside, pixel_indices=None, mpi_comm=None):
    model = eval(key)(nside, pixel_indices=pixel_indices, mpi_comm=mpi_comm)
    for m in model:
        m['pixel_indices'] = pixel_indices # include pixel indices in the model dictionary
        m['nside'] = nside
    return model

def d0(nside, pixel_indices=None, mpi_comm=None):
    A_I = read_map(template('dust_t_new.fits'), nside, field=0, pixel_indices=pixel_indices, mpi_comm=mpi_comm)
    return [{
        'model': 'modified_black_body',
        'nu_0_I': 545.,
        'nu_0_P': 353.,
        'A_I': A_I,
        'A_Q': read_map(template('dust_q_new.fits'), nside, field=0, pixel_indices=pixel_indices, mpi_comm=mpi_comm),
        'A_U': read_map(template('dust_u_new.fits'), nside, field=0, pixel_indices=pixel_indices, mpi_comm=mpi_comm),
        'spectral_index': np.ones(len(A_I)) * 1.54,
        'temp': np.ones(len(A_I)) * 20.,
        'add_decorrelation': False,
    }]

def d1(nside, pixel_indices=None, mpi_comm=None):
    return [{
        'model': 'modified_black_body',
        'nu_0_I': 545.,
        'nu_0_P': 353.,
        'A_I': read_map(template('dust_t_new.fits'), nside, field=0, pixel_indices=pixel_indices, mpi_comm=mpi_comm),
        'A_Q': read_map(template('dust_q_new.fits'), nside, field=0, pixel_indices=pixel_indices, mpi_comm=mpi_comm),
        'A_U': read_map(template('dust_u_new.fits'), nside, field=0, pixel_indices=pixel_indices, mpi_comm=mpi_comm),
        'spectral_index': read_map(template('dust_beta.fits'), nside=nside, field=0, pixel_indices=pixel_indices, mpi_comm=mpi_comm),
        'temp': read_map(template('dust_temp.fits'), nside, field=0, pixel_indices=pixel_indices, mpi_comm=mpi_comm),
        'add_decorrelation': False,
    }]

def d2(nside, pixel_indices=None, mpi_comm=None):
    return [{
        'model': 'modified_black_body',
        'nu_0_I': 545.,
        'nu_0_P': 353.,
        'A_I': read_map(template('dust_t_new.fits'), nside, field=0, pixel_indices=pixel_indices, mpi_comm=mpi_comm),
        'A_Q': read_map(template('dust_q_new.fits'), nside, field=0, pixel_indices=pixel_indices, mpi_comm=mpi_comm),
        'A_U': read_map(template('dust_u_new.fits'), nside, field=0, pixel_indices=pixel_indices, mpi_comm=mpi_comm),
        'spectral_index': read_map(template('beta_mean1p59_std0p2.fits'), nside, field=0, pixel_indices=pixel_indices, mpi_comm=mpi_comm),
        'temp': read_map(template('dust_temp.fits'), nside, field=0, pixel_indices=pixel_indices, mpi_comm=mpi_comm),
        'add_decorrelation': False,
    }]

def d3(nside, pixel_indices=None, mpi_comm=None):
    return [{
        'model': 'modified_black_body',
        'nu_0_I': 545.,
        'nu_0_P': 353.,
        'A_I': read_map(template('dust_t_new.fits'), nside, field=0, pixel_indices=pixel_indices, mpi_comm=mpi_comm),
        'A_Q': read_map(template('dust_q_new.fits'), nside, field=0, pixel_indices=pixel_indices, mpi_comm=mpi_comm),
        'A_U': read_map(template('dust_u_new.fits'), nside, field=0, pixel_indices=pixel_indices, mpi_comm=mpi_comm),
        'spectral_index': read_map(template('beta_mean1p59_std0p3.fits'), nside, field=0, pixel_indices=pixel_indices, mpi_comm=mpi_comm),
        'temp': read_map(template('dust_temp.fits'), nside, field=0, pixel_indices=pixel_indices, mpi_comm=mpi_comm),
        'add_decorrelation': False,
    }]

def d4(nside, pixel_indices=None, mpi_comm=None):
    return [{
        'model': 'modified_black_body',
        'nu_0_I': 545.,
        'nu_0_P': 353.,
        'A_I': read_map(template('dust2comp_I1_ns512_545.fits'), nside, field=0, pixel_indices=pixel_indices, mpi_comm=mpi_comm),
        'A_Q': read_map(template('dust2comp_Q1_ns512_353.fits'), nside, field=0, pixel_indices=pixel_indices, mpi_comm=mpi_comm),
        'A_U': read_map(template('dust2comp_U1_ns512_353.fits'), nside, field=0, pixel_indices=pixel_indices, mpi_comm=mpi_comm),
        'spectral_index': read_map(template('dust2comp_beta1_ns512.fits'), nside, field=0, pixel_indices=pixel_indices, mpi_comm=mpi_comm),
        'temp': read_map(template('dust2comp_temp1_ns512.fits'), nside, field=0, pixel_indices=pixel_indices, mpi_comm=mpi_comm),
        'add_decorrelation': False,
    }, {
        'model': 'modified_black_body',
        'nu_0_I': 545.,
        'nu_0_P': 353.,
        'A_I': read_map(template('dust2comp_I2_ns512_545.fits'), nside, field=0, pixel_indices=pixel_indices, mpi_comm=mpi_comm),
        'A_Q': read_map(template('dust2comp_Q2_ns512_353.fits'), nside, field=0, pixel_indices=pixel_indices, mpi_comm=mpi_comm),
        'A_U': read_map(template('dust2comp_U2_ns512_353.fits'), nside, field=0, pixel_indices=pixel_indices, mpi_comm=mpi_comm),
        'spectral_index': read_map(template('dust2comp_beta2_ns512.fits'), nside, field=0, pixel_indices=pixel_indices, mpi_comm=mpi_comm),
        'temp': read_map(template('dust2comp_temp2_ns512.fits'), nside, field=0, pixel_indices=pixel_indices, mpi_comm=mpi_comm),
        'add_decorrelation': False,
    }]

def d5(nside, pixel_indices=None, mpi_comm=None):
    return [{
        'model': 'hensley_draine_2017',
        'draw_uval': True,
        'draw_uval_seed': 4632,
        'fcar': 1.,
        'f_fe': 0.,
        'nu_0_I': 545.,
        'nu_0_P': 353.,
        'A_I': read_map(template('dust_t_new.fits'), nside, field=0, pixel_indices=pixel_indices, mpi_comm=mpi_comm),
        'A_Q': read_map(template('dust_q_new.fits'), nside, field=0, pixel_indices=pixel_indices, mpi_comm=mpi_comm),
        'A_U': read_map(template('dust_u_new.fits'), nside, field=0, pixel_indices=pixel_indices, mpi_comm=mpi_comm),
        'add_decorrelation': False,
    }]

def d6(nside, pixel_indices=None, mpi_comm=None):
    return [{
        'model': 'modified_black_body',
        'nu_0_I': 545.,
        'nu_0_P': 353.,
        'A_I': read_map(template('dust_t_new.fits'), nside, field=0, pixel_indices=pixel_indices, mpi_comm=mpi_comm),
        'A_Q': read_map(template('dust_q_new.fits'), nside, field=0, pixel_indices=pixel_indices, mpi_comm=mpi_comm),
        'A_U': read_map(template('dust_u_new.fits'), nside, field=0, pixel_indices=pixel_indices, mpi_comm=mpi_comm),
        'spectral_index': read_map(template('dust_beta.fits'), nside, field=0, pixel_indices=pixel_indices, mpi_comm=mpi_comm),
        'temp': read_map(template('dust_temp.fits'), nside, field=0, pixel_indices=pixel_indices, mpi_comm=mpi_comm),
        'add_decorrelation': True,
        'corr_len': 5.0
    }]

def d7(nside, pixel_indices=None, mpi_comm=None):
    return [{
        'model': 'hensley_draine_2017',
        'draw_uval': True,
        'draw_uval_seed': 4632,
        'fcar': 1.,
        'f_fe': 0.44,
        'nu_0_I': 545.,
        'nu_0_P': 353.,
        'A_I': read_map(template('dust_t_new.fits'), nside, field=0, pixel_indices=pixel_indices, mpi_comm=mpi_comm),
        'A_Q': read_map(template('dust_q_new.fits'), nside, field=0, pixel_indices=pixel_indices, mpi_comm=mpi_comm),
        'A_U': read_map(template('dust_u_new.fits'), nside, field=0, pixel_indices=pixel_indices, mpi_comm=mpi_comm),
        'add_decorrelation' : False,
    }]

def d8(nside, pixel_indices=None, mpi_comm=None):
    return [{
        'model': 'hensley_draine_2017',
        'draw_uval': False,
        'uval': 0.2,
        'draw_uval_seed': 4632,
        'fcar': 1.,
        'f_fe': 0.44,
        'nu_0_I': 545.,
        'nu_0_P': 353.,
        'A_I': read_map(template('dust_t_new.fits'), nside, field=0, pixel_indices=pixel_indices, mpi_comm=mpi_comm),
        'A_Q': read_map(template('dust_q_new.fits'), nside, field=0, pixel_indices=pixel_indices, mpi_comm=mpi_comm),
        'A_U': read_map(template('dust_u_new.fits'), nside, field=0, pixel_indices=pixel_indices, mpi_comm=mpi_comm),
        'add_decorrelation': False,
    }]

def s0(nside, pixel_indices=None, mpi_comm=None):
    A_I = read_map(template('synch_t_new.fits'), nside, field=0, pixel_indices=pixel_indices, mpi_comm=mpi_comm)
    return [{
        'model': 'power_law',
        'nu_0_I': 0.408,
        'nu_0_P': 23.,
        'A_I': A_I,
        'A_Q': read_map(template('synch_q_new.fits'), nside, field=0, pixel_indices=pixel_indices, mpi_comm=mpi_comm),
        'A_U': read_map(template('synch_u_new.fits'), nside, field=0, pixel_indices=pixel_indices, mpi_comm=mpi_comm),
        'spectral_index': np.ones(len(A_I)) * -3,
    }]

def s1(nside, pixel_indices=None, mpi_comm=None):
    return [{
        'model': 'power_law',
        'nu_0_I': 0.408,
        'nu_0_P': 23.,
        'A_I': read_map(template('synch_t_new.fits'), nside, field=0, pixel_indices=pixel_indices, mpi_comm=mpi_comm),
        'A_Q': read_map(template('synch_q_new.fits'), nside, field=0, pixel_indices=pixel_indices, mpi_comm=mpi_comm),
        'A_U': read_map(template('synch_u_new.fits'), nside, field=0, pixel_indices=pixel_indices, mpi_comm=mpi_comm),
        'spectral_index': read_map(template('synch_beta.fits'), nside, field=0, pixel_indices=pixel_indices, mpi_comm=mpi_comm),
    }]

def s2(nside, pixel_indices=None, mpi_comm=None):
    return [{
        'model': 'power_law',
        'nu_0_I': 0.408,
        'nu_0_P': 23.,
        'A_I': read_map(template('synch_t_new.fits'), nside, field=0, pixel_indices=pixel_indices, mpi_comm=mpi_comm),
        'A_Q': read_map(template('synch_q_new.fits'), nside, field=0, pixel_indices=pixel_indices, mpi_comm=mpi_comm),
        'A_U': read_map(template('synch_u_new.fits'), nside, field=0, pixel_indices=pixel_indices, mpi_comm=mpi_comm),
        'spectral_index': read_map(template('beta_latvar.fits'), nside, field=0, pixel_indices=pixel_indices, mpi_comm=mpi_comm),
    }]

def s3(nside, pixel_indices=None, mpi_comm=None):
    return [{
        'model': 'curved_power_law',
        'nu_0_I': 0.408,
        'nu_0_P': 23.,
        'A_I': read_map(template('synch_t_new.fits'), nside, field=0, pixel_indices=pixel_indices, mpi_comm=mpi_comm),
        'A_Q': read_map(template('synch_q_new.fits'), nside, field=0, pixel_indices=pixel_indices, mpi_comm=mpi_comm),
        'A_U': read_map(template('synch_u_new.fits'), nside, field=0, pixel_indices=pixel_indices, mpi_comm=mpi_comm),
        'spectral_index': read_map(template('synch_beta.fits'), nside, field=0, pixel_indices=pixel_indices, mpi_comm=mpi_comm),
        'spectral_curvature': -0.052,
        'nu_curve': 23.,
    }]

def f1(nside, pixel_indices=None, mpi_comm=None):
    return [{
        'model': 'power_law',
        'nu_0_I': 30.,
        'A_I': read_map(template('ff_t_new.fits'), nside, field=0, pixel_indices=pixel_indices, mpi_comm=mpi_comm),
        'spectral_index': -2.14,
    }]

def c1(nside, pixel_indices=None, mpi_comm=None):
    return [{
        'model': 'taylens',
        'cmb_specs': loadtxt(template('camb_lenspotentialCls.dat'), mpi_comm=mpi_comm, unpack=True),
        'delens': False,
        'delensing_ells': loadtxt(template('delens_ells.txt'), mpi_comm=mpi_comm),
        'nside': nside,
        'cmb_seed': 1111
    }]

def c2(nside, pixel_indices=None, mpi_comm=None):
    return [{
        'model': 'pre_computed',
        'A_I': read_map(template('lensed_cmb.fits'), nside, field=0, pixel_indices=pixel_indices, mpi_comm=mpi_comm),
        'A_Q': read_map(template('lensed_cmb.fits'), nside, field=1, pixel_indices=pixel_indices, mpi_comm=mpi_comm),
        'A_U': read_map(template('lensed_cmb.fits'), nside, field=2, pixel_indices=pixel_indices, mpi_comm=mpi_comm),
        'nside': nside
    }]

def a1(nside, pixel_indices=None, mpi_comm=None):
    return [{
        'model': 'spdust',
        'nu_0_I': 22.8,
        'nu_0_P': 22.8,
        'A_I': read_map(template('ame_t_new.fits'), nside, field=0, pixel_indices=pixel_indices, mpi_comm=mpi_comm),
        'nu_peak_0': 30.,
        'emissivity': loadtxt(template('emissivity.txt'), mpi_comm=mpi_comm, unpack=True),
        'nu_peak': read_map(template('ame_nu_peak_0.fits'), nside, field=0, pixel_indices=pixel_indices, mpi_comm=mpi_comm),
    }, {
        'model': 'spdust',
        'nu_0_I': 41.0,
        'nu_0_P': 41.0,
        'A_I': read_map(template('ame2_t_new.fits'), nside, field=0, pixel_indices=pixel_indices, mpi_comm=mpi_comm),
        'nu_peak_0': 30.,
        'emissivity': loadtxt(template('emissivity.txt'), mpi_comm=mpi_comm, unpack=True),
        'nu_peak': 33.35
    }]

def a2(nside, pixel_indices=None, mpi_comm=None):
    return [{
        'model': 'spdust_pol',
        'nu_0_I': 22.8,
        'A_I': read_map(template('ame_t_new.fits'), nside, field=0, pixel_indices=pixel_indices, mpi_comm=mpi_comm),
        'nu_peak_0': 30.,
        'emissivity': loadtxt(template('emissivity.txt'), mpi_comm=mpi_comm, unpack=True),
        'nu_peak': read_map(template('ame_nu_peak_0.fits'), nside, field=0, pixel_indices=pixel_indices, mpi_comm=mpi_comm),
        'pol_frac': 0.02,
        'angle_q': read_map(template('dust_q_new.fits'), nside, field=0, pixel_indices=pixel_indices, mpi_comm=mpi_comm),
        'angle_u': read_map(template('dust_u_new.fits'), nside, field=0, pixel_indices=pixel_indices, mpi_comm=mpi_comm)
    }, {
        'model': 'spdust_pol',
        'nu_0_I': 41.0,
        'A_I': read_map(template('ame2_t_new.fits'), nside, field=0, pixel_indices=pixel_indices, mpi_comm=mpi_comm),
        'nu_peak_0': 30.,
        'emissivity': loadtxt(template('emissivity.txt'), mpi_comm=mpi_comm, unpack=True),
        'nu_peak': 33.35,
        'pol_frac': 0.02,
        'angle_q': read_map(template('dust_q_new.fits'), nside, field=0, pixel_indices=pixel_indices, mpi_comm=mpi_comm),
        'angle_u': read_map(template('dust_u_new.fits'), nside, field=0, pixel_indices=pixel_indices, mpi_comm=mpi_comm)
    }]


text:
<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>An element with role button without the aria-pressed state.</title>

This div has role button


text:
function createTable() {
    console.log("creating table...");

    var TABLE = [
        ["Header 1", "Header 2", "Header 3", "Header 4"],
        ["1, 1", "2, 1", "3, 1", "4, 1"],
        ["1, 2", "2, 2", "3, 2", "4, 2"],
        ["1, 3", "2, 3", "3, 3", "4, 3"],
    ];

    // allocate a new table
    var newTable = document.createElement("table");

    // loop through the table contents and create rows for them.
    for (var i = 0; i < TABLE.length; i++) {

        // create a new row
        var newRow = document.createElement("tr");
        var rowData = TABLE[i];

        // loop through the entries and create elements for them.
        for (var x = 0; x < rowData.length; x++) {

            // pick the right type of element to create
            var newDataType = "td";
            if (i == 0) {
                newDataType = "th";
            }

            var newData = document.createElement(newDataType);
            newData.appendChild(document.createTextNode(rowData[x]));
            newData.style.padding = '10px';  // create text node for the info
            newRow.appendChild(newData);
        }

        // append to newTable
        newTable.appendChild(newRow);
    }

    // set top left element as active element
    newTable.rows[0].cells[0].className += " selected"

    // append the new table to the document.
    document.body.appendChild(newTable);
}

function addButtons() {
    console.log("adding buttons...");

    var BUTTONS = ["LEFT", "UP", "DOWN", "RIGHT"];

    // create a table to store the buttons in
    var newTable = document.createElement("table");
    newTable.id = "the-table";

    // populate with buttons
    var newRow = document.createElement("tr");
    for (var i = 0; i < BUTTONS.length; i++) {
        newData = document.createElement("td")
        newButton = document.createElement("button");
        newButton.innerHTML = BUTTONS[i];
        newButton.id = BUTTONS[i];
        newData.appendChild(newButton);
        newRow.appendChild(newData);
    }

    newTable.appendChild(newRow);

    // create a row to store the "mark" button
    var newRow2 = document.createElement("tr");
    var newData2 = document.createElement("td");
    newData2.colSpan = 4;
    newButton2 = document.createElement("button");
    newButton2.innerHTML = "MARK";
    newButton2.id = 'mark-button'
    newButton2.style.margin = "auto";
    newButton2.style.display = "block";

    newData2.appendChild(newButton2);
    newRow2.appendChild(newData2);
    newTable.appendChild(newRow2);

    document.body.appendChild(newTable);
}

/**
 * Function mark()
 * @param  {[type]} cell Event passed clicking the 'mark' button.
 * @return {void}
 */
function mark() {

    console.log("Marking...");
    var cellToMark = document.getElementsByClassName('selected')[0];

    cellToMark.style.background = "#FFD707";
}

/**
 * [moveTableSelection description]
 * @param  {string} direction [Describes which direction the selected cell should move.]
 * @return {void}
 */
function moveTableSelection(direction) {
    // takes a direction as a parameter and applies movement in that direction
    var selectedCell = document.getElementsByClassName('selected')[0];

    // get x and y coordinates in the table.
    var xCoord = selectedCell.cellIndex;
    var xCoordNew = xCoord;
    var row = selectedCell.parentElement;
    var table = row.parentElement;
    var yCoord = selectedCell.parentElement.rowIndex;
    var yCoordNew = yCoord;
    console.log("Current cell is at position " + xCoord + ", " + yCoord + ", moving " + direction);

    // update new coordinates
    if (direction == "down") {
        yCoordNew += 1;
        yCoordNew = (yCoordNew > table.rows.length - 1) ? table.rows.length - 1 : yCoordNew;
    }
    else if (direction == "up") {
        yCoordNew -= 1;
        yCoordNew = (yCoordNew > 0) ? yCoordNew : 0;
    }
    else if (direction == "right") {

        xCoordNew += 1;
        xCoordNew = (xCoordNew <= row.cells.length - 1) ? xCoordNew : row.cells.length - 1;
        console.log("new x coord = " + xCoordNew);
    }
    else if (direction == 'left') {
        xCoordNew -= 1;
        xCoordNew = (xCoordNew > 0) ? xCoordNew : 0;
        console.log("new x coord = " + xCoordNew);
    }
    console.log("New cell is at position " + xCoordNew + ", " + yCoordNew);

    // select the correct set of cells based on the new coordinates.
    selectedCell.className -= " selected";
    table.rows[yCoordNew].cells[xCoordNew].className += " selected"
}

// set up the html page.
createTable();
addButtons();

// add event listeners
document.getElementById('mark-button').addEventListener('click', mark);
document.getElementById('LEFT').addEventListener('click', function() { moveTableSelection('left'); } );
document.getElementById('RIGHT').addEventListener('click', function() { moveTableSelection('right'); } );
document.getElementById('DOWN').addEventListener('click', function() { moveTableSelection('down'); } );
document.getElementById('UP').addEventListener('click', function() { moveTableSelection('up'); } );


text:
import { getTextContent, getTreeNodeWithParents } from '../tree-util';
import {
  hasEmptyLabel,
  hasInput,
  hasLabelWithUniqueForAttribute,
  hasLabelWithValidElements,
  hasUniqueLabels,
} from './labels';

describe('labels', function () {
  describe('hasEmptyLabel', function () {
    it('should not return audit error when label has text', function () {
      const tree = getTreeNodeWithParents({ children: [{ name: 'label', children: [{ text: 'hello' }] }] });
      const result = hasEmptyLabel(tree);
      expect(result).toBeUndefined();
    });

    it('should not return audit error when label has children with text', function () {
      const tree = getTreeNodeWithParents({
        children: [{ name: 'label', children: [{ name: 'span', children: [{ text: 'hello' }] }] }],
      });
      const result = hasEmptyLabel(tree);
      expect(result).toBeUndefined();
    });

    it('should return audit error when label has no text', function () {
      const tree = getTreeNodeWithParents({ children: [{ name: 'label' }] });
      const result = hasEmptyLabel(tree);

      expect(result!.items[0].name).toEqual('label');
      expect(result!.score).toBe(0);
    });

    it('should return audit error when label has no children with text', function () {
      const tree = getTreeNodeWithParents({ children: [{ name: 'label', children: [{ name: 'span' }] }] });
      const result = hasEmptyLabel(tree);

      expect(result!.items[0].name).toEqual('label');
      expect(result!.score).toBe(0);
    });
  });

  describe('hasUniqueLabels', function () {
    it('should not return audit error when with single label', function () {
      const tree = getTreeNodeWithParents({ children: [{ name: 'label', children: [{ text: 'hello' }] }] });
      const result = hasUniqueLabels(tree);
      expect(result).toBeUndefined();
    });

    it('should not return audit error when with multiple empty labels', function () {
      const tree = getTreeNodeWithParents({ children: [{ name: 'label' }, { name: 'label' }] });
      const result = hasUniqueLabels(tree);
      expect(result).toBeUndefined();
    });

    it('should return audit error when with duplicate labels', function () {
      const tree = getTreeNodeWithParents({
        children: [
          {
            name: 'label',
            children: [{ text: 'hello' }],
          },
          {
            name: 'label',
            children: [{ text: 'hello' }],
          },
        ],
      });
      const result = hasUniqueLabels(tree);

      expect(result!.items[0].name).toEqual('label');
      expect(getTextContent(result!.items[0])).toEqual('hello');
      expect(getTextContent(result!.items[0].context.duplicates[0])).toEqual('hello');
      expect(result!.score).toBe(0);
    });

    it('should not return audit error when with multiple unique labels', function () {
      const tree = getTreeNodeWithParents({
        children: [
          {
            name: 'label',
            children: [{ text: 'hello' }],
          },
          {
            name: 'label',
            children: [{ text: 'world' }],
          },
        ],
      });
      const result = hasUniqueLabels(tree);
      expect(result).toBeUndefined();
    });

    it('should not return audit error when with multiple labels in different forms', function () {
      const tree = getTreeNodeWithParents({
        children: [
          {
            name: 'form',
            children: [
              {
                name: 'label',
                children: [{ text: 'hello' }],
              },
            ],
          },
          {
            name: 'form',
            children: [
              {
                name: 'label',
                children: [{ text: 'hello' }],
              },
            ],
          },
        ],
      });
      const result = hasUniqueLabels(tree);
      expect(result).toBeUndefined();
    });
  });

  describe('hasLabelWithValidElements', function () {
    it('should not return audit error with text label', function () {
      const tree = getTreeNodeWithParents({ children: [{ name: 'label', children: [{ text: 'hello' }] }] });
      const result = hasLabelWithValidElements(tree);
      expect(result).toBeUndefined();
    });

    it('should return audit error when label contains anchor tag', function () {
      const tree = getTreeNodeWithParents({
        children: [
          {
            name: 'label',
            children: [
              {
                name: 'span',
                children: [{ text: 'hello' }],
              },
              {
                name: 'a',
                children: [{ text: 'anchor' }],
              },
              {
                name: 'h1',
                children: [{ text: 'heading' }],
              },
            ],
          },
        ],
      });
      const result = hasLabelWithValidElements(tree);

      expect(result!.items[0].name).toEqual('label');
      expect(getTextContent(result!.items[0])).toEqual('hello anchor heading');
      expect(result!.items[0].context.fields[0].name).toEqual('a');
      expect(result!.items[0].context.fields[1].name).toEqual('h1');
      expect(result!.score).toBe(0);
    });
  });

  describe('hasLabelWithUniqueForAttribute', function () {
    it('should not return audit error for single label with for attribute', function () {
      const tree = getTreeNodeWithParents({
        children: [{ name: 'label', attributes: { for: 'input' }, children: [{ text: 'hello' }] }],
      });
      const result = hasLabelWithUniqueForAttribute(tree);
      expect(result).toBeUndefined();
    });

    it('should return audit error for multiple labels with the same for attribute', function () {
      const tree = getTreeNodeWithParents({
        children: [
          { name: 'label', attributes: { for: 'input' }, children: [{ text: 'hello' }] },
          { name: 'label', attributes: { for: 'input' }, children: [{ text: 'world' }] },
        ],
      });
      const result = hasLabelWithUniqueForAttribute(tree);

      expect(result!.items[0].name).toEqual('label');
      expect(result!.items[0].context.duplicates).toHaveLength(1);
      expect(result!.score).toBe(0);
    });

    it('should not return audit error for mutliple labels with different for attribute', function () {
      const tree = getTreeNodeWithParents({
        children: [
          { name: 'label', attributes: { for: 'input1' }, children: [{ text: 'hello' }] },
          { name: 'label', attributes: { for: 'input2' }, children: [{ text: 'world' }] },
        ],
      });
      const result = hasLabelWithUniqueForAttribute(tree);
      expect(result).toBeUndefined();
    });
  });

  describe('hasInput', function () {
    it('should not return audit error for label with matching input (for)', function () {
      const tree = getTreeNodeWithParents({
        children: [
          { name: 'label', attributes: { for: 'input1' }, children: [{ text: 'hello' }] },
          { name: 'input', attributes: { id: 'input1' } },
        ],
      });
      const result = hasInput(tree);
      expect(result).toBeUndefined();
    });

    it('should not return audit error for label with matching input (for) with id', function () {
      const tree = getTreeNodeWithParents({
        children: [
          { name: 'label', attributes: { id: 'label', for: 'input1' }, children: [{ text: 'hello' }] },
          { name: 'input', attributes: { id: 'input1' } },
        ],
      });
      const result = hasInput(tree);
      expect(result).toBeUndefined();
    });

    it('should not return audit error for label with matching input (child)', function () {
      const tree = getTreeNodeWithParents({
        children: [
          {
            name: 'label',
            attributes: {},
            children: [{ text: 'hello' }, { name: 'input', attributes: { id: 'input1' } }],
          },
        ],
      });
      const result = hasInput(tree);
      expect(result).toBeUndefined();
    });

    it('should not return audit error for label with matching input (aria-labelledby)', function () {
      const tree = getTreeNodeWithParents({
        children: [
          { name: 'label', attributes: { id: 'label1' }, children: [{ text: 'hello' }] },
          { name: 'input', attributes: { 'aria-labelledby': 'label1' } },
        ],
      });
      const result = hasInput(tree);
      expect(result).toBeUndefined();
    });

    it('should return audit error for label without matching input (for)', function () {
      const tree = getTreeNodeWithParents({
        children: [
          { name: 'label', attributes: { for: 'input1' }, children: [{ text: 'hello' }] },
          { name: 'input', attributes: { id: 'input2' } },
        ],
      });
      const result = hasInput(tree);
      expect(result).not.toBeUndefined();
    });

    it('should return audit error for label without matching input (child)', function () {
      const tree = getTreeNodeWithParents({
        children: [
          {
            name: 'label',
            attributes: {},
            children: [{ text: 'hello' }],
          },
        ],
      });
      const result = hasInput(tree);
      expect(result).not.toBeUndefined();
    });

    it('should return audit error for label without matching input (aria-labelledby)', function () {
      const tree = getTreeNodeWithParents({
        children: [
          { name: 'label', attributes: { id: 'label1' }, children: [{ text: 'hello' }] },
          { name: 'input', attributes: { 'aria-labelledby': 'label' } },
        ],
      });
      const result = hasInput(tree);
      expect(result).not.toBeUndefined();
    });

    it('should return audit error for label with empty for attribute', function () {
      const tree = getTreeNodeWithParents({
        children: [{ name: 'label', attributes: { id: 'label1', for: '' }, children: [{ text: 'hello' }] }],
      });
      const result = hasInput(tree);
      expect(result).not.toBeUndefined();
    });

    it('should return audit error for label with no for attribute', function () {
      const tree = getTreeNodeWithParents({
        children: [{ name: 'label', attributes: { id: 'label1' }, children: [{ text: 'hello' }] }],
      });
      const result = hasInput(tree);
      expect(result).not.toBeUndefined();
    });
  });
});


text:
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
<html>
<head>
<script src="../../resources/js-test.js"></script>
</head>
<body>
<script>
description("Tests to ensure correct behaviour of canvas loss and restoration when size is extremely large then, restored to a reasonable value.");

if (window.testRunner) {
    testRunner.dumpAsText();
    testRunner.waitUntilDone();
}

var canvas = document.createElement('canvas')
canvas.addEventListener('contextlost', contextLost);
canvas.addEventListener('contextrestored', contextRestored);
var ctx = canvas.getContext('2d');
var lostEventHasFired = false;
verifyContextLost(false);

// WebIDL defines width and height as int. 2147483647 is int max.
var extremelyLargeNumber = 2147483647;
canvas.width = extremelyLargeNumber;
canvas.height = extremelyLargeNumber;
verifyContextLost(true);
canvas.width = extremelyLargeNumber;
verifyContextLost(true);
canvas.width = 100;
canvas.height = 100;
verifyContextLost(true); // Restoration is async.
// Restore a sane dimension

function verifyContextLost(shouldBeLost) {
    // Verify context loss experimentally as well as isContextLost()
    ctx.fillStyle = '#0f0';
    ctx.fillRect(0, 0, 1, 1);
    contextLostTest = ctx.getImageData(0, 0, 1, 1).data[1] == 0;
    if (shouldBeLost) {
        shouldBeTrue('contextLostTest');
        shouldBeTrue('ctx.isContextLost()');
    } else {
        shouldBeFalse('contextLostTest');
        shouldBeFalse('ctx.isContextLost()');
    }
}

function contextLost() {
    if (lostEventHasFired) {
        testFailed('Context lost event was dispatched more than once.');
    } else {
        testPassed('Graphics context lost event dispatched.');
    }
    lostEventHasFired = true;
    verifyContextLost(true);
}

function contextRestored() {
    if (lostEventHasFired) {
        testPassed('Context restored event dispatched after context lost.');
    } else {
        testFailed('Context restored event was dispatched before a context lost event.');
    }
    verifyContextLost(false);
	if (window.testRunner) {
    	testRunner.notifyDone();
    }
}
</script>
</body>
</html>


text:
<?php
/**
 * Social Sharing Buttons
 */
?>

  <?= ! empty( $heading ) ? "
$heading
" : null; ?>

    <a target="_blank" title="Share on Facebook" href="http://www.facebook.com/sharer/sharer.php?url=<?= the_permalink(); ?>" class="btn btn-default btn-md">
      Facebook

    <a target="_blank" title="Share on Google+" href="https://plus.google.com/share?url=<?= the_permalink(); ?>" class="btn btn-default btn-md" onclick="javascript:window.open(this.href,'', 'menubar=no,toolbar=no,resizable=yes,scrollbars=yes,height=600,width=600');return false;">
      Google +

    <a target="_blank" title="Share on Twitter"href="https://twitter.com/intent/tweet?url=<?= the_permalink(); ?>&text=<?= the_title(); ?>" class="btn btn-default btn-md">
      Twitter

    <a target="_blank" title="Share on LinkedIn" href="http://www.linkedin.com/shareArticle?mini=true&url=<?= the_permalink(); ?>&title=<?= the_title(); ?>&summary=&source=" class="btn btn-default btn-md">
      LinkedIn


text:
package com.scaleunlimited.tenaya.data;

import java.util.Iterator;

import com.scaleunlimited.tenaya.sample.Sample;

public class KmerGenerator implements Iterator<String> {

	private Sample sample;
	private boolean more;
	private String currentSequence;
	private int ksize;
	private int currentIndex;
	private int len;

	public KmerGenerator(int ksize, Sample sample) {
		this.ksize = ksize;

		setSample(sample);
	}

	public void setSample(Sample sample) {
		this.sample = sample;
		more = true;
		currentSequence = sample.readSequence();
		currentIndex = 0;
		len = currentSequence.length();
	}

	@Override
	public boolean hasNext() {
		return more;
	}

	@Override
	public String next() {
		String kmer = currentSequence.substring(currentIndex++, currentIndex + ksize - 1);
		if ((currentIndex + ksize) > len) {
			currentSequence = sample.readSequence();
			if (currentSequence == null) {
				more = false;
			} else {
				currentIndex = 0;
				len = currentSequence.length();
			}
		}
		return kmer;
	}

	@Override
	public void remove() {
		throw new UnsupportedOperationException("KmerGenerator doesn't support remove");
	}

}


text:
{% extends "base.html" %}
{% import "bootstrap/wtf.html" as wtf %}

{% block title %}Fuzzy Flask{% endblock %}

{% block page_content %}

    {# Animation via ngAnimate + angular-ui/bootstrap,  https://github.com/angular-ui/bootstrap/tree/master/src/collapse #}
    <form class="form-horizontal" role="form" ng-submit="app.sendData()" uib-collapse="isFormCollapsed">
      {# Create form by hand as opposed to using wtf.quick_form() #}
      {# this allows sending in parameters to #}
      {# source: https://pythonhosted.org/Flask-Bootstrap/forms.html #}
      {{ data_form.csrf_token }}

            {{ wtf.form_field(data_form.dataset, ng_model="form.dataset", placeholder="Paste single-column data here...", rows="10") }}

            {{ wtf.form_field(data_form.dictionary, ng_model="form.dictionary", placeholder="Paste dictionary here...", rows="10") }}

        {{ wtf.form_field(data_form.submit) }}

    </form>
    {# button only shows when form hidden #}

      <button type="button" class="btn btn-default ng-cloak" ng-click="isFormCollapsed = !isFormCollapsed">Show search form</button>

    {# use ng-cloak and css file to avoid flicker effect #}
    {# source: https://docs.angularjs.org/api/ng/directive/ngCloak #}

        <uib-progressbar max="progressTotal" value="progressCurrent">{a progressCurrent a} / {a progressTotal a}</uib-progressbar>

        <button class="btn btn-default col-centered" ng-click="app.stopMatch()">Stop </button>

    {# using ng-csv to export file: https://github.com/asafdav/ng-csv #}

      <button class="btn btn-default"  ng-csv="dataframe" filename="test.csv" csv-header="tableHeader">Save to CSV </button>

          {a h a}
          Edit

      {# Partially adapted from http://ng-table.com/#/editing/demo-inline #}

        {a row.data a}

          {a row.match a}
          <select ng-switch-when="true" ng-model="row.match" ng-options="o as o for o in dictionary" required class="form-control"></select>

        {a row.score a}
        <input type="checkbox" ng-model="row.selected">

          <button class="btn btn-primary btn-sm" ng-click="app.save(row, rowForm)" ng-if="row.isEditing"></button>
          <button class="btn btn-default btn-sm" ng-click="row.isEditing = true" ng-if="!row.isEditing"></button>

{% endblock %}

{% block scripts %}
  {{ super() }}

{% endblock %}