text:
<?php

namespace Oro\Bundle\SecurityBundle\Acl\Persistence;

use Symfony\Component\Security\Acl\Domain\RoleSecurityIdentity;
use Symfony\Component\Security\Acl\Domain\UserSecurityIdentity;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Role\Role;
use Symfony\Component\Security\Core\User\UserInterface;

class BaseAclManager implements AclSidInterface
{
    /**
     * {@inheritdoc}
     */
    public function getSid($identity)
    {
        if (is_string($identity)) {
            return new RoleSecurityIdentity($identity);
        } elseif ($identity instanceof Role) {
            return new RoleSecurityIdentity($identity->getRole());
        } elseif ($identity instanceof UserInterface) {
            return UserSecurityIdentity::fromAccount($identity);
        } elseif ($identity instanceof TokenInterface) {
            return UserSecurityIdentity::fromToken($identity);
        }

        throw new \InvalidArgumentException(
            sprintf(
                '$identity must be a string or implement one of RoleInterface, UserInterface, TokenInterface'
                . ' (%s given)',
                is_object($identity) ? get_class($identity) : gettype($identity)
            )
        );
    }
}


text:
		%time%

		%message%

redpajama_set_name: RedPajamaGithub


text:
class BaseHeap(object):
    """Base class of heap queue

    This class should not be instantiated. Subclass need to implement methods
    below.

    A heap is a specialized tree-based data structure that satisfies the heap
    property: If A is a parent node of B then the key (the value) of node A is
    ordered with respect to the key of node B with the same ordering applying
    across the heap. A heap can be classified further as either a "max heap" or
    a "min heap". In a max heap, the keys of parent nodes are always greater
    than or equal to those of the children and the highest key is in the root
    node. In a min heap, the keys of parent nodes are less than or equal to
    those of the children and the lowest key is in the root node. (Wikipedia)

    """

    def __init__(self, **kwargs):
        """Initialization for an xHeap

        Args:
            kwargs (dict): A dictionary contains config info.

        Attributes:
            comp (function): Indicating how to compare two elements.
                Return negtive number if a < b, positive number if a > b,
                0 if they are equal.
        """
        self.comp = lambda a, b: a - b

    def push(self, item):
        """Add a new item to the heap

        Args:
            item (any): The primitive value or object to be added into heap.

        Returns:
            True if successful, False otherwise.
        """
        raise NotImplementedError('subclass with push() implementation '
                                  'is required')

    def pop(self):
        """Delete and return the max/min item.

        Returns:
            The max/min item in the heap.
        """
        raise NotImplementedError('subclass with pop() implementation '
                                  'is required')

    def peek(self):
        """Return the max/min item.

        Return the max/min item in the heap without deleting it.

        Returns:
            The max/min item in the heap.
        """
        raise NotImplementedError('subclass with peek() implementation '
                                  'is required')

    def remove(self, item):
        """Remove item from heap.

        Remove item equals to the given one according to `comp` from the heap.

        Args:
            item (any): The item to be deleted.

        Returns:
            The deleted item.
        """
        raise NotImplementedError('subclass with remove() implementation '
                                  'is required')

    def merge(self, a_heap):
        """Merge two heaps, which have same `comp` result.

        Args:
            a_heap (BaseHeap): The heap to be merged.

        Returns:
            True if successful, False otherwise.
        """
        raise NotImplementedError('subclass with merge() implementation '
                                  'is required')


text:
<?php
/**
 * WordPress Generic Request (POST/GET) Handler
 *
 * Intended for form submission handling in themes and plugins.
 *
 * @package WordPress
 * @subpackage Administration
 */

/** We are located in WordPress Administration Screens */
define('WP_ADMIN', true);

if ( defined('ABSPATH') )
	require_once(ABSPATH . 'wp-load.php');
else
	require_once( dirname( dirname( __FILE__ ) ) . '/wp-load.php' );

/** Allow for cross-domain requests (from the frontend). */
send_origin_headers();

require_once(ABSPATH . 'wp-admin/includes/admin.php');

nocache_headers();

/** This action is documented in wp-admin/admin.php */
do_action( 'admin_init' );

$action = 'admin_post';

if ( !wp_validate_auth_cookie() )
	$action .= '_nopriv';

if ( !empty($_REQUEST['action']) )
	$action .= '_' . $_REQUEST['action'];

/**
 * Fires the requested handler action.
 *
 * admin_post_nopriv_{$_REQUEST['action']} is called for not-logged-in users.
 * admin_post_{$_REQUEST['action']} is called for logged-in users.
 *
 * @since 2.6.0
 */
do_action( $action );


text:
using System;

using Xunit;

namespace BeanIO.Parser.IgnoreUnidentifiedRecords
{
    public class IgnoreUnidentifiedRecordsParserTest : ParserTest
    {
        [Fact]
        public void TestIgnoreUnidentifiedRecords()
        {
            var factory = NewStreamFactory("ignore_mapping.xml");
            var reader = factory.CreateReader("stream1", LoadReader("ignoreUnidentifiedRecords1.txt"));
            try
            {
                reader.Read();
                Assert.Equal("header", reader.RecordName);
                reader.Read();
                Assert.Equal("group_header", reader.RecordName);
                reader.Read();
                Assert.Equal("group_trailer", reader.RecordName);

                reader.Read();
                Assert.Equal("header", reader.RecordName);
                reader.Read();
                Assert.Equal("group_header", reader.RecordName);
                reader.Read();
                Assert.Equal("group_trailer", reader.RecordName);

                Assert.Null(reader.Read());
            }
            finally
            {
                reader.Close();
            }
        }
    }
}


text:
use serde_derive::{Deserialize, Serialize};

use config::Config;

#[derive(Debug, Serialize, Deserialize)]
struct Settings {
    #[serde(skip)]
    foo: isize,
    #[serde(skip)]
    bar: u8,
}

#[test]
fn empty_deserializes() {
    let s: Settings = Config::default()
        .try_deserialize()
        .expect("Deserialization failed");
    assert_eq!(s.foo, 0);
    assert_eq!(s.bar, 0);
}


