text:
function warnBeforeLeavingIfChangesBeenMade() {
    $('input').change(function () {
        if (window.warningRegistered !== true) {
            window.onbeforeunload = function () { return 'There might be changes that will be lost!'; };
            window.warningRegistered = true;
        }
    });

    $('.form-actions a').click(function () {
        window.onbeforeunload = null;
    });
    $('.form-actions button').click(function () {
        window.onbeforeunload = null;
    });
    $('.form-actions input').click(function () {
        window.onbeforeunload = null;
    });
}

function initHtmlEditor(assetsPath) {
    // TODO: Get editor options/toolbar from property attribute and web.config
    tinymce.init({
        skin_url: assetsPath + 'vendors/tinymce/skins/lightgray',
        selector: "textarea.html-editor",
        plugins: [
            "advlist autolink lists link image charmap anchor",
            "searchreplace visualblocks code hr",
            "media table contextmenu paste"
        ],
        resize: true,
        height: 300,
        menu: {
            edit: { title: 'Edit', items: 'undo redo | cut copy paste pastetext | selectall' },
            insert: { title: 'Insert', items: 'link image media | charmap anchor hr' },
            view: { title: 'View', items: 'visualaid visualblocks' },
            format: { title: 'Format', items: 'bold italic underline strikethrough superscript subscript | formats | removeformat' },
            table: { title: 'Table', items: 'inserttable tableprops deletetable | cell row column' },
            tools: { title: 'Tools', items: 'code' }
        },
        paste_data_images: true,
        extended_valid_elements: "i[class],span,span[class]",
        convert_urls: false,
        relative_urls: false,
        toolbar: "undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image | code",
        file_picker_callback: function (callback, value, meta) {
            if (meta.filetype === 'file') {
                top.registerCallback(function (newUrl, newType) { callback(newUrl); });
                top.propertyEditor.dialogs.openSelectLinkDialog(value, 0);
            }
            if (meta.filetype === 'image') {
                top.registerCallback(function (imagePath, cropX, cropY, cropW, cropH, originalPath, description) { callback(imagePath, { alt: description }); });
                top.propertyEditor.dialogs.openEditImageDialog(value, value, '', '', '', '', '', '', '');
            }
        }
    });
}

function initMarkdownEditor() {
    $(".markdown-editor").markdown({
        savable: false,
        iconlibrary: 'fa-3',
        reorderButtonGroups: ['groupHeaders', 'groupFont', 'groupLink', 'groupMisc', 'groupExtras', 'groupUtil', 'groupHelp'],
        onPreview: function (e) {
            var retval = "";
            jQuery.ajax({
                type: 'POST',
                url: 'Handlers/MarkdownHandler.ashx',
                data: { 'markdown': e.getContent() },
                success: function (result) {
                    retval = result;
                },
                error: function () {
                    alert('Could not preview the Markdown, please check the syntax.');
                },
                async: false
            });

            return retval;
        }
    });
}

function initDropDowns() {
    $('select.selectbox')
        .each(function(index) {
            var element = $(this);

            var render;
            if (element.hasClass('dropdown--enhanced')) {
                render = renderEnhancedOption;
            }
            else if (element.hasClass('dropdown--full')) {
                render = renderFullOption;
            }
            else {
                render = renderSimpleOption;
            }

            element.selectric({
                optionsItemBuilder: function(itemData, element, index) {
                    var description = element.attr('data-description');
                    var image = element.attr('data-image');
                    return render(itemData.text, description, image);
                },
                labelBuilder: function(currItem) {
                    var description = currItem.element.attr('data-description');
                    var image = currItem.element.attr('data-image');
                    return render(currItem.text, description, image);
                }
            });
        });
}

function renderSimpleOption(text, description, image) {
    return text;
}
function renderEnhancedOption(text, description, image) {
    return '

' + text + '

' + description + '

';
}
function renderFullOption(text, description, image) {
    return '

' +
        text + '

' + description + '

';
}


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

<title>Uses of Class py4j.reflection.MethodInvoker</title>
<meta name="date" content="2015-07-25">
<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

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
py4j.reflection.MethodInvoker

Packages that use MethodInvoker

Package
Description

py4j.reflection

Uses of MethodInvoker in py4j.reflection

Fields in py4j.reflection declared as MethodInvoker

Modifier and Type
Field and Description

static MethodInvoker
MethodInvoker.INVALID_INVOKER

Methods in py4j.reflection that return MethodInvoker

Modifier and Type
Method and Description

static MethodInvoker
MethodInvoker.buildInvoker(Constructor<?> constructor,
            Class<?>[] arguments)

static MethodInvoker
MethodInvoker.buildInvoker(Method method,
            Class<?>[] arguments)

MethodInvoker
ReflectionEngine.getConstructor(Class<?> clazz,
              Class<?>[] parameters)

MethodInvoker
ReflectionEngine.getConstructor(String classFQN,
              Object[] parameters)

MethodInvoker
ReflectionEngine.getMethod(Class<?> clazz,
         String name,
         Class<?>[] parameters)

MethodInvoker
ReflectionEngine.getMethod(Object object,
         String name,
         Object[] parameters)

MethodInvoker
ReflectionEngine.getMethod(String classFQN,
         String name,
         Object[] parameters)

Methods in py4j.reflection with parameters of type MethodInvoker

Modifier and Type
Method and Description

Object
ReflectionEngine.invoke(Object object,
      MethodInvoker invoker,
      Object[] parameters)

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

redpajama_set_name: RedPajamaGithub


text:
<refentry id="olink.debug">
<refmeta>
<refentrytitle>olink.debug</refentrytitle>
<refmiscinfo role="type">boolean</refmiscinfo>
</refmeta>
<refnamediv>
<refname>olink.debug</refname>
<refpurpose>Turn on debugging messages for olinks</refpurpose>
</refnamediv>

<refsynopsisdiv>
<src:fragment id='olink.debug.frag'>
<xsl:param name="olink.debug" select="0"/>
</src:fragment>
</refsynopsisdiv>

<refsect1><title>Description</title>

<para>If non-zero, then each olink will generate several
messages about how it is being resolved during processing.
This is useful when an olink does not resolve properly
and the standard error messages are not sufficient to
find the problem.
</para>

<para>You may need to read through the olink XSL templates
to understand the context for some of the debug messages.
</para>

</refsect1>
</refentry>


text:
+++
date = "2013-12-05T08:35:30+08:00"
draft = true
title = "setup awesome in ubuntu 1310"

+++

## Configuration

* add /usr/share/gnome-session/sessions/awesome.session

[GNOME Session]
Name=Awesome session
RequiredComponents=awesome;gnome-settings-daemon;
DesktopName=Awesome

* add /usr/share/applications/awesome.desktop

[Desktop Entry]
Version=1.0
Type=Application
Name=Awesome
Comment=The awesome launcher!
TryExec=awesome
Exec=awesome

* add /usr/share/xsessions/awesome-gnome.desktop

[Desktop Entry]
Name=Awesome GNOME
Comment=Dynamic window manager
Exec=gnome-session --session=awesome
TryExec=awesome
Type=Application
X-LightDM-DesktopName=Awesome GNOME
X-Ubuntu-Gettext-Domain=gnome-session-3.0

* edit /etc/xdg/autostart/gnome-settings-daemon.desktop

[Desktop Entry]
Type=Application
Name=GNOME Settings Daemon
Exec=/usr/lib/gnome-settings-daemon/gnome-settings-daemon-localeexec
OnlyShowIn=GNOME;Unity;Awesome;
NoDisplay=true
X-GNOME-Autostart-Phase=Initialization
X-GNOME-Autostart-Notify=true
X-GNOME-AutoRestart=true
X-Ubuntu-Gettext-Domain=gnome-settings-daemon

## Usage

* choose Awesome in gdm

## Reference

* <http://awesome.naquadah.org/wiki/Quickly_Setting_up_Awesome_with_Gnome>


text:
<?php
//
// Copyright (c) 2014-2015 Oliver Lehmann <lehmann@ans-netz.de>
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
// OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
// SUCH DAMAGE.
//
// $Id: showMonthlySettlementCreateResponse.php,v 1.4 2015/08/07 23:00:53 olivleh1 Exp $
//
namespace api\model\monthlysettlement;

class showMonthlySettlementCreateResponse {
	public $year;
	public $month;
	public $editMode;
	public $monthlySettlementTransport;
	public $importedMonthlySettlementTransport;

	public final function getYear() {
		return $this->year;
	}

	public final function setYear($year) {
		$this->year = $year;
	}

	public final function getMonth() {
		return $this->month;
	}

	public final function setMonth($month) {
		$this->month = $month;
	}

	public final function getMonthlySettlementTransport() {
		return $this->monthlySettlementTransport;
	}

	public final function setMonthlySettlementTransport(array $monthlySettlementTransport) {
		$this->monthlySettlementTransport = $monthlySettlementTransport;
	}

	public final function getImportedMonthlySettlementTransport() {
		return $this->importedMonthlySettlementTransport;
	}

	public final function setImportedMonthlySettlementTransport(array $importedMonthlySettlementTransport) {
		$this->importedMonthlySettlementTransport = $importedMonthlySettlementTransport;
	}

	public final function getEditMode() {
		return $this->editMode;
	}

	public final function setEditMode($editMode) {
		$this->editMode = $editMode;
	}
}

?>


text:
@extends('layouts.master')

@section('content')

        @if(isset($school))
        <form action="/school/update" method="POST">
            {!! csrf_field() !!}

update school

            <input type="hidden" name="id" value="{{$school->id}}">
        @else
        <form action="/school/add" method="POST">
            {!! csrf_field() !!}

add school

        @endif

        @include('model.form.school', ['school' => $school,
            'consumer' => isset($consumer_id) ? Consumer::find($consumer_id) : NULL])

        @if(isset($consumer_id))
            <input type="hidden" name="consumer_id" value="{{$consumer_id}}">
        @endif

        <input type="submit" value="save"/>
        </form>

@stop


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="spp_out_of_resource">Quá nhiều ứng dụng đang sử dụng Bluetooth</string>
    <string name="sdl_error_notification_channel_name">Lỗi SDL</string>
</resources>


text:
var map = require('./map');

module.exports = function toString() {
  return map(function(chunk) {
    return chunk.toString();
  });
};


text:
import getCmdKey from 'ember-keyboard/utils/get-cmd-key';

function sortedKeys(keyArray) {
  return keyArray.sort().join('+');
}

export default function listenerName(type, keyArrayOrString = []) {
  let keyArray = keyArrayOrString;
  if (typeof keyArrayOrString === 'string') {
    keyArray = keyArrayOrString.split('+');
  }

  if (keyArray.indexOf('cmd') > -1) {
    keyArray[keyArray.indexOf('cmd')] = getCmdKey();
  }

  let keys = sortedKeys(keyArray || []);
  if (keys === '') {
    keys = '_all';
  }

  return `${type}:${keys}`;
}


text:
class CopyBodyStringToBodyText < ActiveRecord::Migration
  def self.up
     Hubstats::Comment.update_all("body_text=body")
  end

  def self.down
  	Hubstats::Comment.update_all("body=body_text")
  end
end


text:
var bcrypt = require('bcrypt');
var User = require('../models/user').User;

exports.addUser = function(user, next) {
  bcrypt.hash(user.password, 10, function(err, hash) {
    if (err) {
      return next(err);
    }
    user.password = hash;

    var newUser = new User({
      firstName: user.firstName,
      lastName: user.lastName,
      roomNumber: user.roomNumber,
      email: user.email.toLowerCase(),
      password: user.password
    });

    newUser.save(function(err) {
      if (err) {
        return next(err);
      }
      next(null);
    });
  });
};

