from __future__ import unicode_literals

import frappe
from frappe import _
import frappe.permissions
import re, csv, os
from frappe.utils.csvutils import UnicodeWriter
from frappe.utils import cstr, formatdate, format_datetime, parse_json, cint, format_duration
from frappe.core.doctype.data_import_legacy.importer import get_data_keys
from six import string_types
from frappe.core.doctype.access_log.access_log import make_access_log

reflags = {
	"I":re.I,
	"L":re.L,
	"M":re.M,
	"U":re.U,
	"S":re.S,
	"X":re.X,
	"D": re.DEBUG
}

@frappe.whitelist()
def export_data(doctype=None, parent_doctype=None, all_doctypes=True, with_data=False,
		select_columns=None, file_type='CSV', template=False, filters=None):
	_doctype = doctype
	if isinstance(_doctype, list):
		_doctype = _doctype[0]
	make_access_log(doctype=_doctype, file_type=file_type, columns=select_columns, filters=filters, method=parent_doctype)
	exporter = DataExporter(doctype=doctype, parent_doctype=parent_doctype, all_doctypes=all_doctypes, with_data=with_data,
		select_columns=select_columns, file_type=file_type, template=template, filters=filters)
	exporter.build_response()

class DataExporter:
	def __init__(self, doctype=None, parent_doctype=None, all_doctypes=True, with_data=False,
		select_columns=None, file_type='CSV', template=False, filters=None):
		self.doctype = doctype
		self.parent_doctype = parent_doctype
		self.all_doctypes = all_doctypes
		self.with_data = cint(with_data)
		self.select_columns = select_columns
		self.file_type = file_type
		self.template = template
		self.filters = filters
		self.data_keys = get_data_keys()

		self.prepare_args()

	def prepare_args(self):
		if self.select_columns:
			self.select_columns = parse_json(self.select_columns)
		if self.filters:
			self.filters = parse_json(self.filters)

		self.docs_to_export = {}
		if self.doctype:
			if isinstance(self.doctype, string_types):
				self.doctype = [self.doctype]

			if len(self.doctype) > 1:
				self.docs_to_export = self.doctype[1]
			self.doctype = self.doctype[0]

		if not self.parent_doctype:
			self.parent_doctype = self.doctype

		self.column_start_end = {}

		if self.all_doctypes:
			self.child_doctypes = []
			for df in frappe.get_meta(self.doctype).get_table_fields():
				self.child_doctypes.append(dict(doctype=df.options, parentfield=df.fieldname))

	def build_response(self):
		self.writer = UnicodeWriter()
		self.name_field = 'parent' if self.parent_doctype != self.doctype else 'name'

		if self.template:
			self.add_main_header()

		self.writer.writerow([''])
		self.tablerow = [self.data_keys.doctype]
		self.labelrow = [_("Column Labels:")]
		self.fieldrow = [self.data_keys.columns]
		self.mandatoryrow = [_("Mandatory:")]
		self.typerow = [_('Type:')]
		self.inforow = [_('Info:')]
		self.columns = []

		self.build_field_columns(self.doctype)

		if self.all_doctypes:
			for d in self.child_doctypes:
				self.append_empty_field_column()
				if (self.select_columns and self.select_columns.get(d['doctype'], None)) or not self.select_columns:
					# if atleast one column is selected for this doctype
					self.build_field_columns(d['doctype'], d['parentfield'])

		self.add_field_headings()
		self.add_data()
		if self.with_data and not self.data:
			frappe.respond_as_web_page(_('No Data'), _('There is no data to be exported'), indicator_color='orange')

		if self.file_type == 'Excel':
			self.build_response_as_excel()
		else:
			# write out response as a type csv
			frappe.response['result'] = cstr(self.writer.getvalue())
			frappe.response['type'] = 'csv'
			frappe.response['doctype'] = self.doctype

	def add_main_header(self):
		self.writer.writerow([_('Data Import Template')])
		self.writer.writerow([self.data_keys.main_table, self.doctype])

		if self.parent_doctype != self.doctype:
			self.writer.writerow([self.data_keys.parent_table, self.parent_doctype])
		else:
			self.writer.writerow([''])

		self.writer.writerow([''])
		self.writer.writerow([_('Notes:')])
		self.writer.writerow([_('Please do not change the template headings.')])
		self.writer.writerow([_('First data column must be blank.')])
		self.writer.writerow([_('If you are uploading new records, leave the "name" (ID) column blank.')])
		self.writer.writerow([_('If you are uploading new records, "Naming Series" becomes mandatory, if present.')])
		self.writer.writerow([_('Only mandatory fields are necessary for new records. You can delete non-mandatory columns if you wish.')])
		self.writer.writerow([_('For updating, you can update only selective columns.')])
		self.writer.writerow([_('You can only upload upto 5000 records in one go. (may be less in some cases)')])
		if self.name_field == "parent":
			self.writer.writerow([_('"Parent" signifies the parent table in which this row must be added')])
			self.writer.writerow([_('If you are updating, please select "Overwrite" else existing rows will not be deleted.')])

	def build_field_columns(self, dt, parentfield=None):
		meta = frappe.get_meta(dt)

		# build list of valid docfields
		tablecolumns = []
		table_name = 'tab' + dt
		for f in frappe.db.get_table_columns_description(table_name):
			field = meta.get_field(f.name)
			if field and ((self.select_columns and f.name in self.select_columns[dt]) or not self.select_columns):
				tablecolumns.append(field)

		tablecolumns.sort(key = lambda a: int(a.idx))

		_column_start_end = frappe._dict(start=0)

		if dt==self.doctype:
			if (meta.get('autoname') and meta.get('autoname').lower()=='prompt') or (self.with_data):
				self._append_name_column()

			# if importing only child table for new record, add parent field
			if meta.get('istable') and not self.with_data:
				self.append_field_column(frappe._dict({
					"fieldname": "parent",
					"parent": "",
					"label": "Parent",
					"fieldtype": "Data",
					"reqd": 1,
					"info": _("Parent is the name of the document to which the data will get added to.")
				}), True)

			_column_start_end = frappe._dict(start=0)
		else:
			_column_start_end = frappe._dict(start=len(self.columns))

			if self.with_data:
				self._append_name_column(dt)

		for docfield in tablecolumns:
			self.append_field_column(docfield, True)

		# all non mandatory fields
		for docfield in tablecolumns:
			self.append_field_column(docfield, False)

		# if there is one column, add a blank column (?)
		if len(self.columns)-_column_start_end.start == 1:
			self.append_empty_field_column()

		# append DocType name
		self.tablerow[_column_start_end.start + 1] = dt

		if parentfield:
			self.tablerow[_column_start_end.start + 2] = parentfield

		_column_start_end.end = len(self.columns) + 1

		self.column_start_end[(dt, parentfield)] = _column_start_end

	def append_field_column(self, docfield, for_mandatory):
		if not docfield:
			return
		if for_mandatory and not docfield.reqd:
			return
		if not for_mandatory and docfield.reqd:
			return
		if docfield.fieldname in ('parenttype', 'trash_reason'):
			return
		if docfield.hidden:
			return
		if self.select_columns and docfield.fieldname not in self.select_columns.get(docfield.parent, []) \
			and docfield.fieldname!="name":
			return

		self.tablerow.append("")
		self.fieldrow.append(docfield.fieldname)
		self.labelrow.append(_(docfield.label))
		self.mandatoryrow.append(docfield.reqd and 'Yes' or 'No')
		self.typerow.append(docfield.fieldtype)
		self.inforow.append(self.getinforow(docfield))
		self.columns.append(docfield.fieldname)

	def append_empty_field_column(self):
		self.tablerow.append("~")
		self.fieldrow.append("~")
		self.labelrow.append("")
		self.mandatoryrow.append("")
		self.typerow.append("")
		self.inforow.append("")
		self.columns.append("")

	@staticmethod
	def getinforow(docfield):
		"""make info comment for options, links etc."""
		if docfield.fieldtype == 'Select':
			if not docfield.options:
				return ''
			else:
				return _("One of") + ': %s' % ', '.join(filter(None, docfield.options.split('\n')))
		elif docfield.fieldtype == 'Link':
			return 'Valid %s' % docfield.options
		elif docfield.fieldtype == 'Int':
			return 'Integer'
		elif docfield.fieldtype == "Check":
			return "0 or 1"
		elif docfield.fieldtype in ["Date", "Datetime"]:
			return cstr(frappe.defaults.get_defaults().date_format)
		elif hasattr(docfield, "info"):
			return docfield.info
		else:
			return ''

	def add_field_headings(self):
		self.writer.writerow(self.tablerow)
		self.writer.writerow(self.labelrow)
		self.writer.writerow(self.fieldrow)
		self.writer.writerow(self.mandatoryrow)
		self.writer.writerow(self.typerow)
		self.writer.writerow(self.inforow)
		if self.template:
			self.writer.writerow([self.data_keys.data_separator])

	def add_data(self):
		if self.template and not self.with_data:
			return

		frappe.permissions.can_export(self.parent_doctype, raise_exception=True)

		# sort nested set doctypes by `lft asc`
		order_by = None
		table_columns = frappe.db.get_table_columns(self.parent_doctype)
		if 'lft' in table_columns and 'rgt' in table_columns:
			order_by = '`tab{doctype}`.`lft` asc'.format(doctype=self.parent_doctype)
		# get permitted data only
		self.data = frappe.get_list(self.doctype, fields=["*"], filters=self.filters, limit_page_length=None, order_by=order_by)

		for doc in self.data:
			op = self.docs_to_export.get("op")
			names = self.docs_to_export.get("name")

			if names and op:
				if op == '=' and doc.name not in names:
					continue
				elif op == '!=' and doc.name in names:
					continue
			elif names:
				try:
					sflags = self.docs_to_export.get("flags", "I,U").upper()
					flags = 0
					for a in re.split('\W+',sflags):
						flags = flags | reflags.get(a,0)

					c = re.compile(names, flags)
					m = c.match(doc.name)
					if not m:
						continue
				except Exception:
					if doc.name not in names:
						continue
			# add main table
			rows = []

			self.add_data_row(rows, self.doctype, None, doc, 0)

			if self.all_doctypes:
				# add child tables
				for c in self.child_doctypes:
					for ci, child in enumerate(frappe.db.sql("""select * from `tab{0}`
						where parent=%s and parentfield=%s order by idx""".format(c['doctype']),
						(doc.name, c['parentfield']), as_dict=1)):
						self.add_data_row(rows, c['doctype'], c['parentfield'], child, ci)

			for row in rows:
				self.writer.writerow(row)

	def add_data_row(self, rows, dt, parentfield, doc, rowidx):
		d = doc.copy()
		meta = frappe.get_meta(dt)
		if self.all_doctypes:
			d.name = '"'+ d.name+'"'

		if len(rows) < rowidx + 1:
			rows.append([""] * (len(self.columns) + 1))
		row = rows[rowidx]

		_column_start_end = self.column_start_end.get((dt, parentfield))

		if _column_start_end:
			for i, c in enumerate(self.columns[_column_start_end.start:_column_start_end.end]):
				df = meta.get_field(c)
				fieldtype = df.fieldtype if df else "Data"
				value = d.get(c, "")
				if value:
					if fieldtype == "Date":
						value = formatdate(value)
					elif fieldtype == "Datetime":
						value = format_datetime(value)
					elif fieldtype == "Duration":
						value = format_duration(value, df.hide_days)

				row[_column_start_end.start + i + 1] = value

	def build_response_as_excel(self):
		filename = frappe.generate_hash("", 10)
		with open(filename, 'wb') as f:
			f.write(cstr(self.writer.getvalue()).encode('utf-8'))
		f = open(filename)
		reader = csv.reader(f)

		from frappe.utils.xlsxutils import make_xlsx
		xlsx_file = make_xlsx(reader, "Data Import Template" if self.template else 'Data Export')

		f.close()
		os.remove(filename)

		# write out response as a xlsx type
		frappe.response['filename'] = self.doctype + '.xlsx'
		frappe.response['filecontent'] = xlsx_file.getvalue()
		frappe.response['type'] = 'binary'

	def _append_name_column(self, dt=None):
		self.append_field_column(frappe._dict({
			"fieldname": "name" if dt else self.name_field,
			"parent": dt or "",
			"label": "ID",
			"fieldtype": "Data",
			"reqd": 1,
		}), True)