text:
var JXON = new (function () {
  var
    sValueProp = "keyValue", sAttributesProp = "keyAttributes", sAttrPref = "@", /* you can customize these values */
    aCache = [], rIsNull = /^\s*$/, rIsBool = /^(?:true|false)$/i;

  function parseText (sValue) {
    if (rIsNull.test(sValue)) { return null; }
    if (rIsBool.test(sValue)) { return sValue.toLowerCase() === "true"; }
    if (isFinite(sValue)) { return parseFloat(sValue); }
    if (isFinite(Date.parse(sValue))) { return new Date(sValue); }
    return sValue;
  }

  function EmptyTree () { }
  EmptyTree.prototype.toString = function () { return "null"; };
  EmptyTree.prototype.valueOf = function () { return null; };

  function objectify (vValue) {
    return vValue === null ? new EmptyTree() : vValue instanceof Object ? vValue : new vValue.constructor(vValue);
  }

  function createObjTree (oParentNode, nVerb, bFreeze, bNesteAttr) {
    var
      nLevelStart = aCache.length, bChildren = oParentNode.hasChildNodes(),
      bAttributes = oParentNode.hasAttributes(), bHighVerb = Boolean(nVerb & 2);

    var
      sProp, vContent, nLength = 0, sCollectedTxt = "",
      vResult = bHighVerb ? {} : /* put here the default value for empty nodes: */ true;

    if (bChildren) {
      for (var oNode, nItem = 0; nItem < oParentNode.childNodes.length; nItem++) {
        oNode = oParentNode.childNodes.item(nItem);
        if (oNode.nodeType === 4) { sCollectedTxt += oNode.nodeValue; } /* nodeType is "CDATASection" (4) */
        else if (oNode.nodeType === 3) { sCollectedTxt += oNode.nodeValue.trim(); } /* nodeType is "Text" (3) */
        else if (oNode.nodeType === 1 && !oNode.prefix) { aCache.push(oNode); } /* nodeType is "Element" (1) */
      }
    }

    var nLevelEnd = aCache.length, vBuiltVal = parseText(sCollectedTxt);

    if (!bHighVerb && (bChildren || bAttributes)) { vResult = nVerb === 0 ? objectify(vBuiltVal) : {}; }

    for (var nElId = nLevelStart; nElId < nLevelEnd; nElId++) {
      sProp = aCache[nElId].nodeName.toLowerCase();
      vContent = createObjTree(aCache[nElId], nVerb, bFreeze, bNesteAttr);
      if (vResult.hasOwnProperty(sProp)) {
        if (vResult[sProp].constructor !== Array) { vResult[sProp] = [vResult[sProp]]; }
        vResult[sProp].push(vContent);
      } else {
        vResult[sProp] = vContent;
        nLength++;
      }
    }

    if (bAttributes) {
      var
        nAttrLen = oParentNode.attributes.length,
        sAPrefix = bNesteAttr ? "" : sAttrPref, oAttrParent = bNesteAttr ? {} : vResult;

      for (var oAttrib, nAttrib = 0; nAttrib < nAttrLen; nLength++, nAttrib++) {
        oAttrib = oParentNode.attributes.item(nAttrib);
        oAttrParent[sAPrefix + oAttrib.name.toLowerCase()] = parseText(oAttrib.value.trim());
      }

      if (bNesteAttr) {
        if (bFreeze) { Object.freeze(oAttrParent); }
        vResult[sAttributesProp] = oAttrParent;
        nLength -= nAttrLen - 1;
      }
    }

    if (nVerb === 3 || (nVerb === 2 || nVerb === 1 && nLength > 0) && sCollectedTxt) {
      vResult[sValueProp] = vBuiltVal;
    } else if (!bHighVerb && nLength === 0 && sCollectedTxt) {
      vResult = vBuiltVal;
    }

    if (bFreeze && (bHighVerb || nLength > 0)) { Object.freeze(vResult); }

    aCache.length = nLevelStart;

    return vResult;
  }

  function loadObjTree (oXMLDoc, oParentEl, oParentObj) {
    var vValue, oChild;

    if (oParentObj instanceof String || oParentObj instanceof Number || oParentObj instanceof Boolean) {
      oParentEl.appendChild(oXMLDoc.createTextNode(oParentObj.toString())); /* verbosity level is 0 */
    } else if (oParentObj.constructor === Date) {
      oParentEl.appendChild(oXMLDoc.createTextNode(oParentObj.toGMTString()));
    }

    for (var sName in oParentObj) {
      vValue = oParentObj[sName];
      if (isFinite(sName) || vValue instanceof Function) { continue; } /* verbosity level is 0 */
      if (sName === sValueProp) {
        if (vValue !== null && vValue !== true) { oParentEl.appendChild(oXMLDoc.createTextNode(vValue.constructor === Date ? vValue.toGMTString() : String(vValue))); }
      } else if (sName === sAttributesProp) { /* verbosity level is 3 */
        for (var sAttrib in vValue) { oParentEl.setAttribute(sAttrib, vValue[sAttrib]); }
      } else if (sName.charAt(0) === sAttrPref) {
        oParentEl.setAttribute(sName.slice(1), vValue);
      } else if (vValue.constructor === Array) {
        for (var nItem = 0; nItem < vValue.length; nItem++) {
          oChild = oXMLDoc.createElement(sName);
          loadObjTree(oXMLDoc, oChild, vValue[nItem]);
          oParentEl.appendChild(oChild);
        }
      } else {
        oChild = oXMLDoc.createElement(sName);
        if (vValue instanceof Object) {
          loadObjTree(oXMLDoc, oChild, vValue);
        } else if (vValue !== null && vValue !== true) {
          oChild.appendChild(oXMLDoc.createTextNode(vValue.toString()));
        }
        oParentEl.appendChild(oChild);
     }
   }
  }

  this.build = function (oXMLParent, nVerbosity /* optional */, bFreeze /* optional */, bNesteAttributes /* optional */) {
    var _nVerb = arguments.length > 1 && typeof nVerbosity === "number" ? nVerbosity & 3 : /* put here the default verbosity level: */ 1;
    return createObjTree(oXMLParent, _nVerb, bFreeze || false, arguments.length > 3 ? bNesteAttributes : _nVerb === 3);
  };

  this.unbuild = function (oObjTree) {
    var oNewDoc = document.implementation.createDocument("", "", null);
    loadObjTree(oNewDoc, oNewDoc, oObjTree);
    return oNewDoc;
  };

  this.stringify = function (oObjTree) {
    return (new XMLSerializer()).serializeToString(JXON.unbuild(oObjTree));
  };
})();
// var myObject = JXON.build(doc);
// we got our javascript object! try: alert(JSON.stringify(myObject));

// var newDoc = JXON.unbuild(myObject);
// we got our Document instance! try: alert((new XMLSerializer()).serializeToString(newDoc));


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/layout_fragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.lanian.nfctest.MainActivity$PlaceholderFragment" >

    <TextView
        android:id="@+id/textView_action"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/blank"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <LinearLayout
        android:id="@+id/layout_change_tag_buttons"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:orientation="horizontal" >

        <ImageButton
            android:id="@+id/button_write_tag_home"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight=".5"
            android:contentDescription="@string/button_home"
            android:src="@drawable/ic_home" />

        <ImageButton
            android:id="@+id/button_write_tag_work"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight=".5"
            android:contentDescription="@string/button_work"
            android:src="@drawable/ic_work" />

    </LinearLayout>

    <TextView
        android:id="@+id/textView_tag"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/textView_action"
        android:text="@string/no_tag"
        android:textAppearance="?android:attr/textAppearanceLarge" />

</RelativeLayout>