exports.findUser = function(email, next) {
  User.findOne({email:email.toLowerCase()}, function(err, user) {
    next(err, user);
  });
};


text:
const config = require('../config')

/**
 * Adds a table function to the IntSchema that retrieves eligibility data for a reference number and dob or
 * eligibilityId and grants the external web user permissions to call it.
 *
 * This information should be masked so the external web cannot query personal information.
 */
exports.seed = function (knex, Promise) {
  return knex.schema
    .raw('DROP FUNCTION IF EXISTS IntSchema.getMaskedEligibility')
    .then(function () {
      return knex.schema
        .raw(
          `
            CREATE FUNCTION IntSchema.getMaskedEligibility(@reference varchar(7), @dob datetime, @eligibiltyId int)
            RETURNS TABLE
            AS
            RETURN
            (
              SELECT TOP(1)
                Eligibility.EligibilityId,
                Visitor.FirstName,
                STUFF(Visitor.LastName, 2, 100, REPLICATE('*', LEN(Visitor.LastName) - 1)) AS LastName,
                STUFF(Visitor.HouseNumberAndStreet, 4, 100, REPLICATE('*', LEN(Visitor.HouseNumberAndStreet) -3)) AS HouseNumberAndStreet,
                Visitor.Town,
                REPLICATE('*', LEN(Visitor.PostCode) -3) + RIGHT(Visitor.PostCode, 3) AS PostCode,
                Visitor.Country,
                Visitor.Benefit,
                Visitor.Relationship,
                Visitor.EmailAddress,
                CASE
                  WHEN ISNULL(Visitor.PhoneNumber, '') = '' THEN ''
                  ELSE '******' + RIGHT(Visitor.PhoneNumber, 4)
                END AS PhoneNumber,
                Prisoner.FirstName AS PrisonerFirstName,
                STUFF(Prisoner.LastName, 2, 100, REPLICATE('*', LEN(Prisoner.LastName) - 1)) AS PrisonerLastName,
                Prisoner.NameOfPrison,
                Prisoner.PrisonNumber
              FROM IntSchema.Eligibility AS Eligibility
                JOIN IntSchema.Visitor AS Visitor ON Visitor.EligibilityId = Eligibility.EligibilityId
                JOIN IntSchema.Prisoner AS Prisoner ON Prisoner.EligibilityId = Eligibility.EligibilityId
              WHERE
                Eligibility.Reference = @reference AND
                (Visitor.DateOfBirth = @dob OR Eligibility.EligibilityId = @eligibiltyId)
              ORDER BY Eligibility.DateSubmitted DESC
            )
          `
        )
        .raw('GRANT SELECT ON IntSchema.getMaskedEligibility TO ??;', [config.EXT_WEB_USERNAME])
    })
    .catch(function (error) {
      console.log(error)
      throw error
    })
}


text:
export PYLINTRC=${HOME}/.pylintrc
export PIPENV_VENV_IN_PROJECT=true


text:
package com.systemcode.sainsburys.util;

import com.systemcode.sainsburys.pojo.Product;
import com.systemcode.sainsburys.pojo.Products;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.regex.Pattern;

@Component
public class ProductsMapper implements Mapper {

    private Document doc;

    private UrlUtils urlUtils = new UrlUtils();

    public ProductsMapper() {
        // empty
    }

    public void parseDocument(String html) {
        doc = Jsoup.parse(html);
    }

    public Products parseProducts() {

        Products products = new Products();

        Elements productElements = doc.getElementsByClass("product");

        for (Element element : productElements) {

            Product product = new Product();

            Elements productInfoElements = element.getElementsByClass("productInfo");

            Element link = productInfoElements.select("a").first();
            product.setTitle(link.text());

            String href = link.attr("href");
            product.setSize(urlUtils.getSizeAsString(href));

            String description = urlUtils.getHeaderItem(href, "meta", "description");
            product.setDescription(description);

            Element pricePerUnit = element.getElementsByClass("pricePerUnit").first();
            String text = pricePerUnit.textNodes().get(0).text();
            product.setUnitPrice(new BigDecimal(extractPrice(text)));

            products.add(product);
        }

        return products;
    }

    private String extractPrice(String text) {

        Pattern pattern = Pattern.compile("^[\\d\\.]");
        return text.replaceAll("[^\\d^\\.]","");
    }

}


text:
    <meta name="description" content="Pmw - a toolkit for building high-level compound widgets in Python">
    <meta name="content" content="python, megawidget, mega widget, compound widget, gui, tkinter">
    <title>List of known bugs</title>

List of known bugs

This is a list of some of the known bugs in Pmw.  If you fix any of
these, please let the maintainer (gregm@iname.com) know.

Under the Enlightenment window manager, if show() is called when
      a window is already displayed (and is not obscured by other
      windows), then the application will hang for two seconds.  This
      is either a bug in Tcl/Tk or in Enlightenment.  See the comment
      in the Tk function WaitForConfigureNotify() in the Tk source
      file tk8.3.2/unix/tkUnixWm.c:

 /*
  * One more tricky detail about this procedure.  In some cases the
  * window manager will decide to ignore a configure request (e.g.
  * because it thinks the window is already in the right place).
  * To avoid hanging in this situation, only wait for a few seconds,
  * then give up.
  */

On NT, Pmw.MenuBar does not display message bar help for menu
      items.  It seems that Tk menu widgets do not support <Motion>
      events on MS.  This probably is an issue that should be taken up
      with the Tcl/Tk people.  (Reported by Stefan Schone.  Pmw.0.7)

Run the CounterDialog.py demo, select the show dialog button and
      press ok.  Now exit the dialog (either with the exit button or
      the close box).  The following error appears:

 Menu ID 256 is already in use!Fatal Python Error: Tcl/Tk panic

      This may be a problem with Mac version of Tk.  (Reported by
      Anthony Wilson.)

