text:
package com.clearspring.analytics.stream;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.clearspring.analytics.util.DoublyLinkedList;
import com.clearspring.analytics.util.ListNode2;
import com.clearspring.analytics.util.Pair;

/**
 * Based on the Space-Saving algorithm and the Stream-Summary
 * data structure as described in:
 * Efficient Computation of Frequent and Top-k Elements in Data Streams
 * by Metwally, Agrawal, and Abbadi
 *
 * @param <T> type of data in the stream to be summarized
 */
public class StreamSummary<T> implements ITopK<T>, Externalizable
{
    protected class Bucket
    {
        protected DoublyLinkedList<Counter<T>> counterList;

        private long count;

        public Bucket(long count)
        {
            this.count = count;
            this.counterList = new DoublyLinkedList<Counter<T>>();
        }
    }

    /*
    public class Counter implements Externalizable
    {
        private ListNode2<Bucket> bucketNode;

        private T item;
        private long count;
        private long error;

        public Counter(ListNode2<Bucket> bucket, T item)
        {
            this.bucketNode = bucket;
            this.count = 0;
            this.error = 0;
            this.item = item;
        }

        public T getItem() { return item; }
        public long getCount() { return count; }
        public long getError() { return error; }

        @Override
        public String toString()
        {
            return item+":"+count+':'+error;
        }

        @SuppressWarnings("unchecked")
        @Override
        public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException
        {
            item = (T)in.readObject();
            count = in.readLong();
            error = in.readLong();
        }

        @Override
        public void writeExternal(ObjectOutput out) throws IOException
        {
            out.writeObject(item);
            out.writeLong(count);
            out.writeLong(error);
        }
    }
    */

    protected int capacity;
    private HashMap<T, ListNode2<Counter<T>>> counterMap;
    protected DoublyLinkedList<Bucket> bucketList;

    /**
     *
     * @param capacity maximum size (larger capacities improve accuracy)
     */
    public StreamSummary(int capacity)
    {
        this.capacity = capacity;
        counterMap = new HashMap<T, ListNode2<Counter<T>>>();
        bucketList = new DoublyLinkedList<Bucket>();
    }

    public int getCapacity() { return capacity; }

    /**
     * Algorithm: Space-Saving
     *
     * @param item stream element (e)
     * @return false if item was already in the stream summary, true otherwise
     */
     @Override
     public boolean offer(T item)
     {
         return offerReturnAll(item).left;
     }

     /**
      * @param item stream element (e)
      * @return item dropped from summary if an item was dropped, null otherwise
      */
     public T offerReturnDropped(T item)
     {
         return offerReturnAll(item).right;
     }

     /**
      * @param item stream element (e)
      * @return Pair<isNewItem, itemDropped> where isNewItem is the return value of offer() and itemDropped is null if no item was dropped
      */
     public Pair<Boolean, T> offerReturnAll(T item)
     {
         ListNode2<Counter<T>> counterNode = counterMap.get(item);
         boolean isNewItem = (counterNode == null);
         T droppedItem = null;
         if(isNewItem)
         {

             if(size() < capacity)
             {
                 counterNode = bucketList.enqueue(new Bucket(0)).getValue().counterList.add(new Counter<T>(bucketList.tail(), item));
             }
             else
             {
                 Bucket min = bucketList.first();
                 counterNode = min.counterList.tail();
                 Counter<T> counter = counterNode.getValue();
                 droppedItem = counter.item;
                 counterMap.remove(droppedItem);
                 counter.item = item;
                 counter.error = min.count;
             }
             counterMap.put(item, counterNode);
         }

         incrementCounter(counterNode);

         return new Pair<Boolean, T>(isNewItem, droppedItem);
     }

     protected void incrementCounter(ListNode2<Counter<T>> counterNode)
     {
         Counter<T> counter = counterNode.getValue();       // count_i
         ListNode2<Bucket> bucketNode = counter.bucketNode;
         Bucket bucket = bucketNode.getValue();         // Let Bucket_i be the bucket of count_i
         ListNode2<Bucket> bucketNodeNext = bucketNode.getNext();
         Bucket bucketNext = bucketNodeNext == null ? null : bucketNodeNext.getValue(); // Let Bucket_i^+ be Bucket_i's neighbor of larger value
         bucket.counterList.remove(counterNode);            // Detach count_i from Bucket_i's child-list
         counter.count++;                   // Increment count_i

         // Finding the right bucket for count_i
         if(bucketNext != null && counter.count == bucketNext.count)
         {
             bucketNext.counterList.add(counterNode);       // Attach count_i to Bucket_i^+'s child-list
         }
         else // A new bucket has to be created
         {
             bucketNext = new Bucket(counter.count);        // Create a new Bucket Bucket_new
             // Assign Bucket_new the value of count_i
             bucketNext.counterList.add(counterNode);       // Attach count_i to Bucket_new's child-list
             bucketNodeNext = bucketList.addAfter(bucketNode, bucketNext);  // Insert Bucket_new after Bucket_i
         }

         counter.bucketNode = bucketNodeNext;

         //Cleaning up
         if(bucket.counterList.isEmpty())           // If Bucket_i's child-list is empty
         {
             bucketList.remove(bucketNode);         // Detach Bucket_i from the Stream-Summary
         }
     }

     @Override
     public List<T> peek(int k)
     {
         List<T> topK = new ArrayList<T>(k);

         for(ListNode2<Bucket> bNode = bucketList.head(); bNode != null; bNode = bNode.getPrev())
         {
             Bucket b = bNode.getValue();
             for(Counter<T> c : b.counterList)
             {
                 if(topK.size() == k) return topK;
                 topK.add(c.item);
             }
         }

         return topK;
     }

     public List<Counter<T>> topK(int k)
     {
         List<Counter<T>> topK = new ArrayList<Counter<T>>(k);

         for(ListNode2<Bucket> bNode = bucketList.head(); bNode != null; bNode = bNode.getPrev())
         {
             Bucket b = bNode.getValue();
             for(Counter<T> c : b.counterList)
             {
                 if(topK.size() == k) return topK;
                 topK.add(c);
             }
         }

         return topK;
     }

     /**
      *
      * @return number of items stored
      */
     public int size()
     {
         return counterMap.size();
     }

     @Override
     public String toString()
     {
         StringBuilder sb = new StringBuilder();
         sb.append('[');
         for(ListNode2<Bucket> bNode = bucketList.head(); bNode != null; bNode = bNode.getPrev())
         {
             Bucket b = bNode.getValue();
             sb.append('{');
             sb.append(b.count);
             sb.append(":[");
             for(Counter<T> c : b.counterList)
             {
                 sb.append('{');
                 sb.append(c.item);
                 sb.append(':');
                 sb.append(c.error);
                 sb.append("},");
             }
             if(b.counterList.size() > 0) sb.deleteCharAt(sb.length()-1);
             sb.append("]},");
         }
         if(bucketList.size() > 0) sb.deleteCharAt(sb.length()-1);
         sb.append(']');
         return sb.toString();
     }

    @SuppressWarnings("unchecked")
    @Override
    public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException
    {
        this.bucketList = new DoublyLinkedList<Bucket>();
        this.capacity = in.readInt();

        int size = in.readInt();
        this.counterMap = new HashMap<T, ListNode2<Counter<T>>>(size);

        Bucket currentBucket = null;
        ListNode2<Bucket> currentBucketNode = null;
        for(int i=0; i<size; i++)
        {
            Counter<T> c = (Counter<T>)in.readObject();
            if(currentBucket == null || c.count != currentBucket.count)
            {
                currentBucket = new Bucket(c.count);
                currentBucketNode =  bucketList.add(currentBucket);
            }
            c.bucketNode = currentBucketNode;
            counterMap.put(c.item, currentBucket.counterList.add(c));
        }
    }

    @Override
    public void writeExternal(ObjectOutput out) throws IOException
    {
        out.writeInt(this.capacity);
        out.writeInt(this.size());
        for(ListNode2<Bucket> bNode = bucketList.tail(); bNode != null; bNode = bNode.getNext())
        {
            Bucket b = bNode.getValue();
            for(Counter<T> c : b.counterList)
            {
                out.writeObject(c);
            }
        }
    }

    /**
     * For de-serialization
     */
    public StreamSummary() {}

    /**
     * For de-serialization
     * @param bytes
     * @throws IOException
     * @throws ClassNotFoundException
     */
    public StreamSummary(byte[] bytes) throws IOException, ClassNotFoundException
    {
        fromBytes(bytes);
    }

    public void fromBytes(byte[] bytes) throws IOException, ClassNotFoundException
    {
        ObjectInput oi = null;
        try
        {
            ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
            oi = new ObjectInputStream(bais);
            readExternal(oi);
        }
        finally { if(oi != null) oi.close(); }
    }

    public byte[] toBytes() throws IOException
    {
        byte[] bytes = null;
        ObjectOutput oo = null;
        ByteArrayOutputStream baos = null;

        try
        {
            baos = new ByteArrayOutputStream();
            oo = new ObjectOutputStream(baos);
            this.writeExternal(oo);
        }
        finally { if(oo != null) oo.close(); }

        try
        {
            bytes = baos.toByteArray();
        }
        catch (Exception e) { throw new IOException(e); }

        return bytes;
    }
}


text:
import contextlib
import os
import unittest

from systrace import decorators
from systrace import run_systrace
from systrace import update_systrace_trace_viewer
from systrace import util

TEST_DIR = os.path.join(os.path.dirname(__file__), '..', 'test_data')

COMPRESSED_ATRACE_DATA = os.path.join(TEST_DIR, 'compressed_atrace_data.txt')
DECOMPRESSED_ATRACE_DATA = os.path.join(TEST_DIR,
                                        'decompressed_atrace_data.txt')
NON_EXISTENT_DATA = os.path.join(TEST_DIR, 'THIS_FILE_DOES_NOT_EXIST.txt')

class AtraceFromFileAgentTest(unittest.TestCase):
  @decorators.HostOnlyTest
  def test_from_file(self):
    update_systrace_trace_viewer.update(force_update=True)
    self.assertTrue(os.path.exists(
        update_systrace_trace_viewer.SYSTRACE_TRACE_VIEWER_HTML_FILE))
    output_file_name = util.generate_random_filename_for_test()
    try:
      # use from-file to create a specific expected output
      run_systrace.main_impl(['./run_systrace.py',
                              '--from-file',
                              COMPRESSED_ATRACE_DATA,
                              '-o',
                              output_file_name])
      # and verify file contents
      with contextlib.nested(open(output_file_name, 'r'),
                             open(DECOMPRESSED_ATRACE_DATA, 'r')) as (f1, f2):
        full_trace = f1.read()
        expected_contents = f2.read()
        self.assertTrue(expected_contents in full_trace)
    except:
      raise
    finally:
      os.remove(update_systrace_trace_viewer.SYSTRACE_TRACE_VIEWER_HTML_FILE)
      if os.path.exists(output_file_name):
        os.remove(output_file_name)

  @decorators.HostOnlyTest
  def test_missing_file(self):
    try:
      run_systrace.main_impl(['./run_systrace.py',
                              '--from-file',
                              NON_EXISTENT_DATA])
      self.fail('should not get here')
    except IOError:
      pass

redpajama_set_name: RedPajamaGithub


text:
@interface UIView (XHExt)

@property (nonatomic, assign) CGFloat xh_x;

@property (nonatomic, assign) CGFloat xh_y;

@property (nonatomic, assign) CGFloat xh_width;

@property (nonatomic, assign) CGFloat xh_height;