text:
namespace autofill {

// static
GaiaIdHash GaiaIdHash::FromGaiaId(const std::string& gaia_id) {
  return FromBinary(crypto::SHA256HashString(gaia_id));
}

// static
GaiaIdHash GaiaIdHash::FromBinary(const std::string& gaia_id_hash) {
  return GaiaIdHash(gaia_id_hash);
}

// static
GaiaIdHash GaiaIdHash::FromBase64(const std::string& gaia_id_base64_hash) {
  std::string gaia_id_hash;
  base::Base64Decode(gaia_id_base64_hash, &gaia_id_hash);
  return FromBinary(gaia_id_hash);
}

GaiaIdHash::GaiaIdHash() = default;

GaiaIdHash::GaiaIdHash(const GaiaIdHash& other) = default;

GaiaIdHash::GaiaIdHash(GaiaIdHash&& other) = default;

GaiaIdHash::~GaiaIdHash() = default;

GaiaIdHash::GaiaIdHash(const std::string& gaia_id_hash)
    : gaia_id_hash_(gaia_id_hash) {}

std::string GaiaIdHash::ToBinary() const {
  return gaia_id_hash_;
}

std::string GaiaIdHash::ToBase64() const {
  std::string gaia_id_base64_hash;
  base::Base64Encode(gaia_id_hash_, &gaia_id_base64_hash);
  return gaia_id_base64_hash;
}

bool GaiaIdHash::IsValid() const {
  return gaia_id_hash_.size() == crypto::kSHA256Length;
}

bool operator<(const GaiaIdHash& lhs, const GaiaIdHash& rhs) {
  return lhs.gaia_id_hash_ < rhs.gaia_id_hash_;
}

bool operator==(const GaiaIdHash& lhs, const GaiaIdHash& rhs) {
  return lhs.gaia_id_hash_ == rhs.gaia_id_hash_;
}

bool operator!=(const GaiaIdHash& lhs, const GaiaIdHash& rhs) {
  return !(lhs == rhs);
}

GaiaIdHash& GaiaIdHash::operator=(const GaiaIdHash& form) = default;

GaiaIdHash& GaiaIdHash::operator=(GaiaIdHash&& form) = default;

}  // namespace autofill


text:
<?xml version="1.0" encoding="utf-8"?>
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/splash_image"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/black"
    tools:context=".activities.SplashScreen"
    tools:src="@drawable/susi_image" />


text:
package cmd

import (
	"flag"
	"fmt"

	"github.com/driusan/dgit/git"
)

// Parses the arguments from git-ls-files as if they were passed on the commandline
// and calls git.LsFiles
func LsFiles(c *git.Client, args []string) error {
	flags := flag.NewFlagSet("ls-files", flag.ExitOnError)
	flags.SetOutput(flag.CommandLine.Output())
	flags.Usage = func() {
		flag.Usage()
		fmt.Fprintf(flag.CommandLine.Output(), "\n\nOptions:\n")
		flags.PrintDefaults()
	}
	options := git.LsFilesOptions{}

	cached := flags.Bool("cached", true, "Show cached files in output (default)")
	ca := flags.Bool("c", true, "Alias for --cached")

	deleted := flags.Bool("deleted", false, "Show deleted files in output")
	d := flags.Bool("d", false, "Alias for --deleted")

	modified := flags.Bool("modified", false, "Show modified files in output")
	m := flags.Bool("m", false, "Alias of --modified")

	others := flags.Bool("others", false, "Show other (ie. untracked) files in output")
	o := flags.Bool("o", false, "Alias of --others")

	ignored := flags.Bool("ignored", false, "Show only ignored files in output")
	i := flags.Bool("i", false, "Alias of --ignored")

	stage := flags.Bool("stage", false, "Show staged content")
	s := flags.Bool("s", false, "Alias of --stage")

	unmerged := flags.Bool("unmerged", false, "Show unmerged files. Implies --stage")
	u := flags.Bool("u", false, "Alias of --unmerged")

	flags.BoolVar(&options.Killed, "killed", false, "Show files that need to be removed for checkout-index to succeed")
	flags.BoolVar(&options.Killed, "k", false, "Alias of --killed")

	flags.BoolVar(&options.Status, "t", false, "Show status of files")

	flags.BoolVar(&options.ExcludeStandard, "exclude-standard", false, "Add the standard Git exclusions.")

	flags.BoolVar(&options.Directory, "directory", false, "Show only directory, not its contents if a directory is untracked")
	flags.BoolVar(&options.NoEmptyDirectory, "no-empty-directory", false, "Do not show empty untracked directories in output")

	var excludefiles, excludeperdirectory []string
	flags.Var(NewMultiStringValue(&options.ExcludePatterns), "exclude", "Skip untracked files matching pattern.")
	flags.Var(NewMultiStringValue(&options.ExcludePatterns), "x", "Alias for --exclude")

	flags.Var(NewMultiStringValue(&excludefiles), "exclude-from", "Read exclude patterns from a file.")
	flags.Var(NewMultiStringValue(&excludefiles), "X", "Alias for --exclude-from")

	flags.Var(NewMultiStringValue(&excludeperdirectory), "exclude-per-directory", "Read additional exclude patterns for each directory.")

	flags.BoolVar(&options.ErrorUnmatch, "error-unmatch", false, "Exit with an error if any unmatched paths are specified on the command line")

	flags.Parse(args)
	oargs := flags.Args()

	for _, f := range excludefiles {
		options.ExcludeFiles = append(options.ExcludeFiles, git.File(f))
	}
	for _, f := range excludeperdirectory {
		options.ExcludePerDirectory = append(options.ExcludePerDirectory, git.File(f))
	}
	options.Cached = *cached || *ca

	rdeleted := *deleted || *d
	rmodified := *modified || *m
	rothers := *others || *o
	runmerged := *unmerged || *u

	options.Deleted = rdeleted
	options.Modified = rmodified
	options.Others = rothers
	options.Ignored = *ignored || *i
	options.Stage = *stage || *s
	if runmerged {
		options.Unmerged = true
		options.Stage = true
	}

	// If -u, -m or -o are given, cached is turned off.
	if rdeleted || rmodified || rothers || runmerged {
		options.Cached = false
		// Check if --cache was explicitly given, in which case it shouldn't
		// have been turned off. (flag doesn't provide any way to differentiate
		// between "explicitly passed" and "default value")
		for _, arg := range args {
			if arg == "--cached" || arg == "-c" {
				options.Cached = true
				break
			}
		}
	}

	rargs := make([]git.File, len(oargs), len(oargs))
	for i := range oargs {
		rargs[i] = git.File(oargs[i])
	}

	files, err := git.LsFiles(c, options, rargs)
	if err != nil {
		return err
	}

	// LsFiles converted them to IndexEntries so that it could return the
	// stage, sha1, and mode if --stage was passed. We need to convert them
	// back to relative paths.
	for _, file := range files {
		path, err := file.PathName.FilePath(c)
		if err != nil {
			return err
		}
		if options.Status {
			fmt.Printf("%c ", file.StatusCode)
		}
		if options.Stage {
			fmt.Printf("%o %v %v\t%v\n", file.Mode, file.Sha1, file.Stage(), path)
		} else {
			if options.Directory && path.IsDir() {
				fmt.Println(path + "/")
			} else {
				fmt.Println(path)
			}
		}
	}
	return err
}


text:
<?php the_title(); ?>

    <?php get_template_part( 'templates/entry-block', 'meta' ); ?>

    <?php the_content(); ?>
    <?php wp_link_pages(); ?>


text:
require 'open-uri'