Pmw.Balloons bind to widgets and canvas items.  This means that
      bindings made by other users are deleted when the balloon makes
      its bindings.  (For example, the "Delete" canvas item in the
      Balloon demo overrides that <ButtonPress> binding and so that
      balloon is not withdrawn when the mouse button is pressed over
      the item.)

      The obvious solution is for Pmw.Balloon to add its bindings with
      a +.  But this would make the unbind and tagunbind methods
      inconsistent - they would remove all bindings, not just the ones
      added by the balloon.  A better way would be for the balloon to
      add a bindtag to each widget`s bindtag list - then it would not
      upset any other bindings and it could be deleted cleanly.
      (Reported by Joe Saltiel)

 import Tkinter
 import Pmw

 def foo(event):
     print '<Enter> event on text'

 root = Pmw.initialise()
 balloon = Pmw.Balloon()

 canvas = Tkinter.Canvas()
 canvas.pack()

 text1 = canvas.create_text(50, 50, text = 'hello
there')

 # As is, the balloon does not appear over the text, but foo
 # is called.  Swap the following two lines and the balloon
 # appears but foo will not be called.
 canvas.tag_bind(text1, "<Enter>", foo)
 balloon.tagbind(canvas, text1, 'text 1 help')

 root.mainloop()

In Pmw.Balloon, the balloon should not be withdrawn when the
      pointer leaves a widget or item and it immediatly enters another
      widget or item with balloon help.  Instead, the balloon should
      be moved and its contents changed immediately.

When a Pmw.Balloon is bound to a canvas item, moving the item
      becomes very slow.  (Reported by Joe Saltiel)

 > Second, after I fixed my ordering problem I noticed, there
 > is a pretty big delay in updating widgets that have balloon
 > messages bound to them.  (For example dragging a box across
 > a screen, the box has a delayed reaction.) I believe this is
 > due to some of the timing functions used in PmwBalloon, I am
 > not sure if there is a way around it.  I set all timers to
 > zero, and still had the problem.

When running Pmw demos under ptui the busy cursor does not
      appear.

If a combobox has a horizontal scrollbar and it displays its
      listbox above the entry, then it is misplaced.

Bug in Pmw.PanedWidget:  repeat by creating new panes in Demo -
      existing panes jump to the right 1 or 2 pixels.

Bug in Pmw.PanedWidget:  repeat by setting hull_borderwidth to
      20 in demo - initial drag jumps to right by about 20 pixels.
      Also right hand side border is missing.  (Fix may be similar to
      method used in Pmw.ScrolledFrame to give canvas border.)

Fix ButtonRelease events so they do not trigger without a
      corresponding ButtonPress event.

      From Joe Saltiel:  I was playing around with a scrolledlistbox
      and tkFileDialog.  When I have the dialog open above the list
      box and I doubleclick on it, I invoke the selectioncmd of the
      listbox as well as the tkFileDialog box, should this be
      happening?

      Attached is small sample program you can try.  To get the bug to
      show you must do two things.  First, when you open the file
      dialog box, make sure the item you are going to select if
      over(above) the scrolledlistbox.  Second, you have to double
      click on that item.  If you single click and hit "Open" you do
      not get the bug.  Nor do you get it unless the file you click on
      is directly over the clickable region of the scrolledlist box.

 import Tkinter
 import Pmw
 import tkFileDialog
 import string

 def askOpen():
     file = tkFileDialog.askopenfile(filetypes=[("all files", "*")])
     print file

 def printMe():
     print "Me"

 root = Tkinter.Tk()
 Pmw.initialise(root)

 frame1 = Tkinter.Frame(root)
 lst = string.split("abc def ghi jkl mno pqr stu vwx yz")
 lstbox = Pmw.ScrolledListBox(frame1, items=lst, selectioncommand=printMe)
 lstbox.grid(row=0, column=0, columnspan=2)
 Tkinter.Button(frame1, text='open', command=askOpen).grid(row=1, column=0)
 Tkinter.Button(frame1, text='exit', command=root.destroy).grid(row=1, column=1)
 frame1.pack()

 root.mainloop()

      Response:  I have found where the problem is but I am not sure
      how to fix it.  It appears that the tkFileDialog box closes on a
      ButtonPress event.  The corresponding ButtonRelease event is
      then sent to whichever widget is under the cursor at the time of
      the Release.  I have reproduced the problem with a Tcl-only
      script:

 listbox .l
 .l insert 0 1 2 3 4
 bind .l <ButtonRelease-1> {puts AAAGGHHH!}

 button .b -text open -command tk_getOpenFile
 pack .l .b

      If you do a quick Press-Release-Press over the file dialog, it
      is withdrawn.  If you then keep the mouse button down and move
      the mouse around, you will see that the button and the listbox
      still respond to it.  If you do the final button Release over
      the listbox, its <ButtonRelease-1> binding is invoked.

      I think the correct solution is to modify Pmw to be very careful
      when to accept ButtonRelease events.  It will need to also bind
      to ButtonPress events and make sure that it gets a Press before
      it accepts the Release.  I'll try to do the change as soon as
      possible, but the code involved is fairly complex so I it may
      take a little time.

Investigate bug in Tk8.0:  When a dialog pops up over the
      pointer then the keyboard focus is not set and so <Return> does
      not invoke default button.

Under both X and NT, the arrows in the timecounter, counter and
      combobox do not match the scrollbar arrows.

Pmw.Group does not work correctly when the tag is a compound
      widget.  The tag is placed such that the top of the tag is cut
      off.  (Reported by Peter Stoehr.)

 import Tkinter
 import Pmw

 root = Tkinter.Tk()
 Pmw.initialise(root, fontScheme = 'pmw1')
 exitButton = Tkinter.Button(root, text = 'Exit', command = root.destroy)
 exitButton.pack(side = 'bottom')

 def makeGroup(tagClassName):
     tagClass = eval(tagClassName)
     group = Pmw.Group(
         tag_pyclass = tagClass,
         hull_background = 'red',
         groupchildsite_background = 'blue',
     )
     group.pack(fill = 'both', expand = 1, padx = 6, pady = 6)
     child = Tkinter.Label(group.interior(),
         text = 'Group with tag ' + tagClassName,
         background = 'aliceblue',
     )
     child.pack(padx = 10, pady = 5, expand = 1, fill = 'both')

     return group

 grp1 = makeGroup('Pmw.EntryField')
 grp2 = makeGroup('Pmw.ComboBox')
 grp3 = makeGroup('Tkinter.Entry')

 root.mainloop()

      Also, Pmw.Group does not resize correctly if the simple widget
      changes size.  For example:

 grp3.configure(tag_font = ('Helveltica', '-160'))

Bug(s) in PmwScrolledCanvas.  There is a bug in 0.8.1
      PmwScrolledCanvas._setRegion.  If there are no objects in the
      canvas, then error occurs on len(region) because region is None.
      Below is an attempt to fix it.  Click on Show, then on Delete.
      The window then continuously resizes.  If the ScrolledCanvas is
      created with canvasmargin = 0, the problem goes away.  (Reported
      by Anders Henja.)

 import Tkinter
 import Pmw

 def _setRegion(self):
     # Attempt to fix PmwScrolledCanvas._setRegion.
     self.setregionTimer = None

     region = self._canvas.bbox('all')
     canvasmargin = self['canvasmargin']
     if region is None:
         region = (0, 0, 0, 0)
     region = (region[0] - canvasmargin, region[1] - canvasmargin,
         region[2] + canvasmargin, region[3] + canvasmargin)
     self._canvas.configure(scrollregion = region)

 def show():
     canvas.component('canvas').delete('all')
     canvas.create_oval(0, 0, 800, 600, fill = 'red')
     canvas.configure(canvas_width = 600, canvas_height = 450)
     canvas.resizescrollregion()

 def delete():
     canvas.component('canvas').delete('all')
     canvas.configure(canvas_width = 0, canvas_height = 0)
     canvas.resizescrollregion()

 root=Tkinter.Tk()
 Pmw.initialise(root)

 buttonbox=Pmw.ButtonBox()
 buttonbox.pack(fill='x',side='bottom',padx=5,pady=5)
 buttonbox.add('Show',command=show)
 buttonbox.add('Delete',command=delete)
 buttonbox.alignbuttons()

 canvas=Pmw.ScrolledCanvas(canvasmargin=2)
 canvas.__class__._setRegion = _setRegion
 canvas.pack(fill='both',side='right',expand=1)

 root.mainloop()

Bug in Pmw.Dialog:  if defaultbutton is configured before
      buttons during self.initialiseoptions() (that is if
      self._constructorKeywords.keys() returns a different order),
      then setdefault() fails.

Bugs in Tk which affect Pmw.MainMenuBar:

Extra bindings assigned to a Tkinter.Menu widget using
          bindtags have no effect.  Hence the method used in
          Pmw.MenuBar for status help (bind_class followed by
          bindtags) does not work and therefore binding to the menu
          widget is used instead.

The 'active' tag for the index() method of Tkinter.Menu
          always returns None.  Hence, in the menu widget motion
          binding, event.y and the '@' format is used instead, for
          all menus except the toplevel main menu.

For the toplevel main menu, event.x must be used for the
          index() method, but it returns the wrong index.  It
          appears that the Tk widget is assuming vertical layout
          to calculate distances, rather than horizontal.

For toplevel main menus, several Tk commands, such as
          winfo_height(), do not work.  This prevents the use of
          balloon help for Pmw.MainMenuBar.

Bug in Pmw.ComboBox:  Tab to combobox arrow, use up/down arrow
     keys to change selection, hit return, nothing happens, <Shift
     Tab> to entry window, hit return, combobox changes

actually, it would be better if you could not tab to
          the arrow, only the entry field, like the Pmw.Counter.

the problem is if the entry field is not editable, what to
          do then?

Bug in TimeCounter: Arrow keys don't work when focus is on entry.

Bug in Pmw.NoteBook: The size of the tab does not change when
    the text value changes

Bug in Pmw.NoteBook: The name of the tab components has a "-" sign
    in it, which means that component options can not be used in the
    configure command. Eg:

 n = Pmw.NoteBook()
 p = n.add('page1')
 n.configure(page1_background = 'red')   # works
 n.configure(page1-tab_background = 'red')   # fail, must do this:
 n.component('page1-tab').configure(background = 'red')   # works

    Pmw 1.3 -
     6 Aug 2007
     - Home


text:
$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "")
Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan
. "$PSScriptRoot\constants.ps1"

Describe "$CommandName Unit Tests" -Tag 'UnitTests' {
    Context "Validate parameters" {
        [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object { $_ -notin ('whatif', 'confirm') }
        [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Database', 'Query', 'QueryTimeout', 'File', 'SqlObject', 'As', 'SqlParameter', 'AppendServerInstance', 'MessagesToOutput', 'InputObject', 'ReadOnly', 'EnableException', 'CommandType', 'NoExec'
        $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters
        It "Should only contain our specific parameters" {
            (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object { $_ }) -DifferenceObject $params).Count ) | Should Be 0
        }
    }
    Context "Validate alias" {
        It "Should contain the alias: ivq" {
            (Get-Alias ivq) | Should -Not -BeNullOrEmpty
        }
    }
}

Describe "$CommandName Integration Tests" -Tag "IntegrationTests" {
    BeforeAll {
        $db = Get-DbaDatabase -SqlInstance $script:instance2 -Database tempdb
        $null = $db.Query("CREATE PROCEDURE dbo.dbatoolsci_procedure_example @p1 [INT] = 0 AS BEGIN SET NOCOUNT OFF; SELECT TestColumn = @p1; END")
    }
    AfterAll {
        try {
            $null = $db.Query("DROP PROCEDURE dbo.dbatoolsci_procedure_example")
            $null = $db.Query("DROP PROCEDURE dbo.my_proc")
        } catch {
            $null = 1
        }
        Remove-Item ".\hellorelative.sql" -ErrorAction SilentlyContinue
    }
    It "supports pipable instances" {
        $results = $script:instance2, $script:instance3 | Invoke-DbaQuery -Database tempdb -Query "Select 'hello' as TestColumn"
        foreach ($result in $results) {
            $result.TestColumn | Should -Be 'hello'
        }
    }
    It "supports parameters" {
        $sqlParams = @{ testvalue = 'hello' }
        $results = $script:instance2 | Invoke-DbaQuery -Database tempdb -Query "Select @testvalue as TestColumn" -SqlParameters $sqlParams
        foreach ($result in $results) {
            $result.TestColumn | Should -Be 'hello'
        }
    }
    It "supports AppendServerInstance" {
        $conn1 = Connect-DbaInstance $script:instance2
        $conn2 = Connect-DbaInstance $script:instance3
        $serverInstances = $conn1.Name, $conn2.Name
        $results = $script:instance2, $script:instance3 | Invoke-DbaQuery -Database tempdb -Query "Select 'hello' as TestColumn" -AppendServerInstance
        foreach ($result in $results) {
            $result.ServerInstance | Should -Not -Be Null
            $result.ServerInstance | Should -BeIn $serverInstances
        }
    }
    It "supports pipable databases" {
        $dbs = Get-DbaDatabase -SqlInstance $script:instance2, $script:instance3
        $results = $dbs | Invoke-DbaQuery -Query "Select 'hello' as TestColumn, DB_NAME() as dbname"
        foreach ($result in $results) {
            $result.TestColumn | Should -Be 'hello'
        }
        'tempdb' | Should -BeIn $results.dbname
    }
    It "stops when piped databases and -Database" {
        $dbs = Get-DbaDatabase -SqlInstance $script:instance2, $script:instance3
        { $dbs | Invoke-DbaQuery -Query "Select 'hello' as TestColumn, DB_NAME() as dbname" -Database tempdb -EnableException } | Should Throw "You can't"
    }
    It "supports reading files" {
        $testPath = "TestDrive:\dbasqlquerytest.txt"
        Set-Content $testPath -Value "Select 'hello' as TestColumn, DB_NAME() as dbname"
        $results = Invoke-DbaQuery -SqlInstance $script:instance2 -Database tempdb -File $testPath
        foreach ($result in $results) {
            $result.TestColumn | Should -Be 'hello'
        }
        'tempdb' | Should -BeIn $results.dbname
    }
    It "supports reading entire directories, just *.sql" {
        $testPath = "TestDrive:\"
        Set-Content "$testPath\dbasqlquerytest.sql" -Value "Select 'hello' as TestColumn, DB_NAME() as dbname"
        Set-Content "$testPath\dbasqlquerytest2.sql" -Value "Select 'hello2' as TestColumn, DB_NAME() as dbname"
        Set-Content "$testPath\dbasqlquerytest2.txt" -Value "Select 'hello3' as TestColumn, DB_NAME() as dbname"
        $pathinfo = Get-Item $testpath
        $results = Invoke-DbaQuery -SqlInstance $script:instance2 -Database tempdb -File $pathinfo
        'hello' | Should -BeIn $results.TestColumn
        'hello2' | Should -BeIn $results.TestColumn
        'hello3' | Should -Not -BeIn $results.TestColumn
        'tempdb' | Should -BeIn $results.dbname

    }
    It "supports http files" {
        $cleanup = "IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[CommandLog]') AND type in (N'U')) DROP TABLE [dbo].[CommandLog]"
        $null = Invoke-DbaQuery -SqlInstance $script:instance2 -Database tempdb -Query $cleanup
        $CloudQuery = 'https://raw.githubusercontent.com/sqlcollaborative/appveyor-lab/master/sql2016-startup/ola/CommandLog.sql'
        $null = Invoke-DbaQuery -SqlInstance $script:instance2 -Database tempdb -File $CloudQuery
        $check = "SELECT name FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[CommandLog]') AND type in (N'U')"
        $results = Invoke-DbaQuery -SqlInstance $script:instance2 -Database tempdb -Query $check
        $results.Name | Should -Be 'CommandLog'
        $null = Invoke-DbaQuery -SqlInstance $script:instance2 -Database tempdb -Query $cleanup
    }
    It "supports smo objects" {
        $cleanup = "IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[CommandLog]') AND type in (N'U')) DROP TABLE [dbo].[CommandLog]"
        $null = Invoke-DbaQuery -SqlInstance $script:instance2, $script:instance3 -Database tempdb -Query $cleanup
        $CloudQuery = 'https://raw.githubusercontent.com/sqlcollaborative/appveyor-lab/master/sql2016-startup/ola/CommandLog.sql'
        $null = Invoke-DbaQuery -SqlInstance $script:instance2 -Database tempdb -File $CloudQuery
        $smoobj = Get-DbaDbTable -SqlInstance $script:instance2 -Database tempdb | Where-Object Name -EQ 'CommandLog'
        $null = Invoke-DbaQuery -SqlInstance $script:instance3 -Database tempdb -SqlObject $smoobj
        $check = "SELECT name FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[CommandLog]') AND type in (N'U')"
        $results = Invoke-DbaQuery -SqlInstance $script:instance3 -Database tempdb -Query $check
        $results.Name | Should Be 'CommandLog'
        $null = Invoke-DbaQuery -SqlInstance $script:instance2, $script:instance3 -Database tempdb -Query $cleanup
    }
    <#
    It "supports loose objects (with SqlInstance and database props)" {
        $dbs = Get-DbaDbState -SqlInstance $script:instance2, $script:instance3
        $results = $dbs | Invoke-DbaQuery -Query "Select 'hello' as TestColumn, DB_NAME() as dbname"
        foreach ($result in $results) {
            $result.TestColumn | Should -Be 'hello'
        }
    }    #>
    It "supports queries with GO statements" {
        $Query = @'
SELECT DB_NAME() as dbname
GO
SELECT @@servername as dbname
'@
        $results = $script:instance2, $script:instance3 | Invoke-DbaQuery -Database tempdb -Query $Query
        $results.dbname -contains 'tempdb' | Should -Be $true
    }
    It "streams correctly 'messages' with Verbose" {
        $query = @'
        DECLARE @time char(19)
        PRINT 'stmt_1|PRINT start|' + CONVERT(VARCHAR(19), GETUTCDATE(), 126)
        SET @time= CONVERT(VARCHAR(19), GETUTCDATE(), 126)
        RAISERROR ('stmt_2|RAISERROR before WITHOUT NOWAIT|%s', 0, 1, @time)
        WAITFOR DELAY '00:00:01'
        PRINT 'stmt_3|PRINT after the first delay|' + CONVERT(VARCHAR(19), GETUTCDATE(), 126)
        SET @time= CONVERT(VARCHAR(19), GETUTCDATE(), 126)
        RAISERROR ('stmt_4|RAISERROR with NOWAIT|%s', 0, 1, @time) WITH NOWAIT
        WAITFOR DELAY '00:00:01'
        PRINT 'stmt_5|PRINT after the second delay|' + CONVERT(VARCHAR(19), GETUTCDATE(), 126)
        SELECT 'hello' AS TestColumn
        WAITFOR DELAY '00:00:01'
        PRINT 'stmt_6|PRINT end|' + CONVERT(VARCHAR(19), GETUTCDATE(), 126)
'@
        $results = @()
        Invoke-DbaQuery -SqlInstance $script:instance2 -Database tempdb -Query $query -Verbose 4>&1 | ForEach-Object {
            $results += [pscustomobject]@{
                FiredAt = (Get-Date).ToUniversalTime()
                Out     = $_
            }
        }
        $results.Length | Should -Be 7 # 6 'messages' plus the actual resultset
        ($results | ForEach-Object { Get-Date -Date $_.FiredAt -Format s } | Get-Unique).Count | Should -Not -Be 1 # the first WITH NOWAIT (stmt_4) and after
        #($results[0..3]  | ForEach-Object { Get-Date -Date $_.FiredAt -f s } | Get-Unique).Count | Should -Be 1 # everything before stmt_4 is fired at the same time
        #$parsedstmt_1 = Get-Date -Date $results[0].Out.Message.split('|')[2]
        #(Get-Date -Date (Get-Date -Date $parsedstmt_1).AddSeconds(3) -f s) | Should -Be (Get-Date -Date $results[0].FiredAt -f s) # stmt_1 is fired 3 seconds after the logged date
        #$parsedstmt_4 = Get-Date -Date $results[3].Out.Message.split('|')[2]
        #(Get-Date -Date (Get-Date -Date $parsedstmt_4) -f s) | Should -Be (Get-Date -Date $results[0].FiredAt -f s) # stmt_4 is fired at the same time the logged date is
    }
    It "streams correctly 'messages' with MessagesToOutput" {
        $query = @'
        DECLARE @time char(19)
        PRINT 'stmt_1|PRINT start|' + CONVERT(VARCHAR(19), GETUTCDATE(), 126)
        SET @time= CONVERT(VARCHAR(19), GETUTCDATE(), 126)
        RAISERROR ('stmt_2|RAISERROR before WITHOUT NOWAIT|%s', 0, 1, @time)
        WAITFOR DELAY '00:00:01'
        PRINT 'stmt_3|PRINT after the first delay|' + CONVERT(VARCHAR(19), GETUTCDATE(), 126)
        SET @time= CONVERT(VARCHAR(19), GETUTCDATE(), 126)
        RAISERROR ('stmt_4|RAISERROR with NOWAIT|%s', 0, 1, @time) WITH NOWAIT
        WAITFOR DELAY '00:00:01'
        PRINT 'stmt_5|PRINT after the second delay|' + CONVERT(VARCHAR(19), GETUTCDATE(), 126)
        SELECT 'hello' AS TestColumn
        WAITFOR DELAY '00:00:01'
        PRINT 'stmt_6|PRINT end|' + CONVERT(VARCHAR(19), GETUTCDATE(), 126)
'@
        $results = @()
        Invoke-DbaQuery -SqlInstance $script:instance2 -Database tempdb -Query $query -MessagesToOutput | ForEach-Object {
            $results += [pscustomobject]@{
                FiredAt = (Get-Date).ToUniversalTime()
                Out     = $_
            }
        }
        $results.Length | Should -Be 7 # 6 'messages' plus the actual resultset
        ($results | ForEach-Object { Get-Date -Date $_.FiredAt -Format s } | Get-Unique).Count | Should -Not -Be 1 # the first WITH NOWAIT (stmt_4) and after
    }
    It "Executes stored procedures with parameters" {
        $results = Invoke-DbaQuery -SqlInstance $script:instance2 -Database tempdb -Query "dbatoolsci_procedure_example" -SqlParameters @{p1 = 1 } -CommandType StoredProcedure
        $results.TestColumn | Should Be 1
    }
    It "Executes script file with a relative path (see #6184)" {
        Set-Content -Path ".\hellorelative.sql" -Value "Select 'hello' as TestColumn, DB_NAME() as dbname"
        $results = Invoke-DbaQuery -SqlInstance $script:instance2 -Database tempdb -File ".\hellorelative.sql"
        foreach ($result in $results) {
            $result.TestColumn | Should -Be 'hello'
        }
        'tempdb' | Should -BeIn $results.dbname
    }
    It "supports multiple datatables also as array of PSObjects (see #6921)" {
        $results = Invoke-DbaQuery -SqlInstance $script:instance2 -Database tempdb -Query "select 1 as a union all select 2 union all select 3; select 4 as b, 5 as c union all select 6, 7;" -As PSObjectArray
        $results.Count | Should -Be 2
        $results[0].Count | Should -Be 3
        $results[0][0].a | Should -Be 1
        $results[1].Count | Should -Be 2
        $results[1][0].b | Should -Be 4
        $results[1][1].c | Should -Be 7
    }
    It "supports multiple datatables also as PSObjects (see #6921)" {
        $results = Invoke-DbaQuery -SqlInstance $script:instance2 -Database tempdb -Query "select 1 as a union all select 2 union all select 3; select 4 as b, 5 as c union all select 6, 7;" -As PSObject
        $results.Count | Should -Be 5
        $results[0].a | Should -Be 1
        $results[3].b | Should -Be 4
        $results[4].c | Should -Be 7
    }

    It "supports using SqlParameters as Microsoft.Data.SqlClient.SqlParameter (#7434)" {
        $null = Invoke-DbaQuery -SqlInstance $script:instance2 -Database tempdb -Query "CREATE OR ALTER PROC [dbo].[my_proc]
                    @json_result nvarchar(max) output
                AS
                BEGIN
                set @json_result = (
                    select 'sample' as 'example'
                    for json path, without_array_wrapper
                );
                END"
        $output = New-DbaSqlParameter -ParameterName json_result -SqlDbType NVarChar -Size -1 -Direction Output
        Invoke-DbaQuery -SqlInstance $script:instance2 -Database tempdb -CommandType StoredProcedure -Query my_proc -SqlParameters $output
        $output.Value | Should -Be '{"example":"sample"}'
    }

    It "supports using multiple and mixed params, even with different names (#7434)" {
        $null = Invoke-DbaQuery -SqlInstance $script:instance2 -Database tempdb -Query "CREATE OR ALTER PROCEDURE usp_Insertsomething
    @somevalue varchar(10),
    @newid varchar(50) OUTPUT
        AS
        BEGIN
            SELECT 'fixedval' as somevalue, @somevalue as 'input param'
            SELECT @newid = '12345'
        END"
        $outparam = New-DbaSqlParameter -Direction Output -Size -1
        $sqlparams = @{
            'newid' = $outparam
            'somevalue' = 'asd'
        }
        $result = Invoke-DbaQuery -SqlInstance $script:instance2 -Database tempdb -Query "EXEC usp_Insertsomething @somevalue, @newid output" -SqlParameters $sqlparams
        $outparam.Value | Should -Be '12345'
        $result.'input param' | Should -Be 'asd'
        $result.somevalue | Should -Be 'fixedval'
    }

    It "supports complex types, such as datatables (#7434)" {
        $null = Invoke-DbaQuery -SqlInstance $script:instance2 -Database tempdb -Query "
IF NOT EXISTS (SELECT * FROM sys.types WHERE name = N'dbatools_tabletype')
CREATE TYPE dbatools_tabletype AS TABLE(
    somestring varchar(50),
    somedate datetime2(7)
)
GO
CREATE OR ALTER PROCEDURE usp_Insertsomething
    @sometable dbatools_tabletype READONLY,
    @newid varchar(50) OUTPUT
AS
BEGIN
    SELECT * FROM @sometable ORDER BY somestring
    SELECT @newid = '12345'
END"
        $outparam = New-DbaSqlParameter -Direction Output -Size -1
        $inparam = @()
        $inparam += [pscustomobject]@{
            somestring = 'string1'
            somedate = '2021-07-15T01:02:00'
        }
        $inparam += [pscustomobject]@{
            somestring = 'string2'
            somedate = '2021-07-15T02:03:00'
        }
        $sqlparams = @{
            'newid' = $outparam
            'sometable' = New-DbaSqlParameter -SqlDbType structured -Value (ConvertTo-DbaDataTable -InputObject $inparam) -TypeName 'dbatools_tabletype'
        }
        $result = Invoke-DbaQuery -SqlInstance $script:instance2 -Database tempdb -Query "EXEC usp_Insertsomething @sometable, @newid output" -SqlParameters $sqlparams
        $outparam.Value | Should -Be '12345'
        $result.Count | Should -Be 2
        $result[0].somestring | Should -Be 'string1'
        (Get-Date -Date $result[1].somedate -f 'yyyy-MM-ddTHH:mm:ss') | Should -Be '2021-07-15T02:03:00'
    }

    It "support NOEXEC mode" {
        $result = Invoke-DbaQuery -SqlInstance $script:instance2 -Database tempdb -Query "SELECT 1" -NoExec
        $result | Should -BeNullOrEmpty
        #for multiple batches, too
        $q = @'
SELECT 1
GO
SELECT 2
'@
        $result = Invoke-DbaQuery -SqlInstance $script:instance2 -Database tempdb -Query $q -NoExec
        $result | Should -BeNullOrEmpty

        { Invoke-DbaQuery -SqlInstance $script:instance2 -Database tempdb -Query "SELEC p FROM c" -NoExec -EnableException } | Should -Throw "Incorrect syntax near 'selec'"
    }

    It "supports dropping temp objects (#8472)" {
        $sql = "CREATE PROC #DropStatistics
                AS
                SELECT 1
                GO
                drop procedure #DropStatistics
                go"
        { Invoke-DbaQuery -SqlInstance $script:instance2 -Database tempdb -Query $sql -EnableException } | Should -Not -Throw
    }
}


text:
package edu.washington.escience.myria.column;

import com.google.common.base.Preconditions;

/**
 * A column of Int values.
 *
 *
 */
public final class IntArrayColumn extends IntColumn {
  /**
   *
   */
  private static final long serialVersionUID = 1L;
  /** Internal representation of the column data. */
  private final int[] data;
  /** The number of existing rows in this column. */
  private final int position;

  /**
   * Constructs a new column.
   *
   * @param data the data
   * @param numData number of tuples.
   * */
  public IntArrayColumn(final int[] data, final int numData) {
    this.data = data;
    position = numData;
  }

  @Override
  public Integer getObject(final int row) {
    return Integer.valueOf(getInt(row));
  }

  @Override
  public int getInt(final int row) {
    Preconditions.checkElementIndex(row, position);
    return data[row];
  }

  @Override
  public int size() {
    return position;
  }
}


text:
using System;
using System.Threading.Tasks;
using Google.Cloud.Datastore.V1;

namespace hutel.Session
{
    public class GoogleSessionClient : ISessionClient
    {
        private const string _envGoogleProjectId = "GOOGLE_PROJECT_ID";
        private const string _entityKind = "session";

        private readonly string _googleProjectId;
        private readonly DatastoreDb _db;
        private readonly KeyFactory _keyFactory;

        public GoogleSessionClient()
        {
            _googleProjectId = Environment.GetEnvironmentVariable(_envGoogleProjectId);
            _db = DatastoreDb.Create(_googleProjectId);
            _keyFactory = _db.CreateKeyFactory(_entityKind);
        }

        public async Task<SessionInfo> LookupSessionAsync(string sessionId)
        {
            var key = _keyFactory.CreateKey(sessionId);
            using (var transaction = await _db.BeginTransactionAsync())
            {
                var entity = await transaction.LookupAsync(key);
                if (entity == null)
                {
                    return null;
                }
                var session = new SessionInfo
                {
                    SessionId = entity["SessionId"].StringValue,
                    UserId = entity["UserId"].StringValue,
                    Expiration = DateTime.FromBinary(entity["Expiration"].IntegerValue)
                };
                return session;
            }
        }

        public async Task SaveSessionAsync(SessionInfo session)
        {
            var key = _keyFactory.CreateKey(session.SessionId);
            var entity = new Entity
            {
                Key = key,
                ["SessionId"] = session.SessionId,
                ["UserId"] = session.UserId,
                ["Expiration"] = session.Expiration.ToBinary()
            };
            using (var transaction = await _db.BeginTransactionAsync())
            {
                transaction.Upsert(entity);
                await transaction.CommitAsync();
            }
        }

        public async Task DeleteSessionAsync(string sessionId)
        {
            var key = _keyFactory.CreateKey(sessionId);
            using (var transaction = await _db.BeginTransactionAsync())
            {
                transaction.Delete(key);
                await transaction.CommitAsync();
            }
        }
    }
}


text:
class UTankAimingComponent;

UCLASS()
class BUTTELTUNK_API ATankPlayerController : public APlayerController
{
	GENERATED_BODY()

protected:

	UFUNCTION(BlueprintImplementableEvent, Category = "Setup")
	void FoundAimingComponent(UTankAimingComponent* AimingCompRef);

private:
	virtual void BeginPlay() override;
	virtual void Tick(float DeltaTime) override;

	virtual void SetPawn(APawn* InPawn) override;

	UFUNCTION()
	virtual void OnTankDeath();

	// Start the tank moving the barrel so shot
	// would hit where the crosshair intersects the world.
	void AimTowardsCrosshair();

	// return an out parameter, true if hit landscape
	bool GetSightRayHitLocation(FVector& HitLocation) const;

	UPROPERTY(EditDefaultsOnly)
	float CrosshairXLocation = 0.5f;

	UPROPERTY(EditDefaultsOnly)
	float CrosshairYLocation = 0.33333f;

	UPROPERTY(EditDefaultsOnly)
	float LineTraceRange = 1000000.f;

	bool GetLookDirection(FVector2D ScreenLocation, FVector& LookDirection) const;
	bool GetLookVectorHitLocation(FVector LookDirection, FVector& HitLocation) const;
};


text:
using Azure.Core;

namespace Azure.ResourceManager.Batch.Models
{
    /// <summary> A reference to an Azure Virtual Machines Marketplace image or the Azure Image resource of a custom Virtual Machine. To get the list of all imageReferences verified by Azure Batch, see the 'List supported node agent SKUs' operation. </summary>
    public partial class BatchImageReference
    {
        /// <summary> Initializes a new instance of BatchImageReference. </summary>
        public BatchImageReference()
        {
        }

        /// <summary> Initializes a new instance of BatchImageReference. </summary>
        /// <param name="publisher"> For example, Canonical or MicrosoftWindowsServer. </param>
        /// <param name="offer"> For example, UbuntuServer or WindowsServer. </param>
        /// <param name="sku"> For example, 18.04-LTS or 2022-datacenter. </param>
        /// <param name="version"> A value of 'latest' can be specified to select the latest version of an image. If omitted, the default is 'latest'. </param>
        /// <param name="id"> This property is mutually exclusive with other properties. The Shared Image Gallery image must have replicas in the same region as the Azure Batch account. For information about the firewall settings for the Batch node agent to communicate with the Batch service see https://docs.microsoft.com/en-us/azure/batch/batch-api-basics#virtual-network-vnet-and-firewall-configuration. </param>
        internal BatchImageReference(string publisher, string offer, string sku, string version, ResourceIdentifier id)
        {
            Publisher = publisher;
            Offer = offer;
            Sku = sku;
            Version = version;
            Id = id;
        }

        /// <summary> For example, Canonical or MicrosoftWindowsServer. </summary>
        public string Publisher { get; set; }
        /// <summary> For example, UbuntuServer or WindowsServer. </summary>
        public string Offer { get; set; }
        /// <summary> For example, 18.04-LTS or 2022-datacenter. </summary>
        public string Sku { get; set; }
        /// <summary> A value of 'latest' can be specified to select the latest version of an image. If omitted, the default is 'latest'. </summary>
        public string Version { get; set; }
        /// <summary> This property is mutually exclusive with other properties. The Shared Image Gallery image must have replicas in the same region as the Azure Batch account. For information about the firewall settings for the Batch node agent to communicate with the Batch service see https://docs.microsoft.com/en-us/azure/batch/batch-api-basics#virtual-network-vnet-and-firewall-configuration. </summary>
        public ResourceIdentifier Id { get; set; }
    }
}


text:
/*==================================================
 *  Exhibit.ImageFacet
 *==================================================
 */

Exhibit.ImageFacet = function(containerElmt, uiContext) {
    Exhibit.EnumeratedFacet.call(this,"image",containerElmt,uiContext);
    this.addSettingSpecs(Exhibit.ImageFacet._settingSpecs);
    this._div = containerElmt;
    this._colorCoder = null;

    this._expression = null;
    this._valueSet = new Exhibit.Set();
    this._selectMissing = false;

    this._settings = {};
    this._dom = null;
};
Exhibit.ImageFacet.prototype = new Exhibit.EnumeratedFacet();

Exhibit.ImageFacet._settingSpecs = {
    "image":            { type: "text" },
    "tooltip":          { type: "text" },
    "thumbNail":        { type: "uri" },
    "overlayCounts":    { type: "boolean", defaultValue: true },
    "scroll":           { type: "boolean", defaultValue: true },
    "height":           { type: "text" },
    "colorCoder":       { type: "text", defaultValue: null },
    "collapsible":      { type: "boolean", defaultValue: false },
    "collapsed":        { type: "boolean", defaultValue: false }
};

/**
 * @static
 * @param {Element} configElmt
 * @param {Element} containerElmt
 * @param {Exhibit.UIContext} uiContext
 * @param {Object} settingsFromDOM
 * @returns {Exhibit.ListFacet}
 */
Exhibit.ImageFacet.createFromDOM = function(configElmt, containerElmt,
                                           uiContext) {
    return Exhibit.EnumeratedFacet.createFromDOM(Exhibit.ImageFacet, configElmt, containerElmt, uiContext);
};

/**
 * @static
 * @param {Object} configObj
 * @param {Element} containerElmt
 * @param {Exhibit.UIContext} uiContext
 * @returns {Exhibit.ListFacet}
 */
Exhibit.ImageFacet.create = function(configObj, containerElmt, uiContext) {
    var settingsFromDOM, facet;

    return Exhibit.EnumeratedFacet.createFromObj(Exhibit.ImageFacet, configObj, containerElmt, uiContext);
};

Exhibit.ImageFacet.prototype._configure = function(configuration) {
    var i, segment, property, selection, values, orderMap;
    Exhibit.SettingsUtilities.collectSettings(configuration, Exhibit.ImageFacet._settingSpecs, this._settings);

    if ("expression" in configuration) {
        this._expression = Exhibit.ExpressionParser.parse(configuration.expression);
    }
    if ("image" in configuration) {
        this._imageExpression = Exhibit.ExpressionParser.parse(configuration.image);
    }
    if ("tooltip" in configuration) {
        this._tooltipExpression = Exhibit.ExpressionParser.parse(configuration.tooltip);
    }

	if (!(this._imageExpression)) {
        this._imageExpression = Exhibit.ExpressionParser.parse("value");
	}
	if (!(this._tooltipExpression)) {
        this._tooltipExpression = Exhibit.ExpressionParser.parse("value");
	}

    if ("selection" in configuration) {
        selection = configuration.selection;
        for (i = 0; i < selection.length; i++) {
            this._valueSet.add(selection[i]);
        }
    }
    if ("selectMissing" in configuration) {
        this._selectMissing = configuration.selectMissing;
    }

    if (!("facetLabel" in this._settings)) {
        this._settings.facetLabel = "missing ex:facetLabel";
        if (this._expression != null && this._expression.isPath()) {
            segment = this._expression.getPath().getLastSegment();
            property = this.getUIContext().getDatabase().getProperty(segment.property);
            if (property != null) {
                this._settings.facetLabel = segment.forward ? property.getLabel() : property.getReverseLabel();
            }
        }
    }
    if ("fixedOrder" in this._settings) {
        values = this._settings.fixedOrder.split(";");
        orderMap = {};
        for (i = 0; i < values.length; i++) {
            orderMap[values[i].trim()] = i;
        }

        this._orderMap = orderMap;
    }

    if ("colorCoder" in this._settings) {
        this._colorCoder = this.getUIContext().getMain().getComponent(this._settings.colorCoder);
    }

    if (this._settings.collapsed) {
        this._settings.collapsible = true;
    }

    this._cache = new Exhibit.FacetUtilities.Cache(
        this.getUIContext().getDatabase(),
        this.getUIContext().getCollection(),
        this._expression
    );
}

Exhibit.ImageFacet.prototype.dispose = function() {
    this._cache.dispose();
    this._cache = null;

    this.getUIContext().getCollection().removeFacet(this);
    this.getUIContext() = null;
    this._colorCoder = null;

    this._div.innerHTML = "";
    this._div = null;
    this._dom = null;

    this._expression = null;
    this._valueSet = null;
    this._settings = null;
    Exhibit.EnumeratedFacet.dispose.call(this);
};

Exhibit.ImageFacet.prototype.update = function(items) {
    this._dom.valuesContainer.hide();
    this._dom.valuesContainer.innerHTML = "";
    this._constructBody(this._computeFacet(items));
    this._dom.valuesContainer.show();
};

Exhibit.ImageFacet.prototype._computeFacet = function(items) {
    var database, r, entries, valueType, selection, labeler, i, entry, count, span;
    database = this.getUIContext().getDatabase();
    r = this._cache.getValueCountsFromItems(items);
    entries = r.entries;

    valueType = r.valueType;

    if (entries.length > 0) {
        selection = this._valueSet;
        labeler = valueType == "item" ?
            function(v) { var l = database.getObject(v, "label");
                          return l != null ? l : v; } :
            function(v) { return v; }

        for (i = 0; i < entries.length; i++) {
            entry = entries[i];
            entry.actionLabel = entry.selectionLabel = labeler(entry.value);
	    entry.image = this._imageExpression.evaluateSingleOnItem(entry.value, database).value;
	    entry.tooltip = this._tooltipExpression.evaluateSingleOnItem(entry.value, database).value;
            entry.selected = selection.contains(entry.value);
        }

        entries.sort(this._createSortFunction(valueType));
    }
    /* should display something to account for items that don't have this field

       if (this._settings.showMissing || this._selectMissing) {
       var count = this._cache.countItemsMissingValue(items);
        if (count > 0 || this._selectMissing) {
            var span = document.createElement("span");
            span.innerHTML = ("missingLabel" in this._settings) ?
                this._settings.missingLabel : Exhibit.FacetUtilities.l10n.missingThisField;
            span.className = "exhibit-facet-value-missingThisField";

            entries.unshift({
                value:          null,
                count:          count,
                selected:       this._selectMissing,
                selectionLabel: span,
                actionLabel:    Exhibit.FacetUtilities.l10n.missingThisField
            });
        }
    }
    */
    return entries;
}

Exhibit.ImageFacet.prototype._initializeUI = function() {
    var self = this;
    this._dom = Exhibit.FacetUtilities[this._settings.scroll ? "constructFacetFrame" : "constructFlowingFacetFrame"](
		this,
        this._div,
        this._settings.facetLabel,
        function(elmt, evt, target) { self._clearSelections(); },
        this.getUIContext(),
        this._settings.collapsible,
        this._settings.collapsed
    );

    if ("height" in this._settings && this._settings.scroll) {
        this._dom.valuesContainer.style.height = this._settings.height;
    }
};

Exhibit.ImageFacet.prototype._constructBody = function(entries) {
    var wrapper, self = this;
    var shouldOverlayCounts = this._settings.overlayCounts;
    var containerDiv = this._dom.valuesContainer;

    containerDiv.hide().empty();
    var facetHasSelection = this._valueSet.size() > 0 || this._selectMissing;
    var constructValue = function(entry) {
        var onSelectOnly = function(evt) {
            self._filter(entry.value, entry.actionLabel, !(evt.ctrlKey || evt.metaKey));
            evt.preventDefault();
            evt.stopPropagation();
        };
        wrapper = Exhibit.jQuery("<img>")
            .attr("src",entry.image)
            .wrap("<div>").parent()
            .addClass("wrapper");

	if(shouldOverlayCounts == true) {
	    var countDiv = document.createElement("div");
	    countDiv.className = "countDiv";
	    var countBackground = document.createElement("div");
	    countBackground.className = "countBackground";
	    countDiv.appendChild(countBackground);
	    var innerCount = document.createElement("div");
	    innerCount.className = "text";
	    innerCount.innerHTML = entry.count;
	    countDiv.appendChild(innerCount);
	    wrapper.append(countDiv);
	}

	Exhibit.jQuery("<span>")
            .append(wrapper)
            .addClass("inline-block exhibit-imageFacet-value" +
                     (entry.selected ? " exhibit-imageFacet-value-selected"
                      : "" ))
            .prop("title", entry.count + " " + entry.tooltip)
            .click(onSelectOnly)
            .appendTo(containerDiv);
    };

    for (var j = 0; j < entries.length; j++) {
        constructValue(entries[j]);
    }
    containerDiv.show();

    this._dom.setSelectionCount(this._valueSet.size() + (this._selectMissing ? 1 : 0));
};


text:
import {NotImplementedError} from '../errors/NotImplementedError';

/**
 * Abstract class to define CommandBus interface
 */
export class AbstractCommandBus {
    /**
     * Execute command, return promise that will be resolved with execution result.
     * @param {AbstractCommand} command
     * @returns {Promise.<AbstractCommandExecutionResult>}
     */
    execute (command) {
        throw new NotImplementedError('execute', 'CommandBus');
    }

    /**
     * Register command handler in command bus, so command bus will be able to route command
     * @param {AbstractCommandHandler} commandHandler
     */
    registerCommandHandler (commandHandler) {
        throw new NotImplementedError('registerCommandHandler', 'CommandBus');
    }
}


text:
/**
 *	Animated Graph Tutorial for Smashing Magazine
 *	July 2011
 *
 * 	Author:	Derek Mack
 *			derekmack.com
 *			@derek_mack
 *
 *	Example 3 - Animated Bar Chart via jQuery
 */

// Wait for the DOM to load everything, just to be safe
$(document).ready(function() {

	// Create our graph from the data table and specify a container to put the graph in
	createGraph('#data-table', '.chart');

	// Here be graphs
	function createGraph(data, container) {
		// Declare some common variables and container elements
		var bars = [];
		var figureContainer = $('

');
		var graphContainer = $('

');
		var barContainer = $('

');
		var data = $(data);
		var container = $(container);
		var chartData;
		var chartYMax;
		var columnGroups;

		// Timer variables
		var barTimer;
		var graphTimer;

		// Create table data object
		var tableData = {
			// Get numerical data from table cells
			chartData: function() {
				var chartData = [];
				data.find('tbody td').each(function() {
					chartData.push($(this).text());
				});
				return chartData;
			},
			// Get heading data from table caption
			chartHeading: function() {
				var chartHeading = data.find('caption').text();
				return chartHeading;
			},
			// Get legend data from table body
			chartLegend: function() {
				var chartLegend = [];
				// Find th elements in table body - that will tell us what items go in the main legend
				data.find('tbody th').each(function() {
					chartLegend.push($(this).text());
				});
				return chartLegend;
			},
			// Get highest value for y-axis scale
			chartYMax: function() {
				var chartData = this.chartData();
				// Round off the value
				var chartYMax = Math.max.apply(Math, chartData)  ;
				return chartYMax;
			},
			// Get y-axis data from table cells
			yLegend: function() {
				var chartYMax = this.chartYMax();
				var yLegend = [];
				// Number of divisions on the y-axis
				var yAxisMarkings = 5;
				// Add required number of y-axis markings in order from 0 - max
				for (var i = 0; i < yAxisMarkings; i++) {
					yLegend.unshift(((chartYMax * i) / (yAxisMarkings - 1)) );
				}
				return yLegend;
			},
			// Get x-axis data from table header
			xLegend: function() {
				var xLegend = [];
				// Find th elements in table header - that will tell us what items go in the x-axis legend
				data.find('thead th').each(function() {
					xLegend.push($(this).text());
				});
				return xLegend;
			},
			// Sort data into groups based on number of columns
			columnGroups: function() {
				var columnGroups = [];
				// Get number of columns from first row of table body
				var columns = data.find('tbody tr:eq(0) td').length;
				for (var i = 0; i < columns; i++) {
					columnGroups[i] = [];
					data.find('tbody tr').each(function() {
						columnGroups[i].push($(this).find('td').eq(i).text());
					});
				}
				return columnGroups;
			}
		}

		// Useful variables for accessing table data
		chartData = tableData.chartData();
		chartYMax = tableData.chartYMax();
		columnGroups = tableData.columnGroups();

		// Construct the graph

		// Loop through column groups, adding bars as we go
		$.each(columnGroups, function(i) {
			// Create bar group container
			var barGroup = $('

');
			// Add bars inside each column
			for (var j = 0, k = columnGroups[i].length; j < k; j++) {
				// Create bar object to store properties (label, height, code etc.) and add it to array
				// Set the height later in displayGraph() to allow for left-to-right sequential display
				var barObj = {};
				barObj.label = this[j];
				barObj.height = Math.floor(barObj.label / chartYMax * 100) + '%';
				barObj.bar = $('
' + barObj.label + '
')
					.appendTo(barGroup);
				bars.push(barObj);
			}
			// Add bar groups to graph
			barGroup.appendTo(barContainer);
		});

		// Add heading to graph
		var chartHeading = tableData.chartHeading();
		var heading = $('
' + chartHeading + '
');
		heading.appendTo(figureContainer);

		// Add legend to graph
		var chartLegend	= tableData.chartLegend();
		var legendList	= $('

');
		$.each(chartLegend, function(i) {
			var listItem = $('
' + this + '
')
				.appendTo(legendList);
		});
		legendList.appendTo(figureContainer);

		// Add x-axis to graph
		var xLegend	= tableData.xLegend();
		var xAxisList	= $('

');
		$.each(xLegend, function(i) {
			var listItem = $('
' + this + '
')
				.appendTo(xAxisList);
		});
		xAxisList.appendTo(graphContainer);

		// Add y-axis to graph
		var yLegend	= tableData.yLegend();
		var yAxisList	= $('

');
		$.each(yLegend, function(i) {
			var listItem = $('
' + this + '
')
				.appendTo(yAxisList);
		});
		yAxisList.appendTo(graphContainer);

		// Add bars to graph
		barContainer.appendTo(graphContainer);

		// Add graph to graph container
		graphContainer.appendTo(figureContainer);

		// Add graph container to main container
		figureContainer.appendTo(container);

		// Set individual height of bars
		function displayGraph(bars, i) {
			// Changed the way we loop because of issues with $.each not resetting properly
			if (i < bars.length) {
				// Animate height using jQuery animate() function
				$(bars[i].bar).animate({
					height: bars[i].height
				}, 0);
				// Wait the specified time then run the displayGraph() function again for the next bar
				barTimer = setTimeout(function() {
					i++;
					displayGraph(bars, i);
				}, 0);
			}
		}

		// Reset graph settings and prepare for display
		function resetGraph() {
			// Stop all animations and set bar height to 0
			$.each(bars, function(i) {
				$(bars[i].bar).stop().css('height', 0);
			});

			// Clear timers
			clearTimeout(barTimer);
			clearTimeout(graphTimer);

			// Restart timer
			graphTimer = setTimeout(function() {
				displayGraph(bars, 0);
			}, 0);
		}

		// Helper functions

		// Call resetGraph() when button is clicked to start graph over
		$('#reset-graph-button').click(function() {
			resetGraph();
			return false;
		});

		// Finally, display graph via reset function
		resetGraph();
	}
});


text:
package net.jgp.labs.spark.l600_ml.l300_gradient_boosted_tree;

import org.apache.spark.ml.evaluation.RegressionEvaluator;
import org.apache.spark.ml.feature.VectorIndexer;
import org.apache.spark.ml.feature.VectorIndexerModel;
import org.apache.spark.ml.linalg.Vector;
import org.apache.spark.ml.linalg.Vectors;
import org.apache.spark.ml.regression.GBTRegressionModel;
import org.apache.spark.ml.regression.GBTRegressor;
import org.apache.spark.sql.Dataset;
import org.apache.spark.sql.Row;
import org.apache.spark.sql.SparkSession;

/**
 * Inspired by Apache Spark's example.
 *
 * @author jgp
 */
public class GradientBoostedTreeRegressorApp {
  public static void main(String[] args) {
    SparkSession spark = SparkSession
      .builder()
      .appName("GradientBoostedTreeRegressorApp")
      .master("local[*]")
      .getOrCreate();

    // Load and parse the data file, converting it to a DataFrame.
    Dataset<Row> df = spark.read().format("libsvm").load("data/sample-ml/simplegauss.txt");

    // Automatically identify categorical features, and index them.
    // Set maxCategories so features with > 4 distinct values are treated as continuous.
    VectorIndexerModel featureIndexer = new VectorIndexer()
      .setInputCol("features")
      .setOutputCol("indexedFeatures")
      .setMaxCategories(4)
      .fit(df);

    // Train a GBT model
    GBTRegressor gbt = new GBTRegressor()
      .setLabelCol("label")
      .setFeaturesCol("features")
      .setMaxIter(100)
      ;

    // Train model
    GBTRegressionModel model = gbt.fit(df);

    // Make predictions
    Dataset<Row> predictions = model.transform(df);

    // Select example rows to display
    predictions.show(20, false);

    // Select (prediction, true label) and compute test error.
    RegressionEvaluator evaluator = new RegressionEvaluator()
      .setLabelCol("label")
      .setPredictionCol("prediction")
      .setMetricName("rmse");
    double rmse = evaluator.evaluate(predictions);
    System.out.println("Root Mean Squared Error (RMSE) on test data = " + rmse);

    System.out.println("Learned regression GBT model:\n" + model.toDebugString());

    Double feature = 2.0;
    Vector features = Vectors.dense(feature);
    double p = model.predict(features);
    System.out.println("Prediction for feature " + feature + " is " + p +
        " (expected: 2)");

    feature = 11.0;
    features = Vectors.dense(feature);
    p = model.predict(features);
    System.out.println("Prediction for feature " + feature + " is " + p +
        " (expected: 2)");

    spark.stop();
  }
}


text:
package evg.tests.appmanager;

import evg.tests.model.ContactData1;
import evg.tests.model.ContactData2;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.Select;
import org.testng.Assert;

public class ContactHelper extends HelperBase {

  public ContactHelper(WebDriver wd) {
    super(wd);
  }

  public void fillContactForm(ContactData1 contactData1) {
    type(By.name("address"), contactData1.getAddress());
  }

  public void fillContactForm2(ContactData2 contactData2, boolean creation) {
    type(By.name("email"), contactData2.getEmail());
    type(By.name("lastname"), contactData2.getLastname());
    type(By.name("middlename"), contactData2.getMiddlename());
    type(By.name("nickname"), contactData2.getNickname());
    type(By.name("address"), contactData2.getAddress());

    if (creation) {
      new Select(wd.findElement(By.name("new_group"))).selectByVisibleText(contactData2.getGroup());
    } else {
      Assert.assertFalse(isElementPresent(By.name("new_group")));
    }
  }

  public void initNextPageContactCreation() {
    click(By.xpath("//div[@id='content']/form/input[1]"));
  }

  public void initSubmitContactCreation() {
    click(By.name("submit"));
  }

  public void initContactModification() {
    click(By.xpath("//table[@id='maintable']/tbody/tr[2]/td[8]/a/img"));
  }

  public void initSubmitContactModification() {
    click(By.name("update"));
  }

  public void createContact1(ContactData1 contact) {
    gotoContactCreation();
    fillContactForm(contact);
    initNextPageContactCreation();
    initSubmitContactCreation();
    returnToHomePage();
  }

  public void returnToHomePage() {
    click(By.linkText("Главная"));
  }

  public void selectContact() {

    click(By.name("selected[]"));
  }

  public boolean isThereAContact() {
    return isElementPresent(By.xpath("//table[@id='maintable']/tbody/tr[2]/td[8]/a/img"));
  }
}


text:
module PrisonParser
  class Node
    attr_reader :nodes
    attr_reader :properties
    attr_reader :label

    def initialize(label=nil)
      @label = label
      @nodes = Hash.new
      @properties = Hash.new
      @allow_inline = true
    end

    def allow_inline?
      @allow_inline
    end

    def prevent_inlining!
      @allow_inline = false
    end

    def inspect
      str = StringIO.new("")
      str.write "<#{label} "
      str.write properties.entries.map { |e| "#{e[0]}=#{e[1].inspect}" }.join(", ")
      str.write ">"
      str.string
    end

    # ReadKey, PushProperty
    def add_property(key, value)
      return if key == "BEGIN" || key == "END"
      if properties[key]
        if properties[key].is_a?(Array)
          @properties[key] << value
        else
          @properties[key] = [properties[key], value]
        end
      else
        @properties[key] = value
      end
    end

    def create_node(node_label)
      node = get_node_class(node_label).new(node_label)
      if nodes.has_key?(node_label)
        if nodes[node_label].is_a?(Array)
          @nodes[node_label] << node
        else
          @nodes[node_label] = [nodes[node_label], node]
        end
      else
        @nodes[node_label] = node
      end
      node
    end

    def finished_reading_node(node)
      # do nothing
    end

    # Equality

    def eql?(other)
      # quick check:
        # make sure property keys are the same
        # make sure node labels are equal

      # Semi deep: compare the properties

      # DEEP:
        # Compare the nodes

      return false unless other.is_a?(Node)

      # Check properties
      return false unless properties.eql?(other.properties)

      # Check node labels
      node_labels = nodes.values.map(&:label).sort
      other_labels = other.nodes.values.map(&:label).sort

      # Quick check to ensure both have the same labels
      return false unless node_labels.eql?(other_labels)

      # Compare all the nodes
      nodes.each_key do |node_key|
        return false unless nodes[node_key].eql?(other.nodes[node_key])
      end

      return true
    end

    alias_method :==, :eql?

    # WRITING

    def write_nodes(writer)
      nodes.values.each do |node|
        if node.is_a?(Array)
          node.map { |n| writer.write_node(n) }
        else
          writer.write_node(node)
        end
      end
    end

    def write_properties(writer)
      properties.each_pair do |k,value|
        if value.is_a?(Array)
          value.map { |v| writer.write_property(k, v) }
        else
          writer.write_property(k, value)
        end
      end
    end

    # For accessing properties/nodes
    def [](key)
      if properties.has_key?(key)
        properties[key]
      elsif nodes.has_key?(key)
        nodes[key]
      else
        nil
      end
    end

    def method_missing(name, *args, &block)
      if properties.has_key?(name.to_s) || nodes.has_key?(name.to_s)
        self[name.to_s]
      else
        super
      end
    end

    # Class methods
    class << self

      # Specifies a specialized class to be used for nodes with a specific label
      #
      # @example
      #   class Prison < Node
      #     node_class :Finance, PrisonParser::Models::Finance
      #   end
      #
      # @param label [String,Symbol] The label value that should use the specified class
      # @param klass [Class] The class that the node should use. This should inherit from {PrisonParser::Node}
      # @param options [Hash] Additional options
      # @option options [Boolean] :multiple
      #
      # @return [void]
      def node_class(label, klass, options={})
        node_classes["#{label}"] = klass
      end

      def node_classes
        @node_classes ||= Hash.new
      end
    end

    protected

    def get_node_class(lbl)
      if self.class.node_classes.has_key?(lbl)
        self.class.node_classes[lbl]
      else
        PrisonParser::Node
      end
    end

  end
end


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>bcml package — BioCompoundML 1a documentation</title>

    <link rel="stylesheet" href="_static/alabaster.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />

    <link rel="top" title="BioCompoundML 1a documentation" href="index.html" />

  <meta name="viewport" content="width=device-width, initial-scale=0.9, maximum-scale=0.9" />

bcml package¶

Subpackages¶

bcml.Analytics package

Submodules

bcml.Analytics.cluster module

bcml.Analytics.cross_validate module

Module contents

bcml.Boruta package

Subpackages

bcml.Boruta.test package

Submodules

bcml.Boruta.test.unit_tests module

Module contents

Submodules

bcml.Boruta.boruta_py module

bcml.Boruta.setup module

Module contents

bcml.Chemoinformatics package

Subpackages

bcml.Chemoinformatics.tests package

Submodules

bcml.Chemoinformatics.tests.chemofeatures_tests module

bcml.Chemoinformatics.tests.experimental_tests module

bcml.Chemoinformatics.tests.fingerprint_tests module

bcml.Chemoinformatics.tests.user_tests module

Module contents

Submodules

bcml.Chemoinformatics.chemofeatures module

bcml.Chemoinformatics.experimental module

bcml.Chemoinformatics.fingerprints module

bcml.Chemoinformatics.user module

Module contents

bcml.Distance package

Subpackages

bcml.Distance.tests package

Submodules

bcml.Distance.tests.distance_tests module

Module contents

Submodules

bcml.Distance.distance module

Module contents

bcml.KNNImpute package

Subpackages

bcml.KNNImpute.knnimpute package

Submodules

bcml.KNNImpute.knnimpute.argpartition module

bcml.KNNImpute.knnimpute.common module

bcml.KNNImpute.knnimpute.few_observed_entries module

bcml.KNNImpute.knnimpute.normalized_distance module

bcml.KNNImpute.knnimpute.optimistic module

bcml.KNNImpute.knnimpute.reference module

Module contents

Module contents

bcml.Parser package

Submodules

bcml.Parser.build_testing module

bcml.Parser.build_training module

bcml.Parser.read_testing module

bcml.Parser.read_training module

Module contents

bcml.PubChemUtils package

Subpackages

bcml.PubChemUtils.tests package

Submodules

bcml.PubChemUtils.tests.pubchempy_utils_tests module

Module contents

Submodules

bcml.PubChemUtils.pubchempy_utils module

Module contents

bcml.Train package

Submodules

bcml.Train.train_model module

Module contents

bcml.tests package

Submodules

bcml.tests.bcml_tests module

Module contents

Submodules¶

bcml.bcml module¶

Module contents¶

Table Of Contents

bcml package

Subpackages

Submodules

bcml.bcml module

Module contents

Related Topics

Documentation overview

This Page

Show Source

Quick search

    <form class="search" action="search.html" method="get">

<input type="text" name="q" />

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

      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

      ©2016, Sandia National Laboratories.

      |
      Powered by Sphinx 1.4.5
      & Alabaster 0.7.7

      |
      Page source


text:
var Immutable = require('immutable');
var parseOrders = require('./parse_orders');

var OrdersFetcher = {
  fetch() {
    return fetch('http://localhost:8000/orders.json')
      .then((resp) => resp.json())
      .then(parseOrders)
      .then((orders) => Immutable.fromJS(orders));
  }
};

module.exports = OrdersFetcher;


text:
package org.gbougeard.model.changes

/**
 * Created with IntelliJ IDEA.
 * User: gbougeard
 * Date: 13/07/13
 * Time: 21:08
 * To change this template use File | Settings | File Templates.
 */
case class ReviewInfo(labels:Map[String, String])

object ReviewInfo {

  import play.api.libs.json.Json
  import play.api.libs.functional.syntax._

  implicit val format = Json.format[ReviewInfo]
}


text:
package com.google.ads.googleads.v12.enums;

public interface ContentLabelTypeEnumOrBuilder extends
    // @@protoc_insertion_point(interface_extends:google.ads.googleads.v12.enums.ContentLabelTypeEnum)
    com.google.protobuf.MessageOrBuilder {
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>br.com.thiaguten.json</groupId>
    <artifactId>json-parse-helper</artifactId>
    <version>1.0.0-SNAPSHOT</version>

    <name>JsonParseHelper</name>
    <description>Helper MongoDB BSON strict/shell mode to 'standard' JSON format</description>
    <url>https://github.com/thiaguten/simple-dao</url>

    <inceptionYear>2016</inceptionYear>

    <licenses>
        <license>
            <name>The Apache Software License, Version 2.0</name>
            <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
            <distribution>repo</distribution>
        </license>
    </licenses>

    <organization>
        <name>Thiago Gutenberg Carvalho da Costa</name>
        <url>http://www.thiaguten.com.br</url>
    </organization>

    <developers>
        <developer>
            <id>thiaguten</id>
            <name>Thiago Gutenberg Carvalho da Costa</name>
            <email>thiaguten@gmail.com</email>
            <url>http://www.thiaguten.com.br</url>
            <roles>
                <role>architect</role>
                <role>developer</role>
            </roles>
            <timezone>America/Sao_Paulo</timezone>
        </developer>
    </developers>

    <scm>
        <connection>scm:git:git@github.com:thiaguten/json-parse-helper.git</connection>
        <developerConnection>scm:git@github.com:thiaguten/json-parse-helper.git</developerConnection>
        <url>git@github.com:thiaguten/json-parse-helper.git</url>
        <tag>HEAD</tag>
    </scm>

    <build>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.6.0</version>
                <configuration>
                    <source>${java.version}</source>
                    <target>${java.version}</target>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-source-plugin</artifactId>
                <version>3.0.1</version>
                <executions>
                    <execution>
                        <id>attach-sources</id>
                        <phase>verify</phase>
                        <goals>
                            <goal>jar-no-fork</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <artifactId>maven-javadoc-plugin</artifactId>
                <version>2.10.4</version>
                <configuration>
                    <show>public</show>
                    <maxmemory>1024m</maxmemory>
                </configuration>
                <executions>
                    <execution>
                        <id>attach-javadocs</id>
                        <phase>package</phase>
                        <goals>
                            <goal>jar</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>license-maven-plugin</artifactId>
                <version>1.10</version>
                <configuration>
                    <verbose>false</verbose>
                    <addSvnKeyWords>false</addSvnKeyWords>
                    <addJavaLicenseAfterPackage>false</addJavaLicenseAfterPackage>
                </configuration>
                <executions>
                    <execution>
                        <id>first</id>
                        <goals>
                            <goal>update-file-header</goal>
                        </goals>
                        <phase>process-sources</phase>
                        <configuration>
                            <licenseName>apache_v2</licenseName>
                            <excludes>
                                <exclude>**/*.xml</exclude>
                                <exclude>**/*.xsd</exclude>
                            </excludes>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.jacoco</groupId>
                <artifactId>jacoco-maven-plugin</artifactId>
                <version>0.7.7.201606060606</version>
                <configuration>
                    <destFile>${project.reporting.outputDirectory}/jacoco-unit.exec</destFile>
                    <dataFile>${project.reporting.outputDirectory}/jacoco-unit.exec</dataFile>
                </configuration>
                <executions>
                    <execution>
                        <id>jacoco-initialize</id>
                        <goals>
                            <goal>prepare-agent</goal>
                        </goals>
                    </execution>
                    <execution>
                        <id>jacoco-site</id>
                        <phase>package</phase>
                        <goals>
                            <goal>report</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.eluder.coveralls</groupId>
                <artifactId>coveralls-maven-plugin</artifactId>
                <version>4.3.0</version>
            </plugin>
        </plugins>
    </build>

    <dependencies>
        <dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>bson</artifactId>
            <version>${bson.version}</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <properties>
        <java.version>1.8</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <bson.version>3.3.0</bson.version>
        <junit.version>4.12</junit.version>
    </properties>

</project>


text:
id: 27-HTMLTemplate-notes
author: matthew
title: 'HTML::Template notes'
draft: false
public: true
created: '2004-02-05T20:18:20-05:00'
updated: '2004-09-20T13:44:23-04:00'
tags:
    - programming
    - perl
    - personal
---
I've used `HTML::Template` a little, mainly in the Secret Santa project I did
this past Christmas for my wife's family. One thing I disliked was using the
normal syntax: `<TMPL_VAR NAME=IMAGE_SRC>` — it made looking at it difficult (it
wasn't always easy to tell what was an HTML tag, what was plain text, and what
was `HTML::Template` stuff), and it made it impossible to validate my pages
before they had data.

Fortunately, there's an alternate syntax: wrap the syntax in HTML comments:
`<!-- TMPL_VAR NAME=IMAGE_SRC -->` does the job. It uses more characters, true,
but it gets highlighted different than HTML tags, as well, and that's worth a
lot.

And why do I have to say "NAME=" every time? That gets annoying. As it turns
out, I can simply say: `<!-- TMPL_VAR IMAGE_SRC -->`, and that, too will get the
job done.

Finally, what about those times when I want to define a template, but have it
broken into parts, too? Basically, I want `HTML::Template` to behave a little
like SSI. No worries; there's a `TMPL_INCLUDE` tag that can do this: `<!--
TMPL_INCLUDE NAME="filename.tmpl" -->`.


text:
module Replicate
  # Dump replicants in a streaming fashion.
  #
  # The Dumper takes objects and generates one or more replicant objects. A
  # replicant has the form [type, id, attributes] and describes exactly one
  # addressable record in a datastore. The type and id identify the model
  # class name and model primary key id. The attributes Hash is a set of attribute
  # name to primitively typed object value mappings.
  #
  # Example dump session:
  #
  #     >> Replicate::Dumper.new do |dumper|
  #     >>   dumper.marshal_to $stdout
  #     >>   dumper.log_to $stderr
  #     >>   dumper.dump User.find(1234)
  #     >> end
  #
  class Dumper < Emitter
    # Create a new Dumper.
    #
    # io     - IO object to write marshalled replicant objects to.
    # block  - Dump context block. If given, the end of the block's execution
    #          is assumed to be the end of the dump stream.
    def initialize(io=nil)
      @memo = Hash.new { |hash,k| hash[k] = {} }
      super() do
        marshal_to io if io
        yield self if block_given?
      end
    end

    # Register a filter to write marshalled data to the given IO object.
    def marshal_to(io)
      listen { |type, id, attrs, obj| Marshal.dump([type, id, attrs], io) }
    end

    # Register a filter to write status information to the given stream. By
    # default, a single line is used to report object counts while the dump is
    # in progress; dump counts for each class are written when complete. The
    # verbose and quiet options can be used to increase or decrease
    # verbosity.
    #
    # out - An IO object to write to, like stderr.
    # verbose - Whether verbose output should be enabled.
    # quiet - Whether quiet output should be enabled.
    #
    # Returns the Replicate::Status object.
    def log_to(out=$stderr, verbose=false, quiet=false)
      use Replicate::Status, 'dump', out, verbose, quiet
    end

    # Load a dump script. This evals the source of the file in the context
    # of a special object with a #dump method that forwards to this instance.
    # Dump scripts are useful when you want to dump a lot of stuff. Call the
    # dump method as many times as necessary to dump all objects.
    def load_script(path)
      dumper = self
      object = ::Object.new
      meta = (class<<object;self;end)
      [:dump, :load_script].each do |method|
        meta.send(:define_method, method) { |*args| dumper.send(method, *args) }
      end
      file = find_file(path)
      object.instance_eval File.read(file), file, 0
    end

    # Dump one or more objects to the internal array or provided dump
    # stream. This method guarantees that the same object will not be dumped
    # more than once.
    #
    # objects - ActiveRecord object instances.
    #
    # Returns nothing.
    def dump(*objects)
      opts = if objects.last.is_a? Hash
        objects.pop
      else
        {}
      end
      objects = objects[0] if objects.size == 1 && objects[0].respond_to?(:to_ary)
      objects.each do |object|
        next if object.nil? || dumped?(object)
        if object.respond_to?(:dump_replicant)
          args = [self]
          args << opts unless object.method(:dump_replicant).arity == 1
          object.dump_replicant(*args)
        else
          raise NoMethodError, "#{object.class} must respond to #dump_replicant"
        end
      end
    end

    # Check if object has been written yet.
    def dumped?(object)
      if object.respond_to?(:replicant_id)
        type, id = object.replicant_id
      elsif object.is_a?(Array)
        type, id = object
      else
        return false
      end
      @memo[type.to_s][id]
    end

    # Called exactly once per unique type and id. Emits to all listeners.
    #
    # type       - The model class name as a String.
    # id         - The record's id. Usually an integer.
    # attributes - All model attributes.
    # object     - The object this dump is generated for.
    #
    # Returns the object.
    def write(type, id, attributes, object)
      type = type.to_s
      return if dumped?([type, id])
      @memo[type][id] = true

      emit type, id, attributes, object
    end

    # Retrieve dumped object counts for all classes.
    #
    # Returns a Hash of { class_name => count } where count is the number of
    # objects dumped with a class of class_name.
    def stats
      stats = {}
      @memo.each { |class_name, items| stats[class_name] = items.size }
      stats
    end

    protected
    def find_file(path)
      path = "#{path}.rb" unless path =~ /\.rb$/
      return path if File.exists? path
      $LOAD_PATH.each do |prefix|
        full_path = File.expand_path(path, prefix)
        return full_path if File.exists? full_path
      end
      false
    end
  end
end


text:
package com.sphericalelephant.example.sugarorm.entity;

import com.orm.SugarRecord;
import com.orm.dsl.Ignore;

import java.util.Date;

/**
 * Created by siyb on 30/09/15.
 */
public class Person extends SugarRecord<Person> {
	@Ignore
	private boolean ignored;
	private String name;
	private Date birthday;
	private int height;
	// this is everything we need to define a relationship, unfortunately, Many-To-Many and One-To-Many are not supported yet m(
	// https://github.com/satyan/sugar/issues/60
	private EmailAddress email;
	// accesscard relationship (To-One)
	private AccessCard accessCard;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Date getBirthday() {
		return birthday;
	}

	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}

	public int getHeight() {
		return height;
	}

	public void setHeight(int height) {
		this.height = height;
	}

	public EmailAddress getEmail() {
		return email;
	}

	public void setEmail(EmailAddress email) {
		this.email = email;
	}

	public AccessCard getAccessCard() {
		return accessCard;
	}

	public void setAccessCard(AccessCard accessCard) {
		this.accessCard = accessCard;
	}
}


text:
<?php

namespace Akamon\OAuth2\Server\Domain\Service\Client\ClientObtainer;

use Akamon\OAuth2\Server\Domain\Exception\OAuthError\InvalidClientCredentialsOAuthErrorException;
use Akamon\OAuth2\Server\Domain\Model\Client\Client;
use Akamon\OAuth2\Server\Domain\Model\Client\ClientRepositoryInterface;
use Akamon\OAuth2\Server\Domain\Service\Client\ClientCredentialsObtainer\ClientCredentialsObtainerInterface;
use Symfony\Component\HttpFoundation\Request;

class AuthenticatedClientObtainer implements ClientObtainerInterface
{
    private $credentialsObtainer;
    private $repository;

    public function __construct(ClientCredentialsObtainerInterface $credentialsObtainer, ClientRepositoryInterface $repository)
    {
        $this->credentialsObtainer = $credentialsObtainer;
        $this->repository = $repository;
    }

    /**
     * @return Client
     */
    public function getClient(Request $request)
    {
        $credentials = $this->credentialsObtainer->getClientCredentials($request);
        $client = $this->repository->find($credentials->getId());

        if (is_null($client) || !($client->checkSecret($credentials->getSecret()))) {
            throw new InvalidClientCredentialsOAuthErrorException();
        }

        return $client;
    }
}