@property (nonatomic, assign) CGFloat xh_centerX;

@property (nonatomic, assign) CGFloat xh_centerY;

@property (nonatomic, assign) CGFloat xh_right;

@property (nonatomic, assign) CGFloat xh_bottom;

+ (instancetype)viewFromXib;

@end


text:
/*
Includes inventory types as used in the trade package
*/
package inventory

import (
	"bytes"
	"encoding/json"
	"fmt"
	"github.com/Philipp15b/go-steam/jsont"
	"strconv"
)

type GenericInventory map[uint32]map[uint64]*Inventory

func NewGenericInventory() GenericInventory {
	iMap := make(map[uint32]map[uint64]*Inventory)
	return GenericInventory(iMap)
}

// Get inventory for specified AppId and ContextId
func (i *GenericInventory) Get(appId uint32, contextId uint64) (*Inventory, error) {
	iMap := (map[uint32]map[uint64]*Inventory)(*i)
	iMap2, ok := iMap[appId]
	if !ok {
		return nil, fmt.Errorf("inventory for specified appId not found")
	}
	inv, ok := iMap2[contextId]
	if !ok {
		return nil, fmt.Errorf("inventory for specified contextId not found")
	}
	return inv, nil
}

func (i *GenericInventory) Add(appId uint32, contextId uint64, inv *Inventory) {
	iMap := (map[uint32]map[uint64]*Inventory)(*i)
	iMap2, ok := iMap[appId]
	if !ok {
		iMap2 = make(map[uint64]*Inventory)
		iMap[appId] = iMap2
	}
	iMap2[contextId] = inv
}

type Inventory struct {
	Items        Items        `json:"rgInventory"`
	Currencies   Currencies   `json:"rgCurrency"`
	Descriptions Descriptions `json:"rgDescriptions"`
	AppInfo      *AppInfo     `json:"rgAppInfo"`
}

// Items key is an AssetId
type Items map[string]*Item

func (i *Items) ToMap() map[string]*Item {
	return (map[string]*Item)(*i)
}

func (i *Items) Get(assetId uint64) (*Item, error) {
	iMap := (map[string]*Item)(*i)
	if item, ok := iMap[strconv.FormatUint(assetId, 10)]; ok {
		return item, nil
	}
	return nil, fmt.Errorf("item not found")
}

func (i *Items) UnmarshalJSON(data []byte) error {
	if bytes.Equal(data, []byte("[]")) {
		return nil
	}
	return json.Unmarshal(data, (*map[string]*Item)(i))
}

type Currencies map[string]*Currency

func (c *Currencies) ToMap() map[string]*Currency {
	return (map[string]*Currency)(*c)
}

func (c *Currencies) UnmarshalJSON(data []byte) error {
	if bytes.Equal(data, []byte("[]")) {
		return nil
	}
	return json.Unmarshal(data, (*map[string]*Currency)(c))
}

// Descriptions key format is %d_%d, first %d is ClassId, second is InstanceId
type Descriptions map[string]*Description

func (d *Descriptions) ToMap() map[string]*Description {
	return (map[string]*Description)(*d)
}

func (d *Descriptions) Get(classId uint64, instanceId uint64) (*Description, error) {
	dMap := (map[string]*Description)(*d)
	descId := fmt.Sprintf("%v_%v", classId, instanceId)
	if desc, ok := dMap[descId]; ok {
		return desc, nil
	}
	return nil, fmt.Errorf("description not found")
}

func (d *Descriptions) UnmarshalJSON(data []byte) error {
	if bytes.Equal(data, []byte("[]")) {
		return nil
	}
	return json.Unmarshal(data, (*map[string]*Description)(d))
}

type Item struct {
	Id         uint64 `json:",string"`
	ClassId    uint64 `json:",string"`
	InstanceId uint64 `json:",string"`
	Amount     uint64 `json:",string"`
	Pos        uint32
}

type Currency struct {
	Id         uint64 `json:",string"`
	ClassId    uint64 `json:",string"`
	IsCurrency bool   `json:"is_currency"`
	Pos        uint32
}

type Description struct {
	AppId      uint32 `json:",string"`
	ClassId    uint64 `json:",string"`
	InstanceId uint64 `json:",string"`

	IconUrl      string `json:"icon_url"`
	IconUrlLarge string `json:"icon_url_large"`
	IconDragUrl  string `json:"icon_drag_url"`

	Name           string
	MarketName     string `json:"market_name"`
	MarketHashName string `json:"market_hash_name"`

	// Colors in hex, for example `B2B2B2`
	NameColor       string `json:"name_color"`
	BackgroundColor string `json:"background_color"`

	Type string

	Tradable                  jsont.UintBool
	Marketable                jsont.UintBool
	Commodity                 jsont.UintBool
	MarketTradableRestriction uint32 `json:"market_tradable_restriction,string"`

	Descriptions DescriptionLines
	Actions      []*Action
	// Application-specific data, like "def_index" and "quality" for TF2
	AppData map[string]string
	Tags    []*Tag
}

type DescriptionLines []*DescriptionLine

func (d *DescriptionLines) UnmarshalJSON(data []byte) error {
	if bytes.Equal(data, []byte(`""`)) {
		return nil
	}
	return json.Unmarshal(data, (*[]*DescriptionLine)(d))
}

type DescriptionLine struct {
	Value string
	Type  *string // Is `html` for HTML descriptions
	Color *string
}

type Action struct {
	Name string
	Link string
}

type AppInfo struct {
	AppId uint32
	Name  string
	Icon  string
	Link  string
}