class WordPressRecord

  include ActiveModel::Validations
  include ActiveModel::Conversion
  extend ActiveModel::Naming

  class_attribute :_wp_fields, :_wp_url, :_wp_headers, :_wp_custom_fields, :_wp_after_load, :_wp_post_type, :_wp_queries

  self._wp_fields = [
    [:id, :integer],
    [:slug, :string],
    [:attachments, :array],
    [:images, :array],
    [:categories, :array],
    [:tags, :array]
  ]

  self._wp_fields.each { |f| attr_accessor f[0] }

  def self.wp_field(*args)
    attr_accessor args[0]
    self._wp_fields = self._wp_fields.clone
    self._wp_fields.push args
  end

  self._wp_url = nil
  def self.wp_url(url)
    self._wp_url = url
  end

  self._wp_headers = {}
  def self.wp_headers(headers)
    self._wp_headers = headers
  end

  self._wp_custom_fields = []
  def self.wp_custom_field(*args)
    attr_accessor args[0]
    self._wp_custom_fields = self._wp_custom_fields.clone
    self._wp_custom_fields.push args
  end

  self._wp_after_load = nil
  def self.wp_after_load(symbol)
    self._wp_after_load = symbol
  end

  self._wp_post_type = :post
  def self.wp_post_type(post_type)
    self._wp_post_type = post_type
  end

  self._wp_queries = {}
  def self.wp_add_query(key, value)
    self._wp_queries = self._wp_queries.clone
    self._wp_queries[key] = value
  end

  def persisted?
    false
  end

  def initialize(attributes = {})
    wp_post = attributes[:wp_post]
    attributes.delete :wp_post

    attributes.each do |name, value|
      send("#{name}=", value)
    end

    load(wp_post) if self.slug or self.id or wp_post
  end

  def self.find(*args)

    # Find by id
    if args[0].is_a? Fixnum
      obj = new(:id => args[0])
      return obj.id ? obj : nil
    end

    # Find by slug
    if args[0].is_a? String
      obj = new(:slug => args[0])
      return obj.id ? obj : nil
    end

    # Find all
    if args[0] == :all
      return all(args[1])
    end

    nil
  end

  def self.all(params = nil)
    params ||= {}
    params[:results_metadata] ||= {}

    count = params[:count] || params[:limit] || 10
    page = (params[:page] || 0) + 1

    category = nil
    search = nil
    tags = nil

    method = 'queries.general'

    if params[:category]
      category = CGI.escape(params[:category])
    end

    if params[:search]
      search = CGI.escape(params[:search].strip)
    end

    if params[:tagged]
      tags = CGI.escape(params[:tagged].to_s.gsub(/\s*,\s*/, ',').gsub(/\s+/, ' '))
    end

    url = "#{self._wp_url}/?json=#{method}&post_type=#{self._wp_post_type}&count=#{count}&page=#{page}#{wp_query_string}"
    url += "&search=#{search}" if search
    url += "&category=#{category}" if category
    url += "&tags=#{tags}" if tags

    content = open(url, self._wp_headers).read
    json = JSON.parse(content)

    params[:results_metadata][:url] = url
    params[:results_metadata][:count] = json['count']
    params[:results_metadata][:count_total] = json['count_total']
    params[:results_metadata][:pages] = json['pages']

    return if json["status"] == 'error'
    return json["posts"].map{|post| new(:wp_post => post)}
  end

  private

  # Load an object from WordPress
  def load(post = nil)

    # Query WordPress, if necessary
    if post.nil?
      num_related = 3
      max_description_size = 160

      # Fetch the post
      url = "#{self._wp_url}/?json=get_post&post_type=#{self._wp_post_type}#{self.class.wp_query_string}"

      if self.id
        url += "&id=#{self.id}"
      elsif self.slug
        url += "&slug=#{self.slug}"
      else
        self.id = nil
        return
      end

      content = open(url, self._wp_headers).read
      json = JSON.parse(content)

      if json['status'] == 'error'
        self.id = nil
      else
        post = json['post']
      end
    end

    return if post.nil?

    # Populate the model's fields
    self._wp_fields.each do |field|
      name = field[0]
      if post["#{name}"]
        process_and_set_field(field, post["#{name}"])
      end
    end

    if post['custom_fields']
      self._wp_custom_fields.each do |field|
        name = field[0]
        if post['custom_fields']["#{name}"]
          process_and_set_field(field, post['custom_fields']["#{name}"][0])
        end
      end
    end

    # Special case for attachments / images
    self.images = self.attachments.map do |attachment|
      return nil unless attachment['images']
      {
        "files" => attachment['images'],
        "caption" => attachment['caption'],
        "title" => attachment['title']
      }
    end.compact

    # Custom post processing
    self.send(self._wp_after_load, post) if self._wp_after_load

    self
  end

  def self.wp_query_string
    wp_query = ''

    self._wp_queries.each do |key, value|
      wp_query += "&#{CGI.escape(key.to_s)}=#{CGI.escape(value)}"
    end

    unless self._wp_custom_fields.empty?
      wp_query += "&custom_fields=#{self._wp_custom_fields.map{|f| f[0]}.join(',')}"
    end

    wp_query
  end

  def process_and_set_field(field, value)
    name = field[0]
    type = field[1]
    proc = field[2]

    if proc and proc.is_a? Proc
      value = proc.call(value)
    end

    if type == :string
      value = value.to_s
    elsif type == :text
      value = value.to_s
    elsif type == :integer
      value = value.to_i
    elsif type == :float
      value = value.to_f
    elsif type == :datetime
      value = Time.parse(value) rescue Time.at(value) rescue nil
    elsif type == :array
      value = value.to_a
    elsif type == :hash
      value ||= {}
    end

    send("#{name}=", value)
  end

end


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

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Uses of Package org.apache.lucene.search.suggest.document (Lucene 6.0.1 API)</title>
<meta name="date" content="2016-05-23">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Package
org.apache.lucene.search.suggest.document

Packages that use org.apache.lucene.search.suggest.document

Package
Description

org.apache.lucene.search.suggest.document

Support for document suggestion

Classes in org.apache.lucene.search.suggest.document used by org.apache.lucene.search.suggest.document

Class and Description

CompletionAnalyzer