#include "stdafx.h"

int _tmain(int argc, _TCHAR* argv[])
{
	printf("nf1_init.exe [command] [setting]\r\n");
	printf("Commands:\r\n");
	printf("test [device serial number] - runs bitfury tests to that device\r\n");
	printf("fixID [ignored] - Tests for NanoFury devices and fixes Product String\r\n\r\n");

	switch(argc){
		case 2:
			if (wcscmp(argv[1],L"fixID")==0){
				printf("fixID mode specified.\r\n\r\n");
				spi_init(NULL, L"NanoFury NF1 v0.6");
				printf("\r\nfixID mode completed. Please run command again to read new values.\r\n\r\n");
			}
		case 3:
			if (wcscmp(argv[1],L"test")==0){
				printf("test mode specified for device %s.\r\n\r\n", argv[2]);
				if (spi_init(argv[2], NULL)){
					printf("DEVICE FOUND! Proceeding with testing... Press ESC to cancel testing at any time\r\n\r\n", argv[3]);
					spitest_main(osc50);
					nanofury_device_off(hndNanoFury);
					ReleaseMCP2210(hndNanoFury);
				}
				else{
					printf("Device not found. No tests have been performed.\r\n\r\n");
				}

			}
		case 4:
			if (wcscmp(argv[1],L"test")==0){
				int n = _wtoi(argv[3]);
				if ((n<48)||(n>56)) n=48;
				printf("test mode specified for device %s with %u bit speed.\r\n\r\n", argv[2], n);
				if (spi_init(argv[2], NULL)){
					printf("DEVICE FOUND! Proceeding with testing... Press ESC to cancel testing at any time\r\n\r\n", argv[3]);
					switch (n){
						case 49: spitest_main(osc49); break;
						case 50: spitest_main(osc50); break;
						case 51: spitest_main(osc51); break;
						case 52: spitest_main(osc52); break;
						case 53: spitest_main(osc53); break;
						case 54: spitest_main(osc54); break;
						case 55: spitest_main(osc55); break;
						case 56: spitest_main(osc56); break;
						default: spitest_main(osc48); break;
					}
					nanofury_device_off(hndNanoFury);
					ReleaseMCP2210(hndNanoFury);
				}
				else{
					printf("Device not found. No tests have been performed.\r\n\r\n");
				}

			}
			break;
	default: spi_init(NULL, NULL);
	}

	//spi_init(true, L"NanoFury NF1 v0.6");
	//spi_init(true, NULL);

	printf("Press [ENTER] to exit...");
	getchar();

	return 0;
}


//Copyright (C) Microsoft Corporation.  All rights reserved.

// explicit1.cs
interface IDimensions
{
   float Length();
   float Width();
}

class Box : IDimensions
{
   float lengthInches;
   float widthInches;

   public Box(float length, float width)
   {
      lengthInches = length;
      widthInches = width;
   }
   // Explicit interface member implementation:
   float IDimensions.Length()
   {
      return lengthInches;
   }
   // Explicit interface member implementation:
   float IDimensions.Width()
   {
      return widthInches;
   }

   public static void Main()
   {
      // Declare a class instance "myBox":
      Box myBox = new Box(30.0f, 20.0f);
      // Declare an interface instance "myDimensions":
      IDimensions myDimensions = (IDimensions) myBox;
      // Print out the dimensions of the box:
      /* The following commented lines would produce compilation
         errors because they try to access an explicitly implemented
         interface member from a class instance:                   */
      //System.Console.WriteLine("Length: {0}", myBox.Length());
      //System.Console.WriteLine("Width: {0}", myBox.Width());
      /* Print out the dimensions of the box by calling the methods
         from an instance of the interface:                         */
      System.Console.WriteLine("Length: {0}", myDimensions.Length());
      System.Console.WriteLine("Width: {0}", myDimensions.Width());
   }
}


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

<title>Uses of Class net.floodlightcontroller.packet.BPDU</title>
<meta name="date" content="2015-06-22">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
net.floodlightcontroller.packet.BPDU

No usage of net.floodlightcontroller.packet.BPDU

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


asp-classic-cms
===============

ASP classic and SQL based Content Management System

I first built this CMS in 2007 for a client. I have since moved to Wordpress for the CMS now, so I'm making this CMS available free to use. If you have questions, Google my name and get in touch.


"""Main command line interface for fm_server."""


yii2-widget-sidenav
===================