type Tag struct {
	InternalName string `json:internal_name`
	Name         string
	Category     string
	CategoryName string `json:category_name`
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!-- Generated by org.testng.reporters.JUnitReportReporter -->
<testsuite hostname="retina.dellroad.org" name="org.jsimpledb.CompositeIndexTest" tests="1" failures="0" timestamp="24 Aug 2015 22:16:26 GMT" time="2.219" errors="0">
  <testcase name="testCompositeIndex" time="2.219" classname="org.jsimpledb.CompositeIndexTest"/>
</testsuite> <!-- org.jsimpledb.CompositeIndexTest -->


text:
<?php
namespace Home\Controller;
use Think\Controller;

class IndexController extends Controller {
    public function index(){
        $ip=json_decode(file_get_contents('http://apistore.baidu.com/microservice/iplookup?ip='.get_client_ip()), true);
        if(strcmp($ip['errMsg'], 'success')!=0){
            echo 'error:ip';
            exit;
        }
        $this->assign('ipData', $ip['retData']);

        $Books=M('books');
        $book_result=$Books->select();
        $this->assign('books',$book_result);

        $this->display('index');
    }
}


text:
<?php

namespace cii\db;

interface MigrationInterface extends UpgradeInterface
{
    public function down();
}


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="AssemblyInfo.cs" company="saramgsilva">
//   Copyright (c) 2014 saramgsilva. All rights reserved.
// </copyright>
// <summary>
//   AssemblyInfo.cs
// </summary>
// --------------------------------------------------------------------------------------------------------------------

using System.Reflection;
using System.Runtime.InteropServices;
using CustomersSampleService;
using Microsoft.WindowsAzure.Mobile.Service.Config;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("customers_sampleService")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("customers_sampleService")]
[assembly: AssemblyCopyright("Copyright ©  2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components.  If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("2e8cfaa1-3743-49ef-9e21-2926ca18c058")]

// Version information for an assembly consists of the following four values:
//
//      Major Version
//      Minor Version
//      Build Number
//      Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: Bootstrapper(typeof(WebApiConfig))]


text:
package com.francetelecom.clara.cloud.activation.plugin.cf;

import com.francetelecom.clara.cloud.activation.plugin.cf.domain.OrganizationActivationService;
import com.francetelecom.clara.cloud.commons.tasks.TaskStatus;
import com.francetelecom.clara.cloud.model.ModelItemRepository;
import com.francetelecom.clara.cloud.techmodel.cf.Organization;
import com.francetelecom.clara.cloud.techmodel.cf.OrganizationRepository;
import org.fest.assertions.Assertions;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;

@RunWith(MockitoJUnitRunner.class)
public class OrganizationActivationPluginTest {

    @Mock
    OrganizationActivationService organizationActivationService;
    @Mock
    ModelItemRepository modelItemRepository;
    @Mock
    OrganizationRepository organizationRepository;

    @Test
    public void fail_to_activate_org_if_organization_does_not_exist() throws Exception {
        final OrganizationActivationPlugin organizationActivationPlugin = new OrganizationActivationPlugin(organizationActivationService, modelItemRepository, organizationRepository);

        final TaskStatus status = organizationActivationPlugin.activate(99, Organization.class, new ActivationTestContext());

        Assertions.assertThat(status.hasFailed()).isEqualTo(true);

    }

    @Test
    public void should_return_success_task_on_activation_success() throws Exception {
        Organization organization = new Organization();
        //given space exists
        Mockito.when(organizationRepository.findOne(1)).thenReturn(organization);
        Mockito.when(organizationActivationService.activate(Mockito.anyString())).thenReturn("test");
        Mockito.when(organizationActivationService.getCurrentOrganizationName()).thenReturn("aTestOrg");

        final OrganizationActivationPlugin organizationActivationPlugin = new OrganizationActivationPlugin(organizationActivationService, modelItemRepository, organizationRepository);
        final TaskStatus status = organizationActivationPlugin.activate(1, Organization.class, new ActivationTestContext());

        Assertions.assertThat(status.hasSucceed()).isEqualTo(true);
        Assertions.assertThat(status.getTitle()).isEqualTo("Organization <aTestOrg> has been activated.");
    }

}


text:
package org.apache.felix.ipojo;

/**
* A field interceptor is notified when a monitored field asks for a value or
* receives a new value. A class implementing this interface is able to be
* notified of field accesses, and is able to inject a value to this field.
* The listener needs to be register on the instance manager.
* @author Felix Project Team
*/
public interface FieldInterceptor {

    /**
     * This method is called when a PUTFIELD operation is detected,
     * e.g. an assignation.
     * @param pojo the pojo object setting the value
     * @param fieldName the field name
     * @param value the value passed to the field
     */
    void onSet(Object pojo, String fieldName, Object value);

    /**
     * This method is called when a GETFIELD operation is detected.
     * This method allows to inject a value to the field.
     * @param pojo the pojo object getting the value
     * @param fieldName the field name
     * @param value the value passed to the field (by the previous call)
     * @return the managed value of the field
     */
    Object onGet(Object pojo, String fieldName, Object value);

}


text:
package com.alorma.github.ui.adapter.users;

import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.ButterKnife;
import com.alorma.github.R;
import com.alorma.github.ui.adapter.base.RecyclerArrayAdapter;
import com.alorma.github.ui.view.UserAvatarView;
import core.User;

public class UsersAdapterSpinner extends RecyclerArrayAdapter<User, UsersAdapterSpinner.Holder> {

  public UsersAdapterSpinner(LayoutInflater inflater) {
    super(inflater);
  }

  @Override
  protected void onBindViewHolder(Holder holder, User user) {
    holder.fill(user);
  }

  @Override
  public Holder onCreateViewHolder(ViewGroup parent, int viewType) {
    return new Holder(getInflater().inflate(R.layout.item_profile, parent, false));
  }

  public class Holder extends RecyclerView.ViewHolder {
    @BindView(R.id.profileIcon) UserAvatarView authorAvatar;
    @BindView(R.id.name) TextView authorLogin;
    @BindView(R.id.email) TextView authorEmail;

    public Holder(View itemView) {
      super(itemView);
      ButterKnife.bind(this, itemView);

      itemView.setOnClickListener(view -> {
        if (getCallback() != null) {
          getCallback().onItemSelected(getItem(getAdapterPosition()));
        }
      });
    }

    public void fill(User user) {
      if (authorAvatar != null) {
        this.authorAvatar.setVisibility(View.VISIBLE);
        authorAvatar.setUser(user);
      }

      if (authorLogin != null) {
        this.authorLogin.setVisibility(View.VISIBLE);

        if (!TextUtils.isEmpty(user.getLogin())) {
          authorLogin.setText(user.getLogin());
        }
      }

      if (authorEmail != null) {
        this.authorEmail.setVisibility(View.VISIBLE);
        if (!TextUtils.isEmpty(user.getLogin())) {
          authorEmail.setText(user.getEmail());
        }
      }
    }

    public void clear() {
      if (authorLogin != null) {
        authorLogin.setText("");
        this.authorLogin.setVisibility(View.INVISIBLE);
      }
      if (authorEmail != null) {
        authorEmail.setText("");
        this.authorEmail.setVisibility(View.INVISIBLE);
      }
      if (authorAvatar != null) {
        authorAvatar.setImageDrawable(null);
        this.authorAvatar.setVisibility(View.INVISIBLE);
      }
    }
  }
}


text:
<?php
/**
 * The contents of this file was generated using the WSDLs as provided by eBay.
 *
 * DO NOT EDIT THIS FILE!
 */

namespace DTS\eBaySDK\Trading\Types;

/**
 *
 * @property integer $PackageID
 * @property string $Description
 * @property \DTS\eBaySDK\Trading\Enums\ShippingPackageCodeType $ShippingPackage
 * @property boolean $DefaultValue
 * @property boolean $DimensionsSupported
 * @property string $DetailVersion
 * @property \DateTime $UpdateTime
 */
class ShippingPackageDetailsType extends \DTS\eBaySDK\Types\BaseType
{
    /**
     * @var array Properties belonging to objects of this class.
     */
    private static $propertyTypes = [
        'PackageID' => [
            'type' => 'integer',
            'repeatable' => false,
            'attribute' => false,
            'elementName' => 'PackageID'
        ],
        'Description' => [
            'type' => 'string',
            'repeatable' => false,
            'attribute' => false,
            'elementName' => 'Description'
        ],
        'ShippingPackage' => [
            'type' => 'string',
            'repeatable' => false,
            'attribute' => false,
            'elementName' => 'ShippingPackage'
        ],
        'DefaultValue' => [
            'type' => 'boolean',
            'repeatable' => false,
            'attribute' => false,
            'elementName' => 'DefaultValue'
        ],
        'DimensionsSupported' => [
            'type' => 'boolean',
            'repeatable' => false,
            'attribute' => false,
            'elementName' => 'DimensionsSupported'
        ],
        'DetailVersion' => [
            'type' => 'string',
            'repeatable' => false,
            'attribute' => false,
            'elementName' => 'DetailVersion'
        ],
        'UpdateTime' => [
            'type' => 'DateTime',
            'repeatable' => false,
            'attribute' => false,
            'elementName' => 'UpdateTime'
        ]
    ];

    /**
     * @param array $values Optional properties and values to assign to the object.
     */
    public function __construct(array $values = [])
    {
        list($parentValues, $childValues) = self::getParentValues(self::$propertyTypes, $values);

        parent::__construct($parentValues);

        if (!array_key_exists(__CLASS__, self::$properties)) {
            self::$properties[__CLASS__] = array_merge(self::$properties[get_parent_class()], self::$propertyTypes);
        }

        if (!array_key_exists(__CLASS__, self::$xmlNamespaces)) {
            self::$xmlNamespaces[__CLASS__] = 'xmlns="urn:ebay:apis:eBLBaseComponents"';
        }

        $this->setValues(__CLASS__, $childValues);
    }
}


text:
#ifndef __itkMaskedFFTNormalizedCorrelationImageFilter_h
#define __itkMaskedFFTNormalizedCorrelationImageFilter_h

#include "itkImageToImageFilter.h"
#include "itkImage.h"

namespace itk
{
/**
 * \class MaskedFFTNormalizedCorrelationImageFilter
 * \brief Calculate masked normalized cross correlation using FFTs.
 *
 * This filter calculates the masked normalized cross correlation (NCC) of two
 * images under masks using FFTs instead of spatial correlation.
 * It is much faster than spatial correlation
 * for reasonably large structuring elements.
 * This filter is not equivalent to simply masking the images first and then
 * correlating them; the latter approach yields incorrect results because the
 * zeros in the images still affect the metric in the correlation process.
 * This filter implements the masked NCC correctly so that the masked-out regions are completely ignored.
 * The fundamental difference is described in detail in the references below.
 * If the masks are set to images of all ones, the result of this filter is
 * the same as standard NCC.
 *
 * Inputs:
 * Two images are required as inputs, fixedImage and movingImage,
 * and two are optional, fixedMask and movingMask.
 * In the context of correlation, inputs are often defined as: "image"
 * and "template".  In this filter, the fixedImage plays the role of the
 * image, and the movingImage plays the role of the template.
 * However, this filter is capable of correlating any two images and
 * is not restricted to small movingImages (templates).
 * In the fixedMask and movingMask, non-zero positive values
 * indicate locations of useful information in the corresponding image,
 * whereas zero and negative values indicate locations that should be
 * masked out (ignored).
 * Internally, the masks are converted to have values of only 0 and 1.
 * For each optional mask that is not set, the filter
 * internally creates an image of ones, which is equivalent to not
 * masking the image.  Thus, if both masks are not set, the result
 * will be equivalent to unmasked NCC.
 * For example, if only a mask for the fixed image is needed, the
 * movingMask can either not be set or can be set to an image of ones.
 *
 * Optional parameters:
 * The RequiredNumberOfOverlappingPixels enables the user to specify how many voxels
 * of the two images must overlap; any location in the correlation map that results
 * from fewer than this number of voxels will be set to zero.
 * Larger values zero-out pixels on a larger border around the correlation image.
 * Thus, larger values remove less stable computations but also limit the capture range.
 * If RequiredNumberOfOverlappingPixels is set to 0, the default, no zeroing will take place.
 *
 * Image size:
 * fixedImage and movingImage need not be the same size, but fixedMask
 * must be the same size as fixedImage, and movingMask must be the same
 * size as movingImage.
 * Furthermore, whereas some algorithms require that the "template"
 * be smaller than the "image" because of errors in the regions where
 * the two are not fully overlapping, this filter has no such restriction.
 *
 * Image spacing:
 * Since the computations are done in the pixel domain, all input
 * images must have the same spacing.
 *
 * Outputs;
 * The output is an image of RealPixelType that is the masked NCC of
 * the two images and its values range from -1.0 to 1.0.
 * The size of this NCC image is, by definition,
 * size(fixedImage) + size(movingImage) - 1.
 *
 * Example filter usage:
 * \code
 * typedef itk::MaskedFFTNormalizedCorrelationImageFilter< ShortImageType, DoubleImageType > FilterType;
 * FilterType::Pointer filter = FilterType::New();
 * filter->SetFixedImage( fixedImage );
 * filter->SetMovingImage( movingImage );
 * filter->SetFixedImageMask( fixedMask );
 * filter->SetMovingImageMask( movingMask );
 * filter->SetRequiredNumberOfOverlappingPixels(20);
 * filter->Update();
 * \endcode
 *
 * \warning The pixel type of the output image must be of real type
 * (float or double). ConceptChecking is used to enforce the output pixel
 * type. You will get a compilation error if the pixel type of the
 * output image is not float or double.
 *
 * References:
 * 1) D. Padfield. "Masked object registration in the Fourier domain."
 * Transactions on Image Processing.
 * 2) D. Padfield. "Masked FFT registration". In Proc. Computer
 * Vision and Pattern Recognition, 2010.
 *
 * \author: Dirk Padfield, GE Global Research, padfield@research.ge.com
 * \ingroup ITKConvolution
 */

template <class TInputImage, class TOutputImage >
class ITK_EXPORT MaskedFFTNormalizedCorrelationImageFilter :
    public ImageToImageFilter< TInputImage, TOutputImage >
{
public:
  /** Standard class typedefs. */
  typedef MaskedFFTNormalizedCorrelationImageFilter                     Self;
  typedef ImageToImageFilter < TInputImage, TOutputImage >              Superclass;
  typedef SmartPointer<Self>                                            Pointer;
  typedef SmartPointer<const Self>                                      ConstPointer;

  /** Method for creation through the object factory. */
  itkNewMacro(Self);

  /** Run-time type information (and related methods). */
  itkTypeMacro(MaskedFFTNormalizedCorrelationImageFilter, MaskedFFTNormalizedCrossCorrelationImageFilter);

  /** Extract some information from the image types.  Dimensionality
   * of the two images is assumed to be the same. */
  itkStaticConstMacro(ImageDimension, unsigned int,
                      TOutputImage::ImageDimension);

  /** Extract some information from the image types. */
  typedef TInputImage                               InputImageType;
  typedef TOutputImage                              OutputImageType;
  typedef typename InputImageType::RegionType       InputRegionType;
  typedef typename InputImageType::Pointer          InputImagePointer;
  typedef typename InputImageType::ConstPointer     InputImageConstPointer;
  typedef typename InputImageType::SizeType         InputSizeType;
  typedef typename OutputImageType::Pointer         OutputImagePointer;
  typedef typename OutputImageType::PixelType       OutputPixelType;

  typedef OutputPixelType                           RealPixelType;
  typedef Image< RealPixelType, ImageDimension>     RealImageType;
  typedef typename RealImageType::Pointer           RealImagePointer;
  typedef typename RealImageType::IndexType         RealIndexType;
  typedef typename RealImageType::SizeType          RealSizeType;
  typedef typename RealImageType::RegionType        RealRegionType;

  typedef Image< std::complex<RealPixelType>, ImageDimension >  FFTImageType;
  typedef typename FFTImageType::Pointer                        FFTImagePointer;

  /** Set and get the fixed image */
  void SetFixedImage(InputImageType *input)
    {
      this->SetNthInput(0, const_cast<InputImageType *>(input) );
    }
  InputImageType * GetFixedImage()
    {
      return static_cast<InputImageType*>(const_cast<DataObject *>(this->ProcessObject::GetInput(0)));
    }

  /** Set and get the moving image */
  void SetMovingImage(InputImageType *input)
    {
      this->SetNthInput(1, const_cast<InputImageType *>(input) );
    }
  InputImageType * GetMovingImage()
    {
      return static_cast<InputImageType*>(const_cast<DataObject *>(this->ProcessObject::GetInput(1)));
    }

  /** Set and get the fixed mask */
  void SetFixedImageMask(InputImageType *input)
    {
      this->SetNthInput(2, const_cast<InputImageType *>(input) );
    }
  InputImageType * GetFixedImageMask()
    {
      return static_cast<InputImageType*>(const_cast<DataObject *>(this->ProcessObject::GetInput(2)));
    }

  /** Set and get the moving mask */
  void SetMovingImageMask(InputImageType *input)
    {
      this->SetNthInput(3, const_cast<InputImageType *>(input) );
    }
  InputImageType * GetMovingImageMask()
    {
      return static_cast<InputImageType*>(const_cast<DataObject *>(this->ProcessObject::GetInput(3)));
    }

  /** Set and get the required percentage of overlapping pixels */
  itkSetMacro(RequiredNumberOfOverlappingPixels,SizeValueType);
  itkGetMacro(RequiredNumberOfOverlappingPixels,SizeValueType);

#ifdef ITK_USE_CONCEPT_CHECKING
  /** Begin concept checking */
  itkConceptMacro( OutputPixelTypeIsFloatingPointCheck,
                   ( Concept::IsFloatingPoint< OutputPixelType > ) );
  /** End concept checking */
#endif

protected:
  MaskedFFTNormalizedCorrelationImageFilter()
  {
    this->SetNumberOfRequiredInputs(2);
    m_RequiredNumberOfOverlappingPixels = 0;
  }
  virtual ~MaskedFFTNormalizedCorrelationImageFilter() {}
  void PrintSelf(std::ostream& os, Indent indent) const;

  /** Overlap the VerifyInputInformation method */
  void VerifyInputInformation();

  /** Standard pipeline method.*/
  void GenerateData();

  /** This filter needs a different input requested region than the output
   * requested region.  As such, it needs to provide an
   * implementation for GenerateInputRequestedRegion() in order to inform the
   * pipeline execution model.
   * \sa ProcessObject::GenerateInputRequestedRegion() */
  virtual void GenerateInputRequestedRegion();

  /** Since the output of this filter is a different
   * size than the input, it must provide an implementation of
   * GenerateOutputInformation.
   * \sa ProcessObject::GenerateOutputRequestedRegion() */
  void GenerateOutputInformation();

  template< class LocalInputImageType >
  typename LocalInputImageType::Pointer PreProcessMask( const LocalInputImageType * inputImage, const LocalInputImageType * inputMask );

  template< class LocalInputImageType >
  typename LocalInputImageType::Pointer PreProcessImage( const LocalInputImageType * inputImage, LocalInputImageType * inputMask );

  typename TInputImage::Pointer RotateImage( InputImageType * inputImage );

  template< class LocalInputImageType, class LocalOutputImageType >
  typename LocalOutputImageType::Pointer CalculateForwardFFT( LocalInputImageType * inputImage, InputSizeType & FFTImageSize );

  template< class LocalInputImageType, class LocalOutputImageType >
  typename LocalOutputImageType::Pointer CalculateInverseFFT( LocalInputImageType * inputImage, RealSizeType & combinedImageSize );

  // Helper math methods.
  template< class LocalInputImageType, class LocalOutputImageType >
  typename LocalOutputImageType::Pointer ElementProduct( LocalInputImageType * inputImage1, LocalInputImageType * inputImage2 );

  template< class LocalInputImageType >
  typename LocalInputImageType::Pointer ElementQuotient( LocalInputImageType * inputImage1, LocalInputImageType * inputImage2 );

  template< class LocalInputImageType >
  typename LocalInputImageType::Pointer ElementSubtraction( LocalInputImageType * inputImage1, LocalInputImageType * inputImage2 );

  template< class LocalInputImageType >
  typename LocalInputImageType::Pointer ElementPositive( LocalInputImageType * inputImage );

  template< class LocalInputImageType, class LocalOutputImageType >
  typename LocalOutputImageType::Pointer ElementRound( LocalInputImageType * inputImage );

  // This function factorizes the image size uses factors of 2, 3, and
  // 5.  After this factorization, if there are any remaining values,
  // the function returns this value.
  int FactorizeNumber( int n );

  // Find the closest valid dimension above the desired dimension.  This
  // will be a combination of 2s, 3s, and 5s.
  int FindClosestValidDimension( int n );

  template< class LocalInputImageType >
  double CalculatePrecisionTolerance( LocalInputImageType * inputImage );

private:
  MaskedFFTNormalizedCorrelationImageFilter(const Self&); //purposely not implemented
  void operator=(const Self&); //purposely not implemented

  /** Larger values zero-out pixels on a larger border around the correlation image.
   * Thus, larger values remove less stable computations but also limit the capture range.
   * The default is set to 0. */
  SizeValueType m_RequiredNumberOfOverlappingPixels;
};
} // end namespace itk

#ifndef ITK_MANUAL_INSTANTIATION
#include "itkMaskedFFTNormalizedCorrelationImageFilter.hxx"
#endif

#endif


text:
export SHRUTI_CLIENT_HOST=0.0.0.0
export SHRUTI_CLIENT_PORT=9576
export SHRUTI_CLIENT_ID=webclient1234567
export SHRUTI_CLIENT_REFRESH_INTERVAL=10
export SHRUTI_API_URL=http://127.0.0.1:9574/
export SHRUTI_IVONA_URL=http://127.0.0.1:9575/

export SHRUTI_PUSHER_API_KEY=
export SHRUTI_PUSHER_CHANNEL=shruti
export SHRUTI_PUSHER_EVENT=new-notification

rm shruti-client
go build
./shruti-client


text:
package model

type ServerStatusInfo struct {
	Type string
	Info string
}


text:
<!-- Do not edit this file. It is automatically generated by API Documenter. -->

[Home](./index.md) > [puppeteer](./puppeteer.md) > [Protocol](./puppeteer.protocol.md) > [Console](./puppeteer.protocol.console.md) > [ConsoleMessage](./puppeteer.protocol.console.consolemessage.md) > [text](./puppeteer.protocol.console.consolemessage.text.md)

## Protocol.Console.ConsoleMessage.text property

Message text.

<b>Signature:</b>

```typescript
text: string;
```


text:
/**
 * @file 	PrimeNumbers.cpp
 * @author 	Fabian Wegscheider
 * @date 	Jul 14, 2017
 */

#include "PrimeNumbers.h"

/*
 * An implementation of find_primes which uses the fact that if a natural number
 * has a divisor it also has at least one prime divisor.
 */
vector<int> PrimeNumbers::find_primes(int n) {

	vector<int> primes;
	if (n >= 2) primes.push_back(2);

	for (int i = 3; i < n; ++i) {
		bool isPrime = true;
		for (unsigned int j = 0; j < primes.size() && primes[j]*primes[j] <= i; j++) {
			if (i % primes[j] == 0) {
				isPrime = false;
				break;
			}
		}
		if (isPrime) {
			primes.push_back(i);
		}
	}

	// primes are decreased by one to fit the purpose of this program
	for (unsigned int i = 0; i < primes.size(); ++i) {
		primes[i]--;
	}

	return primes;
}


text:
class cMtlTex;

__declspec(align(16)) class cFrame
{
	friend class cAseLoader;
private:
	std::string					m_sNodeName;
	std::string					m_sParentName;

	stSceneInfo					m_stSceneInfo;
	stAseTrackAni				m_stNodeAni;
	std::vector<D3DXQUATERNION>	m_vecAccumRotQuat;
	//std::vector<D3DXQUATERNION>	m_vecAccumTCBRotQuat;

	std::vector<cFrame*>		m_vecChildren;
	//std::vector<int>			m_vecTframe;
	std::vector<int>			m_vecFrame;

	D3DXMATRIXA16				m_matLocalTM;
	D3DXMATRIXA16				m_matWorldTM;
	LPD3DXMESH					m_pMesh;
	cMtlTex*					m_pMtlTex;

	float						m_fTotalAccum = 0.0f;

	float						m_fTransAccum = 0.0f;
	float						m_fRotAccum = 0.0f;
	float						m_fTRotAccum = 0.0f;
	int							m_nTrsIndex = 0;
	int							m_nRotIndex = 0;
	int							m_nTRotIndex = 0;
public:
	cFrame(void);
	~cFrame(void);

	// override keyword new
	void* operator new(size_t i)
	{
		return _mm_malloc(i, 16);
	}

		void operator delete(void* p)
	{
		_mm_free(p);
	}

	void AddChild(cFrame* pChild);
	void CalcLocalTM(D3DXMATRIXA16* pParent);
	void BuidlMesh(std::vector<ST_PNT_VERTEX>& vecVertex);
	void SetMtlTex(cMtlTex* pMtlTex);
	void Update(D3DXMATRIXA16* pmatParent, float delta);
	void Render();
	void Destroy();

	void CalcAccumRotTracks();
	void CalcAccumRotTracksTCB();

	void GetRotationMatrixFromAnimation(float delta, OUT D3DXMATRIXA16& mat);
	void GetTranslationMatrixFromAnimation(float delta, OUT D3DXMATRIXA16& mat);
	void GetTCBRotationMatrixFromAnimation(float delta, OUT D3DXMATRIXA16& mat);
};


text:
namespace buzz {
class XmppTaskParentInterface;
}  // namespace buzz

namespace notifier {
class PushClient;
}  // namespace notifier

namespace syncer {

class RegistrationManager;

typedef std::map<invalidation::ObjectId,
                 std::string,
                 ObjectIdLessThan> ObjectIdPayloadMap;

// ChromeInvalidationClient is not thread-safe and lives on the sync
// thread.
class ChromeInvalidationClient
    : public invalidation::InvalidationListener,
      public StateWriter,
      public notifier::PushClientObserver,
      public base::NonThreadSafe {
 public:
  class Listener {
   public:
    virtual ~Listener();

    virtual void OnInvalidate(const ObjectIdPayloadMap& id_payloads) = 0;

    virtual void OnNotificationsEnabled() = 0;

    virtual void OnNotificationsDisabled(
        NotificationsDisabledReason reason) = 0;
  };

  explicit ChromeInvalidationClient(
      scoped_ptr<notifier::PushClient> push_client);

  // Calls Stop().
  virtual ~ChromeInvalidationClient();

  // Does not take ownership of |listener| or |state_writer|.
  // |invalidation_state_tracker| must be initialized.
  void Start(
      const std::string& client_id, const std::string& client_info,
      const std::string& state,
      const InvalidationVersionMap& initial_max_invalidation_versions,
      const WeakHandle<InvalidationStateTracker>& invalidation_state_tracker,
      Listener* listener);

  void UpdateCredentials(const std::string& email, const std::string& token);

  // Register the object IDs that we're interested in getting
  // notifications for.  May be called at any time.
  void RegisterIds(const ObjectIdSet& ids);

  // invalidation::InvalidationListener implementation.
  virtual void Ready(
      invalidation::InvalidationClient* client) OVERRIDE;
  virtual void Invalidate(
      invalidation::InvalidationClient* client,
      const invalidation::Invalidation& invalidation,
      const invalidation::AckHandle& ack_handle) OVERRIDE;
  virtual void InvalidateUnknownVersion(
      invalidation::InvalidationClient* client,
      const invalidation::ObjectId& object_id,
      const invalidation::AckHandle& ack_handle) OVERRIDE;
  virtual void InvalidateAll(
      invalidation::InvalidationClient* client,
      const invalidation::AckHandle& ack_handle) OVERRIDE;
  virtual void InformRegistrationStatus(
      invalidation::InvalidationClient* client,
      const invalidation::ObjectId& object_id,
      invalidation::InvalidationListener::RegistrationState reg_state) OVERRIDE;
  virtual void InformRegistrationFailure(
      invalidation::InvalidationClient* client,
      const invalidation::ObjectId& object_id,
      bool is_transient,
      const std::string& error_message) OVERRIDE;
  virtual void ReissueRegistrations(
      invalidation::InvalidationClient* client,
      const std::string& prefix,
      int prefix_length) OVERRIDE;
  virtual void InformError(
      invalidation::InvalidationClient* client,
      const invalidation::ErrorInfo& error_info) OVERRIDE;

  // StateWriter implementation.
  virtual void WriteState(const std::string& state) OVERRIDE;

  // notifier::PushClientObserver implementation.
  virtual void OnNotificationsEnabled() OVERRIDE;
  virtual void OnNotificationsDisabled(
      notifier::NotificationsDisabledReason reason) OVERRIDE;
  virtual void OnIncomingNotification(
      const notifier::Notification& notification) OVERRIDE;

 private:
  friend class ChromeInvalidationClientTest;

  void Stop();

  NotificationsDisabledReason GetState() const;

  void EmitStateChange();

  void EmitInvalidation(const ObjectIdPayloadMap& id_payloads);

  // Owned by |chrome_system_resources_|.
  notifier::PushClient* const push_client_;
  ChromeSystemResources chrome_system_resources_;
  InvalidationVersionMap max_invalidation_versions_;
  WeakHandle<InvalidationStateTracker> invalidation_state_tracker_;
  Listener* listener_;
  scoped_ptr<invalidation::InvalidationClient> invalidation_client_;
  scoped_ptr<RegistrationManager> registration_manager_;
  // Stored to pass to |registration_manager_| on start.
  ObjectIdSet registered_ids_;

  // The states of the ticl and the push client (with
  // NO_NOTIFICATION_ERROR meaning notifications are enabled).
  NotificationsDisabledReason ticl_state_;
  NotificationsDisabledReason push_client_state_;

  DISALLOW_COPY_AND_ASSIGN(ChromeInvalidationClient);
};

}  // namespace syncer

#endif  // SYNC_NOTIFIER_CHROME_INVALIDATION_CLIENT_H_


text:
package org.auraframework.integration.test.adapter.format.html;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.inject.Inject;

import org.auraframework.def.ApplicationDef;
import org.auraframework.def.ComponentDef;
import org.auraframework.def.DefDescriptor;
import org.auraframework.def.StyleDef;
import org.auraframework.impl.adapter.format.html.BaseComponentDefHTMLFormatAdapterTest;
import org.auraframework.service.DefinitionService;
import org.auraframework.system.AuraContext;
import org.auraframework.util.AuraTextUtil;
import org.auraframework.util.test.annotation.ThreadHostileTest;
import org.junit.Test;

/**
 * Tests for BaseComponentDefHTMLFormatAdapter, as it relates to ApplicationDef
 *
 * @since 0.0.224
 */
public class ApplicationDefHTMLFormatAdapterTest extends BaseComponentDefHTMLFormatAdapterTest<ApplicationDef> {

    @Inject
    DefinitionService definitionService;

    @Override
    public Class<ApplicationDef> getDefClass() {
        return ApplicationDef.class;
    }

    /**
     * Manifest is not appended to <html> if system config is set to disable appcache (aura.noappcache = true).
     */
    @ThreadHostileTest("disables AppCache")
    @Test
    public void testWriteManifestWithConfigDisabled() throws Exception {
        AuraContext context = contextService.getCurrentContext();
        getMockConfigAdapter().setIsClientAppcacheEnabled(false);
        DefDescriptor<ApplicationDef> desc = addSourceAutoCleanup(ApplicationDef.class,
                "<aura:application useAppcache='true' render='client'></aura:application>");
        context.setApplicationDescriptor(desc);
        context.addLoaded(desc, definitionService.getUid(null, desc));
        String body = doWrite(definitionService.getDefinition(desc));
        int start = body.indexOf("<html");
        String tag = body.substring(start, body.indexOf('>', start) + 1);
        if (tag.contains("manifest=")) {
            fail("Should not have included a manifest attribute with config disabled:\n" + body);
        }
    }

    /**
     * Manifest is not appended to <html> if useAppcache is false.
     */
    @Test
    public void testWriteManifestWithUseAppCacheFalse() throws Exception {
        AuraContext context = contextService.getCurrentContext();
        DefDescriptor<ApplicationDef> desc = addSourceAutoCleanup(ApplicationDef.class,
                "<aura:application render='client' useAppcache='false'></aura:application>");
        context.setApplicationDescriptor(desc);
        context.addLoaded(desc, definitionService.getUid(null, desc));
        String body = doWrite(definitionService.getDefinition(desc));
        int start = body.indexOf("<html");
        String tag = body.substring(start, body.indexOf('>', start) + 1);
        if (tag.contains(" manifest=")) {
            fail("Should not have included a manifest attribute useAppCache = false:\n" + body);
        }
    }

    /**
     * Manifest is not appended to <html> if useAppcache is missing (inherits false from aura:application).
     */
    @Test
    public void testWriteManifestWithUseAppCacheInherited() throws Exception {
        AuraContext context = contextService.getCurrentContext();
        DefDescriptor<ApplicationDef> desc = addSourceAutoCleanup(ApplicationDef.class,
                "<aura:application render='client'></aura:application>");
        context.setApplicationDescriptor(desc);
        context.addLoaded(desc, definitionService.getUid(null, desc));
        String body = doWrite(definitionService.getDefinition(desc));
        int start = body.indexOf("<html");
        String tag = body.substring(start, body.indexOf('>', start) + 1);
        if (tag.contains(" manifest=")) {
            fail("Should not have included a manifest attribute with inherited useAppCache = false:\n" + body);
        }
    }

    /**
     * Manifest is appended to <html> if current app has useAppCache.
     */
    @Test
    public void testWriteManifest() throws Exception {
        AuraContext context = contextService.getCurrentContext();
        DefDescriptor<ApplicationDef> desc = addSourceAutoCleanup(ApplicationDef.class,
                "<aura:application render='client' useAppcache='true'></aura:application>");
        context.setApplicationDescriptor(desc);
        final String uid = definitionService.getUid(null, desc);
        context.addLoaded(desc, uid);
        String body = doWrite(definitionService.getDefinition(desc));
        int start = body.indexOf("<html");
        String tag = body.substring(start, body.indexOf('>', start) + 1);
        String isLockerServiceEnabled =  configAdapter.isLockerServiceEnabled() ? ",\"ls\":1" : "";

        String expectedSubPath = AuraTextUtil.urlencode(String.format(
                "{\"mode\":\"UTEST\",\"app\":\"%s\",\"pathPrefix\":\"\",\"test\":\"org.auraframework.integration.test.adapter.format.html.ApplicationDefHTMLFormatAdapterTest.testWriteManifest\"%s}",
                desc.getDescriptorName(), isLockerServiceEnabled));
        String expectedAttribute = " manifest=\"/l/" + expectedSubPath + "/app.manifest";

        if (!tag.contains(expectedAttribute)) {
            fail("Did not find expected manifest attribute <" + expectedAttribute + "> in:" + tag);
        }
    }

    /**
     * Context path should be prepended to urls
     */
    @Test
    public void testUrlContextPath() throws Exception {
        AuraContext context = contextService.getCurrentContext();
        String coolContext = "/cool";
        context.setContextPath(coolContext);
        DefDescriptor<ApplicationDef> desc = addSourceAutoCleanup(ApplicationDef.class,
                "<aura:application render='client' useAppcache='true'></aura:application>");
        context.setApplicationDescriptor(desc);
        final String uid = definitionService.getUid(null, desc);
        context.addLoaded(desc, uid);
        String body = doWrite(definitionService.getDefinition(desc));
        Pattern pattern = Pattern.compile("/auraFW|/l/");
        Matcher matcher = pattern.matcher(body);
        while(matcher.find()) {
            int start =  matcher.start();
            String cool = body.substring(start - 5, start);
            if (!cool.equals(coolContext)) {
                fail("Context path was not prepended to Aura urls");
            }
        }
    }

    /**
     * Verify that comments in Template CSS are stripped out before sending it to client.
     *
     * @throws Exception
     */
    @ThreadHostileTest("NamespaceDef modification affects namespace")
    @Test
    public void testCommentsInTemplateCssNotInjectedToPage() throws Exception {
        String css = "/*" + "*Multi line comment" + "*/\n" + "body{" + "background-color: #ededed;"
                + "font-size: 13px;" + "/**Inline comment*/\n" + "line-height: 1.3" + "}";
        DefDescriptor<StyleDef> styleDef = definitionService.getDefDescriptor(
                "templateCss://string.thing" + System.currentTimeMillis() + "template", StyleDef.class);
        addSourceAutoCleanup(styleDef, css);
        String templateCss = String.format("%s://%s.%s", DefDescriptor.TEMPLATE_CSS_PREFIX, styleDef.getNamespace(),
                styleDef.getName());
        String templateMarkup = String.format(baseComponentTag, "style='" + templateCss
                + "'  isTemplate='true'  extends='aura:template' ", "");
        DefDescriptor<ComponentDef> template = addSourceAutoCleanup(ComponentDef.class, templateMarkup);

        DefDescriptor<ApplicationDef> testApp = addSourceAutoCleanup(ApplicationDef.class,
                "<aura:application render='client' template='" + template.getQualifiedName() + "'></aura:application>");

        String body = doWrite(definitionService.getDefinition(testApp));
        assertNotNull(body);
        assertFalse("Comments were not stripped out from template CSS", body.contains("Multi line comment"));
        assertFalse("Inline comments were not stripped our from template CSS", body.contains("Inline comment"));
        assertTrue("Expected template css not found in serialized response.",
                body.contains("<style>body {background-color:#ededed; font-size:13px; line-height:1.3}</style>"));
    }
}


text:
Zaloguj się

        <form name="form" (ngSubmit)="f.form.valid && login()" #f="ngForm" novalidate>

                Nazwa użytkownika
                <input type="text" class="form-control" id="login_username" name="username" [(ngModel)]="model.username" #username="ngModel"
                       required/>

Username is required

                Hasło
                <input type="password" class="form-control" id="login_password" name="password" [(ngModel)]="model.password"
                       #password="ngModel" required/>

Password is required

                <button [disabled]="loading" class="btn btn-primary">

                    Zaloguj
                </button>

{{error}}

        </form>


text:
    <title>React Starter App</title>
    <link href='https://fonts.googleapis.com/css?family=Vibur|Damion|Poppins:400,300' rel='stylesheet' type='text/css'>
    <link rel="stylesheet" type="text/css" href="./css/style.css" />

Cinnamon Roller


text:
"""distutils.command.config

Implements the Distutils 'config' command, a (mostly) empty command class
that exists mainly to be sub-classed by specific module distributions and
applications.  The idea is that while every "config" command is different,
at least they're all named the same, and users always see "config" in the
list of standard commands.  Also, this is a good place to put common
configure-like tasks: "try to compile this C code", or "figure out where
this header file lives".
"""

__revision__ = "$Id$"

import os
import re

from distutils.core import Command
from distutils.errors import DistutilsExecError
from distutils.sysconfig import customize_compiler
from distutils import log

LANG_EXT = {'c': '.c', 'c++': '.cxx'}

class config(Command):

    description = "prepare to build"

    user_options = [
        ('compiler=', None,
         "specify the compiler type"),
        ('cc=', None,
         "specify the compiler executable"),
        ('include-dirs=', 'I',
         "list of directories to search for header files"),
        ('define=', 'D',
         "C preprocessor macros to define"),
        ('undef=', 'U',
         "C preprocessor macros to undefine"),
        ('libraries=', 'l',
         "external C libraries to link with"),
        ('library-dirs=', 'L',
         "directories to search for external C libraries"),

        ('noisy', None,
         "show every action (compile, link, run, ...) taken"),
        ('dump-source', None,
         "dump generated source files before attempting to compile them"),
        ]

    # The three standard command methods: since the "config" command
    # does nothing by default, these are empty.

    def initialize_options(self):
        self.compiler = None
        self.cc = None
        self.include_dirs = None
        self.libraries = None
        self.library_dirs = None

        # maximal output for now
        self.noisy = 1
        self.dump_source = 1

        # list of temporary files generated along-the-way that we have
        # to clean at some point
        self.temp_files = []

    def finalize_options(self):
        if self.include_dirs is None:
            self.include_dirs = self.distribution.include_dirs or []
        elif isinstance(self.include_dirs, str):
            self.include_dirs = self.include_dirs.split(os.pathsep)

        if self.libraries is None:
            self.libraries = []
        elif isinstance(self.libraries, str):
            self.libraries = [self.libraries]

        if self.library_dirs is None:
            self.library_dirs = []
        elif isinstance(self.library_dirs, str):
            self.library_dirs = self.library_dirs.split(os.pathsep)

    def run(self):
        pass

    # Utility methods for actual "config" commands.  The interfaces are
    # loosely based on Autoconf macros of similar names.  Sub-classes
    # may use these freely.

    def _check_compiler(self):
        """Check that 'self.compiler' really is a CCompiler object;
        if not, make it one.
        """
        # We do this late, and only on-demand, because this is an expensive
        # import.
        from distutils.ccompiler import CCompiler, new_compiler
        if not isinstance(self.compiler, CCompiler):
            self.compiler = new_compiler(compiler=self.compiler,
                                         dry_run=self.dry_run, force=1)
            customize_compiler(self.compiler)
            if self.include_dirs:
                self.compiler.set_include_dirs(self.include_dirs)
            if self.libraries:
                self.compiler.set_libraries(self.libraries)
            if self.library_dirs:
                self.compiler.set_library_dirs(self.library_dirs)

    def _gen_temp_sourcefile(self, body, headers, lang):
        filename = "_configtest" + LANG_EXT[lang]
        file = open(filename, "w")
        if headers:
            for header in headers:
                file.write("#include <%s>\n" % header)
            file.write("\n")
        file.write(body)
        if body[-1] != "\n":
            file.write("\n")
        file.close()
        return filename

    def _preprocess(self, body, headers, include_dirs, lang):
        src = self._gen_temp_sourcefile(body, headers, lang)
        out = "_configtest.i"
        self.temp_files.extend([src, out])
        self.compiler.preprocess(src, out, include_dirs=include_dirs)
        return (src, out)

    def _compile(self, body, headers, include_dirs, lang):
        src = self._gen_temp_sourcefile(body, headers, lang)
        if self.dump_source:
            dump_file(src, "compiling '%s':" % src)
        (obj,) = self.compiler.object_filenames([src])
        self.temp_files.extend([src, obj])
        self.compiler.compile([src], include_dirs=include_dirs)
        return (src, obj)

    def _link(self, body, headers, include_dirs, libraries, library_dirs,
              lang):
        (src, obj) = self._compile(body, headers, include_dirs, lang)
        prog = os.path.splitext(os.path.basename(src))[0]
        self.compiler.link_executable([obj], prog,
                                      libraries=libraries,
                                      library_dirs=library_dirs,
                                      target_lang=lang)

        if self.compiler.exe_extension is not None:
            prog = prog + self.compiler.exe_extension
        self.temp_files.append(prog)

        return (src, obj, prog)

    def _clean(self, *filenames):
        if not filenames:
            filenames = self.temp_files
            self.temp_files = []
        log.info("removing: %s", ' '.join(filenames))
        for filename in filenames:
            try:
                os.remove(filename)
            except OSError:
                pass

    # XXX these ignore the dry-run flag: what to do, what to do? even if
    # you want a dry-run build, you still need some sort of configuration
    # info.  My inclination is to make it up to the real config command to
    # consult 'dry_run', and assume a default (minimal) configuration if
    # true.  The problem with trying to do it here is that you'd have to
    # return either true or false from all the 'try' methods, neither of
    # which is correct.

    # XXX need access to the header search path and maybe default macros.

    def try_cpp(self, body=None, headers=None, include_dirs=None, lang="c"):
        """Construct a source file from 'body' (a string containing lines
        of C/C++ code) and 'headers' (a list of header files to include)
        and run it through the preprocessor.  Return true if the
        preprocessor succeeded, false if there were any errors.
        ('body' probably isn't of much use, but what the heck.)
        """
        from distutils.ccompiler import CompileError
        self._check_compiler()
        ok = 1
        try:
            self._preprocess(body, headers, include_dirs, lang)
        except CompileError:
            ok = 0

        self._clean()
        return ok

    def search_cpp(self, pattern, body=None, headers=None, include_dirs=None,
                   lang="c"):
        """Construct a source file (just like 'try_cpp()'), run it through
        the preprocessor, and return true if any line of the output matches
        'pattern'.  'pattern' should either be a compiled regex object or a
        string containing a regex.  If both 'body' and 'headers' are None,
        preprocesses an empty file -- which can be useful to determine the
        symbols the preprocessor and compiler set by default.
        """
        self._check_compiler()
        src, out = self._preprocess(body, headers, include_dirs, lang)

        if isinstance(pattern, str):
            pattern = re.compile(pattern)

        file = open(out)
        match = 0
        while 1:
            line = file.readline()
            if line == '':
                break
            if pattern.search(line):
                match = 1
                break

        file.close()
        self._clean()
        return match

    def try_compile(self, body, headers=None, include_dirs=None, lang="c"):
        """Try to compile a source file built from 'body' and 'headers'.
        Return true on success, false otherwise.
        """
        from distutils.ccompiler import CompileError
        self._check_compiler()
        try:
            self._compile(body, headers, include_dirs, lang)
            ok = 1
        except CompileError:
            ok = 0

        log.info(ok and "success!" or "failure.")
        self._clean()
        return ok

    def try_link(self, body, headers=None, include_dirs=None, libraries=None,
                 library_dirs=None, lang="c"):
        """Try to compile and link a source file, built from 'body' and
        'headers', to executable form.  Return true on success, false
        otherwise.
        """
        from distutils.ccompiler import CompileError, LinkError
        self._check_compiler()
        try:
            self._link(body, headers, include_dirs,
                       libraries, library_dirs, lang)
            ok = 1
        except (CompileError, LinkError):
            ok = 0

        log.info(ok and "success!" or "failure.")
        self._clean()
        return ok

    def try_run(self, body, headers=None, include_dirs=None, libraries=None,
                library_dirs=None, lang="c"):
        """Try to compile, link to an executable, and run a program
        built from 'body' and 'headers'.  Return true on success, false
        otherwise.
        """
        from distutils.ccompiler import CompileError, LinkError
        self._check_compiler()
        try:
            src, obj, exe = self._link(body, headers, include_dirs,
                                       libraries, library_dirs, lang)
            self.spawn([exe])
            ok = 1
        except (CompileError, LinkError, DistutilsExecError):
            ok = 0

        log.info(ok and "success!" or "failure.")
        self._clean()
        return ok

    # -- High-level methods --------------------------------------------
    # (these are the ones that are actually likely to be useful
    # when implementing a real-world config command!)

    def check_func(self, func, headers=None, include_dirs=None,
                   libraries=None, library_dirs=None, decl=0, call=0):

        """Determine if function 'func' is available by constructing a
        source file that refers to 'func', and compiles and links it.
        If everything succeeds, returns true; otherwise returns false.

        The constructed source file starts out by including the header
        files listed in 'headers'.  If 'decl' is true, it then declares
        'func' (as "int func()"); you probably shouldn't supply 'headers'
        and set 'decl' true in the same call, or you might get errors about
        a conflicting declarations for 'func'.  Finally, the constructed
        'main()' function either references 'func' or (if 'call' is true)
        calls it.  'libraries' and 'library_dirs' are used when
        linking.
        """

        self._check_compiler()
        body = []
        if decl:
            body.append("int %s ();" % func)
        body.append("int main () {")
        if call:
            body.append("  %s();" % func)
        else:
            body.append("  %s;" % func)
        body.append("}")
        body = "\n".join(body) + "\n"

        return self.try_link(body, headers, include_dirs,
                             libraries, library_dirs)

    # check_func ()

    def check_lib(self, library, library_dirs=None, headers=None,
                  include_dirs=None, other_libraries=[]):
        """Determine if 'library' is available to be linked against,
        without actually checking that any particular symbols are provided
        by it.  'headers' will be used in constructing the source file to
        be compiled, but the only effect of this is to check if all the
        header files listed are available.  Any libraries listed in
        'other_libraries' will be included in the link, in case 'library'
        has symbols that depend on other libraries.
        """
        self._check_compiler()
        return self.try_link("int main (void) { }",
                             headers, include_dirs,
                             [library]+other_libraries, library_dirs)

    def check_header(self, header, include_dirs=None, library_dirs=None,
                     lang="c"):
        """Determine if the system header file named by 'header_file'
        exists and can be found by the preprocessor; return true if so,
        false otherwise.
        """
        return self.try_cpp(body="/* No body */", headers=[header],
                            include_dirs=include_dirs)

def dump_file(filename, head=None):
    """Dumps a file content into log.info.

    If head is not None, will be dumped before the file content.
    """
    if head is None:
        log.info('%s' % filename)
    else:
        log.info(head)
    file = open(filename)
    try:
        log.info(file.read())
    finally:
        file.close()


text:
import {
    fail,
    createScalarNode,
    SimpleType,
    TypeFlags,
    isType,
    IValidationContext,
    IValidationResult,
    typeCheckFailure,
    ModelType,
    typeCheckSuccess,
    ISimpleType,
    AnyObjectNode,
    ScalarNode,
    assertArg
} from "../../internal"

abstract class BaseIdentifierType<T> extends SimpleType<T, T, T> {
    readonly flags = TypeFlags.Identifier

    constructor(name: string, private readonly validType: "string" | "number") {
        super(name)
    }

    instantiate(
        parent: AnyObjectNode | null,
        subpath: string,
        environment: any,
        initialValue: this["C"]
    ): this["N"] {
        if (!parent || !(parent.type instanceof ModelType))
            throw fail(`Identifier types can only be instantiated as direct child of a model type`)

        return createScalarNode(this, parent, subpath, environment, initialValue)
    }

    reconcile(current: this["N"], newValue: this["C"], parent: AnyObjectNode, subpath: string) {
        // we don't consider detaching here since identifier are scalar nodes, and scalar nodes cannot be detached
        if (current.storedValue !== newValue)
            throw fail(
                `Tried to change identifier from '${current.storedValue}' to '${newValue}'. Changing identifiers is not allowed.`
            )
        current.setParent(parent, subpath)
        return current
    }

    isValidSnapshot(value: this["C"], context: IValidationContext): IValidationResult {
        if (typeof value !== this.validType) {
            return typeCheckFailure(
                context,
                value,
                `Value is not a valid ${this.describe()}, expected a ${this.validType}`
            )
        }
        return typeCheckSuccess()
    }
}

/**
 * @internal
 * @hidden
 */
export class IdentifierType extends BaseIdentifierType<string> {
    readonly flags = TypeFlags.Identifier

    constructor() {
        super(`identifier`, "string")
    }

    describe() {
        return `identifier`
    }
}

/**
 * @internal
 * @hidden
 */
export class IdentifierNumberType extends BaseIdentifierType<number> {
    constructor() {
        super("identifierNumber", "number")
    }

    getSnapshot(node: ScalarNode<number, number, number>): number {
        return node.storedValue
    }

    describe() {
        return `identifierNumber`
    }
}

/**
 * `types.identifier` - Identifiers are used to make references, lifecycle events and reconciling works.
 * Inside a state tree, for each type can exist only one instance for each given identifier.
 * For example there couldn't be 2 instances of user with id 1. If you need more, consider using references.
 * Identifier can be used only as type property of a model.
 * This type accepts as parameter the value type of the identifier field that can be either string or number.
 *
 * Example:
 * ```ts
 *  const Todo = types.model("Todo", {
 *      id: types.identifier,
 *      title: types.string
 *  })
 * ```
 *
 * @returns
 */
export const identifier: ISimpleType<string> = new IdentifierType()

/**
 * `types.identifierNumber` - Similar to `types.identifier`. This one will serialize from / to a number when applying snapshots
 *
 * Example:
 * ```ts
 *  const Todo = types.model("Todo", {
 *      id: types.identifierNumber,
 *      title: types.string
 *  })
 * ```
 *
 * @returns
 */
export const identifierNumber: ISimpleType<number> = new IdentifierNumberType()

/**
 * Returns if a given value represents an identifier type.
 *
 * @param type
 * @returns
 */
export function isIdentifierType<IT extends typeof identifier | typeof identifierNumber>(
    type: IT
): type is IT {
    return isType(type) && (type.flags & TypeFlags.Identifier) > 0
}

/**
 * Valid types for identifiers.
 */
export type ReferenceIdentifier = string | number

/**
 * @internal
 * @hidden
 */
export function normalizeIdentifier(id: ReferenceIdentifier): string {
    return "" + id
}

/**
 * @internal
 * @hidden
 */
export function isValidIdentifier(id: any): id is ReferenceIdentifier {
    return typeof id === "string" || typeof id === "number"
}

/**
 * @internal
 * @hidden
 */
export function assertIsValidIdentifier(id: ReferenceIdentifier, argNumber: number | number[]) {
    assertArg(id, isValidIdentifier, "string or number (identifier)", argNumber)
}


text:
{{+bindTo:partials.standard_nacl_article}}

3D Graphics

Native Client applications use the OpenGL ES 2.0 API for 3D rendering. This document
describes how to call the OpenGL ES 2.0 interface in a Native Client module and
how to build an efficient rendering loop. It also explains how to validate GPU
drivers and test for specific GPU capabilities, and provides tips to help ensure
your rendering code runs efficiently.

Note: 3D drawing and OpenGL are complex topics. This document deals only
with issues directly related to programming in the Native Client
environment. To learn more about OpenGL ES 2.0 itself, see the OpenGL ES 2.0
Programming Guide.

Validating the client graphics platform

Native Client is a software technology that lets you code an application once
and run it on multiple platforms without worrying about the implementation
details on every possible target platform. It’s difficult to provide the same
support at the hardware level. Graphics hardware comes from many different
manufacturers and is controlled by drivers of varying quality. A particular GPU
driver may not support every OpenGL ES 2.0 feature, and some drivers are known
to have vulnerabilities that can be exploited.

Even if the GPU driver is safe to use, your program should perform a validation
check before you launch your application to ensure that the driver supports all
the features you need.

Vetting the driver in JavaScript

At startup, the application should perform a few additional tests that can be
implemented in JavaScript on its hosting web page. The script that performs
these tests should be included before the module’s embed tag, and ideally
the embed tag should appear on the hosting page only if these tests succeed.

The first thing to check is whether you can create a graphics context. If you
can, use the context to confirm the existence of any required OpenGL ES 2.0
extensions.  You may want to refer to the extension registry and include vendor
prefixes
when checking for extensions.

Vetting the driver in Native Client

Create a context

Once you’ve passed the JavaScript validation tests, it’s safe to add a Native
Client embed tag to the hosting web page and load the module. As part of the
module initialization code, you must create a graphics context for the app by
either creating a C++ Graphics3D object or calling PPB_Graphics3D API
function Create. Don’t assume this will always succeed; you still might have
problems creating the context. If you are in development mode and can’t create
the context, try creating a simpler version to see if you’re asking for an
unsupported feature or exceeding a driver resource limit. Your production code
should always check that the context was created and fail gracefully if that’s
not the case.

Check for extensions and capabilities

Not every GPU supports every extension or has the same amount of texture units,
vertex attributes, etc. On startup, call glGetString(GL_EXTENSIONS) and
check for the extensions and the features you need. For example:

If you are using non power-of-2 texture with mipmaps, make sure
GL_OES_texture_npot exists.

If you are using floating point textures, make sure GL_OES_texture_float
exists.

If you are using DXT1, DXT3, or DXT5 textures, make sure the corresponding
extensions EXT_texture_compression_dxt1,
GL_CHROMIUM_texture_compression_dxt3, and
GL_CHROMIUM_texture_compression_dxt5 exist.

If you are using the functions glDrawArraysInstancedANGLE,
glDrawElementsInstancedANGLE, glVertexAttribDivisorANGLE, or the PPAPI
interface PPB_OpenGLES2InstancedArrays, make sure the corresponding
extension GL_ANGLE_instanced_arrays exists.

If you are using the function glRenderbufferStorageMultisampleEXT, or the
PPAPI interface PPB_OpenGLES2FramebufferMultisample, make sure the
corresponding extension GL_CHROMIUM_framebuffer_multisample exists.

If you are using the functions glGenQueriesEXT, glDeleteQueriesEXT,
glIsQueryEXT, glBeginQueryEXT, glEndQueryEXT, glGetQueryivEXT,
glGetQueryObjectuivEXT, or the PPAPI interface PPB_OpenGLES2Query,
make sure the corresponding extension GL_EXT_occlusion_query_boolean
exists.

If you are using the functions glMapBufferSubDataCHROMIUM,
glUnmapBufferSubDataCHROMIUM, glMapTexSubImage2DCHROMIUM,
glUnmapTexSubImage2DCHROMIUM, or the PPAPI interface
PPB_OpenGLES2ChromiumMapSub, make sure the corresponding extension
GL_CHROMIUM_map_sub exists.

Check for system capabilites with glGetIntegerv and adjust shader programs
as well as texture and vertex data accordingly:

If you are using textures in vertex shaders, make sure
glGetIntegerv(GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS, ...) and
glGetIntegerv(GL_MAX_TEXTURE_SIZE, ...) return values greater than 0.

If you are using more than 8 textures in a single shader, make sure
glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS, ...) returns a value greater
than or equal to the number of simultaneous textures you need.

Vetting the driver in the Chrome Web Store

If you choose to place your application in the Chrome Web Store,
its Web Store manifest file can include the webgl
feature in the requirements parameter. It looks like this:

"requirements": {
  "3D": {
    "features": ["webgl"]
  }
}

While WebGL is technically a JavaScript API, specifying the webgl feature
also works for OpenGL ES 2.0 because both interfaces use the same driver.

This manifest item is not required, but if you include it, the Chrome Web Store
will prevent a user from installing the application if the browser is running on
a machine that does not support OpenGL ES 2.0 or that is using a known
blacklisted GPU driver that could invite an attack.

If the Web Store determines that the user’s driver is deficient, the app won’t
appear on the store’s tile display. However, it will appear in store search
results or if the user links to it directly, in which case the user could still
download it. But the manifest requirements will be checked when the user reaches
the install page, and if there is a problem, the browser will display the
message “This application is not supported on this computer. Installation has
been disabled.”

The manifest-based check applies only to downloads directly from the Chrome Web
Store. It is not performed when an application is loaded via inline
installation.

What to do when there are problems

Using the vetting procedure described above, you should be able to detect the
most common problems before your application runs. If there are problems, your
code should describe the issue as clearly as possible. That’s easy if there is a
missing feature. Failure to create a graphics context is tougher to diagnose. At
the very least, you can suggest that the user try to update the driver.  You
might want to linke to the Chrome page that describes how to do updates.

If a user can’t update the driver, or their problem persists, be sure to gather
information about their graphics environment. Ask for the contents of the Chrome
about:gpu page.

Document unreliable drivers

It can be helpful to include information about known dubious drivers in your
user documentation. This might help identify if a rogue driver is the cause of a
problem. There are many sources of GPU driver blacklists. Two such lists can be
found at the Chromium project
and Khronos. You
can use these lists to include information in your documentation that warns
users about dangerous drivers.

Test your defenses

You can test your driver validation code by running Chrome with the following
flags (all at once) and watching how your application responds:

--disable-webgl

--disable-pepper-3d

--disable_multisampling

--disable-accelerated-compositing

--disable-accelerated-2d-canvas

Calling OpenGL ES 2.0 commands

There are three ways to write OpenGL ES 2.0 calls in Native Client.

Use “pure” OpenGL ES 2.0 function calls

You can make OpenGL ES 2.0 calls through a Pepper extension library.  The SDK
example examples/api/graphics_3d works this way.  In the file
graphics_3d.cc, the key initialization steps are as follows:

Add these includes at the top of the file:

#include <GLES2/gl2.h>
#include "ppapi/lib/gl/gles2/gl2ext_ppapi.h"

Define the function InitGL. The exact specification of attrib_list
will be application specific.

bool InitGL(int32_t new_width, int32_t new_height) {
  if (!glInitializePPAPI(pp::Module::Get()->get_browser_interface())) {
    fprintf(stderr, "Unable to initialize GL PPAPI!\n");
    return false;
  }

  const int32_t attrib_list[] = {
    PP_GRAPHICS3DATTRIB_ALPHA_SIZE, 8,
    PP_GRAPHICS3DATTRIB_DEPTH_SIZE, 24,
    PP_GRAPHICS3DATTRIB_WIDTH, new_width,
    PP_GRAPHICS3DATTRIB_HEIGHT, new_height,
    PP_GRAPHICS3DATTRIB_NONE
  };

  context_ = pp::Graphics3D(this, attrib_list);
  if (!BindGraphics(context_)) {
    fprintf(stderr, "Unable to bind 3d context!\n");
    context_ = pp::Graphics3D();
    glSetCurrentContextPPAPI(0);
    return false;
  }

  glSetCurrentContextPPAPI(context_.pp_resource());
  return true;
}

Include logic in Instance::DidChangeView to call InitGL whenever
necessary: upon application launch (when the graphics context is NULL) and
whenever the module’s View changes size.

Use Regal

If you are porting an OpenGL ES 2.0 application, or are comfortable writing in
OpenGL ES 2.0, you should stick with the Pepper APIs or pure OpenGL ES 2.0 calls
described above. If you are porting an application that uses features not in
OpenGL ES 2.0, consider using Regal. Regal is an open source library that
supports many versions of OpenGL. Regal recently added support for Native
Client. Regal forwards most OpenGL calls directly to the underlying graphics
library, but it can also emulate other calls that are not included (when
hardware support exists). See libregal
for more info.

Use the Pepper API

Your code can call the Pepper PPB_OpenGLES2 API directly, as with any Pepper
interface. When you write in this way, each invocation of an OpenGL ES 2.0
function must begin with a reference to the Pepper interface, and the first
argument is the graphics context. To invoke the function glCompileShader,
your code might look like:

ppb_g3d_interface->CompileShader(graphicsContext, shader);

This approach specifically targets the Pepper APIs. Each call corresponds to a
OpenGL ES 2.0 function, but the syntax is unique to Native Client, so the source
file is not portable.

Implementing a rendering loop

Graphics applications require a continuous frame render-and-redraw cycle that
runs at a high frequency. To achieve the best frame rate, is important to
understand how the OpenGL ES 2.0 code in a Native Client module interacts with
Chrome.

The Chrome and Native Client processes

Chrome is a multi-process browser. Each Chrome tab is a separate process that is
running an application with its own main thread (we’ll call it the Chrome main
thread). When an application launches a Native Client module, the module runs in
a new, separate sandboxed process. The module’s process has its own main thread
(the Native Client thread). The Chrome and Native Client processes communicate
with each other using Pepper API calls on their main threads.

When the Chrome main thread calls the Native Client thread (keyboard and mouse
callbacks, for example), the Chrome main thread will block. This means that
lengthy operations on the Native Client thread can steal cycles from Chrome, and
performing blocking operations on the Native Client thread can bring your app to
a standstill.

Native Client uses callback functions to synchronize the main threads of the
two processes. Only certain Pepper functions use callbacks; SwapBuffers
is one.

SwapBuffers and its callback function

SwapBuffers is non-blocking; it is called from the Native Client thread and
returns immediately. When SwapBuffers is called, it runs asynchronously on
the Chrome main thread. It switches the graphics data buffers, handles any
needed compositing operations, and redraws the screen. When the screen update is
complete, the callback function that was included as one of SwapBuffer‘s
arguments will be called from the Chrome thread and executed on the Native
Client thread.

To create a rendering loop, your Native Client module should include a function
that does the rendering work and then executes SwapBuffers, passing itself
as the SwapBuffer callback. If your rendering code is efficient and runs
quickly, this scheme will achieve the highest frame rate possible. The
documentation for SwapBuffers explains why this is optimal: because the
callback is executed only when the plugin’s current state is actually on the
screen, this function provides a way to rate-limit animations. By waiting until
the image is on the screen before painting the next frame, you can ensure you’re
not generating updates faster than the screen can be updated.

The following diagram illustrates the interaction between the Chrome and Native
Client processes. The application-specific rendering code runs in the function
called Draw on the Native Client thread. Blue down-arrows are blocking calls
from the main thread to Native Client, green up-arrows are non-blocking
SwapBuffers calls from Native Client to the main thread. All OpenGL ES 2.0
calls are made from Draw in the Native Client thread.

SDK example graphics_3d

The SDK example graphics_3d uses the function MainLoop (in
hello_world.cc) to create a rendering loop as described above. MainLoop
calls Render to do the rendering work, and then invokes SwapBuffers,
passing itself as the callback.

void MainLoop(void* foo, int bar) {
  if (g_LoadCnt == 3) {
    InitProgram();
    g_LoadCnt++;
  }
  if (g_LoadCnt > 3) {
    Render();
    PP_CompletionCallback cc = PP_MakeCompletionCallback(MainLoop, 0);
    ppb_g3d_interface->SwapBuffers(g_context, cc);
  } else {
    PP_CompletionCallback cc = PP_MakeCompletionCallback(MainLoop, 0);
    ppb_core_interface->CallOnMainThread(0, cc, 0);
  }
}

Managing the OpenGL ES 2.0 pipeline

OpenGL ES 2.0 commands do not run in the Chrome or Native Client processes. They
are passed into a FIFO queue in shared memory which is best understood as a GPU
command buffer. The
command buffer is shared by a dedicated GPU process. By using a separate GPU
process, Chrome implements another layer of runtime security, vetting all OpenGL
ES 2.0 commands and their arguments before they are sent on to the
GPU. Buffering commands through the FIFO also speeds up your code, since each
OpenGL ES 2.0 call in your Native Client thread returns immediately, while the
processing may be delayed as the GPU works down the commands queued up in the
FIFO.

Before the screen is updated, all the intervening OpenGL ES 2.0 commands must be
processed by the GPU. Programmers often try to ensure this by using the
glFlush and glFinish commands in their rendering code. In the case of
Native Client this is usually unnecessary. The SwapBuffers command does an
implicit flush, and the Chrome team is continually tweaking the GPU code to
consume the OpenGL ES 2.0 FIFO as fast as possible.

Sometimes a 3D application can write to the FIFO in a way that’s difficult to
handle. The command pipeline may fill up and your code will have to wait for the
GPU to flush the FIFO. If this is the case, you may be able to add glFlush
calls to speed up the flow of the OpenGL ES 2.0 command FIFO. Before you start
to add your own flushes, first try to determine if pipeline saturation is really
the problem by monitoring the rendering time per frame and looking for irregular
spikes that do not consistently fall on the same OpenGL ES 2.0 call. If you’re
convinced the pipeline needs to be accelerated, insert glFlush calls in your
code before starting blocks of processing that do not generate OpenGL ES 2.0
commands. For example, issue a flush before you begin any multithreaded particle
work, so that the command buffer will be clear when you start doing OpenGL ES
2.0 calls again. Determining where and how often to call glFlush can be
tricky, you will need to experiment to find the sweet spot.

Rendering and inactive tabs

Users will often switch between tabs in a multi-tab browser. A well-behaved
application that’s performing 3D rendering should pause any real-time processing
and yield cycles to other processes when its tab becomes inactive.

In Chrome, an inactive tab will continue to execute timed functions (such as
setInterval and setTimeout) but the timer interval will be automatically
overridden and limited to not less than one second while the tab is inactive. In
addition, any callback associated with a SwapBuffers call will not be sent
until the tab is active again. You may receive asynchronous callbacks from
functions other than SwapBuffers while a tab is inactive. Depending on the
design of your application, you might choose to handle them as they arrive, or
to queue them in a buffer and process them when the tab becomes active.

The time that passes while a tab is inactive can be considerable. If your main
thread pulse is based on the SwapBuffers callback, your app won’t update
while a tab is inactive. A Native Client module should be able to detect and
respond to the state of the tab in which it’s running. For example, when a tab
becomes inactive, you can set an atomic flag in the Native Client thread that
will skip the 3D rendering and SwapBuffers calls and continue to call the
main thread every 30 msec or so. This provides time to update features that
should still run in the background, like audio. It may also be helpful to call
sched_yield or usleep on any worker threads to release resources and
cede cycles to the OS.

Handling tab activation from the main thread

You can detect and respond to the activation or deactivation of a tab with
JavaScript on your hosting page. Add an EventListener for visibilitychange
that sends a message to the Native Client module, as in this example:

document.addEventListener('visibilitychange', function(){
  if (document.hidden) {
    // PostMessage to your Native Client module
    document.nacl_module.postMessage('INACTIVE');
  } else {
    // PostMessage to your Native Client module
    document.nacl_module.postMessage('ACTIVE');
  }

}, false);

Handling tab activation from the Native Client thread

You can also detect and respond to the activation or deactivation of a tab
directly from your Native Client module by including code in the function
pp::Instance::DidChangeView, which is called whenever a change in the
module’s view occurs. The code can call ppb::View::IsPageVisible to
determine if the page is visible or not. The most common cause of invisible
pages is that the page is in a background tab.

Tips and best practices

Here are some suggestions for writing safe code and getting the maximum
performance with the Pepper 3D API.

Do’s

Make sure to enable attrib 0. OpenGL requires that you enable attrib 0,
but OpenGL ES 2.0 does not. For example, you can define a vertex shader with 2
attributes, numbered like this:

glBindAttribLocation(program, "positions", 1);
glBindAttribLocation(program, "normals", 2);

In this case the shader is not using attrib 0 and Chrome may have to perform
some additional work if it is emulating OpenGL ES 2.0 on top of OpenGL. It’s
always more efficient to enable attrib 0, even if you do not use it.

Check how shaders compile. Shaders can compile differently on different
systems, which can result in glGetAttrib* functions returning different
results. Be sure that the vertex attribute indices match the corresponding
name each time you recompile a shader.

Update indices sparingly. For security reasons, all indices must be
validated. If you change indices, Native Client will validate them
again. Structure your code so indices are not updated often.

Use a smaller plugin and let CSS scale it. If you’re running into fillrate
issues, it may be beneficial to perform scaling via CSS. The size your plugin
renders is determined by the width and height attributes of the <embed>
element for the module. The actual size displayed on the web page is
controlled by the CSS styles applied to the element.

Avoid matrix-to-matrix conversions. With some versions of Mac OS, there is
a driver problem when compiling shaders. If you get compiler errors for matrix
transforms, avoid matrix-to-matrix conversions. For instance, upres a vec3 to
a vec4 before transforming it by a mat4, rather than converting the mat4 to a
mat3.

Don’ts

Don’t use client side buffers. OpenGL ES 2.0 can use client side data with
glVertexAttribPointer and glDrawElements, but this is really slow. Try
to avoid client side buffers. Use Vertex Buffer Objects (VBOs) instead.

Don’t mix vertex data and index data. By default, Pepper 3D binds buffers
to a single point. You could create a buffer and bind it to both
GL_ARRAY_BUFFER and GL_ELEMENT_ARRAY_BUFFER, but that would be
expensive overhead and it is not recommended.

Don’t call glGet* or glCheck* during rendering. This is normal
advice for OpenGL programs, but is particularly important for 3D on
Chrome. Calls to any OpenGL ES 2.0 function whose name begins with these
strings blocks the Native Client thread. This includes glGetError; avoid
calling it in release builds.

Don’t use fixed point (GL_FIXED) vertex attributes. Fixed point
attributes are not supported in OpenGL ES 2.0, so emulating them in OpenGL ES
2.0 is slow. By default, GL_FIXED support is turned off in the Pepper 3D
API.

Don’t read data from the GPU. Don’t call glReadPixels, as it is slow.

Don’t update a small portion of a large buffer. In the current OpenGL ES
2.0 implementation when you update a portion of a buffer (with
glSubBufferData for example) the entire buffer must be reprocessed. To
avoid this problem, keep static and dynamic data in different buffers.

Don’t call glDisable(GL_TEXTURE_2D). This is an OpenGL ES 2.0
error. Each time it is called, an error messages will appear in Chrome’s
about:gpu tab.

{{/partials.standard_nacl_article}}


text:
package com.emerchantpay.gateway.api;

import java.lang.reflect.InvocationTargetException;

import com.emerchantpay.gateway.model.Notification;
import com.emerchantpay.gateway.model.WPFNotification;
import com.emerchantpay.gateway.util.NodeWrapper;

public class NotificationResult<T> {

	private Notification notification;
	private WPFNotification wpfNotification;
	private ValidationErrors errors;
	private T target;

	public static <T> T newInstanceFromNode(Class<T> klass, NodeWrapper node) {
		Throwable cause = null;
		try {
			return klass.getConstructor(NodeWrapper.class).newInstance(node);
		} catch (InstantiationException e) {
			cause = e;
		} catch (IllegalAccessException e) {
			cause = e;
		} catch (InvocationTargetException e) {
			cause = e;
		} catch (NoSuchMethodException e) {
			cause = e;
		}

		throw new IllegalArgumentException("Unknown class: " + klass, cause);
	}

	public NotificationResult() {
	}

	public NotificationResult(NodeWrapper node, Class<T> klass) {
		if (node.isSuccess()) {
			this.target = newInstanceFromNode(klass, node);
		} else {
			this.errors = new ValidationErrors(node);

			NodeWrapper notificationNode = node.findFirst("echo_notification");
			if (notificationNode != null) {
				this.notification = new Notification(notificationNode);
				this.wpfNotification = new WPFNotification(notificationNode);
			}
		}

		this.notification = new Notification(node);
		this.wpfNotification = new WPFNotification(node);
	}

	public Notification getNotification() {
		return notification;
	}

	public WPFNotification getWPFNotification() {
		return wpfNotification;
	}

	public ValidationErrors getErrors() {
		return errors;
	}

	public T getTarget() {
		return target;
	}

	public boolean isSuccess() {
		return errors == null;
	}
}


text:
set(ENABLED OFF)

wn_has_architecture(ARM64 HAS)

if (HAS)
  set(ENABLED ON)
endif()

register_overlay(${ENABLED} arm64)