Wraps an Analyzer
 to provide additional completion-only tuning
 (e.g.

CompletionPostingsFormat

 A PostingsFormat which supports document suggestion based on
 indexed SuggestFields.

CompletionQuery

Abstract Query that match documents containing terms with a specified prefix
 filtered by BitsProducer.

CompletionScorer

Expert: Responsible for executing the query against an
 appropriate suggester and collecting the results
 via a collector.

CompletionTokenStream

Token stream which converts a provided token stream to an automaton.

CompletionTokenStream.BytesRefBuilderTermAttribute

Attribute providing access to the term builder and UTF-16 conversion

CompletionWeight

Expert: the Weight for CompletionQuery, used to
 score and explain these queries.

NRTSuggester

 NRTSuggester executes Top N search on a weighted FST specified by a CompletionScorer

PrefixCompletionQuery

A CompletionQuery which takes an Analyzer
 to analyze the prefix of the query term.

SuggestField

 Field that indexes a string value and a weight as a weighted completion
 against a named suggester.

TopSuggestDocs

TopDocs wrapper with
 an additional CharSequence key per ScoreDoc

TopSuggestDocs.SuggestScoreDoc

ScoreDoc with an
 additional CharSequence key

TopSuggestDocsCollector

Collector that collects completion and
 score, along with document id

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Help

Prev

Next

Frames

No Frames

All Classes

          Copyright © 2000-2016 Apache Software Foundation.  All Rights Reserved.


text:
<!DOCTYPE html>

        <meta charset="UTF-8">
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/caiuss/1.0.2/caiuss.min.css" type="text/css" media="screen" charset="utf-8">
        <link rel="stylesheet" href="style.css" type="text/css" media="screen" charset="utf-8">

        <title>donate.js</title>

donate.js

            <form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_top">
                <input type="hidden" name="cmd" value="_donations">
                <input type="hidden" name="business" value="bizauionica@gmail.com">
                <input type="hidden" name="lc" value="US">
                <input type="hidden" name="amount">
                <input type="hidden" name="no_note" value="0">
                <input type="hidden" name="cn" value="Add special instructions to the seller:">
                <input type="hidden" name="no_shipping" value="2">
                <input type="hidden" name="currency_code" value="USD">
                <input type="hidden" name="bn" value="PP-DonationsBF:btn_donateCC_LG.gif:NonHosted">

                    <button class="btn bg-orange">Donate</button>

            </form>

             with  by @IonicaBizau | Contribute on  GitHub.


text:
using System;
using System.Collections.Generic;

namespace angeldnd.dap {
    public interface IHandler {
        int RequestCheckerCount { get; }
        bool AddRequestChecker(IRequestChecker checker);
        bool RemoveRequestChecker(IRequestChecker checker);
        BlockRequestChecker AddRequestChecker(IBlockOwner owner, Func<Handler, Data, bool> block);

        int RequestWatcherCount { get; }
        bool AddRequestWatcher(IRequestWatcher watcher);
        bool RemoveRequestWatcher(IRequestWatcher watcher);
        BlockRequestWatcher AddRequestWatcher(IBlockOwner owner, Action<Handler, Data> block);

        int ResponseWatcherCount { get; }
        bool AddResponseWatcher(IResponseWatcher watcher);
        bool RemoveResponseWatcher(IResponseWatcher watcher);
        BlockResponseWatcher AddResponseWatcher(IBlockOwner owner, Action<Handler, Data, Data> block);

        int AsyncResponseWatcherCount { get; }
        bool AddAsyncResponseWatcher(IAsyncResponseWatcher watcher);
        bool RemoveAsyncResponseWatcher(IAsyncResponseWatcher watcher);
        BlockAsyncResponseWatcher AddAsyncResponseWatcher(IBlockOwner owner, Action<Handler, Data> block);

        bool IsValid { get; }
        bool Setup(IRequestHandler handler);
        Data HandleRequest(Data req);
    }

    public interface IRequestChecker : IBlock {
        bool IsValidRequest(Handler handler, Data req);
    }

    public interface IRequestWatcher : IBlock {
        void OnRequest(Handler handler, Data req);
    }

    public interface IResponseWatcher : IBlock {
        void OnResponse(Handler handler, Data req, Data res);
    }

    public interface IAsyncResponseWatcher : IBlock {
        void OnAsyncResponse(Handler handler, Data res);
    }

    public interface IRequestHandler {
        Data DoHandle(Handler handler, Data req);
    }

    public sealed class BlockRequestChecker : WeakBlock, IRequestChecker {
        private readonly Func<Handler, Data, bool> _Block;

        public BlockRequestChecker(IBlockOwner owner, Func<Handler, Data, bool> block) : base(owner) {
            _Block = block;
        }

        public bool IsValidRequest(Handler handler, Data req) {
            return _Block(handler, req);
        }
    }

    public sealed class BlockRequestWatcher : WeakBlock, IRequestWatcher {
        private readonly Action<Handler, Data> _Block;

        public BlockRequestWatcher(IBlockOwner owner, Action<Handler, Data> block) : base(owner) {
            _Block = block;
        }

        public void OnRequest(Handler handler, Data req) {
            _Block(handler, req);
        }
    }

    public sealed class BlockResponseWatcher : WeakBlock, IResponseWatcher {
        private readonly Action<Handler, Data, Data> _Block;

        public BlockResponseWatcher(IBlockOwner owner, Action<Handler, Data, Data> block) : base(owner) {
            _Block = block;
        }

        public void OnResponse(Handler handler, Data req, Data res) {
            _Block(handler, req, res);
        }
    }

    public sealed class BlockAsyncResponseWatcher : WeakBlock, IAsyncResponseWatcher {
        private readonly Action<Handler, Data> _Block;

        public BlockAsyncResponseWatcher(IBlockOwner owner, Action<Handler, Data> block) : base(owner) {
            _Block = block;
        }

        public void OnAsyncResponse(Handler handler, Data res) {
            _Block(handler, res);
        }
    }

    /* The BlockRequestHandler should NOT be weak */
    public sealed class BlockRequestHandler : IRequestHandler {
        private readonly Func<Handler, Data, Data> _Block;

        public BlockRequestHandler(Func<Handler, Data, Data> block) {
            _Block = block;
        }

        public Data DoHandle(Handler handler, Data req) {
            try {
                return _Block(handler, req);
            } catch (HandlerException e) {
                return e.Response;
            }
        }
    }
}


text:
export { default as Basic } from './Basic'
export { default as External } from './External'
export { default as KeyColor } from './KeyColor'
export { default as Underline } from './Underline'

export default {
  storyshots: { disable: true },
  title: 'Stories/Link',
}


text:
using System.IO;
using System.Text;
using static System.Console;

namespace ReaderWriterSamples
{
    public class Program
    {
        public static void Main()
        {
            ReadFileUsingReader("./Program.cs");
            WriteLine();
            string textFile = Path.ChangeExtension(Path.GetTempFileName(), "txt");
            WriteFileUsingWriter(textFile, new string[] { "one", "two" });
            WriteLine($"Written temp file {textFile}");

            string binFile = Path.ChangeExtension(Path.GetTempFileName(), "bin");
            WriteLine($"writing to {binFile}");
            WriteFileUsingBinaryWriter(binFile);
            WriteLine($"written to {binFile}");
            ReadFileUsingBinaryReader(binFile);
        }

        public static void WriteFileUsingWriter(string fileName, string[] lines)
        {
            var outputStream = File.OpenWrite(fileName);
            using (var writer = new StreamWriter(outputStream))
            {
                byte[] preamble = Encoding.UTF8.GetPreamble();
                outputStream.Write(preamble, 0, preamble.Length);
                writer.Write(lines);
            }
        }

        public static void WriteFileUsingBinaryWriter(string binFile)
        {
            var outputStream = File.Create(binFile);
            using (var writer = new BinaryWriter(outputStream))
            {
                double d = 47.47;
                int i = 42;
                long l = 987654321;
                string s = "sample";

                writer.Write(d);
                writer.Write(i);
                writer.Write(l);
                writer.Write(s);
            }
        }

        public static void ReadFileUsingBinaryReader(string binFile)
        {
            var inputStream = File.Open(binFile, FileMode.Open);
            using (var reader = new BinaryReader(inputStream))
            {
                double d = reader.ReadDouble();

                int i = reader.ReadInt32();
                long l = reader.ReadInt64();
                string s = reader.ReadString();
                WriteLine($"d: {d}, i: {i}, l: {l}, s: {s}");
            }
        }

        public static void ReadFileUsingReader(string fileName)
        {
            var stream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
            using (var reader = new StreamReader(stream))
            {
                while (!reader.EndOfStream)
                {
                    string line = reader.ReadLine();
                    WriteLine(line);
                }
            }
        }
    }
}


text:
[![Build status](https://ci.appveyor.com/api/projects/status/tw2d8ufd3tpwkf5b?svg=true)](https://ci.appveyor.com/project/aoberoi/opentok-net-sdk)  [![Build Status](https://travis-ci.org/opentok/Opentok-.NET-SDK.svg)](https://travis-ci.org/opentok/Opentok-.NET-SDK)

The OpenTok .NET SDK lets you generate
[sessions](https://www.tokbox.com/opentok/tutorials/create-session/) and
[tokens](https://www.tokbox.com/opentok/tutorials/create-token/) for
[OpenTok](https://www.tokbox.com/) applications that run on the .NET platform. The SDK also includes
support for working with [OpenTok archives](https://tokbox.com/opentok/tutorials/archiving).

# Installation

## NuGet (recommended):

Using the [Package Manager Console](http://docs.nuget.org/consume/package-manager-console):

```
PM> Install-Package OpenTok
```

## Manually:

Download the latest release from the [Releases Page](https://github.com/opentok/Opentok-.NET-SDK/releases).
Unzip the file and place the place the `OpenTok.dll`, dependent assemblies, and supporting files into your
own project.

# Usage

## Initializing

Import the `OpenTokSDK` namespace into any files that will be using OpenTok objects. Then initialize an
`OpenTokSDK.OpenTok` object using your own API Key and API Secret.

```csharp
using OpenTokSDK;

// ...

int ApiKey = 000000; // YOUR API KEY
string ApiSecret = "YOUR API SECRET";
var OpenTok = new OpenTok(ApiKey, ApiSecret);
```

## Creating Sessions

To create an OpenTok Session, call the `OpenTok` instance's
`CreateSession(string location, MediaMode mediaMode, ArchiveMode archiveMode)`
method. Each of the parameters are optional and can be omitted if not needed. They are:

* `string location` : An IPv4 address used as a location hint. (default: "")

* `MediaMode mediaMode` : Specifies whether the session will use the OpenTok Media Router
   (MediaMode.ROUTED) or attempt to transmit streams directly between clients
   (MediaMode.RELAYED, the default)

* `ArchiveMode archiveMode` : Specifies whether the session will be automatically archived
  (ArchiveMode.ALWAYS) or not (ArchiveMode.MANUAL, the default)

The return value is a `OpenTokSDK.Session` object. Its `Id` property is useful to get an identifier that can be saved to a
persistent store (such as a database).

```csharp
// Create a session that will attempt to transmit streams directly between clients
var session = OpenTok.CreateSession();
// Store this sessionId in the database for later use:
string sessionId = session.Id;

// Create a session that uses the OpenTok Media Router (which is required for archiving)
var session = OpenTok.CreateSession(mediaMode: MediaMode.ROUTED);
// Store this sessionId in the database for later use:
string sessionId = session.Id;

// Create an automatically archived session:
var session = OpenTok.CreateSession(mediaMode: MediaMode.ROUTED, ArchiveMode.ALWAYS);
// Store this sessionId in the database for later use:
string sessionId = session.Id;
```

## Generating Tokens

Once a Session is created, you can start generating Tokens for clients to use when connecting to it.
You can generate a token either by calling an `OpenTokSDK.OpenTok` instance's
`GenerateToken(string sessionId, Role role, double expireTime, string data)` method, or by calling a `OpenTokSDK.Session`
instance's `GenerateToken(Role role, double expireTime, string data)` method after creating it. In the first method, the
`sessionId` is required and the rest of the parameters are optional. In the second method, all the parameters are optional.

```csharp

// Generate a token from a sessionId (fetched from database)
string token = OpenTok.GenerateToken(sessionId);

// Generate a token by calling the method on the Session (returned from CreateSession)
string token = session.GenerateToken();

// Set some options in a token
double inOneWeek = (DateTime.UtcNow.Add(TimeSpan.FromDays(7)).Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
string token = session.GenerateToken(role: Role.MODERATOR, expireTime: inOneWeek, data: "name=Johnny");

```

## Working with Archives

You can start the recording of an OpenTok Session using a `OpenTokSDK.OpenTok` instance's
`StartArchive(sessionId, name, hasVideo, hasAudio, outputMode)` method. This will return an
`OpenTokSDK.Archive` instance. The parameter `name` is optional and used to assign a name for the
Archive. Note that you can only start an Archive on a Session that has clients connected.

```csharp
// A simple Archive (without a name)
var archive = OpenTok.StartArchive(sessionId);

// Store this archive ID in the database for later use
Guid archiveId = archive.Id;
```
You can add a name for the archive (to use for identification) by setting the `name` parameter of
the `OpenTok.StartArchive()` method.

You can also disable audio or video recording by setting the `hasAudio` or `hasVideo` parameter of
the `OpenTok.StartArchive()` method `false`.

By default, all streams are recorded to a single (composed) file. You can record the different
streams in the session to individual files (instead of a single composed file) by setting the
`outputMode` parameter of the `OpenTok.StartArchive()` method `OutputMode.INDIVIDUAL`.

You can stop the recording of a started Archive using a `OpenTokSDK.OpenTok` instance's
`StopArchive(String archiveId)` method or using the `OpenTokSDK.Archive` instance's `Stop()` method.

```csharp
// Stop an Archive from an archive ID (fetched from database)
var archive = OpenTok.StopArchive(archiveId);
```

To get an `OpenTokSDK.Archive` instance (and all the information about it) from an archive ID, use the
`OpenTokSDK.OpenTok` instance's `GetArchive(archiveId)` method.

```csharp
var archive = OpenTok.GetArchive(archiveId);
```

To delete an archive, you can call a `OpenTokSDK.OpenTok` instance's `DeleteArchive(archiveId)` method or
call the `OpenTokSDK.Archive` instance's `Delete()` method.

```csharp
// Delete an archive from an archive ID (fetched from database)
OpenTok.DeleteArchive(archiveId);

// Delete an archive from an Archive instance (returned from GetArchive)
Archive.Delete();
```

You can also get a list of all the Archives you've created (up to 1000) with your API Key. This is
done using an `OpenTokSDK.OpenTok` instance's `ListArchives(int offset, int count)` method. You may optionally
paginate the Archives you receive using the offset and count parameters. This will return an
`OpenTokSDK.ArchiveList` object.

```csharp
// Get a list with the first 1000 archives created by the API Key
var archives = OpenTok.ListArchives();

// Get a list of the first 50 archives created by the API Key
var archives = OpenTok.ListArchives(0, 50);

// Get a list of the next 50 archives
var archives = OpenTok.ListArchives(50, 50);
```

Note that you can also create an automatically archived session, by passing in `ArchiveMode.ALWAYS`
as the `archiveMode` parameter when you call the `OpenTok.CreateSession()` method (see "Creating
Sessions," above).

# Samples

There are two sample applications included with the SDK. To get going as fast as possible, clone the whole
repository and follow the Walkthroughs:

*  [HelloWorld](Samples/HelloWorld/README.md)
*  [Archiving](Samples/Archiving/README.md)

# Documentation

Reference documentation is available at <https://tokbox.com/developer/sdks/dot-net/reference/>.

# Requirements

You need an OpenTok API key and API secret, which you can obtain at <https://dashboard.tokbox.com>.

The OpenTok .NET SDK requires .NET Framework 3.5 or greater.

# Release Notes

See the [Releases](https://github.com/opentok/opentok-.net-sdk/releases) page for details
about each release.

## Important changes since v2.2.0

**Changes in v2.2.1:**

The default setting for the `CreateSession()` method is to create a session with the media mode set
to relayed. In previous versions of the SDK, the default setting was to use the OpenTok Media Router
(media mode set to routed). In a relayed session, clients will attempt to send streams directly
between each other (peer-to-peer); if clients cannot connect due to firewall restrictions, the
session uses the OpenTok TURN server to relay audio-video streams.

**Changes in v2.2.0:**

This version of the SDK includes support for working with OpenTok archives.

This version of the SDK includes a number of improvements in the API design. These include a number
of API changes:

* New OpenTok class --  The name of the main class has changed from OpenTokSDK to OpenTok.
  In the previous version, the constructor was `OpenTokSDK()`.
  In v2.2, it is `OpenTok(int apiKey, int apiSecret)`.

* CreateSession -- In the previous version, there were two methods to create a session:
  `OpenTokSDK.CreateSession(String location)` and
  `OpenTokSDK.CreateSession(String location, Dictionary<string, object> options)`.
  These methods returned a string (the session ID).

  In v2.2, the OpenTok class includes one method, which takes two parameters (both optional):
  `CreateSession(string location = "", MediaMode mediaMode = MediaMode.ROUTED)`.
  The `mediaMode` parameter replaces the `p2p.preference` setting in the
  previous version. The method returns a Session Object.

* GenerateToken -- In the previous version, there were two methods:
  `OpenTokSDK.GenerateToken(string sessionId)` and
  `OpenTokSDK.GenerateToken(string sessionId, Dictionary<string, object> options)`
  In v2.2, this is replaced with the following method:
  `OpenTokSDK.OpenTok.GenerateToken(string sessionId, Role role = Role.PUBLISHER, double expireTime = 0, string data = null)`.
  All parameters, except the `sessionId` parameter, are optional.

  Also, the Session class includes a method for generating tokens:
  `OpenTokSDK.Session.GenerateToken(Role role = Role.PUBLISHER, double expireTime = 0, string data = null)`.

# Development and Contributing

Interested in contributing? We :heart: pull requests! See the [Development](DEVELOPING.md) and
[Contribution](CONTRIBUTING.md) guidelines.

# Support

See <https://support.tokbox.com/> for all our support options.

Find a bug? File it on the [Issues](https://github.com/opentok/opentok-.net-sdk/issues) page. Hint:
test cases are really helpful!


text:
namespace System.IdentityModel
{
    using System.Collections.Generic;
    using System.Xml;

    /// <summary>
    /// Simple Xml utility class.
    /// </summary>
    internal static class XmlUtil
    {
        /// <summary>
        /// List containing only those XmlNodes that were XmlElements.
        /// </summary>
        /// <param name="nodeList">nodes to parse</param>
        /// <returns>List containing only those XmlNodes that were XmlElements</returns>
        /// <remarks>A null list will return an empty List</remarks>
        public static List<XmlElement> GetXmlElements(XmlNodeList nodeList)
        {
            List<XmlElement> xmlElements = new List<XmlElement>();

            if (null != nodeList)
            {
                foreach (XmlNode node in nodeList)
                {
                    XmlElement tempElement = node as XmlElement;
                    if (tempElement != null)
                    {
                        xmlElements.Add(tempElement);
                    }
                }
            }

            return xmlElements;
        }
    }
}


text:
<?php

namespace QClientTest;

use GuzzleHttp\Psr7\Response;

class ResponseFixture
{
    public function getResponse($name, $status = 200)
    {
        if (!file_exists(__DIR__ . '/responses/' . $name)) {
            throw new \RuntimeException('can not find response: ' . $name);
        }

        $response = new Response($status);
        $response->getBody()->write(file_get_contents(__DIR__ . '/responses/' . $name));
        $response->getBody()->rewind();
        return $response;
    }

    public function getResponseJson($name)
    {
        if (!file_exists(__DIR__ . '/responses/' . $name)) {
            throw new \RuntimeException('can not find response: ' . $name);
        }

        return json_decode(file_get_contents(__DIR__ . '/responses/' . $name), true);
    }
}


text:
.class public interface abstract Lcom/android/server/wifi/hotspot2/AlarmHandler;
.super Ljava/lang/Object;
.source "AlarmHandler.java"

# virtual methods
.method public abstract wake(Ljava/lang/Object;)V
.end method


text:
namespace web_modal {
class SingleWebContentsDialogManagerDelegate;
}

namespace constrained_window {

// Class for parenting a Mac Cocoa sheet on a views tab modal dialog off of a
// views browser, e.g. for tab-modal Cocoa sheets. Since Cocoa sheets are modal
// to the parent window, the sheet is instead parented to an invisible views
// overlay window which is tab-modal.
class NativeWebContentsModalDialogManagerViewsMac
    : public NativeWebContentsModalDialogManagerViews {
 public:
  NativeWebContentsModalDialogManagerViewsMac(
      gfx::NativeWindow dialog,
      web_modal::SingleWebContentsDialogManagerDelegate* native_delegate,
      base::OnceCallback<void(views::Widget*)> show_sheet);
  ~NativeWebContentsModalDialogManagerViewsMac() override;

  // NativeWebContentsModalDialogManagerViews:
  void OnPositionRequiresUpdate() override;
  void ShowWidget(views::Widget* widget) override;
  void HideWidget(views::Widget* widget) override;

 private:
  base::OnceCallback<void(views::Widget*)> show_sheet_;
  DISALLOW_COPY_AND_ASSIGN(NativeWebContentsModalDialogManagerViewsMac);
};

}  // namespace constrained_window

#endif  // COMPONENTS_CONSTRAINED_WINDOW_NATIVE_WEB_CONTENTS_MODAL_DIALOG_MANAGER_VIEWS_MAC_H_


text:
package nl.vu_compmedchem.klifs.information;

import java.io.File;
import java.io.IOException;
import java.util.List;

import org.knime.core.data.DataCell;
import org.knime.core.data.DataColumnSpec;
import org.knime.core.data.DataColumnSpecCreator;
import org.knime.core.data.DataRow;
import org.knime.core.data.DataTableSpec;
import org.knime.core.data.RowKey;
import org.knime.core.data.def.DefaultRow;
import org.knime.core.data.def.IntCell;
import org.knime.core.data.def.StringCell;
import org.knime.core.node.BufferedDataContainer;
import org.knime.core.node.BufferedDataTable;
import org.knime.core.node.CanceledExecutionException;
import org.knime.core.node.defaultnodesettings.SettingsModelString;

import io.swagger.client.ApiException;
import io.swagger.client.api.InformationApi;
import io.swagger.client.model.KinaseInformation;
import nl.vu_compmedchem.klifs.KlifsNodeModel;

import org.knime.core.node.ExecutionContext;
import org.knime.core.node.ExecutionMonitor;
import org.knime.core.node.InvalidSettingsException;
import org.knime.core.node.NodeLogger;
import org.knime.core.node.NodeModel;
import org.knime.core.node.NodeSettingsRO;
import org.knime.core.node.NodeSettingsWO;

/**
 * Knime node to retrieve Kinase IDs from KLIFS
 *
 * @author 3D-e-Chem (Albert J. Kooistra)
 */
public class KinaseIDNodeModel extends KlifsNodeModel {

	public static final String CFGKEY_INPUTCOLUMNNAME = "Input Column";
	public static final String CFGKEY_INPUTSPECIES = "Species (optional)";
	private final SettingsModelString m_inputColumnName = new SettingsModelString(CFGKEY_INPUTCOLUMNNAME, "Name");
	private final SettingsModelString m_inputSpecies = new SettingsModelString(CFGKEY_INPUTSPECIES, null);

    // the logger instance
    private static final NodeLogger logger = NodeLogger
            .getLogger(KinaseIDNodeModel.class);

    /**
     * Constructor for the node model.
     */
    protected KinaseIDNodeModel() {
        super(1, 1);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected BufferedDataTable[] execute(final BufferedDataTable[] inData,
            final ExecutionContext exec) throws Exception {

    	logger.info("Executing KLIFS Kinase IDs node - retrieving kinase IDs from KLIFS server.");

    	// Prepare output table
        // the table will have eleven columns: all kinase information
        DataColumnSpec[] allColSpecs = new DataColumnSpec[11];
        allColSpecs[0] = new DataColumnSpecCreator("Kinase ID", IntCell.TYPE).createSpec();
        allColSpecs[1] = new DataColumnSpecCreator("Kinase name", StringCell.TYPE).createSpec();
        allColSpecs[2] = new DataColumnSpecCreator("HGNC/MGI", StringCell.TYPE).createSpec();
        allColSpecs[3] = new DataColumnSpecCreator("Kinase family", StringCell.TYPE).createSpec();
        allColSpecs[4] = new DataColumnSpecCreator("Kinase group", StringCell.TYPE).createSpec();
        allColSpecs[5] = new DataColumnSpecCreator("Kinase class", StringCell.TYPE).createSpec();
        allColSpecs[6] = new DataColumnSpecCreator("Species", StringCell.TYPE).createSpec();
        allColSpecs[7] = new DataColumnSpecCreator("Full name", StringCell.TYPE).createSpec();
        allColSpecs[8] = new DataColumnSpecCreator("Uniprot ID", StringCell.TYPE).createSpec();
        allColSpecs[9] = new DataColumnSpecCreator("IUPHAR ID", StringCell.TYPE).createSpec();
        allColSpecs[10] = new DataColumnSpecCreator("Pocket Sequence", StringCell.TYPE).createSpec();

        DataTableSpec outputSpec = new DataTableSpec(allColSpecs);
        BufferedDataContainer container = exec.createDataContainer(outputSpec);

        // Check input data and execute query
    	String kinaseNames = null;
    	int columnIndex = inData[0].getDataTableSpec().findColumnIndex(m_inputColumnName.getStringValue());
    	for (DataRow inrow : inData[0]) {
    		String kinaseName = ((StringCell) inrow.getCell(columnIndex)).getStringValue();
    		if (kinaseNames!=null){
    			kinaseNames += ","+kinaseName;
    		} else {
    			kinaseNames = kinaseName;
    		}
    	}

    	if (kinaseNames != null){
            try {
    	        InformationApi client = new InformationApi();
                    client.setApiClient(getApiClient());
    	        List<KinaseInformation> kinaseInfos = client.kinaseIDGet(kinaseNames, m_inputSpecies.getStringValue());

    	        for (KinaseInformation info: kinaseInfos) {
    	            RowKey key = new RowKey(info.getKinaseID().toString());

    	            // the cells of the current row, the types of the cells must match
    	            // the column spec (see above)
    	            DataCell[] cells = new DataCell[11];
    	            cells[0] = new IntCell(info.getKinaseID());
    	            cells[1] = new StringCell(info.getName());
    	            cells[2] = new StringCell(info.getHGNC());
    	            cells[3] = new StringCell(info.getFamily());
    	            cells[4] = new StringCell(info.getGroup());
    	            cells[5] = new StringCell(info.getKinaseClass());
    	            cells[6] = new StringCell(info.getSpecies());
    	            cells[7] = new StringCell(info.getFullName());
    	            cells[8] = new StringCell(info.getUniprot());
    	            cells[9] = new StringCell(info.getIuphar());
    	            cells[10] = new StringCell(info.getPocket());
    	            DataRow row = new DefaultRow(key, cells);
    	            container.addRowToTable(row);
    	        }
            } catch (ApiException e){
                handleApiException(e);
            }

    	}

        // Done: close and return
        container.close();
        BufferedDataTable out = container.getTable();
        return new BufferedDataTable[]{out};
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void reset() {
        // TODO Code executed on reset.
        // Models build during execute are cleared here.
        // Also data handled in load/saveInternals will be erased here.
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected DataTableSpec[] configure(final DataTableSpec[] inSpecs)
            throws InvalidSettingsException {

    	if (inSpecs.length > 0 && inSpecs[0] != null){
        	int columnIndex = inSpecs[0].findColumnIndex(m_inputColumnName.getStringValue());
        	if (columnIndex < 0){
        		throw new InvalidSettingsException("No valid input column selected");
        	}
        }

        return new DataTableSpec[]{null};
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void saveSettingsTo(final NodeSettingsWO settings) {
        super.saveSettingsTo(settings);

    	m_inputColumnName.saveSettingsTo(settings);
    	m_inputSpecies.saveSettingsTo(settings);

    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void loadValidatedSettingsFrom(final NodeSettingsRO settings)
            throws InvalidSettingsException {
        super.loadValidatedSettingsFrom(settings);

    	m_inputColumnName.loadSettingsFrom(settings);
    	m_inputSpecies.loadSettingsFrom(settings);

    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void validateSettings(final NodeSettingsRO settings)
            throws InvalidSettingsException {
        super.loadValidatedSettingsFrom(settings);

    	m_inputColumnName.validateSettings(settings);
    	m_inputSpecies.validateSettings(settings);

    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void loadInternals(final File internDir,
            final ExecutionMonitor exec) throws IOException,
            CanceledExecutionException {

        // TODO load internal data.
        // Everything handed to output ports is loaded automatically (data
        // returned by the execute method, models loaded in loadModelContent,
        // and user settings set through loadSettingsFrom - is all taken care
        // of). Load here only the other internals that need to be restored
        // (e.g. data used by the views).

    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void saveInternals(final File internDir,
            final ExecutionMonitor exec) throws IOException,
            CanceledExecutionException {

        // TODO save internal models.
        // Everything written to output ports is saved automatically (data
        // returned by the execute method, models saved in the saveModelContent,
        // and user settings saved through saveSettingsTo - is all taken care
        // of). Save here only the other internals that need to be preserved
        // (e.g. data used by the views).

    }

}