[![Latest Stable Version](https://poser.pugx.org/kartik-v/yii2-widget-sidenav/v/stable.svg)](https://packagist.org/packages/kartik-v/yii2-widget-sidenav)
[![License](https://poser.pugx.org/kartik-v/yii2-widget-sidenav/license.svg)](https://packagist.org/packages/kartik-v/yii2-widget-sidenav)
[![Total Downloads](https://poser.pugx.org/kartik-v/yii2-widget-sidenav/downloads.svg)](https://packagist.org/packages/kartik-v/yii2-widget-sidenav)
[![Monthly Downloads](https://poser.pugx.org/kartik-v/yii2-widget-sidenav/d/monthly.png)](https://packagist.org/packages/kartik-v/yii2-widget-sidenav)
[![Daily Downloads](https://poser.pugx.org/kartik-v/yii2-widget-sidenav/d/daily.png)](https://packagist.org/packages/kartik-v/yii2-widget-sidenav)

This widget is a collapsible side navigation menu built to seamlessly work with Bootstrap framework. It is built over Bootstrap [stacked nav](http://getbootstrap.com/components/#nav-pills) component. This widget class extends the [Yii Menu widget](https://github.com/yiisoft/yii2/blob/master/framework/widgets/Menu.php). Upto 3 levels of submenus are by default supported by the CSS styles to balance performance and useability. You can choose to extend it to more or less levels by customizing the [CSS](https://github.com/kartik-v/yii2-widgets/blob/master/assets/css/sidenav.css).

> NOTE: This extension is a sub repo split of [yii2-widgets](https://github.com/kartik-v/yii2-widgets). The split has been done since 08-Nov-2014 to allow developers to install this specific widget in isolation if needed. One can also use the extension the previous way with the whole suite of [yii2-widgets](http://demos.krajee.com/widgets).

## Installation

The preferred way to install this extension is through [composer](http://getcomposer.org/download/). Check the [composer.json](https://github.com/kartik-v/yii2-widget-sidenav/blob/master/composer.json) for this extension's requirements and dependencies. Read this [web tip /wiki](http://webtips.krajee.com/setting-composer-minimum-stability-application/) on setting the `minimum-stability` settings for your application's composer.json.

To install, either run

```
$ php composer.phar require kartik-v/yii2-widget-sidenav "*"
```

or add

```
"kartik-v/yii2-widget-sidenav": "*"
```

to the ```require``` section of your `composer.json` file.

## Latest Release

> NOTE: The latest version of the module is v1.0.0 released on 08-Nov-2014. Refer the [CHANGE LOG](https://github.com/kartik-v/yii2-widget-sidenav/blob/master/CHANGE.md) for details.

## Demo

You can refer detailed [documentation and demos](http://demos.krajee.com/widget-details/sidenav) on usage of the extension.

## Usage

```php
use kartik\sidenav\SideNav;

echo SideNav::widget([
	'type' => SideNav::TYPE_DEFAULT,
	'heading' => 'Options',
	'items' => [
		[
			'url' => '#',
			'label' => 'Home',
			'icon' => 'home'
		],
		[
			'label' => 'Help',
			'icon' => 'question-sign',
			'items' => [
				['label' => 'About', 'icon'=>'info-sign', 'url'=>'#'],
				['label' => 'Contact', 'icon'=>'phone', 'url'=>'#'],
			],
		],
	],
]);
```

## License

**yii2-widget-sidenav** is released under the BSD 3-Clause License. See the bundled `LICENSE.md` for details.


struct WebApplicationInfo;

namespace content {
struct LoadCommittedDetails;
}

namespace extensions {
class Extension;
class LocationBarController;
class ScriptBadgeController;
class ScriptBubbleController;

// Per-tab extension helper. Also handles non-extension apps.
class TabHelper : public content::WebContentsObserver,
                  public ExtensionFunctionDispatcher::Delegate,
                  public ImageLoadingTracker::Observer,
                  public AppNotifyChannelSetup::Delegate,
                  public base::SupportsWeakPtr<TabHelper>,
                  public content::NotificationObserver,
                  public content::WebContentsUserData<TabHelper> {
 public:
  // Different types of action when web app info is available.
  // OnDidGetApplicationInfo uses this to dispatch calls.
  enum WebAppAction {
    NONE,             // No action at all.
    CREATE_SHORTCUT,  // Bring up create application shortcut dialog.
    UPDATE_SHORTCUT   // Update icon for app shortcut.
  };

  // Observer base class for classes listening for content script messages
  // from the renderer.
  class ContentScriptObserver {
   public:
    // Map of extensions IDs to the executing script paths.
    typedef std::map<std::string, std::set<std::string> > ExecutingScriptsMap;

    // Automatically observes and unobserves |tab_helper| on construction
    // and destruction. |tab_helper| must outlive |this|.
    explicit ContentScriptObserver(TabHelper* tab_helper);
    ContentScriptObserver();

    virtual void OnContentScriptsExecuting(
        const content::WebContents* web_contents,
        const ExecutingScriptsMap& executing_scripts_map,
        int32 on_page_id,
        const GURL& on_url) = 0;

   protected:
    virtual ~ContentScriptObserver();

    TabHelper* tab_helper_;
  };

  virtual ~TabHelper();

  void AddContentScriptObserver(ContentScriptObserver* observer) {
    content_script_observers_.AddObserver(observer);
  }

  void RemoveContentScriptObserver(ContentScriptObserver* observer) {
    content_script_observers_.RemoveObserver(observer);
  }

  void CreateApplicationShortcuts();
  bool CanCreateApplicationShortcuts() const;

  void set_pending_web_app_action(WebAppAction action) {
    pending_web_app_action_ = action;
  }

  // App extensions ------------------------------------------------------------

  // Sets the extension denoting this as an app. If |extension| is non-null this
  // tab becomes an app-tab. WebContents does not listen for unload events for
  // the extension. It's up to consumers of WebContents to do that.
  //
  // NOTE: this should only be manipulated before the tab is added to a browser.
  // TODO(sky): resolve if this is the right way to identify an app tab. If it
  // is, than this should be passed in the constructor.
  void SetExtensionApp(const Extension* extension);

  // Convenience for setting the app extension by id. This does nothing if
  // |extension_app_id| is empty, or an extension can't be found given the
  // specified id.
  void SetExtensionAppById(const std::string& extension_app_id);

  // Set just the app icon, used by panels created by an extension.
  void SetExtensionAppIconById(const std::string& extension_app_id);

  const Extension* extension_app() const { return extension_app_; }
  bool is_app() const { return extension_app_ != NULL; }
  const WebApplicationInfo& web_app_info() const {
    return web_app_info_;
  }

  // If an app extension has been explicitly set for this WebContents its icon
  // is returned.
  //
  // NOTE: the returned icon is larger than 16x16 (its size is
  // Extension::EXTENSION_ICON_SMALLISH).
  SkBitmap* GetExtensionAppIcon();

  content::WebContents* web_contents() const {
    return content::WebContentsObserver::web_contents();
  }

  ScriptExecutor* script_executor() {
    return &script_executor_;
  }

  LocationBarController* location_bar_controller() {
    return location_bar_controller_.get();
  }

  ActiveTabPermissionGranter* active_tab_permission_granter() {
    return active_tab_permission_granter_.get();
  }

  ScriptBubbleController* script_bubble_controller() {
    return script_bubble_controller_.get();
  }

  // Sets a non-extension app icon associated with WebContents and fires an
  // INVALIDATE_TYPE_TITLE navigation state change to trigger repaint of title.
  void SetAppIcon(const SkBitmap& app_icon);

 private:
  explicit TabHelper(content::WebContents* web_contents);
  friend class content::WebContentsUserData<TabHelper>;

  // content::WebContentsObserver overrides.
  virtual void RenderViewCreated(
      content::RenderViewHost* render_view_host) OVERRIDE;
  virtual void DidNavigateMainFrame(
      const content::LoadCommittedDetails& details,
      const content::FrameNavigateParams& params) OVERRIDE;
  virtual bool OnMessageReceived(const IPC::Message& message) OVERRIDE;
  virtual void DidCloneToNewWebContents(
      content::WebContents* old_web_contents,
      content::WebContents* new_web_contents) OVERRIDE;

  // ExtensionFunctionDispatcher::Delegate overrides.
  virtual extensions::WindowController* GetExtensionWindowController()
      const OVERRIDE;
  virtual content::WebContents* GetAssociatedWebContents() const OVERRIDE;

  // Message handlers.
  void OnDidGetApplicationInfo(int32 page_id, const WebApplicationInfo& info);
  void OnInstallApplication(const WebApplicationInfo& info);
  void OnInlineWebstoreInstall(int install_id,
                               int return_route_id,
                               const std::string& webstore_item_id,
                               const GURL& requestor_url);
  void OnGetAppNotifyChannel(const GURL& requestor_url,
                             const std::string& client_id,
                             int return_route_id,
                             int callback_id);
  void OnGetAppInstallState(const GURL& requestor_url,
                            int return_route_id,
                            int callback_id);
  void OnRequest(const ExtensionHostMsg_Request_Params& params);
  void OnContentScriptsExecuting(
      const ContentScriptObserver::ExecutingScriptsMap& extension_ids,
      int32 page_id,
      const GURL& on_url);

  // App extensions related methods:

  // Resets app_icon_ and if |extension| is non-null creates a new
  // ImageLoadingTracker to load the extension's image.
  void UpdateExtensionAppIcon(const Extension* extension);

  const Extension* GetExtension(
      const std::string& extension_app_id);

  // ImageLoadingTracker::Observer.
  virtual void OnImageLoaded(const gfx::Image& image,
                             const std::string& extension_id,
                             int index) OVERRIDE;

  // WebstoreStandaloneInstaller::Callback.
  virtual void OnInlineInstallComplete(int install_id,
                                       int return_route_id,
                                       bool success,
                                       const std::string& error);

  // AppNotifyChannelSetup::Delegate.
  virtual void AppNotifyChannelSetupComplete(
      const std::string& channel_id,
      const std::string& error,
      const AppNotifyChannelSetup* setup) OVERRIDE;

  // content::NotificationObserver.
  virtual void Observe(int type,
                       const content::NotificationSource& source,
                       const content::NotificationDetails& details) OVERRIDE;

  // Requests application info for the specified page. This is an asynchronous
  // request. The delegate is notified by way of OnDidGetApplicationInfo when
  // the data is available.
  void GetApplicationInfo(int32 page_id);

  // Data for app extensions ---------------------------------------------------

  // Our content script observers. Declare at top so that it will outlive all
  // other members, since they might add themselves as observers.
  ObserverList<ContentScriptObserver> content_script_observers_;

  // If non-null this tab is an app tab and this is the extension the tab was
  // created for.
  const Extension* extension_app_;

  // Icon for extension_app_ (if non-null) or a manually-set icon for
  // non-extension apps.
  SkBitmap extension_app_icon_;

  // Process any extension messages coming from the tab.
  ExtensionFunctionDispatcher extension_function_dispatcher_;

  // Used for loading extension_app_icon_.
  scoped_ptr<ImageLoadingTracker> extension_app_image_loader_;

  // Cached web app info data.
  WebApplicationInfo web_app_info_;

  // Which deferred action to perform when OnDidGetApplicationInfo is notified
  // from a WebContents.
  WebAppAction pending_web_app_action_;

  content::NotificationRegistrar registrar_;

  ScriptExecutor script_executor_;

  scoped_ptr<LocationBarController> location_bar_controller_;

  scoped_ptr<ActiveTabPermissionGranter> active_tab_permission_granter_;

  scoped_ptr<ScriptBubbleController> script_bubble_controller_;

  DISALLOW_COPY_AND_ASSIGN(TabHelper);
};

}  // namespace extensions

#endif  // CHROME_BROWSER_EXTENSIONS_TAB_HELPER_H_


void SystemInit(void)
{
    return;
}


<?php

namespace AppBundle\Repository;

/**
 * RateRepository.
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class RateRepository extends \Doctrine\ORM\EntityRepository
{
    public function getActiveRates()
    {
        return $this
            ->createQueryBuilder('r')
            ->where('r.active = true')
            ->getQuery()
            ->getResult();
    }
}


package dlp.snippets;

// [START dlp_deidentify_table_row_suppress]

import com.google.cloud.dlp.v2.DlpServiceClient;
import com.google.privacy.dlp.v2.ContentItem;
import com.google.privacy.dlp.v2.DeidentifyConfig;
import com.google.privacy.dlp.v2.DeidentifyContentRequest;
import com.google.privacy.dlp.v2.DeidentifyContentResponse;
import com.google.privacy.dlp.v2.FieldId;
import com.google.privacy.dlp.v2.LocationName;
import com.google.privacy.dlp.v2.RecordCondition;
import com.google.privacy.dlp.v2.RecordCondition.Condition;
import com.google.privacy.dlp.v2.RecordCondition.Conditions;
import com.google.privacy.dlp.v2.RecordCondition.Expressions;
import com.google.privacy.dlp.v2.RecordSuppression;
import com.google.privacy.dlp.v2.RecordTransformations;
import com.google.privacy.dlp.v2.RelationalOperator;
import com.google.privacy.dlp.v2.Table;
import com.google.privacy.dlp.v2.Table.Row;
import com.google.privacy.dlp.v2.Value;
import java.io.IOException;

public class DeIdentifyTableRowSuppress {

  public static void deIdentifyTableRowSuppress() throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    Table tableToDeIdentify =
        Table.newBuilder()
            .addHeaders(FieldId.newBuilder().setName("AGE").build())
            .addHeaders(FieldId.newBuilder().setName("PATIENT").build())
            .addHeaders(FieldId.newBuilder().setName("HAPPINESS SCORE").build())
            .addRows(
                Row.newBuilder()
                    .addValues(Value.newBuilder().setStringValue("101").build())
                    .addValues(Value.newBuilder().setStringValue("Charles Dickens").build())
                    .addValues(Value.newBuilder().setStringValue("95").build())
                    .build())
            .addRows(
                Row.newBuilder()
                    .addValues(Value.newBuilder().setStringValue("22").build())
                    .addValues(Value.newBuilder().setStringValue("Jane Austen").build())
                    .addValues(Value.newBuilder().setStringValue("21").build())
                    .build())
            .addRows(
                Row.newBuilder()
                    .addValues(Value.newBuilder().setStringValue("55").build())
                    .addValues(Value.newBuilder().setStringValue("Mark Twain").build())
                    .addValues(Value.newBuilder().setStringValue("75").build())
                    .build())
            .build();

    deIdentifyTableRowSuppress(projectId, tableToDeIdentify);
  }

  public static Table deIdentifyTableRowSuppress(String projectId, Table tableToDeIdentify)
      throws IOException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (DlpServiceClient dlp = DlpServiceClient.create()) {
      // Specify what content you want the service to de-identify.
      ContentItem contentItem = ContentItem.newBuilder().setTable(tableToDeIdentify).build();

      // Specify when the content should be de-identified.
      Condition condition =
          Condition.newBuilder()
              .setField(FieldId.newBuilder().setName("AGE").build())
              .setOperator(RelationalOperator.GREATER_THAN)
              .setValue(Value.newBuilder().setIntegerValue(89).build())
              .build();
      // Apply the condition to record suppression.
      RecordSuppression recordSuppressions =
          RecordSuppression.newBuilder()
              .setCondition(
                  RecordCondition.newBuilder()
                      .setExpressions(
                          Expressions.newBuilder()
                              .setConditions(
                                  Conditions.newBuilder().addConditions(condition).build())
                              .build())
                      .build())
              .build();
      // Use record suppression as the only transformation
      RecordTransformations transformations =
          RecordTransformations.newBuilder().addRecordSuppressions(recordSuppressions).build();

      DeidentifyConfig deidentifyConfig =
          DeidentifyConfig.newBuilder().setRecordTransformations(transformations).build();

      // Combine configurations into a request for the service.
      DeidentifyContentRequest request =
          DeidentifyContentRequest.newBuilder()
              .setParent(LocationName.of(projectId, "global").toString())
              .setItem(contentItem)
              .setDeidentifyConfig(deidentifyConfig)
              .build();

      // Send the request and receive response from the service.
      DeidentifyContentResponse response = dlp.deidentifyContent(request);

      // Print the results.
      System.out.println("Table after de-identification: " + response.getItem().getTable());

      return response.getItem().getTable();
    }
  }
}
// [END dlp_deidentify_table_row_suppress]


set -o errexit
set -o nounset
set -o pipefail

REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE}")/.." && pwd -P)"

reindex_out="$(${REPO_ROOT}/scripts/reindex.sh)"
if [[ -n "${reindex_out}" ]]; then
  echo "Invalid index: file name matches directory name" >&2
  echo "${reindex_out}" >&2
  echo "Please run 'scripts/reindex.sh'" >&2
  exit 1
fi


from django.core.urlresolvers import reverse
from django.views.generic import ListView, CreateView, UpdateView, DeleteView, DetailView
from contacts.models import Address, Contact

import forms

#The ListView that we subclass from is itself composed of several mixins that provide some behaviour !!!
class ListContactView(ListView):

    model = Contact                             # this view is going to list all the Contacts in our database
    template_name = 'contact_list.html'

# Most generic views that do form processing have
# the concept of the 'success URL': where to redirect
# the user when the form is successfully submitted.
class CreateContactView(CreateView):

    model = Contact
    template_name = 'edit_contact.html'
    # after adding 'email_filed' in forms.py we have to tell this view to use it
    form_class = forms.ContactForm

    def get_success_url(self):
        return reverse('contacts-list')   # contact_list - the name of a view defined in URLS !

    # in order to use the same template for create and update (add/edit) we have to add info
    # about where the form should redirect to the context
    def get_context_data(self, **kwargs):
        context = super(CreateContactView, self).get_context_data(**kwargs)
        context['action'] = reverse('contacts-new')

        return context

class UpdateContactView(UpdateView):

    model = Contact
    template_name = 'edit_contact.html'
    # after adding 'email_filed' in forms.py we have to tell this view to use it
    form_class = forms.ContactForm

    def get_success_url(self):
        return reverse('contacts-list')

    # in order to use the same template for create and update (add/edit) we have to add info
    # about where the form should redirect to the context
    def get_context_data(self, **kwargs):
        context = super(UpdateContactView, self).get_context_data(**kwargs)
        context['action'] = reverse('contacts-edit', kwargs = {'pk': self.get_object().id})

        return context

class DeleteContactView(DeleteView):

    model = Contact
    template_name = 'delete_contact.html'

    def get_success_url(self):
        return reverse('contacts-list')

class ContactView(DetailView):

    model = Contact
    template_name = 'contact.html'

    def get_context_data(self, **kwargs):
        context = super(ContactView, self).get_context_data(**kwargs)
        home_addresses = Address.objects.filter(contact_id=self.get_object().id, address_type='HOME')
        context['home_address'] = home_addresses[0] if home_addresses else None

        return context

#
# to work with Contact and Address models together
#
# class EditContactAddressView(UpdateView):

#     model = Contact                     # inline formset takes the parent object as its starting point
#     template_name = 'edit_addresses.html'
#     form_class = forms.ContactAddressFormSet

#     def get_success_url(self):

#         # redirect to the Contact view.
#         return self.get_object().get_absolute_url()

class EditContactAddressView(UpdateView):

    model = Address                     # inline formset takes the parent object as its starting point
    template_name = 'edit_addresses.html'
    #form_class = forms.ContactAddressFormSet

    def get_success_url(self):
        return reverse('contacts-list')

    def get_context_data(self, **kwargs):
        context = super(EditContactAddressView, self).get_context_data(**kwargs)
        context['action'] = reverse('contacts-edit-addresses', kwargs = {'pk': self.get_object().id})

        return context


require 'rubygems'
require 'priority_queue'

class String
  # Convenience method so we can iterate over characters easily

  def to_chars
    a = []
    each_byte do |b|
      a << b.chr
    end
    a
  end
end

module TileMap
  # Although start is a plains, its cost is 0

  START  = 0
  PLAINS = 1
  FOREST = 2
  MOUNTAIN = 3
  WATER = nil

  class TilePath < Array
    def initialize(map)
      @map = map
      super([@map.start])
    end

    def cost
      inject(0) {|sum, c| sum + @map.tile(*c) }
    end
  end

  class Map
    attr_reader :start, :goal

    # parse a string contining a tile map into a nested array

    def initialize(map_str)
      @tiles = []
      map_str.each do |line|
        @tiles << []
        line.chomp.to_chars.each do |c|
          @tiles.last << case c
                         when "@"
                           START
                         when ".", "X"
                           PLAINS
                         when "*"
                           FOREST
                         when "^"
                           MOUNTAIN
                         when "~"
                           WATER
                         else
                           raise "Invalid tile type"
                         end
          if '@' == c
            @start = [@tiles.last.length - 1, @tiles.length - 1]
          elsif 'X' == c
            @goal = [@tiles.last.length - 1, @tiles.length - 1]
          end
        end
      end
      unless @start && @goal
        raise "Either position or goal tile are not set"
      end
    end

    def tile(x, y)
      @tiles[y][x]
    end

    def move_choices(x, y)
      if tile(x, y) == WATER
        raise "Illegal tile"
      end
      choices = []
      (-1..1).each do |i|
        ypos = y + i
        if ypos >= 0 && ypos < @tiles.length
          (-1..1).each do |j|
            xpos = x + j
            if xpos >= 0 && xpos < @tiles[i].length
              new_position = [xpos, ypos]
              if new_position != [x, y] && tile(*new_position) != WATER
                choices << new_position
              end
            end
          end
        end
      end
      choices
    end

    def self.manhattan(point1, point2)
      ((point2[0] - point1[0]) + (point2[1] - point1[1])).abs
    end
  end

  def self.a_star_search(map)
    # To store points we have already visited, so we don't repeat ourselves
    closed = []
    open = PriorityQueue.new
    # Start off the queue with one path, which will contain the start position
    open.push TilePath.new(map), 0
    while ! open.empty?
      # Get the path with the best cost to expand

      current_path = open.delete_min_return_key
      pos = current_path.last
      unless closed.include?(pos)
        if pos == map.goal
          return current_path
        end
        closed << pos
        # Create new paths and add them to the priority queue

        map.move_choices(*pos).each do |p|
          heuristic = Map.manhattan(p, map.goal)
          new_path = current_path.clone << p
          open.push(new_path, new_path.cost + heuristic)
        end
      end
    end
    raise "Cannot be solved"
  end
end

@m = TileMap::Map.new(File.read('large_map.txt'))
results = TileMap.a_star_search(@m)
puts results.map! {|pos| pos.join(",") }.join("  ")


// See https://i3wm.org/docs/ipc.html for protocol information
#define _POSIX_C_SOURCE 200112L
#include <linux/input-event-codes.h>
#include <assert.h>
#include <errno.h>
#include <fcntl.h>
#include <json.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <sys/un.h>
#include <unistd.h>
#include <wayland-server-core.h>
#include "sway/commands.h"
#include "sway/config.h"
#include "sway/desktop/transaction.h"
#include "sway/ipc-json.h"
#include "sway/ipc-server.h"
#include "sway/output.h"
#include "sway/server.h"
#include "sway/input/input-manager.h"
#include "sway/input/keyboard.h"
#include "sway/input/seat.h"
#include "sway/tree/root.h"
#include "sway/tree/view.h"
#include "sway/tree/workspace.h"
#include "list.h"
#include "log.h"
#include "util.h"

static int ipc_socket = -1;
static struct wl_event_source *ipc_event_source =  NULL;
static struct sockaddr_un *ipc_sockaddr = NULL;
static list_t *ipc_client_list = NULL;
static struct wl_listener ipc_display_destroy;

static const char ipc_magic[] = {'i', '3', '-', 'i', 'p', 'c'};

#define IPC_HEADER_SIZE (sizeof(ipc_magic) + 8)

struct ipc_client {
	struct wl_event_source *event_source;
	struct wl_event_source *writable_event_source;
	struct sway_server *server;
	int fd;
	enum ipc_command_type subscribed_events;
	size_t write_buffer_len;
	size_t write_buffer_size;
	char *write_buffer;
	// The following are for storing data between event_loop calls
	uint32_t pending_length;
	enum ipc_command_type pending_type;
};

struct sockaddr_un *ipc_user_sockaddr(void);
int ipc_handle_connection(int fd, uint32_t mask, void *data);
int ipc_client_handle_readable(int client_fd, uint32_t mask, void *data);
int ipc_client_handle_writable(int client_fd, uint32_t mask, void *data);
void ipc_client_disconnect(struct ipc_client *client);
void ipc_client_handle_command(struct ipc_client *client, uint32_t payload_length,
	enum ipc_command_type payload_type);
bool ipc_send_reply(struct ipc_client *client, enum ipc_command_type payload_type,
	const char *payload, uint32_t payload_length);

static void handle_display_destroy(struct wl_listener *listener, void *data) {
	if (ipc_event_source) {
		wl_event_source_remove(ipc_event_source);
	}
	close(ipc_socket);
	unlink(ipc_sockaddr->sun_path);

	while (ipc_client_list->length) {
		ipc_client_disconnect(ipc_client_list->items[ipc_client_list->length-1]);
	}
	list_free(ipc_client_list);

	free(ipc_sockaddr);

	wl_list_remove(&ipc_display_destroy.link);
}

void ipc_init(struct sway_server *server) {
	ipc_socket = socket(AF_UNIX, SOCK_STREAM, 0);
	if (ipc_socket == -1) {
		sway_abort("Unable to create IPC socket");
	}
	if (fcntl(ipc_socket, F_SETFD, FD_CLOEXEC) == -1) {
		sway_abort("Unable to set CLOEXEC on IPC socket");
	}
	if (fcntl(ipc_socket, F_SETFL, O_NONBLOCK) == -1) {
		sway_abort("Unable to set NONBLOCK on IPC socket");
	}

	ipc_sockaddr = ipc_user_sockaddr();

	// We want to use socket name set by user, not existing socket from another sway instance.
	if (getenv("SWAYSOCK") != NULL && access(getenv("SWAYSOCK"), F_OK) == -1) {
		strncpy(ipc_sockaddr->sun_path, getenv("SWAYSOCK"), sizeof(ipc_sockaddr->sun_path) - 1);
		ipc_sockaddr->sun_path[sizeof(ipc_sockaddr->sun_path) - 1] = 0;
	}

	unlink(ipc_sockaddr->sun_path);
	if (bind(ipc_socket, (struct sockaddr *)ipc_sockaddr, sizeof(*ipc_sockaddr)) == -1) {
		sway_abort("Unable to bind IPC socket");
	}

	if (listen(ipc_socket, 3) == -1) {
		sway_abort("Unable to listen on IPC socket");
	}

	// Set i3 IPC socket path so that i3-msg works out of the box
	setenv("I3SOCK", ipc_sockaddr->sun_path, 1);
	setenv("SWAYSOCK", ipc_sockaddr->sun_path, 1);

	ipc_client_list = create_list();

	ipc_display_destroy.notify = handle_display_destroy;
	wl_display_add_destroy_listener(server->wl_display, &ipc_display_destroy);

	ipc_event_source = wl_event_loop_add_fd(server->wl_event_loop, ipc_socket,
			WL_EVENT_READABLE, ipc_handle_connection, server);
}

struct sockaddr_un *ipc_user_sockaddr(void) {
	struct sockaddr_un *ipc_sockaddr = malloc(sizeof(struct sockaddr_un));
	if (ipc_sockaddr == NULL) {
		sway_abort("Can't allocate ipc_sockaddr");
	}

	ipc_sockaddr->sun_family = AF_UNIX;
	int path_size = sizeof(ipc_sockaddr->sun_path);

	// Env var typically set by logind, e.g. "/run/user/<user-id>"
	const char *dir = getenv("XDG_RUNTIME_DIR");
	if (!dir) {
		dir = "/tmp";
	}
	if (path_size <= snprintf(ipc_sockaddr->sun_path, path_size,
			"%s/sway-ipc.%u.%i.sock", dir, getuid(), getpid())) {
		sway_abort("Socket path won't fit into ipc_sockaddr->sun_path");
	}

	return ipc_sockaddr;
}

int ipc_handle_connection(int fd, uint32_t mask, void *data) {
	(void) fd;
	struct sway_server *server = data;
	sway_log(SWAY_DEBUG, "Event on IPC listening socket");
	assert(mask == WL_EVENT_READABLE);

	int client_fd = accept(ipc_socket, NULL, NULL);
	if (client_fd == -1) {
		sway_log_errno(SWAY_ERROR, "Unable to accept IPC client connection");
		return 0;
	}

	int flags;
	if ((flags = fcntl(client_fd, F_GETFD)) == -1
			|| fcntl(client_fd, F_SETFD, flags|FD_CLOEXEC) == -1) {
		sway_log_errno(SWAY_ERROR, "Unable to set CLOEXEC on IPC client socket");
		close(client_fd);
		return 0;
	}
	if ((flags = fcntl(client_fd, F_GETFL)) == -1
			|| fcntl(client_fd, F_SETFL, flags|O_NONBLOCK) == -1) {
		sway_log_errno(SWAY_ERROR, "Unable to set NONBLOCK on IPC client socket");
		close(client_fd);
		return 0;
	}

	struct ipc_client *client = malloc(sizeof(struct ipc_client));
	if (!client) {
		sway_log(SWAY_ERROR, "Unable to allocate ipc client");
		close(client_fd);
		return 0;
	}
	client->server = server;
	client->pending_length = 0;
	client->fd = client_fd;
	client->subscribed_events = 0;
	client->event_source = wl_event_loop_add_fd(server->wl_event_loop,
			client_fd, WL_EVENT_READABLE, ipc_client_handle_readable, client);
	client->writable_event_source = NULL;

	client->write_buffer_size = 128;
	client->write_buffer_len = 0;
	client->write_buffer = malloc(client->write_buffer_size);
	if (!client->write_buffer) {
		sway_log(SWAY_ERROR, "Unable to allocate ipc client write buffer");
		close(client_fd);
		return 0;
	}

	sway_log(SWAY_DEBUG, "New client: fd %d", client_fd);
	list_add(ipc_client_list, client);
	return 0;
}

int ipc_client_handle_readable(int client_fd, uint32_t mask, void *data) {
	struct ipc_client *client = data;

	if (mask & WL_EVENT_ERROR) {
		sway_log(SWAY_ERROR, "IPC Client socket error, removing client");
		ipc_client_disconnect(client);
		return 0;
	}

	if (mask & WL_EVENT_HANGUP) {
		sway_log(SWAY_DEBUG, "Client %d hung up", client->fd);
		ipc_client_disconnect(client);
		return 0;
	}

	sway_log(SWAY_DEBUG, "Client %d readable", client->fd);

	int read_available;
	if (ioctl(client_fd, FIONREAD, &read_available) == -1) {
		sway_log_errno(SWAY_INFO, "Unable to read IPC socket buffer size");
		ipc_client_disconnect(client);
		return 0;
	}

	// Wait for the rest of the command payload in case the header has already been read
	if (client->pending_length > 0) {
		if ((uint32_t)read_available >= client->pending_length) {
			// Reset pending values.
			uint32_t pending_length = client->pending_length;
			enum ipc_command_type pending_type = client->pending_type;
			client->pending_length = 0;
			ipc_client_handle_command(client, pending_length, pending_type);
		}
		return 0;
	}

	if (read_available < (int) IPC_HEADER_SIZE) {
		return 0;
	}

	uint8_t buf[IPC_HEADER_SIZE];
	// Should be fully available, because read_available >= IPC_HEADER_SIZE
	ssize_t received = recv(client_fd, buf, IPC_HEADER_SIZE, 0);
	if (received == -1) {
		sway_log_errno(SWAY_INFO, "Unable to receive header from IPC client");
		ipc_client_disconnect(client);
		return 0;
	}

	if (memcmp(buf, ipc_magic, sizeof(ipc_magic)) != 0) {
		sway_log(SWAY_DEBUG, "IPC header check failed");
		ipc_client_disconnect(client);
		return 0;
	}

	memcpy(&client->pending_length, buf + sizeof(ipc_magic), sizeof(uint32_t));
	memcpy(&client->pending_type, buf + sizeof(ipc_magic) + sizeof(uint32_t), sizeof(uint32_t));

	if (read_available - received >= (long)client->pending_length) {
		// Reset pending values.
		uint32_t pending_length = client->pending_length;
		enum ipc_command_type pending_type = client->pending_type;
		client->pending_length = 0;
		ipc_client_handle_command(client, pending_length, pending_type);
	}

	return 0;
}

static bool ipc_has_event_listeners(enum ipc_command_type event) {
	for (int i = 0; i < ipc_client_list->length; i++) {
		struct ipc_client *client = ipc_client_list->items[i];
		if ((client->subscribed_events & event_mask(event)) != 0) {
			return true;
		}
	}
	return false;
}

static void ipc_send_event(const char *json_string, enum ipc_command_type event) {
	struct ipc_client *client;
	for (int i = 0; i < ipc_client_list->length; i++) {
		client = ipc_client_list->items[i];
		if ((client->subscribed_events & event_mask(event)) == 0) {
			continue;
		}
		if (!ipc_send_reply(client, event, json_string,
				(uint32_t)strlen(json_string))) {
			sway_log_errno(SWAY_INFO, "Unable to send reply to IPC client");
			/* ipc_send_reply destroys client on error, which also
			 * removes it from the list, so we need to process
			 * current index again */
			i--;
		}
	}
}

void ipc_event_workspace(struct sway_workspace *old,
		struct sway_workspace *new, const char *change) {
	if (!ipc_has_event_listeners(IPC_EVENT_WORKSPACE)) {
		return;
	}
	sway_log(SWAY_DEBUG, "Sending workspace::%s event", change);
	json_object *obj = json_object_new_object();
	json_object_object_add(obj, "change", json_object_new_string(change));
	if (old) {
		json_object_object_add(obj, "old",
				ipc_json_describe_node_recursive(&old->node));
	} else {
		json_object_object_add(obj, "old", NULL);
	}

	if (new) {
		json_object_object_add(obj, "current",
				ipc_json_describe_node_recursive(&new->node));
	} else {
		json_object_object_add(obj, "current", NULL);
	}

	const char *json_string = json_object_to_json_string(obj);
	ipc_send_event(json_string, IPC_EVENT_WORKSPACE);
	json_object_put(obj);
}

void ipc_event_window(struct sway_container *window, const char *change) {
	if (!ipc_has_event_listeners(IPC_EVENT_WINDOW)) {
		return;
	}
	sway_log(SWAY_DEBUG, "Sending window::%s event", change);
	json_object *obj = json_object_new_object();
	json_object_object_add(obj, "change", json_object_new_string(change));
	json_object_object_add(obj, "container",
			ipc_json_describe_node_recursive(&window->node));

	const char *json_string = json_object_to_json_string(obj);
	ipc_send_event(json_string, IPC_EVENT_WINDOW);
	json_object_put(obj);
}

void ipc_event_barconfig_update(struct bar_config *bar) {
	if (!ipc_has_event_listeners(IPC_EVENT_BARCONFIG_UPDATE)) {
		return;
	}
	sway_log(SWAY_DEBUG, "Sending barconfig_update event");
	json_object *json = ipc_json_describe_bar_config(bar);

	const char *json_string = json_object_to_json_string(json);
	ipc_send_event(json_string, IPC_EVENT_BARCONFIG_UPDATE);
	json_object_put(json);
}

void ipc_event_bar_state_update(struct bar_config *bar) {
	if (!ipc_has_event_listeners(IPC_EVENT_BAR_STATE_UPDATE)) {
		return;
	}
	sway_log(SWAY_DEBUG, "Sending bar_state_update event");

	json_object *json = json_object_new_object();
	json_object_object_add(json, "id", json_object_new_string(bar->id));
	json_object_object_add(json, "visible_by_modifier",
			json_object_new_boolean(bar->visible_by_modifier));

	const char *json_string = json_object_to_json_string(json);
	ipc_send_event(json_string, IPC_EVENT_BAR_STATE_UPDATE);
	json_object_put(json);
}

void ipc_event_mode(const char *mode, bool pango) {
	if (!ipc_has_event_listeners(IPC_EVENT_MODE)) {
		return;
	}
	sway_log(SWAY_DEBUG, "Sending mode::%s event", mode);
	json_object *obj = json_object_new_object();
	json_object_object_add(obj, "change", json_object_new_string(mode));
	json_object_object_add(obj, "pango_markup",
			json_object_new_boolean(pango));

	const char *json_string = json_object_to_json_string(obj);
	ipc_send_event(json_string, IPC_EVENT_MODE);
	json_object_put(obj);
}

void ipc_event_shutdown(const char *reason) {
	if (!ipc_has_event_listeners(IPC_EVENT_SHUTDOWN)) {
		return;
	}
	sway_log(SWAY_DEBUG, "Sending shutdown::%s event", reason);

	json_object *json = json_object_new_object();
	json_object_object_add(json, "change", json_object_new_string(reason));

	const char *json_string = json_object_to_json_string(json);
	ipc_send_event(json_string, IPC_EVENT_SHUTDOWN);
	json_object_put(json);
}

void ipc_event_binding(struct sway_binding *binding) {
	if (!ipc_has_event_listeners(IPC_EVENT_BINDING)) {
		return;
	}
	sway_log(SWAY_DEBUG, "Sending binding event");

	json_object *json_binding = json_object_new_object();
	json_object_object_add(json_binding, "command", json_object_new_string(binding->command));

	const char *names[10];
	int len = get_modifier_names(names, binding->modifiers);
	json_object *modifiers = json_object_new_array();
	for (int i = 0; i < len; ++i) {
		json_object_array_add(modifiers, json_object_new_string(names[i]));
	}
	json_object_object_add(json_binding, "event_state_mask", modifiers);

	json_object *input_codes = json_object_new_array();
	int input_code = 0;
	json_object *symbols = json_object_new_array();
	json_object *symbol = NULL;

	switch (binding->type) {
	case BINDING_KEYCODE:; // bindcode: populate input_codes
		uint32_t keycode;
		for (int i = 0; i < binding->keys->length; ++i) {
			keycode = *(uint32_t *)binding->keys->items[i];
			json_object_array_add(input_codes, json_object_new_int(keycode));
			if (i == 0) {
				input_code = keycode;
			}
		}
		break;

	case BINDING_KEYSYM:
	case BINDING_MOUSESYM:
	case BINDING_MOUSECODE:; // bindsym/mouse: populate symbols
		uint32_t keysym;
		char buffer[64];
		for (int i = 0; i < binding->keys->length; ++i) {
			keysym = *(uint32_t *)binding->keys->items[i];
			if (keysym >= BTN_LEFT && keysym <= BTN_LEFT + 8) {
				snprintf(buffer, 64, "button%u", keysym - BTN_LEFT + 1);
			} else if (xkb_keysym_get_name(keysym, buffer, 64) < 0) {
				continue;
			}

			json_object *str = json_object_new_string(buffer);
			if (i == 0) {
				// str is owned by both symbol and symbols. Make sure
				// to bump the ref count.
				json_object_array_add(symbols, json_object_get(str));
				symbol = str;
			} else {
				json_object_array_add(symbols, str);
			}
		}
		break;

	default:
		sway_log(SWAY_DEBUG, "Unsupported ipc binding event");
		json_object_put(input_codes);
		json_object_put(symbols);
		json_object_put(json_binding);
		return; // do not send any event
	}

	json_object_object_add(json_binding, "input_codes", input_codes);
	json_object_object_add(json_binding, "input_code", json_object_new_int(input_code));
	json_object_object_add(json_binding, "symbols", symbols);
	json_object_object_add(json_binding, "symbol", symbol);

	bool mouse = binding->type == BINDING_MOUSECODE ||
		binding->type == BINDING_MOUSESYM;
	json_object_object_add(json_binding, "input_type", mouse
			? json_object_new_string("mouse")
			: json_object_new_string("keyboard"));

	json_object *json = json_object_new_object();
	json_object_object_add(json, "change", json_object_new_string("run"));
	json_object_object_add(json, "binding", json_binding);
	const char *json_string = json_object_to_json_string(json);
	ipc_send_event(json_string, IPC_EVENT_BINDING);
	json_object_put(json);
}

static void ipc_event_tick(const char *payload) {
	if (!ipc_has_event_listeners(IPC_EVENT_TICK)) {
		return;
	}
	sway_log(SWAY_DEBUG, "Sending tick event");

	json_object *json = json_object_new_object();
	json_object_object_add(json, "first", json_object_new_boolean(false));
	json_object_object_add(json, "payload", json_object_new_string(payload));

	const char *json_string = json_object_to_json_string(json);
	ipc_send_event(json_string, IPC_EVENT_TICK);
	json_object_put(json);
}

void ipc_event_input(const char *change, struct sway_input_device *device) {
	if (!ipc_has_event_listeners(IPC_EVENT_INPUT)) {
		return;
	}
	sway_log(SWAY_DEBUG, "Sending input event");

	json_object *json = json_object_new_object();
	json_object_object_add(json, "change", json_object_new_string(change));
	json_object_object_add(json, "input", ipc_json_describe_input(device));

	const char *json_string = json_object_to_json_string(json);
	ipc_send_event(json_string, IPC_EVENT_INPUT);
	json_object_put(json);
}

int ipc_client_handle_writable(int client_fd, uint32_t mask, void *data) {
	struct ipc_client *client = data;

	if (mask & WL_EVENT_ERROR) {
		sway_log(SWAY_ERROR, "IPC Client socket error, removing client");
		ipc_client_disconnect(client);
		return 0;
	}

	if (mask & WL_EVENT_HANGUP) {
		sway_log(SWAY_DEBUG, "Client %d hung up", client->fd);
		ipc_client_disconnect(client);
		return 0;
	}

	if (client->write_buffer_len <= 0) {
		return 0;
	}

	sway_log(SWAY_DEBUG, "Client %d writable", client->fd);

	ssize_t written = write(client->fd, client->write_buffer, client->write_buffer_len);

	if (written == -1 && errno == EAGAIN) {
		return 0;
	} else if (written == -1) {
		sway_log_errno(SWAY_INFO, "Unable to send data from queue to IPC client");
		ipc_client_disconnect(client);
		return 0;
	}

	memmove(client->write_buffer, client->write_buffer + written, client->write_buffer_len - written);
	client->write_buffer_len -= written;

	if (client->write_buffer_len == 0 && client->writable_event_source) {
		wl_event_source_remove(client->writable_event_source);
		client->writable_event_source = NULL;
	}

	return 0;
}

void ipc_client_disconnect(struct ipc_client *client) {
	if (!sway_assert(client != NULL, "client != NULL")) {
		return;
	}

	shutdown(client->fd, SHUT_RDWR);

	sway_log(SWAY_INFO, "IPC Client %d disconnected", client->fd);
	wl_event_source_remove(client->event_source);
	if (client->writable_event_source) {
		wl_event_source_remove(client->writable_event_source);
	}
	int i = 0;
	while (i < ipc_client_list->length && ipc_client_list->items[i] != client) {
		i++;
	}
	list_del(ipc_client_list, i);
	free(client->write_buffer);
	close(client->fd);
	free(client);
}

static void ipc_get_workspaces_callback(struct sway_workspace *workspace,
		void *data) {
	json_object *workspace_json = ipc_json_describe_node(&workspace->node);
	// override the default focused indicator because
	// it's set differently for the get_workspaces reply
	struct sway_seat *seat = input_manager_get_default_seat();
	struct sway_workspace *focused_ws = seat_get_focused_workspace(seat);
	bool focused = workspace == focused_ws;
	json_object_object_del(workspace_json, "focused");
	json_object_object_add(workspace_json, "focused",
			json_object_new_boolean(focused));
	json_object_array_add((json_object *)data, workspace_json);

	focused_ws = output_get_active_workspace(workspace->output);
	bool visible = workspace == focused_ws;
	json_object_object_add(workspace_json, "visible",
			json_object_new_boolean(visible));
}

static void ipc_get_marks_callback(struct sway_container *con, void *data) {
	json_object *marks = (json_object *)data;
	for (int i = 0; i < con->marks->length; ++i) {
		char *mark = (char *)con->marks->items[i];
		json_object_array_add(marks, json_object_new_string(mark));
	}
}

void ipc_client_handle_command(struct ipc_client *client, uint32_t payload_length,
		enum ipc_command_type payload_type) {
	if (!sway_assert(client != NULL, "client != NULL")) {
		return;
	}

	char *buf = malloc(payload_length + 1);
	if (!buf) {
		sway_log_errno(SWAY_INFO, "Unable to allocate IPC payload");
		ipc_client_disconnect(client);
		return;
	}
	if (payload_length > 0) {
		// Payload should be fully available
		ssize_t received = recv(client->fd, buf, payload_length, 0);
		if (received == -1)
		{
			sway_log_errno(SWAY_INFO, "Unable to receive payload from IPC client");
			ipc_client_disconnect(client);
			free(buf);
			return;
		}
	}
	buf[payload_length] = '\0';

	switch (payload_type) {
	case IPC_COMMAND:
	{
		char *line = strtok(buf, "\n");
		while (line) {
			size_t line_length = strlen(line);
			if (line + line_length >= buf + payload_length) {
				break;
			}
			line[line_length] = ';';
			line = strtok(NULL, "\n");
		}

		list_t *res_list = execute_command(buf, NULL, NULL);
		transaction_commit_dirty();
		char *json = cmd_results_to_json(res_list);
		int length = strlen(json);
		ipc_send_reply(client, payload_type, json, (uint32_t)length);
		free(json);
		while (res_list->length) {
			struct cmd_results *results = res_list->items[0];
			free_cmd_results(results);
			list_del(res_list, 0);
		}
		list_free(res_list);
		goto exit_cleanup;
	}

	case IPC_SEND_TICK:
	{
		ipc_event_tick(buf);
		ipc_send_reply(client, payload_type, "{\"success\": true}", 17);
		goto exit_cleanup;
	}

	case IPC_GET_OUTPUTS:
	{
		json_object *outputs = json_object_new_array();
		for (int i = 0; i < root->outputs->length; ++i) {
			struct sway_output *output = root->outputs->items[i];
			json_object *output_json = ipc_json_describe_node(&output->node);

			// override the default focused indicator because it's set
			// differently for the get_outputs reply
			struct sway_seat *seat = input_manager_get_default_seat();
			struct sway_workspace *focused_ws =
				seat_get_focused_workspace(seat);
			bool focused = focused_ws && output == focused_ws->output;
			json_object_object_del(output_json, "focused");
			json_object_object_add(output_json, "focused",
				json_object_new_boolean(focused));

			const char *subpixel = sway_wl_output_subpixel_to_string(output->wlr_output->subpixel);
			json_object_object_add(output_json, "subpixel_hinting", json_object_new_string(subpixel));
			json_object_array_add(outputs, output_json);
		}
		struct sway_output *output;
		wl_list_for_each(output, &root->all_outputs, link) {
			if (!output->enabled && output != root->fallback_output) {
				json_object_array_add(outputs,
						ipc_json_describe_disabled_output(output));
			}
		}
		const char *json_string = json_object_to_json_string(outputs);
		ipc_send_reply(client, payload_type, json_string,
			(uint32_t)strlen(json_string));
		json_object_put(outputs); // free
		goto exit_cleanup;
	}

	case IPC_GET_WORKSPACES:
	{
		json_object *workspaces = json_object_new_array();
		root_for_each_workspace(ipc_get_workspaces_callback, workspaces);
		const char *json_string = json_object_to_json_string(workspaces);
		ipc_send_reply(client, payload_type, json_string,
			(uint32_t)strlen(json_string));
		json_object_put(workspaces); // free
		goto exit_cleanup;
	}

	case IPC_SUBSCRIBE:
	{
		// TODO: Check if they're permitted to use these events
		struct json_object *request = json_tokener_parse(buf);
		if (request == NULL || !json_object_is_type(request, json_type_array)) {
			const char msg[] = "{\"success\": false}";
			ipc_send_reply(client, payload_type, msg, strlen(msg));
			sway_log(SWAY_INFO, "Failed to parse subscribe request");
			goto exit_cleanup;
		}

		bool is_tick = false;
		// parse requested event types
		for (size_t i = 0; i < json_object_array_length(request); i++) {
			const char *event_type = json_object_get_string(json_object_array_get_idx(request, i));
			if (strcmp(event_type, "workspace") == 0) {
				client->subscribed_events |= event_mask(IPC_EVENT_WORKSPACE);
			} else if (strcmp(event_type, "barconfig_update") == 0) {
				client->subscribed_events |= event_mask(IPC_EVENT_BARCONFIG_UPDATE);
			} else if (strcmp(event_type, "bar_state_update") == 0) {
				client->subscribed_events |= event_mask(IPC_EVENT_BAR_STATE_UPDATE);
			} else if (strcmp(event_type, "mode") == 0) {
				client->subscribed_events |= event_mask(IPC_EVENT_MODE);
			} else if (strcmp(event_type, "shutdown") == 0) {
				client->subscribed_events |= event_mask(IPC_EVENT_SHUTDOWN);
			} else if (strcmp(event_type, "window") == 0) {
				client->subscribed_events |= event_mask(IPC_EVENT_WINDOW);
			} else if (strcmp(event_type, "binding") == 0) {
				client->subscribed_events |= event_mask(IPC_EVENT_BINDING);
			} else if (strcmp(event_type, "tick") == 0) {
				client->subscribed_events |= event_mask(IPC_EVENT_TICK);
				is_tick = true;
			} else if (strcmp(event_type, "input") == 0) {
				client->subscribed_events |= event_mask(IPC_EVENT_INPUT);
			} else {
				const char msg[] = "{\"success\": false}";
				ipc_send_reply(client, payload_type, msg, strlen(msg));
				json_object_put(request);
				sway_log(SWAY_INFO, "Unsupported event type in subscribe request");
				goto exit_cleanup;
			}
		}

		json_object_put(request);
		const char msg[] = "{\"success\": true}";
		ipc_send_reply(client, payload_type, msg, strlen(msg));
		if (is_tick) {
			const char tickmsg[] = "{\"first\": true, \"payload\": \"\"}";
			ipc_send_reply(client, IPC_EVENT_TICK, tickmsg,
				strlen(tickmsg));
		}
		goto exit_cleanup;
	}

	case IPC_GET_INPUTS:
	{
		json_object *inputs = json_object_new_array();
		struct sway_input_device *device = NULL;
		wl_list_for_each(device, &server.input->devices, link) {
			json_object_array_add(inputs, ipc_json_describe_input(device));
		}
		const char *json_string = json_object_to_json_string(inputs);
		ipc_send_reply(client, payload_type, json_string,
			(uint32_t)strlen(json_string));
		json_object_put(inputs); // free
		goto exit_cleanup;
	}

	case IPC_GET_SEATS:
	{
		json_object *seats = json_object_new_array();
		struct sway_seat *seat = NULL;
		wl_list_for_each(seat, &server.input->seats, link) {
			json_object_array_add(seats, ipc_json_describe_seat(seat));
		}
		const char *json_string = json_object_to_json_string(seats);
		ipc_send_reply(client, payload_type, json_string,
			(uint32_t)strlen(json_string));
		json_object_put(seats); // free
		goto exit_cleanup;
	}

	case IPC_GET_TREE:
	{
		json_object *tree = ipc_json_describe_node_recursive(&root->node);
		const char *json_string = json_object_to_json_string(tree);
		ipc_send_reply(client, payload_type, json_string,
			(uint32_t)strlen(json_string));
		json_object_put(tree);
		goto exit_cleanup;
	}

	case IPC_GET_MARKS:
	{
		json_object *marks = json_object_new_array();
		root_for_each_container(ipc_get_marks_callback, marks);
		const char *json_string = json_object_to_json_string(marks);
		ipc_send_reply(client, payload_type, json_string,
			(uint32_t)strlen(json_string));
		json_object_put(marks);
		goto exit_cleanup;
	}

	case IPC_GET_VERSION:
	{
		json_object *version = ipc_json_get_version();
		const char *json_string = json_object_to_json_string(version);
		ipc_send_reply(client, payload_type, json_string,
			(uint32_t)strlen(json_string));
		json_object_put(version); // free
		goto exit_cleanup;
	}

	case IPC_GET_BAR_CONFIG:
	{
		if (!buf[0]) {
			// Send list of configured bar IDs
			json_object *bars = json_object_new_array();
			for (int i = 0; i < config->bars->length; ++i) {
				struct bar_config *bar = config->bars->items[i];
				json_object_array_add(bars, json_object_new_string(bar->id));
			}
			const char *json_string = json_object_to_json_string(bars);
			ipc_send_reply(client, payload_type, json_string,
				(uint32_t)strlen(json_string));
			json_object_put(bars); // free
		} else {
			// Send particular bar's details
			struct bar_config *bar = NULL;
			for (int i = 0; i < config->bars->length; ++i) {
				bar = config->bars->items[i];
				if (strcmp(buf, bar->id) == 0) {
					break;
				}
				bar = NULL;
			}
			if (!bar) {
				const char *error = "{ \"success\": false, \"error\": \"No bar with that ID\" }";
				ipc_send_reply(client, payload_type, error,
					(uint32_t)strlen(error));
				goto exit_cleanup;
			}
			json_object *json = ipc_json_describe_bar_config(bar);
			const char *json_string = json_object_to_json_string(json);
			ipc_send_reply(client, payload_type, json_string,
				(uint32_t)strlen(json_string));
			json_object_put(json); // free
		}
		goto exit_cleanup;
	}

	case IPC_GET_BINDING_MODES:
	{
		json_object *modes = json_object_new_array();
		for (int i = 0; i < config->modes->length; i++) {
			struct sway_mode *mode = config->modes->items[i];
			json_object_array_add(modes, json_object_new_string(mode->name));
		}
		const char *json_string = json_object_to_json_string(modes);
		ipc_send_reply(client, payload_type, json_string,
			(uint32_t)strlen(json_string));
		json_object_put(modes); // free
		goto exit_cleanup;
	}

	case IPC_GET_BINDING_STATE:
	{
		json_object *current_mode = ipc_json_get_binding_mode();
		const char *json_string = json_object_to_json_string(current_mode);
		ipc_send_reply(client, payload_type, json_string,
			(uint32_t)strlen(json_string));
		json_object_put(current_mode); // free
		goto exit_cleanup;
	}

	case IPC_GET_CONFIG:
	{
		json_object *json = json_object_new_object();
		json_object_object_add(json, "config", json_object_new_string(config->current_config));
		const char *json_string = json_object_to_json_string(json);
		ipc_send_reply(client, payload_type, json_string,
			(uint32_t)strlen(json_string));
		json_object_put(json); // free
		goto exit_cleanup;
	}

	case IPC_SYNC:
	{
		// It was decided sway will not support this, just return success:false
		const char msg[] = "{\"success\": false}";
		ipc_send_reply(client, payload_type, msg, strlen(msg));
		goto exit_cleanup;
	}

	default:
		sway_log(SWAY_INFO, "Unknown IPC command type %x", payload_type);
		goto exit_cleanup;
	}

exit_cleanup:
	free(buf);
	return;
}

bool ipc_send_reply(struct ipc_client *client, enum ipc_command_type payload_type,
		const char *payload, uint32_t payload_length) {
	assert(payload);

	char data[IPC_HEADER_SIZE];

	memcpy(data, ipc_magic, sizeof(ipc_magic));
	memcpy(data + sizeof(ipc_magic), &payload_length, sizeof(payload_length));
	memcpy(data + sizeof(ipc_magic) + sizeof(payload_length), &payload_type, sizeof(payload_type));

	while (client->write_buffer_len + IPC_HEADER_SIZE + payload_length >=
				 client->write_buffer_size) {
		client->write_buffer_size *= 2;
	}

	if (client->write_buffer_size > 4e6) { // 4 MB
		sway_log(SWAY_ERROR, "Client write buffer too big (%zu), disconnecting client",
				client->write_buffer_size);
		ipc_client_disconnect(client);
		return false;
	}

	char *new_buffer = realloc(client->write_buffer, client->write_buffer_size);
	if (!new_buffer) {
		sway_log(SWAY_ERROR, "Unable to reallocate ipc client write buffer");
		ipc_client_disconnect(client);
		return false;
	}
	client->write_buffer = new_buffer;

	memcpy(client->write_buffer + client->write_buffer_len, data, IPC_HEADER_SIZE);
	client->write_buffer_len += IPC_HEADER_SIZE;
	memcpy(client->write_buffer + client->write_buffer_len, payload, payload_length);
	client->write_buffer_len += payload_length;

	if (!client->writable_event_source) {
		client->writable_event_source = wl_event_loop_add_fd(
				server.wl_event_loop, client->fd, WL_EVENT_WRITABLE,
				ipc_client_handle_writable, client);
	}

	sway_log(SWAY_DEBUG, "Added IPC reply of type 0x%x to client %d queue: %s",
		payload_type, client->fd, payload);
	return true;
}


/*

Package cmp defines a set of comparator interfaces and functions,
with default implementations for all standard comparable types.

Compare Results
---------------

comparing two values results in one of the following (int) constants:

	cmp.LT = -1 // Less-Than
	cmp.EQ = 0  // Equal
	cmp.GT = 1  // Greater-Than

Type: cmp.T
-------------

Type cmp.T defines an interface that allows objects to export a comparator function:

	type T interface {
		Cmp(interface{}) int
	}

Type: cmp.F
-------------

Type cmp.F defines a stand-alone comparator function:

	type F func(a, b interface{}) int

Default Implementations
-----------------------

Default implementations are provided for all standard comparable types:

 * byte
 * float(32|64)
 * int & int(8|16|32|64)
 * rune
 * string
 * uint & uint(8|16|32|64)

Below are the definitions of the included int functions.
A complimentary set of functions exists for each of the
standard comparable types (listed above):

	// cmp.Int is a cmp.T wrapper for basic type int.
	// Example:
	//   var comparable cmp.T = cmp.Int(3)
	type Int int

	// cmp.Int::Cmp fulfills the cmp.T interface.
	// b_ is expected to also be type cmp.Int.
	func (a Int) Cmp(b_ interface{}) int

	// cmp.F_Int is a cmp.F for type cmp.Int
	// i.e. You can pass cmp.F_Int to functions
	//      requiring a cmp.F comparator
	// a_ and b_ are expected to be type cmp.Int.
	func F_Int(a_, b_ interface{}) int

	// F_int is a cmp.F for basic type int
	// i.e. You can pass cmp.F_int to functions
	//      requiring a cmp.F comparator
	// a_ and b_ are expected to be basic type int.
	func F_int(a_, b_ interface{}) int

	// cmp.Compare_int is a convenience function
	// for explicitly comparing basic type int.
	func Compare_int(a, b int) int

Extras
------

The package also contains constructs for treating functions
and closures as cmp.T interfaces. See the file "cmp.go" for details.

License
-------

This package is released under the MIT license.

See the file "LICENSE" for more details.

Contributors
------------

David Farrell <DavidPFarrell@yahoo.com>

*/
package cmp


<?php

//include the phal .phar file
include "[phalphar]";


title: NRO Symposium hoger onderwijs
author: Klinkenberg
date: '2021-01-15'
slug: nro-symposium-hoger-onderwijs
categories: []
tags: []
subtitle: 'Nieuwe richtingen na de pandemie?'
summary: ''
authors: []
lastmod: '2021-04-30T10:39:02+02:00'
featured: no
image:
  caption: 'NRO Symposium'
  focal_point: ''
  preview_only: no
projects: []
---

Bijdrage aan het NRO Symposium 2021.

> Het online onderwijs brengt vraagstukken met zich mee over het op afstand of online toetsen en beoordelen van studenten. Hoe kunnen we dat nu en in de toekomst het beste vormgeven? Hoe kunnen we toetsen meer gaan gebruiken om studenten te ondersteunen bij het leren?

Bron: [Toetsen op afstand en monitoren van de studievoortgang](https://www.onderwijskennis.nl/nro-symposium-hoger-onderwijs-nieuwe-richtingen-na-de-pandemie/toetsen-op-afstand-en-monitoren-van-de-studievoortgang)

<iframe width="100%" height="315" src="https://www.youtube.com/embed/g6MiiQzOWfI" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>

Het [verslag van de sessie is hier te lezen](https://www.onderwijskennis.nl/nro-symposium-hoger-onderwijs-nieuwe-richtingen-na-de-pandemie/toetsen-op-afstand-en-monitoren-van-de-studievoortgang/verslag). Mijn [essay over Plaats- en tijdonafhankelijk toetsen is hier](https://www.onderwijskennis.nl/sites/onderwijskennis/files/media-files/Thema%205%20-%20Sharon%20Klinkenberg.pdf) te vinden. De overige essays van [Desirée Joosten-ten Brinke](https://www.linkedin.com/in/desirée-joosten-ten-brinke-15a9905/) en [Kim Schildkamp](https://www.linkedin.com/in/kim-schildkamp/) zijn [hier](https://www.onderwijskennis.nl/nro-symposium-hoger-onderwijs-nieuwe-richtingen-na-de-pandemie/toetsen-op-afstand-en-monitoren-van-de-studievoortgang) beschikbaar.


<!doctype html public "-//W3C//DTD HTML 4.0 Transitional//EN">

<title>Tapestry: Web Application Framework</title>

Provides implementations of callbacks, objects that encapsulate a server request that is deferred,
typically to allow a user to login or otherwise authenticate before proceeding with
some other activity.

In practice, an implementation of {@link org.apache.tapestry.IPage#validate(IRequestCycle)} or
{@link org.apache.tapestry.IActionListener} will create a callback, and assign it as a
persistent page property of an application-specific login page.  After the login completes, it
can use the callback to return the user to the functionality that was deferred.

Another example use would be to collect billing and shipping information as part of
an e-commerce site's checkout wizard.

@author Howard Lewis Ship hlship@apache.org